Type.registerNamespace('Ribo.Cms.JS');
Ribo.Cms.JS.EntityUI = function(entityName) {
    Ribo.Cms.JS.EntityUI._initializeBase(this, entityName);
};
Ribo.Cms.JS.EntityUI._initializeBase = function(obj, entityName) {
    obj._filterContainer = null;
    obj._displayContainer = null;

    obj._insertContainer = null; 	//per contenere i campi di insert 
    obj._updateContainer = null; 	//per contenere i campi di update

    obj._commandContainer = null;
    obj._viewContainer = null;

    obj._detailContainer = null;
    obj._detailContainer_display = null;

    obj._xsltType = 'Xslt_Grid';
    obj._xsltFileCustom_detail = null;
    obj._xsltFileCustom = null;
    obj._xsltFileCustom_insert = null;
    obj._xsltFileCustom_update = null;


    obj._xsltParameter = new Array(); // variabile per la memorizzazione dei parametri da aggiungere ai fogli di stile
    obj._xsltParameter.count = 0;

    obj._filterFunction = null;
    obj._insertFunction = null;
    obj._updateFunction = null;
    obj._getxml_webservice_functionname = null; //Funziona da utilizzare per il recupero dei dati xml di default chiama il ws.GetXmlXslt
    obj._updateBulkFunction = null;
    obj._entityName = entityName;

    obj._currentView = null;
    obj._exportXslt = null;

    obj._progressElement = null;
    obj._uidSelectionElement = null;
    obj._elementIndex = null;
    /*functionality to enable*/
    obj._enabled_multiSelection = true;  //abilità la possibilità di selezionare + uid (la parte di selezione è data dalla pagina

    obj._enabled_filter = true; //permette la ricerca di filtri nel contenitore Filter con key <Entity>.Filter e nome campo
    // viene aggiunto onchange per automatizzare il refresh della pagina

    //abilita il bind con la possibilità di indicare dei parametri
    obj._enabled_bind_withparam = false;
    obj._bind_webservice = null; // specifico un altro web service per il bind


    obj._enabled_insert = false;
    obj._enabled_update = false;
    obj._enabled_updateBulk = false;
    obj._enabled_bind = false;  // abfilita la gestione di entità da bindare
    obj._enabled_paging = true;
    obj._enabled_detail = false;
    obj._enabled_switch = true; //abilita i comandi Enable e Disable
    obj._enabled_rawData = SHOWRAWDATA == null ? true : SHOWRAWDATA;
    obj._enabled_info = SHOWINFO == null ? true : SHOWINFO;
    obj._enabled_progress = true;
    obj._enabled_queryString = true;

    obj._enabled_deleteCommand = true; //abilità la chiave deleteKeyByUid per la cancellazione
    obj._enabled_commands = true; // abilita/disabilita tutti i comandi di lista

    obj._enabled_permission = true;  // * per tutte le permission , altrimenti l'elenco delle entità in gioco
    obj._permission_entities = '*';  // * per tutte le permission , altrimenti l'elenco delle entità in gioco

    obj.uid = entityName + '_' + iObject.count;

    obj._insert_fields = null;
    obj._update_fields = null;
    obj._updateBulk_fields = null;

    //	obj.initializeCommand_extender = null;
    obj._onSwitchFunction = null;
    obj._onListRefreshed = null;
    obj._onBind = null;

    /* proprietà per il controllo server */
    obj._maxRowsNumber = null;

};
Ribo.Cms.JS.EntityUI.prototype = {
    // event worker object constructor
    _checkSettings: function() {
        if (this._entityName == null) { alert('Non è stata valorizzata la proprietà this._entityName'); return false }
        if (this._displayContainer == null) { alert('Non è stata valorizzata la proprietà this._displayContainer'); return false }

        if ((this._enabled_multiSelection
		|| this._enabled_paging) && this._enabled_commands) {
            if (this._commandContainer == null) { alert('Non è stato specificato il contenitore dei command	 (this._commandContainer)'); return false }
        }

        if (this._enabled_insert) {
            if (this._insertFunction == null) { alert('Non è stata specificata la funzione (this._insertFunction) per le operazioni di insert'); return false }
        }
        if (this._enabled_update) {
            if (this._updateContainer == null) { alert('Non è stata specificata il contenitore (this._updateContainer) per le operazioni di update'); return false }
        }
        if (this._enabled_filter) {
            if (this._filterFunction == null) { alert('Non è statao specificata la funzione per recuperare il filtro (this._filterFunction)'); return false }
        }
        if (this._enabled_commands) {
            if (this._commandContainer == null) { alert('Non è stato specificato il contenitore dei comandi (this._commandContainer)'); return false }
        }
        if (this._enabled_progress) {
            if (this._progressElement == null) { alert('Non è stato specificato il contenitore del progress (this._progressElement)'); return false }
        }

        return true

    },
    get_bindToUid: function() { return this._bindToUid },
    get_selectedUids: function() {
        if (this._enabled_multiSelection) { return this._uidSelectionElement.value }
    },
    clear_selectedUids: function() {
        if (this._enabled_multiSelection) { this._uidSelectionElement.value = '' }
    },
    initialize: function(WebService, Object) {
        if (this._checkSettings() == false) { return null }
        _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;

        //se non ho specificato un popUpContainer allora lo genero
        if (this._detailContainer == null) {
            detail_id = 'detail_' + this._entityName;
            //creo il div background
            bg = document.createElement('div');
            bg.id = 'background_' + detail_id;
            bg.className = 'centerDiv';

            //creo il div popup
            pp = document.createElement('div');
            pp.id = detail_id;
            pp.className = 'leightbox';

            //creo il link per chiudere
            lc = document.createElement('a');
            lc.setAttribute('keys', _ename + '.HidePanel');
            lc.appendChild(document.createTextNode('[close]'));

            //creo la lista contenitore
            cc = document.createElement('div');
            cc.setAttribute('keys', _ename + '.PopUpDisplay');
            lc.appendChild(document.createTextNode(''));

            pp.appendChild(lc.cloneNode(1));
            pp.appendChild(cc);
            pp.appendChild(lc.cloneNode(1));

            document.body.appendChild(bg);
            document.body.appendChild(pp);
            this._detailContainer = pp;
            this._detailContainer_display = cc;

        }

        if (this._insertContainer != null) {
            //this._insertContainer.style.display='none'
            detail_id = 'insert_' + this._entityName;
            //creo il div background
            bg_i = document.createElement('div');
            bg_i.id = 'background_' + detail_id;
            bg_i.className = 'centerDiv';

            //creo il div popup
            pp_i = document.createElement('div');
            pp_i.id = detail_id;
            pp_i.className = 'leightbox';

            pp_i.appendChild(this._insertContainer);

            document.body.appendChild(bg_i);
            document.body.appendChild(pp_i);
            this._insertContainer = pp_i;

        }

        if (this._updateContainer != null) {
            //this._insertContainer.style.display='none'
            detail_id = 'update_' + this._entityName;
            //creo il div background
            bg_u = document.createElement('div');
            bg_u.id = 'background_' + detail_id;
            bg_u.className = 'centerDiv';

            //creo il div popup
            pp_u = document.createElement('div');
            pp_u.id = detail_id;
            pp_u.className = 'leightbox';

            pp_u.appendChild(this._updateContainer);

            document.body.appendChild(bg_u);
            document.body.appendChild(pp_u);
            this._updateContainer = pp_u;

        }
        //controllo se il Display del dettaglio è vuoto (perchè non indicato o non creato)
        if (this._detailContainer_display == null) { this._detailContainer_display = this._detailContainer }

        //** se attivo il MULTI SELECTION creo un hidden per storare gli uid selezionati
        //** l'hidden verrà aggiunto nella sezione Filtri.
        if (this._enabled_multiSelection) {
            selection_id = '_uids_' + _ename;
            _obj = $get(selection_id);
            if (_obj == null) {
                _obj = document.createElement("Input");
                _obj.setAttribute("type", "hidden");
                _obj.setAttribute("id", selection_id);
                _obj.setAttribute("name", selection_id);
                _obj.setAttribute("value", '');
            }
            this._uidSelectionElement = _obj;
            this._commandContainer.appendChild(this._uidSelectionElement);
        }

        //** se attivo il PAGING creo un hidden per memorizzare l'indice della pagina selezionata
        //** l'hidden verrà aggiorno nella sezione Filtri.
        if (this._enabled_paging) {
            index_id = '_current_idx_' + _ename;
            _obj2 = $get(index_id);
            if (_obj2 == null) {
                _obj2 = document.createElement("Input");
                _obj2.setAttribute("type", "hidden");
                _obj2.setAttribute("id", index_id);
                _obj2.setAttribute("value", 0);
            }
            this._elementIndex = _obj2;
            this._commandContainer.appendChild(this._elementIndex);
        }

        if (this._enabled_filter) {
            if (this._filterContainer != null) {
                this.initializeCommand(this._filterContainer, '[filter]');
            }
        }

        if (this._enabled_updateBulk) {
            this.initializeCommand(this._commandContainer, '[updatebulkinput][updatebulk]');
        }


        if (this._enabled_commands) {
            if (this._enabled_deleteCommand) {
                this.initializeCommand(this._commandContainer, '[delete][unbind]');
            }
            if (this._enabled_switch) {
                this.initializeCommand(this._commandContainer, '[switch]');
            }
            if (this._enabled_insert || this._enabled_update) {
                this.initializeCommand(this._commandContainer, '[showinsert][update]');
                if (this._enabled_insert) { this.initializeCommand(this._insertContainer, '[insertinput][hideinsert][insert]'); }
                if (this._enabled_update) { this.initializeCommand(this._updateContainer, '[updateinput][hideupdate][update]'); }
            }
            this.initializeCommand(this._commandContainer, '[bindall][unbindall][bindjson]');
            if (this._viewContainer != null) {
                this.initializeCommand(this._viewContainer, '[view]');
            }
            if (this._exportContainer != null) {
                this.initializeCommand(this._exportContainer, '[export]');
            }
        }

        this.progress_hide();
    },
    setFilterValue: function(filterName, value) {
        if (this._filters != null) {
            for (var i = 0; i < this._filters.length; i++) {
                obj = this._filters[i];
                if (obj._filterName == filterName || obj._filtername == filterName) {
                    obj.value = value;
                    return;
                }

            }
        }
    },
    initializeCommand: function(element, cmds) {
        var all = (cmds == '*');
        var _os = 'javascript:iObject[\'' + this.uid + '\']';
        _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('[bind]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Bind', 'img');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.onclick = function() { obj.Bind(this.getAttribute('_' + _ename.toLowerCase() + 'Uid'), this.get_bindToUid(), this._bindToEntity); }
            }
            arr = null;
            var arr = getElementsByKey(element, _ename + '.Bind', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._toUid = obj.getAttribute('_' + _ename.toLowerCase() + 'Uid');
                obj.href = _os + ".Bind('" + obj._toUid + "','" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
            }
            arr = null;
        }
        if (all || cmds.indexOf('[bindall]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.BindAll', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._toUid = obj.getAttribute('_' + _ename.toLowerCase() + 'Uid');
                if (typeof this.get_bindToUid() == 'function') {
                    obj.href = _os + ".BindAll(iObject[\'" + this.uid + "\']._bindToUid(),'" + this._bindToEntity + "');";
                } else {
                    obj.href = _os + ".BindAll('" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
                }

            }
            arr = null;
        }
        if (all || cmds.indexOf('[bindjson]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.BindJson', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._jsonString = obj.getAttribute('_jsonString');
                obj._bindToUid = this._bindToUid == null ? obj.getAttribute('_bindToUid') : this._bindToUid;
                obj.href = _os + ".BindJson('" + obj._jsonString + "','" + obj._bindToUid + "','" + this._bindToEntity + "');";
            }
            arr = null;
        }
        if (all || cmds.indexOf('[view]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.View', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._xslt = obj.getAttribute('_xslt');
                obj.href = _os + ".View('" + obj._xslt + "');";
            }
            arr = null;
        }
        if (all || cmds.indexOf('[export]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Export', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._xslt = obj.getAttribute('_xslt');
                obj._contentType = obj.getAttribute('_contentType');
                if (obj._contentType == null) { obj._contentType = 'application/vnd.ms-excel' }
                obj._extension = obj.getAttribute('_extension');
                if (obj._extension == null) { obj._extension = 'xls' }
                obj.href = _os + ".Export('" + obj._xslt + "','" + obj._contentType + "','" + obj._extension + "');";
            }
            arr = null;
        }

        if (all || cmds.indexOf('[detail]', 0) >= 0
			&& this._enabled_detail) {
            var arr = getElementsByKey(element, _ename + '.Detail', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._toUid = obj.getAttribute('_' + _ename.toLowerCase() + 'Uid');
                obj.href = _os + ".ShowDetail('" + obj._toUid + "');";
            }
            arr = null;
        }

        if (all || cmds.indexOf('[unbind]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Unbind', 'a');
            var _uid; var _euid; var _etype;
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                if (obj.getAttribute('_' + _ename.toLowerCase() + 'Uid') != null) {
                    obj._uid = "'" + obj.getAttribute('_' + _ename.toLowerCase() + 'Uid') + "'";
                }
                obj._entityUid = obj.getAttribute('_entityUid');
                obj._entityType = obj.getAttribute('_entityType');
                if (obj._uid != '' && obj._uid != null) { _uid = obj._uid } else { _uid = "iObject[\'" + this.uid + "\'].get_selectedUids()" };
                if (obj._entityUid != '' && obj._entityUid != null) { _euid = obj._entityUid } else { _euid = this.get_bindToUid() };
                if (obj._entityType != '' && obj._entityType != null) { _etype = obj._entityType } else { _etype = this._bindToEntity };
                obj.href = _os + ".Unbind(" + _uid + ",'" + _euid + "','" + _etype + "');";
                //obj.href = _os + ".Unbind(iObject[\'" + this.uid + "\'].get_selectedUids(),'" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
            }
            arr = null;
        }

        if (all || cmds.indexOf('[unbindall]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.UnbindAll', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.href = _os + ".UnbindAll('" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
            }
            arr = null;
        }
        if (all || cmds.indexOf('[switch]', 0) >= 0
	    && this._enabled_switch) {
            var arr = getElementsByKey(element, _ename + '.Switch', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                this.CreateSwitchCommand(obj);
            }
            arr = null;
        }
        if (all || cmds.indexOf('[delete]', 0) >= 0
	    && this._enabled_deleteCommand) {
            var arr = getElementsByKey(element, _ename + '.DeleteByUid', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj = this._internal_CallUidsFunction(obj, _ename, 'Delete');
            }
            arr = null;
        }
        if (all || cmds.indexOf('[filter]', 0) >= 0
		&& this._enabled_filter) {
            var arr = getElementsByKey(element, _ename + '.Filter', 'input');
            for (var i = 0; i < arr.length; i++) {
                var obj = arr[i];
                obj.setAttribute('_listuid', this.uid); //setto per recuperare il nome dell'oggetto bindato
                rqval = Request.QueryString(obj.getAttribute("_filterName")).Item(1);
                if (rqval != null) { obj.value = rqval }
                if (obj.onchangeHandlers == null) {
                    obj.onchangeHandlers = new Object;
                    obj.onchangeHandlers.uids = new Array();
                    obj.onchangeHandlers.count = 0;
                }
                if (obj.onchangeHandlers[this.uid] == null) { obj.onchangeHandlers.count += 1 }
                obj.onchangeHandlers.uids[obj.onchangeHandlers.count] = this.uid;

                if (obj.onchange == null) {
                    /*ADD 27/04/2009 */
                    obj.onkeypress = function(e) {
                        var keynum;
                        if (window.event) // IE
                        { keynum = window.event.keyCode; }
                        else if (e.which) // Netscape/Firefox/Opera
                        { keynum = e.which; };
                        if (keynum == 13) {
                            window.focus();
                            obj.blur();
                            obj.onchange();
                            return false;
                        }
                        return keynum;
                    };
                    /**/
                    obj.onchange = function() {
                        for (var i = 1; i <= obj.onchangeHandlers.count; i++) {
                            iObject[obj.onchangeHandlers.uids[i]].Refresh(0);
                        }
                    }
                }
            }
            var arr2 = getElementsByKey(element, _ename + '.Filter', 'select');
            for (var i = 0; i < arr2.length; i++) {
                var obj = arr2[i];
                rqval = Request.QueryString(obj.getAttribute("_filterName")).Item(1);
                if (rqval != null) { obj.value = rqval.toLowerCase() }
                obj.setAttribute('_listuid', this.uid); //setto per recuperare il nome dell'oggetto bindato
                if (obj.onchangeHandlers == null) {
                    obj.onchangeHandlers = new Object;
                    obj.onchangeHandlers.uids = new Array();
                    obj.onchangeHandlers.count = 0;
                }
                if (obj.onchangeHandlers[this.uid] == null) { obj.onchangeHandlers.count += 1 }
                obj.onchangeHandlers.uids[obj.onchangeHandlers.count] = this.uid;

                if (obj.onchange == null) {
                    obj.onchange = function() {
                        for (var i = 1; i <= obj.onchangeHandlers.count; i++) {
                            iObject[obj.onchangeHandlers.uids[i]].Refresh(0);
                        }
                    }
                }
            }
            this._filters = arr.concat(arr2);
            arr = null;
        }
        if (this._enabled_insert) {
            if (all || cmds.indexOf('[insertinput]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.InsertInput', '*');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                }
                this._insert_fields = arr;
                arr = null;
            }
            if (all || cmds.indexOf('[insert]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.Insert', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".Insert();";
                }
                arr = null;
            }
            if (all || cmds.indexOf('[showinsert]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.ShowInsert', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".ShowInsert();";
                }
                arr = null;
            }
            if (all || cmds.indexOf('[hideinsert]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.HideInsert', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".HideInsert();";
                }
                arr = null;
            }
        }

        if (this._enabled_update) {
            if (all || cmds.indexOf('[updateinput]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.UpdateInput', '*');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                }
                this._update_fields = arr;
                arr = null;
            }
            if (all || cmds.indexOf('[update]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.Update', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".Update();";
                }
                arr = null;
            }

            if (all || cmds.indexOf('[showupdate]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.ShowUpdate', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".ShowUpdate();";
                }
                arr = null;
            }
            if (all || cmds.indexOf('[hideupdate]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.HideUpdate', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".HideUpdate();";
                }
                arr = null;
            }
        }

        if (this._enabled_updateBulk) {
            if (all || cmds.indexOf('[updatebulkinput]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.UpdateBulkInput', '*');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                }
                this._updateBulk_fields = arr;
                arr = null;
            }
            if (all || cmds.indexOf('[updatebulk]', 0) >= 0) {
                var arr = getElementsByKey(element, _ename + '.UpdateBulk', 'a');
                for (var i = 0; i < arr.length; i++) {
                    obj = arr[i];
                    obj.href = _os + ".UpdateBulk();";
                }
                arr = null;
            }
        }

        if (all || cmds.indexOf('[hidepanel]', 0) >= 0) {
            var 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;
        }
    },
    _internal_CallUidsFunction: function(obj, entity, _command) {
        var _os = 'iObject[\'' + this.uid + '\']';
        obj._toUid = obj.getAttribute('_' + entity.toLowerCase() + 'Uid');
        if (obj._toUid == null) {
            obj.setAttribute('href', 'javascript:' + _os + '.' + _command + '(' + _os + '.get_selectedUids());');
        } else {
            obj.setAttribute('href', 'javascript:' + _os + '.' + _command + '(\'' + obj._toUid + '\');');
        }
        return obj;
    },
    hidePanel: function() {
        hidePopUp(this._detailContainer.id);
        //	if(this._insertContainer != null){hidePopUp(this._insertContainer.id)}
        //	if(this._updateContainer != null){hidePopUp(this._updateContainer.id)}
    },

    View: function(xslt) {
        this._currentView = xslt;
        var index = 0;
        if (this._enabled_paging) { index = this._elementIndex.value }
        this.Refresh(index);
    },
    Bind: function(uid, _toBindUid, _toBindName) {
        //* Deve essere importato il Web service dell'entitàCorre
        if (confirm('Confermare l\'associazione?') == true) {
            if (this._enabled_bind_withparam) {
                /*se non specifico che ws usare prende il predefinito.*/
                if (this._bind_webservice == null) { this._bind_webservice = iWS[this.uid]; }
                /*uso per ora solo il display container per cercare i parametri*/
                json = this.default_bindFilterFunction(this._displayContainer, uid);
                if (json == -1) { return }
                json = '[' + json + ']';
                this._bind_webservice.BindJson(json
		            , _toBindUid
		            , _toBindName
		            , this.onSuccessBind, this.onFailedCallback, { "uid": this.uid, "index": this._elementIndex.value });
            } else {
                iWS[this.uid].Bind(uid
		            , _toBindUid
		            , _toBindName
		            , this.onSuccessBind, this.onFailedCallback, { "uid": this.uid, "index": this._elementIndex.value });

            }
        }

    },
    BindAll: function(_toBindUid, _toBindName) {
        //* Deve essere importato il Web service dell'entitàCorre
        if (confirm('Confermare l\'associazione?') == true) {
            if (this._enabled_bind_withparam) {
                var _split = this.get_selectedUids().split(',');
                if (_split == null) { return };
                var json = '';
                for (var i = 0; i < _split.length; i++) {
                    if (_split[i] != '' && _split[i] != null) {
                        _tmp = this.default_bindFilterFunction(this._displayContainer, _split[i]);
                        if (_tmp != -1) {
                            json += _tmp + ',';
                        }
                    }
                }
                json = '[' + json.substring(0, json.length - 1) + ']'
                if (this._bind_webservice == null) { this._bind_webservice = iWS[this.uid]; }
                this._bind_webservice.BindJson(json
		            , _toBindUid
		            , _toBindName
		            , this.onSuccessBind, this.onFailedCallback, { "uid": this.uid, "index": this._elementIndex.value });
            } else {
                iWS[this.uid].Bind(this.get_selectedUids()
		            , _toBindUid
		            , _toBindName
		            , this.onSuccessBind, this.onFailedCallback, { "uid": this.uid, "index": this._elementIndex.value });

            }

        }
    },
    BindJson: function(_jsonString, _toBindUid, _toBindName) {
        //* Deve essere importato il Web service dell'entitàCorre
        if (confirm('Confermare l\'associazione?') == true) {
            iWS[this.uid].BindJson(_jsonString
		, _toBindUid
		, _toBindName
		, this.onSuccessBind, this.onFailedCallback, { "uid": this.uid, "index": this._elementIndex.value });
        }
    },
    UnbindAll: function(_toBindUid, _toBindName) {
        //* Deve essere importato il Web service dell'entitàCorre
        if (confirm('Confermare la rimozione dell\'associazione?') == true) {
            iWS[this.uid].Unbind(this.get_selectedUids()
		, _toBindUid
		, _toBindName
		, this.onSuccessUnbind, this.onFailedCallback, this.uid);
        }
    },
    Unbind: function(uid, _toUnbindUid, _toUnbindName) {
        if (confirm('Confermare la rimozione dell\'associazione?') == true) {
            this.progress_show();
            iWS[this.uid].Unbind(uid
		, _toUnbindUid
		, _toUnbindName
		, this.onSuccessUnbind, this.onFailedCallback, this.uid);
        }
    },
    CreateSwitchCommand: function(obj) {
        //crea il link perswitchare la proprietà nel caso ci siano valori particoali si comporta diversamente
        // ad esempio se il comando è per uno switch di proprietà verra chiamato un altro metodo
        var _os = 'javascript:iObject[\'' + this.uid + '\']';
        obj._commandKey = obj.getAttribute('_commandKey');
        obj._value = obj.getAttribute('_value');
        obj._toUid = obj.getAttribute('_' + _ename.toLowerCase() + 'Uid');
        if (obj._commandKey == null) { alert('_commandKey non indicato per il comando Switch dell\'entità \'' + _ename + '\''); }
        switch (obj._commandKey.toLowerCase()) {
            case 'property':  //lo switch per l'attivazione di una proprietà dell'entità
                obj._entityUid = obj.getAttribute('_entityUid');
                obj._propEntityType = obj.getAttribute('_propEntityType');
                obj._cdDefinition = obj.getAttribute('_cdDefinition');
                obj.href = _os + ".SwitchProperty('" + obj._entityUid.toLowerCase() + "','" + obj._propEntityType + "','" + obj._cdDefinition + "');";
                break;
            default:
                obj.href = _os + ".Switch('" + obj._toUid + "','" + obj._commandKey + "','" + obj._value + "');";
        }
        if (this._onSwitchFunction != null) { this._onSwitchFunction(obj) }
    },
    SwitchProperty: function(uid, propertyEntityType, cdDefinition, currentvalue) {
        //caso particolare ed unico di switch per il quale cmabio valore ad una proprietà
        if ((uid == 'null' || uid == null || uid == '')
		    || (cdDefinition == 'null' || cdDefinition == null || cdDefinition == '')) { throw "valori uid non completi o non validi" }

        //this.progress_show();
        iWS[this.uid].SwitchProperty(uid, cdDefinition, propertyEntityType, this.onSuccessSwitchProperty, this.onFailedCallback, this.uid);

    },
    Switch: function(uids, commandKey, currentvalue) {
        //esegue ilc omando switch, a seconda del comando chiama funzioni differenti
        if (uids == 'null' || uids == null || uids == '') { uids = this.get_selectedUids() }
        if (commandKey == 'EnableDisable') {
            if (currentvalue == 'true') {
                this.Disable(uids);
            } else {
                this.Enable(uids);
            }
        }
    },

    /*  INSERT */
    ShowInsert: function() {
        if (this._insertContainer != null) {
            this._insertContainer.style.display = 'block';
        }
        this.initializeCommand(this._insertContainer, '[insert][hideinsert]');
        showPopUp(this._insertContainer.id);
    },
    HideInsert: function() {
        if (this._insertContainer != null) {
            hidePopUp(this._insertContainer.id);
        }

    },
    Insert: function() {
        if (!this._enabled_insert) { return }

        if (this._insertFunction != null) {
            json = this._insertFunction(this._insert_fields);
        }
        if (json == '') { alert('Stringa di inserimento non valida') }
        this.progress_show();
        iWS[this.uid].Insert(json, '{}', '{}', this.onSuccessInsert, this.onFailedCallback, this.uid);
    },
    onSuccessInsert: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        obj.HideInsert();
        obj.Refresh();
    },

    /*  UPDATE */
    ShowUpdate: function() {
        if (this._updateContainer != null) {
            this._updateContainer.style.display = 'block';
        }
        this.initializeCommand(this._updateContainer, '[update][hidepanel]');
        showPopUp(this._updateContainer.id);
    },
    HideUpdate: function() {
        if (this._updateContainer != null) {
            hidePopUp(this._updateContainer.id);
        }
    },
    Update: function() {
        if (!this._enabled_update) { return }
        if (this._updateFunction != null) {
            json = this._updateFunction(this._update_fields);
        }
        if (json == '') { alert('Stringa di inserimento non valida') }
        this.progress_show();
        iWS[this.uid].Update(json, '{}', '{}', this.onSuccessUpdate, this.onFailedCallback, this.uid);
    },
    onSuccessUpdate: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        obj.HideUpdate();
        obj.Refresh();
    },
    /* UPDATE BULK */
    UpdateBulk: function() {
        if (!this._enabled_updateBulk) { return }
        uids = this.get_selectedUids();
        if (this._updateBulkFunction != null) {
            json = this._updateBulkFunction(this._updateBulk_fields);
        }
        if (json == '') { alert('Stringa di inserimento non valida') }
        var cp = this.getClientParameter('updatebulk');
        this.progress_show();
        iWS[this.uid].UpdateBulk(uids, json, cp, this.onSuccessUpdateBulk, this.onFailedCallback, this.uid);
    },

    onSuccessUpdateBulk: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        obj.Refresh();
    },

    Enable: function(uids) {
        this.progress_show();
        iWS[this.uid].Enable(uids, this.onSuccessEnable, this.onFailedCallback, this.uid);
    },
    Disable: function(uids) {
        this.progress_show();
        iWS[this.uid].Disable(uids, this.onSuccessDisable, this.onFailedCallback, this.uid);
    },
    onSuccessBind: function(result, context) {
        obj = iObject[context.uid];
        obj.progress_hide();
        if (obj._onBind != null) {
            obj._onBind();
        } else {
            obj.Refresh(context.index);
        }
    },
    onSuccessUnbind: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        if (obj._onBind != null) {
            obj._onBind();
        } else {
            obj.Refresh(context.index);
        }
    },
    onSuccessSwitchProperty: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        SwitchTrueFalse('img_' + result.toUpperCase(), null);
    },
    onSuccessDetail: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();

        showPopUp(obj._detailContainer.id);
        obj._detailContainer_display.innerHTML = result;

        obj.initializeCommand(obj._detailContainer, '[bind][unbind][hidepanel]');
    },
    onSuccessEnable: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        obj._onSwitchChange(obj, result, true);
    },
    onSuccessDisable: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        obj._onSwitchChange(obj, result, false);
    },
    _onSwitchChange: function(iObject, uidsToApply, newvalue) {
        obj = iObject;
        var _os = 'javascript:iObject[\'' + obj.uid + '\']';
        var arr = getElementsByKey(obj._displayContainer, obj._entityName + '.Switch', 'a');
        for (var i = 0; i < arr.length; i++) {
            var xx = arr[i];
            //se l'uid è contenuto nel risultato allora setto abilitato il valore
            var name = obj._entityName.toLowerCase();
            var attr = xx.getAttribute('_' + name + 'Uid');
            if (uidsToApply.indexOf(attr) >= 0) {
                xx.setAttribute('_value', newvalue);
                xx.href = _os + ".Switch('" + xx._toUid + "','" + xx._commandKey + "','" + newvalue + "');";
                //cambio l'immagine
                SwitchTrueFalse('img_' + xx._toUid.toUpperCase(), newvalue);
            }
        }
    },
    Delete: function(uids) {
        if (uids != null && uids != '') {
            this.progress_show();
            iWS[this.uid].DeleteByUid(uids, this.onSuccessDelete, null, this.uid);
        };
    },
    onSuccessDelete: function(result, context) {
        obj = iObject[context];
        obj.progress_hide();
        obj.clear_selectedUids();
        obj.Refresh(obj._elementIndex.value);

    },
    ShowDetail: function(uid) {
        filter = '{';
        filter += this._customFilter;
        if (uid != null && uid != '') {
            filter += '"' + this._entityName + 'Uid":"' + uid + '"';
        }
        filter += '}';


        clientJsonString = this.getClientParameter('detail');
        this.progress_show();

        //chiamo il Ws
        iWS[this.uid].GetXmlXslt(
		filter, clientJsonString
		, this.onSuccessDetail, this.onFailedCallback, this.uid);
    },

    /* REFRESH */
    Refresh: function() {
        if (this._enabled_paging) { idx = this._elementIndex.value; }
        if (idx == null) { idx = 0 }
        this.Refresh(idx);
    },
    Refresh: function(rowIndex) {
        if (isNaN(rowIndex)) { rowIndex = 0 }
        filter = '';
        if (this._enabled_filter) {
            if (this._filterFunction == null) { this._filterFunction = this.default_filterFunction };
            filter = this._filterFunction(this._filters, rowIndex);
        }
        //aggiorno l'indice con il valore richiesto
        if (this._enabled_paging) {
            this._elementIndex.value = rowIndex;
        }
        this.progress_show();

        var clientJsonString = this.getClientParameter('refresh');
        //chiamo il Ws o la funzione specifica
        if (this._getxml_webservice_functionname != null) {
            this._getxml_webservice_functionname(
		        filter, clientJsonString
		        , this.onSuccess, this.onFailedCallback, this.uid);
        } else {
            iWS[this.uid].GetXmlXslt(
		        filter, clientJsonString
		        , this.onSuccess, this.onFailedCallback, this.uid);
        }

    },
    default_bindFilterFunction: function(element, uid) {
        //associo i parametri addizionali per il bind se attivo nell'opzione
        var _bind_fields = null;
        if (this._enabled_bind_withparam) {
            var arr = getElementsByKey(element, _ename + '.BindInput_' + uid, '*');
            var arr2 = getElementsByKey(this._filterContainer, _ename + '.BindInput', '*');
            _bind_fields = arr.concat(arr2);
            arr = null;
        }
        var value; var toAdd;
        var _json = '{';
        //        _json += '"' + this._bindToEntity + 'Uid":"' + this._bindToUid + '",';
        //        _json += '"' + this._entityName + 'Uid":"' + uid + '",';
        if (_bind_fields != null) {
            for (var i = 0; i < _bind_fields.length; i++) {
                obj = _bind_fields[i];
                switch (obj.nodeName.toLowerCase()) {
                    case 'input':
                        switch (obj.type) {
                            case 'checkbox':
                                value = obj.checked;
                                break;
                            default:
                                value = (obj.value == '') ? null : obj.value;
                                break;
                        }
                        break;
                    case 'select':
                        value = (obj.value == '') ? null : obj.value;
                        break;
                }
                /*validazione*/
                if (!validateField(value, obj)) {
                    return -1
                }
                value = (value == '') ? null : obj.value;
                if (value != null) { _json = _json + '"' + obj.getAttribute('_bindToProperty') + '":"' + value + '",'; }
            };
            _json = _json.substring(0, _json.length - 1) + '}';
        }
        return _json;
    },
    default_filterFunction: function(_filters, rowIndex, isxport) {
        var value; var toAdd;
        var _json = '{';
        for (var i = 0; i < _filters.length; i++) {
            obj = _filters[i];
            value = (obj.value == '') ? null : obj.value;
            _name = null;
            if (obj.getAttribute('_filterName') != undefined) { _name = obj.getAttribute('_filterName') }
            if (obj.getAttribute('_filtername') != undefined) { _name = obj.getAttribute('_filtername') }
            if (value != null) { _json = _json + '"' + _name + '":"' + value + '",'; }
        };
        if (isexport == null || isexport == false) { _json = _json + '"MaxRowsNumber":"' + (this._maxRowsNumber == null ? 20 : this._maxRowsNumber) + '",'; };
        _json = _json + '"StartIndexRow":"' + ((rowIndex == null) ? 0 : rowIndex) + '",';
        _json = _json.substring(0, _json.length - 1) + '}';
        return _json;
    },
    Export: function(xslt, contenttype, extension) {

        filter = '';
        this._exportXslt = xslt;
        if (this._enabled_filter) {
            filter = this._filterFunction(this._filters, 0, true);
        }
        var clientJsonString = this.getClientParameter('export');
        //        alert('pre:' + filter);
        //        alert('post:' + URLEncode(filter));

        window.open(this._entityName + '.action?cmd=export&clientparameter=' + URLEncode(clientJsonString) + '&filter=' + URLEncode(filter) + '&contenttype=' + contenttype + '&extension=' + extension, '_blank');

    },
    onSuccess: function(result, context) {
        var obj;
        obj = iObject[context];
        obj.progress_hide();
        obj._displayContainer.innerHTML = result;
        obj.initializeCommand(obj._displayContainer, '[switch][bind][detail][bindjson][unbind]');
        if (obj.clear_selectedUids != null) { obj.clear_selectedUids() };
        if (obj._onListRefreshed != null) { obj._onListRefreshed(context) };
    },
    onFailedCallback: function(result, context) {
        var obj;
        obj = iObject[context];
        obj.progress_hide();
        alert(result.get_message());
    },
    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;
    },
    getClientParameter: function(_command) {
        querystring = '';
        if (this._enabled_queryString) {
            querystring = '"QueryString":[';
            for (var i = 1; i <= Request.QueryString.Count(); ++i) {
                querystring += '{"First":"' + Request.QueryString.Key(i) + '","Second":"' + Request.QueryString.Item(i) + '"}';
                if (i < Request.QueryString.Count) { querystring += ',' }
            }
            if (querystring != '' && this._xsltParameter.count > 0) { querystring += ',' }
            for (var i = 0; i < this._xsltParameter.count; ++i) {
                querystring += '{"First":"' + this._xsltParameter[i].key + '","Second":"' + this._xsltParameter[i].value + '"}';
                if (i < this._xsltParameter.count - 1) { querystring += ',' }
            }
            querystring += ']';
        }
        var _ex_enabled_paging = this._enabled_paging;
        var _ex_enabled_info = this._enabled_info;
        var _ex_enabled_rawdata = this._enabled_rawData;

        xslt_style_toUse = this._xsltType;
        switch (_command) {
            case 'detail':
                xslt_style_toUse = 'Xslt_Detail';
                xslt = '"XsltFileCustom":"' + ((this._xsltFileCustom_detail == null) ? '' : this._xsltFileCustom_detail) + '",';
                break;
            case 'updatebulk':
                break;
            case 'export':
                this._enabled_paging = false;
                this._enabled_info = false;
                this._enabled_rawData = false;
                xslt = '"XsltFileCustom":"' + this._exportXslt + '",';
                break;
            default:
                if (this._currentView == null || this._currentView == '') {
                    xslt = '"XsltFileCustom":"' + ((this._xsltFileCustom == null) ? '' : this._xsltFileCustom) + '",';
                } else {
                    xslt = '"XsltFileCustom":"' + this._currentView + '",';
                }
        };
        var options = 0
		    + (this._enabled_paging ? XSLT_ENABLEPAGING : 0)
		    + (this._enabled_rawData ? XSLT_SHOWRAWDATA : 0)
		    + (this._enabled_info ? XSLT_SHOWINFO : 0)
		    + (this._enabled_queryString ? XSLT_SHOWQUERYSTRINGINXSLTPARAM : 0)
		    + (this._enabled_permission ? ((this._permission_entities = '*') ? XSLT_ALLPERMISSION : XSLT_ENTITYPERMISSION) : 0);

        clientJsonString =
	  '{"ClientId":"' + this.uid + '",'
	+ '"XsltType":"' + xslt_style_toUse + '",'
	+ xslt
	+ '"Options":"' + options + '",'
	+ querystring
	+ '}';

        this._enabled_paging = _ex_enabled_paging;
        this._enabled_rawData = _ex_enabled_rawdata;
        this._enabled_info = _ex_enabled_info;
        return clientJsonString
    },
    progress_show: function() {
        if (this._progressElement != null) { this._progressElement.style.display = 'block'; }
    },
    progress_hide: function() {
        if (this._progressElement != null) { this._progressElement.style.display = 'none'; }
    }

};

function URLEncode(clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString[x] == ' ')
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}
//Ribo.Cms.JS.EntityUI.registerClass('Ribo.Cms.JS.EntityUI', Sys.UI.Component);
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

