/********************************************************************

	FOREX.COM - ORDER TICKET
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 25, 2008
	=========================================	
	
	Description
	-------------------------------------------------------------
	There are two parts for the order ticket
	
	1. OrderTicket - a global order ticket that gets repositioned when spawned
	2. TradeButton - the button that spawns the OrderTicket at it's position
	
	
	HTML Markup Sample
	-------------------------------------------------------------
	_widget_samples/order_ticket.html
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2

*********************************************************************/

 
var currTradeButton = null; // stores reference to the active trade button


/********************************************************************
	
	ORDER TICKET
	
	Public Methods
	-------------------------------------------------------------
	init
		Arguments: none
		Returns: null
			
	hide
		Description: moves the order ticket off screen and hides it
		Arguments: none
		Returns: null
		
	submitPurchase
		Description: this is pseudo code which would be replaced with code required to submit the purchase details. 
		Arguments: none
		Returns: null
		
	confirmOCTPurchase
		Description: this shows the purchase confirmation panel, and hides the trade in progress bar.
		Arguments: none,
		Returns: null
		
	switchPanel
		Description: this hides the current panel, and displays the panel being passed in
		Arguments: 
			- panelID (string) : the id of the HTML panel element
		Returns: null
	
	
*********************************************************************/
var OrderTicket = {
    orderTicketElement: null,
    currPanel: null,
    isProcessingDeal: false,
    callingObject: null,
    dealRate: 0,

    init: function() {
        OrderTicket.orderTicketElement = $('order_ticket');
    },

    hide: function() {
        if (this.isProcessingDeal) {
            return;
        }
        OrderTicket.orderTicketElement.setStyles({
            top: -1000000,
            left: -1000000,
            display: 'none'
        });

        // reset the current trade button to a zero z-index
        if (currTradeButton != null) {
            currTradeButton.tradeButton.setStyles({
                zIndex: 0
            });
        }
    },
    tempHide: function() {
        OrderTicket.orderTicketElement.setStyles({ display: 'none' });
    },
    tempShow: function() {
    var tradeButtonPos = currTradeButton.tradeButton.getPosition('master_container');
        OrderTicket.orderTicketElement.setStyles({
            top: (tradeButtonPos.y - 8),
            left: (tradeButtonPos.x - 8),
            display: 'block'
        });
    },
    submitPurchase: function() {
        //Roy: changed the code to use aTradingManager,removed unnecessary code and added logic to prevent executing other events when another 
        //event is executing
        this.switchPanel('transaction_processing_ticket');
        OrderTicket.isProcessingDeal = true;


        // SEND PURCHASE REQUEST VIA AJAX
        // PROCESS SERVER RESPONSE
        // IF SUCCESSFUL
        // POPULATE THE DETAILS OF THE 'purchase_confirm_ticket'
        // SHOW THE 'purchase_confirm_ticket'

        //Khalil
        //						    if ($('order_ticket_quantity').value==0) 
        //						    {
        //						        alert('Quantity cannot be zero'); return;
        //						    }

        if (currTradeButton.purchaseType == 'buy') {
            this.dealRate = $(currTradeButton.pair_id + '_buy_price').innerHTML;
        }
        else if (currTradeButton.purchaseType == 'sell') {
            this.dealRate = $(currTradeButton.pair_id + '_sell_price').innerHTML;
        }

        //alert(currTradeButton.product + '|' + this.dealRate + '|' + currTradeButton.purchaseType + '|' + $('order_ticket_quantity').value);

        var aDealData = new GAIN.DealData();
        aDealData.Product = currTradeButton.product;

        if (currTradeButton.purchaseType == 'buy') {
            aDealData.BuySell = 'B';
        } else if (currTradeButton.purchaseType == 'sell') {
            aDealData.BuySell = 'S';
        }
        aDealData.Rate = this.dealRate;
        aDealData.Contract = $('order_ticket_quantity').value;

        //Place Deal Now
        //PlaceDeal('ATRATE', aDealData, OrderTicket.DealCallback);
        aTradingManager.PlaceDeal("ATBEST", aDealData, "N", this.DealCallback);

        // IF NOT SUCCESSFUL
        // SHOW ERROR MESSAGE
    },
    //Khalil - Deal Callback
    DealCallback: function(success, result) {

        var resultSet = result.d// Ext.util.JSON.decode(result.d);
        //var objDeal = Ext.util.JSON.encode(result);

        var tplConfirmation = new Ext.XTemplate(
            '<span class="title">Transaction Update</span>',
		        '<p>You {[this.getBuySell(values.BuySell)]}&nbsp;{[this.formatInteger(values.Contract)]}<br />',
		        '{[this.productAlias(values.Product)]} @ {Rate}</p>',
		        '<p>{DealDate}</p>',
		    '<a href="javascript:main_processASSPOrder()"><img id="stop_loss_take_profit_button" src="resources/images/buttons/btn_add_stop_loss_take_profit_green_off.gif" class="hover_button" alt="Add Stop Loss/Take Profit" style="display: none;" /></a>',
			'<div class="close_button"><a href="javascript:OrderTicket.hide();">Close <img src="resources/images/buttons/btn_close_x_green_off.gif" class="icon" alt="x" /></a></div>'
			, {
			    getBuySell: function(buysell) {

			        if (buysell === 'B') {
			            return 'bought';
			        }
			        else if (buysell === 'S') {
			            return 'sold';
			        }
			    }
			}, {
			    productAlias: function(v) {
			        return aTradingManager.getProductAlias(v);
			    }
			}, {
			    formatInteger: function(v) {
			        var re = new RegExp('(\\d{1,3})(?=(?:\\d{3})+(\\.|$))', 'g');
			        return v.toString().replace(re, '$1,');
			    }
			});

        var tplConfirmationError = new Ext.XTemplate(
            '<span class="title">Transaction Error</span>',
                '<p><span id="error_ticket_message">{Message}</span></p>',
            '<div class="close_button"><a href="javascript:OrderTicket.hide();">Close <img src="resources/images/buttons/btn_close_x_red_off.gif" class="icon" alt="x" /></a></div>'
        );
        if (success) {




            if (!result.d.Result.Status) {
                tplConfirmationError.overwrite(document.getElementById("error_ticket"), resultSet);
                OrderTicket.switchPanel('error_ticket');
            } else {
                tplConfirmation.overwrite(document.getElementById("purchase_confirm_ticket"), resultSet);
                OrderTicket.switchPanel('purchase_confirm_ticket');

                //                $('buy_sell_text').innerHTML = tplConfirmation.getBuySell(result.d.BuySell);
                //                $('quantity_confirm_ticket').innerHTML = tplConfirmation.formatInteger(result.d.Contract);
                //                $('pair_name_stop_loss_take_profit').innerHTML = result.d.Product;
                //                $('rate_stop_loss_take_profit').innerHTML = result.d.Rate;
                if (result.d.FireAssp == 'Y') {

                    $('stop_loss_take_profit_button').style.display = "";
                }
                else {

                    $('stop_loss_take_profit_button').style.display = "none";

                }


            }
        } else {
            //Web Service Call Error
            tplConfirmationError.overwrite(document.getElementById("error_ticket"), resultSet);
            //Ext.DomHelper.overwrite('purchase_confirm_ticket','Failed');
            $('error_ticket_message').innerHTML = "WS Call failed - Transaction did not go through, please contact customer support.";
            OrderTicket.switchPanel('error_ticket');
        }
        OrderTicket.isProcessingDeal = false;

    },

    switchPanel: function(panelID, callingObject) {
        var panel = $(panelID);



        OrderTicket.callingObject = callingObject;

        // hide the current panel
        if (OrderTicket.currPanel != null) {
            OrderTicket.currPanel.setStyles({
                display: 'none',
                visibility: 'hidden'
            });
        }

        // set new panel and container to block so we can get the height
        panel.setStyle('display', 'block');
        OrderTicket.orderTicketElement.setStyles({
            display: 'block',
            visibility: 'hidden'
        });

        var panelHeight = panel.getSize().y;

        // set the containers height and display it.
        OrderTicket.orderTicketElement.setStyles({
            height: panelHeight,
            visibility: 'visible'
        });
        panel.setStyle('visibility', 'visible');

        OrderTicket.currPanel = panel;

        if (panelID == 'stop_loss_take_profit_ticket') {
            OrderTicket.toggleStopLoss();
            OrderTicket.toggleTakeProfit();
        }
    }
};



