// Register the namespace for the control.
Type.registerNamespace('Ribo.Cms.JS');
Ribo.Cms.JS.CartUI = function(entityName) {
    if (entityName == '') { entityName = 'Cart' }
    this._popUpContainer = null;
    this._progressContainer = null;
    this._displayContainer = null;
    this._innerDisplayContainer = null;
    this._inputQta = null;

    this._satelliteCommandContainer = new Array();   //altro container per eseguire i comandi
    this._satelliteCommandContainer.count = 0;

    this._entityName = entityName;
    this._xsltFileCustom = null;
    this._xsltType = 'Xslt_List';
    

    this._xsltParameter = new Array(); // variabile per la memorizzazione dei parametri da aggiungere ai fogli di stile
    this._xsltParameter.count = 0;


    this.uid = entityName + '_' + iWS.count;
    
    
    
    this._enabled_rawData = SHOWRAWDATA == null ? true : SHOWRAWDATA;
    this._enabled_info = SHOWINFO == null ? true : SHOWINFO;
    this._enabled_showCurrent = true;
    this._enabled_progress = true;
    this._enabled_queryString = true;
    this._enabled_permission = true;  // * per tutte le permission , altrimenti l'elenco delle entità in gioco
    this._permission_entities = '*';  // * per tutte le permission , altrimenti l'elenco delle entità in gioco

};
Ribo.Cms.JS.CartUI.prototype = {
    initialize: function(WebService, Object) {

        var _ename = this._entityName;
        if (WebService == null) { alert('Importare il servizio web per l\'entitò ' + _ename + ''); return }

        iWS[this.uid] = WebService;
        iWS.count += 1;
        iObject[this.uid] = Object;
        iObject.count += 1;

        popUp_id = 'popUp_' + this._entityName + this.uid;
        //se non ho specificato un popUpContainer allora lo genero
        this._popUpContainer = $get(popUp_id);
        if (this._popUpContainer == null) {
            //creo il div background
            bg = document.createElement('div');
            bg.id = 'background_' + popUp_id;
            bg.className = 'centerDiv';

            //creo il div popup
            pp = document.createElement('div');
            pp.id = popUp_id;
            pp.className = 'leightbox';

            //creo il link per le operazioni
            lc = document.createElement('a');
            lc.setAttribute('keys', _ename + '.AddToCart');
            lc.appendChild(document.createTextNode('[Aggiungi]'));

            lc2 = document.createElement('a');
            lc2.setAttribute('keys', _ename + '.UpdateCartItem');
            lc2.appendChild(document.createTextNode('[Aggiorna]'));

            lc3 = document.createElement('input');
            lc3.setAttribute('keys', _ename + '.InputQuantity');
            lc3.onkeydown = function(event) {
                if (window.event.keyCode == 13) { iObject[this.uid].AddToCart() };
                if (window.event.keyCode == 27) { iObject[this.uid].HidePanel() };
            };
            this._inputQta = lc3;

            lc4 = document.createElement('a');
            lc4.setAttribute('keys', _ename + '.HidePanel');
            lc4.appendChild(document.createTextNode('[close]'));

            pp.appendChild(lc3);
            pp.appendChild(lc);
            pp.appendChild(lc2);
            pp.appendChild(lc4);

            document.body.appendChild(bg);
            document.body.appendChild(pp);
            this._popUpContainer = pp;

        }

        if (this._innerDisplayContainer == null) {
            //creo il div per la lista
            ic = document.createElement('div');
            this._displayContainer.appendChild(ic);

            this._innerDisplayContainer = ic;
        }
        this.initializeCommand(this._displayContainer, '[checkout][refresh]');
    },
    initializeCommand: function(element, cmds) {
        var all = (cmds == '*');
        var arr_;
        _ename = this._entityName;

        if (this.initializeCommand_extender != null) {
            //ritorna i comandi che deve ancora controllare se vengono sostituine nell'estensione
            _new_cmds = this.initializeCommand_extender(element, cmds);
            if (_new_cmds != null) { cmds = _new_cmds }
        }

        if (all || cmds.indexOf('[addtocart]', 0) >= 0) {
            arr = getElementsByKey(element, _ename + '.AddToCart', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                var _productUid = (obj.getAttribute('_productUid') == null) ? 'null' : "\'" + obj.getAttribute('_productUid') + "\'";
                var _umUid = (obj.getAttribute('_umUid') == null) ? 'null' : "\'" + obj.getAttribute('_umUid') + "\'";
                var _quantity = (obj.getAttribute('_quantity') == null) ? 'null' : "\'" + obj.getAttribute('_quantity') + "\'";
                jn = "{ProductUid:" + _productUid + ",UmUid:" + _umUid + ",Quantity:" + _quantity + "}";
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].addToCart(' + jn + ');';

            }
            arr = null;
        }

        if (all || cmds.indexOf('[refresh]', 0) >= 0) {
            arr = getElementsByKey(element, _ename + '.Refresh', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].refresh();';
            }
            arr = null;
        }

        if (all || cmds.indexOf('[updatecartitem]', 0) >= 0) {
            arr = getElementsByKey(element, _ename + '.UpdateCartItem', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].updateCartItem();';
            }
            arr = null;
        }
        //		  
        //	if(all || cmds.indexOf('[checkout]',0) >= 0){
        //		var arr = getElementsByKey(element,_ename + '.Checkout','a');
        //		for ( var i=0;i<arr.length;i++ ){
        //			obj = arr[i];
        //			obj.href='Cart.action?cmd=CheckOut'
        //		}
        //		arr =null;
        //	}

        if (all || cmds.indexOf('[remove]', 0) >= 0) {
            arr = getElementsByKey(element, _ename + '.Remove', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._uid = obj.getAttribute('_cartItemUid');
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].remove(\'' + obj._uid + '\');';
            }
            arr = null;
        }
        if (all || cmds.indexOf('[showpanel]', 0) >= 0) {
            arr = getElementsByKey(element, _ename + '.ShowPanel', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                if (obj.id == null || obj.id == '') { obj.id = 'showpanel_' + this.uid + '_' + i }
                obj._productUid = obj.getAttribute('_productUid');
                obj._umUid = obj.getAttribute('_umUid');
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].showPanel(\'' + obj._productUid + '\',\'' + obj._umUid + '\');';
            }
            arr = null;
        }

        if (all || cmds.indexOf('[hidepanel]', 0) >= 0) {
            arr = getElementsByKey(element, _ename + '.HidePanel', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].hidePanel();';
            }
            arr = null;
        }
    },
    getClientParameter: function(_command) {

        if (this._enabled_queryString) {
            var paramtersstring = '';
            paramtersstring = '"QueryString":[';
            for (var i = 0; i < this._xsltParameter.count; ++i) {
                paramtersstring += '{"First":"' + this._xsltParameter[i].key + '","Second":"' + this._xsltParameter[i].value + '"}';
                if (i < this._xsltParameter.count - 1) { paramtersstring += ',' };
            }
            paramtersstring += ']';
        }

        var options = 0
		+ (this._enabled_rawData ? XSLT_SHOWRAWDATA : 0)
		+ (this._enabled_permission ? ((this._permission_entities = '*') ? XSLT_ALLPERMISSION : XSLT_ENTITYPERMISSION) : 0)
		+ (this._enabled_info ? XSLT_SHOWINFO : 0)
		+ (this._enabled_queryString ? XSLT_SHOWQUERYSTRINGINXSLTPARAM : 0);

        switch (_command) {
            default:
                xslt = '"XsltFileCustom":"' + ((this._xsltFileCustom == null) ? '' : this._xsltFileCustom) + '",';
        }
        clientJsonString =
			  '{"ClientId":"' + this.uid + '",'
			+ '"XsltType":"' + this._xsltType + '",'
			+ xslt
			+ '"Options":"' + options + '",'
			+ paramtersstring
			+ '}';

        return clientJsonString
    },
    hidePanel: function() {
        hidePopUp(this._popUpContainer.id);
    },

    initializeSatelliteContainers: function(commands) {
        for (var i = 0; i < this._satelliteCommandContainer.count; ++i) {
            this.initializeCommand(this._satelliteCommandContainer[i], commands);
        }
    },
    addSatelliteCommandContainer: function(element) {
        if (element != null) {
            this._satelliteCommandContainer[this._satelliteCommandContainer.count] = element;
            this._satelliteCommandContainer.count += 1;
        }
    },

    addXsltParameter: function(key, value) {
        this._xsltParameter[this._xsltParameter.count] = function() { this.key = null; this.value = null; };
        this._xsltParameter[this._xsltParameter.count].key = key;
        this._xsltParameter[this._xsltParameter.count].value = value;
        this._xsltParameter.count += 1;

    },

    refresh: function() {
        //this._refreshCartDelegate();

        filter = '{"CartFlags":"LoadCurrent"}';
        clientJsonString = this.getClientParameter('');

        this.progress_show();

        iWS[this.uid].GetXmlXslt(
		filter, clientJsonString
		, this.onSuccessRefresh, this.onFailedCallback, this.uid);
    },
    onSuccessRefresh: function(result, context) {
        iobj = iObject[context];

        iobj.progress_hide();

        iobj._innerDisplayContainer.innerHTML = result;
        iobj.initializeCommand(iobj._innerDisplayContainer, '[showpanel][remove]');
        iobj.initializeCommand(iobj._displayContainer, '[checkout][refresh]');


    },
    onFailedCallback: function(result, context) {
        iobj = iObject[context];
        alert(result.get_message());
        iobj.progress_hide();
    },
    showPanel: function(_productUid, _umUid) {
        this._inputQta.value = 1;
        this._prdUid = _productUid;
        this._umUid = _umUid;

        showPopUp(this._popUpContainer.id);
        //setFocus(this._inputQta.id);

        this.initializeCommand(this._popUpContainer, '[showpanel][hidepanel][addtocart][updatecartitem][inputquantity]');


    },

    remove: function(cartItemUid) {
        iWS[this.uid].RemoveCartItem(cartItemUid,
		this.onSuccessRemove,
		this.onFailedCallback, this.uid);
        this.refresh();
    },

    onSuccessRemove: function(result, context) {
        iobj = iObject[context];
    },
    addToCart: function(ObjJn) {
        if (ObjJn.ProductUid != null) { this._prdUid = ObjJn.ProductUid };
        if (ObjJn.UmUid != null) { this._umUid = ObjJn.UmUid };
        if (ObjJn.Quantity != null) { this._inputQta.value = ObjJn.Quantity };

        iWS[this.uid].AddToCart(this._prdUid, this._umUid,
			this._inputQta.value,
			this.onSuccessAddToCart,
			this.onFailedCallback, this.uid);
    },
    onSuccessAddToCart: function(result, context) {
        iobj = iObject[context];
        iobj.hidePanel();

        iobj.refresh();
        if (iobj._onAddToCart != null) { iobj._onAddToCart(result, context) };
        iobj._prdUid = null;
        iobj._umUid = null;
    },
    updateCartItem: function() {
        executeUrlSynch('Cart.action?cmd=AddToCart&ProductUid=' + this._prdUid + '&UmUid=' + this._umUid + '&Qta=~' + this._inputQta.value);
        this.hidePanel();
        this.refresh();
    },
    progress_show: function() {
        if (this._progressContainer != null && this._enabled_progress) { this._progressContainer.style.display = 'block'; }
    },
    progress_hide: function() {
        if (this._progressContainer != null && this._enabled_progress) { this._progressContainer.style.display = 'none'; }
    }

};
//Ribo.Cms.JS.CartUI.registerClass('Ribo.Cms.JS.CartUI', Sys.UI.Control);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

