///<reference path="../TESCO.js" />
///<reference path="../event.js" />
///<reference path="../eventManager.js" />
///<reference path="../exception.js" />
///<reference path="../node.js" />
///<reference path="../position.js" />
///<reference path="../validation.js" />
///<reference path="../effects.js" />
///<reference path="../XMLHTTP.js" />
///<reference path="../ajax.js" />
///<reference path="dialogue.js" />

TESCO.UI.Checkout = (function() {

    var _form, _inputId, _formId, _addNewAddress;

    //  constructor
    function _constructor() {
        TESCO.system.event.document.addEventListener("load",
			function() {
			    var _contentContainer = document.getElementById("mainContent");
			    if (_contentContainer) var _addNewAddress = TESCO.system.DOM.node.getElementsByClassName(_contentContainer, "addNewAddress");
			    if (_addNewAddress) {
			        if (_form = document.getElementById('fOrder')) {
			            _formId = 'fOrder';
			            _inputId = 'addresses';
			        } else {
			            _formId = 'fDeliveryDetails';
			            _form = document.getElementById(_formId)
			            _inputId = 'address';
			        }
			        var _sb = new TESCO.UI.inputs.SelectBox(_inputId);
			        if (_sb.selectBox) {
			            _sb.addEventListener("changed",
							function() {
							    _sb.createButtonClone(_formId, "selectAddress", "select");
							    _form.submit();
							}
						);
			            TESCO.system.event.attach("newAddress", "click",
							function(e) {
							    e.prevent();
							    TESCO.system.DOM.node.removeClassName(document.getElementById("addNewAddress"), "hide");
							    TESCO.system.DOM.node.addClassName(document.getElementById("addressBookContainer"), "jshide");
							}, false
						);
			        }
			    }
			}
		);
        this.NAME = "TESCO.UI.Checkout";
        return this;
    }

    //  return new instance
    return new _constructor();
})();



TESCO.$('UI.Checkout').PaymentItem = (function() {

    function _constructor() {
        var _self = this;

        TESCO.system.event.attach($(this.attributes.container), "click",
			function(e) {
			    clickHandler(e, _self);
			}, false);
        new TESCO.UI.Collapse.Section(this.attributes.collapseContainer, this.attributes.collapseBtn, true,
			{ "collapseImg": TESCO.sites.Configuration.application.img.URI + "/Sites/Retail/" + TESCO.sites.Configuration.application.name + "/Online/Checkout/" + this.attributes.toggleClose,
			    "expandImg": TESCO.sites.Configuration.application.img.URI + "/Sites/Retail/" + TESCO.sites.Configuration.application.name + "/Online/Checkout/" + this.attributes.toggleOpen,
			    "preventDefault": true
			});
        return this;
    }

    function clickHandler(e, _self) {

        var t = e.target;
        
        var _control = {
            node: t,
            parent: e.target.parentNode,
            event: e,
            attributes: _self.attributes
        };

        var _actionTable = [{ val: { action: "Remove", stopEvent: true }, className: "removeItem" },
							{ val: { action: t.checked == true ? "Select" : "Deselect", stopEvent: false }, className: "checkItem" },
							{ val: { action: "Add", stopEvent: true }, className: "useItem"}]

        _control.action = TESCO.system.DOM.node.getAction(_actionTable, t);

        if (TESCO.system.DOM.node.getAncestorByAttributeRegExp(t, "class", new RegExp('invalid')) && _control.action.action != "Remove") {
            e.prevent();
            return;
        }

        if (_control.action != "default") {
            if (_control.action.action == 'Add') {
                //if (_self.validate()) {
                    _request(_control, _self);
                //}
            } else if (_control.action.action == 'Remove') {
                _createDialogue(_control, _self);
            } else {
                _request(_control, _self);
            }
            if (_control.action.stopEvent) {
                e.prevent();
            }
        }
    }

    function _request(control, _self) {

        var _ajaxId = getPaymentItemID(control);
        if (control.attributes.ajaxPin) {
            var _pin = document.getElementById(control.attributes.ajaxPin).value;
        } else {
            var _pin = null;
        }

        _self.background.show();
        var _con = new TESCO.system.connection.ajax(false);
        TESCO.system.connection.eggTimer.show($(_self.attributes.container));
        _con.request(control.attributes.ajaxUrl, new control.attributes.ent(_ajaxId, _pin, control.action.action));
        TESCO.system.event.attach(_con, "complete",
			function(e) {
			    _self.background.hide();
			    TESCO.system.connection.eggTimer.hide($(_self.attributes.container));
			    _render(e, control, _self);
			}
        );
        TESCO.system.event.attach(_con, "error",
            function(e) {
                _self.background.hide();
                TESCO.system.connection.eggTimer.hide($(_self.attributes.container));
                e.exception.dialogue.show(e.exception);
            }
        );
    }

    function _createDialogue(control, _self) {

        var _rpiDialogue = new TESCO.UI.Dialogue.Ajax(new TESCO.sites.UI.Dialogue.Request("RemovePaymentItem"));
        _rpiDialogue.show();

        _rpiDialogue.addEventListener("confirm",
            function(e) {
                _request(control, _self);
                _rpiDialogue.removeEventListener("confirm", arguments.callee);
                _rpiDialogue.hide();
            }
        );
        
        _rpiDialogue.addEventListener("cancel",
            function(e) {
                _rpiDialogue.removeEventListener("confirm", arguments.callee);
                _rpiDialogue.removeEventListener("cancel", arguments.callee);
            }
         ); 
    }

    function getPaymentItemID(control) {
        switch (control.action.action) {
            case "Add":
                return $(control.attributes.ajaxId).value;
                break;
            case "Remove":
                var _id = control.parent.getElementsByTagName('input')[0].name;
                return _id.substring(_id.indexOf("-") + 1);
                break;
            default:
                return control.node.name.substring(control.node.id.indexOf("-") + 1);
        }
    }

    function _render(e, control, _self) {

        var _container = document.getElementById(_self.attributes.payOptionContainer);

        //Render item listing
        var _itemList = e.response.response.content[0].nodeValue;
        TESCO.system.DOM.node.removeChildNodes($(_self.attributes.payOptionContainer));
        $(_self.attributes.payOptionContainer).appendChild(_itemList);

        //Render totals
        var _itemTotals = e.response.response.content[1].nodeValue;
        TESCO.system.DOM.node.removeChildNodes($(_self.attributes.totals));
        $(_self.attributes.totals).appendChild(_itemTotals);

        //Render payment summary
        var _paymentSummary = e.response.response.content[2].nodeValue;
        var _paySumContainer = document.getElementById("paymentSummaryContainer");
        TESCO.system.DOM.node.removeChildNodes(_paySumContainer);
        _paySumContainer.appendChild(_paymentSummary);
        
        //Render order summary
        var _orderSummary = e.response.response.content[3].nodeValue;
        var _orderSumContainer = document.getElementById("orderSummaryContainer");
        TESCO.system.DOM.node.removeChildNodes(_orderSumContainer);
        _orderSumContainer.appendChild(_orderSummary);

        //Update title
        updateTitle(control, _self);

        //Clear form fields
        document.getElementById(_self.attributes.ajaxId).value = "";
        if (_self.attributes.ajaxPin) $(_self.attributes.ajaxPin).value = "";
    }

    function updateTitle(control, _self) {
        _self.count = $(_self.attributes.payOptionContainer).getElementsByTagName("div").length - 1;
        _self.count <= -1 ? TESCO.system.DOM.node.addClassName($(control.attributes.payItemTitle), "hide") : TESCO.system.DOM.node.removeClassName($(control.attributes.payItemTitle), "hide");
    }

    _constructor.prototype.NAME = "TESCO.UI.Checkout.PaymentItem";
    

    return _constructor;
})();