window.addEvent('domready', OrderTicket.init);

function main_processASSPOrder()
    {
       aTradingManager.EditOrderInDock('PLACE', null, true, currTradeButton.product,'S',true); 
       OrderTicket.hide();
    }
/********************************************************************
	
	TRADE BUTTON
	
	Public Methods
	-------------------------------------------------------------
	initialize (constructor)
		Arguments: 
			- tradeButtonID (string) : the id of the trade button HTML element
			- pair_id (string): not currently used (would be passed to the order ticket)
			- purchaseType (string) : 'buy' or 'sell' not currently used (would be passed to the order ticket)
		Returns: null
			
	show
		Description: grabs the position of the trade button and opens the Order Ticket at that position
		Arguments: none
		Returns: null
	
	
*********************************************************************/
    var TradeButton = new Class({
        initialize: function(tradeButtonID, pair_id, purchaseType, minLots, maxLots, tradeSize, defaultTradeLot) {
            this.tradeButtonID = tradeButtonID;
            this.pair_id = pair_id;
            this.purchaseType = purchaseType;
            this.minLots = minLots;
            this.maxLots = maxLots;
            this.tradeSize = tradeSize;
            this.defaultTradeLot = defaultTradeLot;


            this.product = pair_id.toUpperCase().replace("_", "/");
            this.tradeButton = $(this.tradeButtonID);
            this.tradeButton.addEvent('click', this.show.bind(this));


        },

        show: function() {
            if (OrderTicket.isProcessingDeal) {

                return;
            }
            var tradeButtonPos = this.tradeButton.getPosition('master_container');
            var orderTicketElement = $('order_ticket');

            // hide any tickets that are currently open
            OrderTicket.hide();

            if (aTradingManager.Rates.get(this.product).Status == 'R' && aTradingManager.ProductSettingObject.data.get(this.product).Type == 'CFD') { return false; }
            // move the order ticket to the trade buttons position
            orderTicketElement.setStyles({
                top: (tradeButtonPos.y - 8),
                left: (tradeButtonPos.x - 8)
            });
            var tmpVar = aTradingManager.getProductAlias(this.product);
            if (tmpVar != "" && tmpVar.indexOf("/") > -1) {
                $('base_quote_Holder2').addClass('hidden');
                $('base_quote_Holder1').removeClass('hidden');
                //Khalil - Base Pair
                $('base_name_purchase_ticket').innerHTML = this.pair_id.toUpperCase().substring(0, 3);
                //Quote Pair
                $('quote_name_purchase_ticket').innerHTML = this.pair_id.toUpperCase().substring(4);                
            }
            else {
                $('base_quote_Holder1').addClass('hidden');
                $('base_quote_Holder2').innerText = tmpVar;
                $('base_quote_Holder2').removeClass('hidden');
            }
            $('current_pair_title').setStyle('display', 'block');
            $('transaction_type').innerHTML = this.purchaseType.capitalize();

            $('order_ticket_quantity').value = this.tradeSize;   //Default Trade Size
            var order_ticket_quantity = new SpinnerControl('order_ticket_quantity', this.tradeSize, 0, this.minLots, this.maxLots, this.defaultTradeLot);

            // check the global oneClickTradingState variable
            if (Cookie.read('OCT') == 'true') {
                OrderTicket.submitPurchase();

                var progressBar = $('trade_in_progress');

                if (this.purchaseType == 'buy') {
                    progressBar.setStyles({
                        top: (tradeButtonPos.y),
                        left: (tradeButtonPos.x - 191),
                        display: 'block'
                    });
                }
                else if (this.purchaseType == 'sell') {
                    progressBar.setStyles({
                        top: (tradeButtonPos.y),
                        left: (tradeButtonPos.x),
                        display: 'block'
                    });
                }
            }
            else {
                //alert(Ext.get('eur_chf_sell_price'));
                OrderTicket.switchPanel('purchase_ticket');
            }


            this.tradeButton.setStyles({
                zIndex: 9550
            });

            // set the global currTradeButton object reference
            currTradeButton = this;
        }
    });