TESCO.$('UI.Checkout.PaymentItem').GiftCard = (function() {

	function _constructor(inputId, inputPin) {	
	    this.attributes.ajaxId = inputId;
	    this.attributes.ajaxPin = inputPin;	
        this.background = new TESCO.UI.effects.Background(TESCO.system.DOM.node.getElementsByClassName(document.getElementById(this.attributes.container), "collapsible")[0]);
        _constructor.base.constructor.call(this);
        return this;
    }
    _constructor.extend(TESCO.UI.Checkout.PaymentItem);

    _constructor.prototype.NAME = "TESCO.UI.Checkout.PaymentItem.GiftCard";
    
    _constructor.prototype.attributes = {
        ajaxUrl: TESCO.sites.Configuration.application.path + "/Ajax/GiftCard.aspx", //	move to locale
        ent: function(id, pin, actionType) {
            this.request = {
                giftCard: {
                    "id": id,
                    "pin": pin || null,
                    "actionType": actionType
                }
            };
        },
        container: "giftWrap",
        payOptionContainer: "giftCardList",
        payItemTitle: "gcTitle",
        collapseContainer: "giftWrap",
        collapseBtn: "gColTrigger",       
        totals: "giftcardTotals",
        toggleOpen: "useGiftCardOpen.gif",
        toggleClose: "useGiftCardClose.gif"
    };

    _constructor.prototype.validate = function() {
        return ($(this.attributes.ajaxId).value && $(this.attributes.ajaxPin).value);
    }

    return _constructor;
})();

TESCO.$('UI.Checkout.PaymentItem').Voucher = (function() {

    function _constructor(inputId) {	
	    this.attributes.ajaxId = inputId;
        this.background = new TESCO.UI.effects.Background(TESCO.system.DOM.node.getElementsByClassName(document.getElementById(this.attributes.container), "collapsible")[0]);
		_constructor.base.constructor.call(this);
		return this;
    }
	_constructor.extend(TESCO.UI.Checkout.PaymentItem);

	_constructor.prototype.NAME = "TESCO.UI.Checkout.PaymentItem.Voucher";
	

	_constructor.prototype.attributes = {
		ajaxUrl: TESCO.sites.Configuration.application.path + "/Ajax/VoucherECoupon.aspx",	//	todo: move to locale
		ent: function(id, pin, actionType) {
			this.request = {
				voucher: {
					"id": id,
					"actionType": actionType
				}
			};
		},
		container:  "voucherEcoupWrap",
		payOptionContainer: "voucherList",
		payItemTitle: "vTitle",
		collapseContainer: "voucherEcoupWrap",
		collapseBtn: "vColTrigger",		
        totals: "voucherTotals",
		toggleOpen : "addVoucherOpen.gif",
		toggleClose : "addVoucherClose.gif"
	};

	_constructor.prototype.validate = function() {
		return !!$(this.attributes.ajaxId).value;
	};

    return _constructor;
})();
