// Register the namespace for the control.

Type.registerNamespace('Ribo.Cms.JS');
Ribo.Cms.JS.EntitySelector = function(entityName) {
    Ribo.Cms.JS.EntitySelector._initializeBase(this, entityName);
};
Ribo.Cms.JS.EntitySelector._initializeBase = function(obj, entityName) {
    obj._popUpContainer = null; //div contenente l'insieme per il popup
    obj._entityName = entityName;
    obj._popUp_displayContainer = null; //risultati del popup(lista)
    obj._current_displayContainer = null; //div contenente gli altri componenti (commands e display)
    obj._currentElementDisplay = null; //div contenente il risultato per la visione del dettaglio
    obj._extendPanel = null; //div panel aggiuntivo vario

    obj._xsltType = 'Xslt_List';
    obj._xsltFileCustom_detail = null;
    obj._xsltFileCustom_popUp = null;

    obj._filterFunction = null;
    obj._filterContainer = null;
    obj._bindToEntity = null;
    obj._bindToUid = null;
    obj._currentUid = null;

    obj._enabled_bind = true;
    obj._enabled_paging = true;
    obj._enabled_filter = true;
    obj._enabled_extendPanel = true;
    obj._enabled_showCurrent = true;
    obj._enabled_queryString = false;

    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._enabled_rawData = SHOWRAWDATA == null ? true : SHOWRAWDATA;
    obj._enabled_info = SHOWINFO == null ? true : SHOWINFO;

    obj.uid = entityName + '_' + iWS.count;


    obj._onCommandSuccessReturn = null; //funzione che viene lanciata al successo dei comandi

};
Ribo.Cms.JS.EntitySelector.prototype = {
    _checkSettings: function() {
        version = '[EntitySelector: ' + this.uid + ' for ' + this._entityName + ']';
        if (this._entityName == null) { alert('Non è stata valorizzata la proprietà this._entityName.' + version); return false }
        //	if(this._current_displayContainer==null){alert('Non è stata valorizzata la proprietà this._current_displayContainer.' + version);return false} 

        if (this._enabled_bind) {
            if (this._bindToEntity == null) {
                alert('Non è stata valorizzata la proprietà this._bindToEntity.' + version); return false
            }
        }
        if (this._enabled_filter) {
            if (this._filterFunction == null) {
                alert('Non è stata valorizzata la proprietà this._filterFunction.' + version); return false
            }
        }
        return true;
    },
    initialize: function(WebService, Object) {

        if (this._checkSettings() == false) { return false };
        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;
        //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 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');
            cc.style.width = '450px';
            lc.appendChild(document.createTextNode(''));

            pp.appendChild(lc.cloneNode(1));
            //il conetnitore del filtro verrà spostato all'interno del popup
            if (this._enabled_filter && this._filterContainer != null) {
                pp.appendChild(this._filterContainer);
            }
            pp.appendChild(cc);
            //il conetnitore dei comandi verranno spostati alla fine della lisa
            //		if(this._popUp_commandContainer != null){
            //			pp.appendChild(this._popUp_commandContainer);		
            //		}
            pp.appendChild(lc.cloneNode(1));
            if (this._extendPanel && this._extendPanel != null) {
                pp.appendChild(this._extendPanel);
            }

            document.body.appendChild(bg);
            document.body.appendChild(pp);
            this._popUpContainer = pp;

        }


        //recupero deove disegnare la lista all'interno del popUpContainer
        if (this._popUp_displayContainer == null) {
            var arr2 = getElementsByKey(this._popUpContainer, _ename + '.PopUpDisplay', 'div');
            if (arr2 != null) {
                this._popUp_displayContainer = arr2[0];
            }
        }

        //recupero deove disegnare il dettaglio all'interno del	_current_displayContainer
        if (this._enabled_showCurrent) {
            if (this._currentElementDisplay == null) {
                var arr1 = getElementsByKey(this._current_displayContainer, _ename + '.CurrentDisplay', 'div');
                if (arr1 != null) {
                    this._currentElementDisplay = arr1[0];
                }
            }
        }

        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._popUpContainer.appendChild(this._elementIndex);
        }

        /*inizializo i comandi base se ho visibile quello corrente*/
        if (this._current_displayContainer != null) {
            this.initializeCommand(this._current_displayContainer, '[unbind][showpanel][cancel]');
        }
        this.initializeCommand(this._popUpContainer, '[hidepanel]');

        if (this._enabled_filter) {
            if (this._filterContainer != null) {
                this.initializeCommand(this._filterContainer, '[filter]');
            }
        }

    },
    get_originalUid: function() { return this._current_displayContainer.getAttribute('_originalUid'); },
    set_originalUid: function(value) {
        if (this._current_displayContainer.getAttribute('_originaluid') == null) {
            this._current_displayContainer.setAttribute('_originaluid', value);
        };
    },
    get_currentUid: function() {
        var r = this._current_displayContainer.getAttribute('_entityuid');
        if (r == null || r == '') { r = '00000000-0000-0000-0000-000000000000' }
        return r
    },
    set_currentUid: function(value) { this._current_displayContainer.setAttribute('_entityuid', (value == null ? '00000000-0000-0000-0000-000000000000' : value)) },
    get_bindToUid: function() { if (this._bindToUid == null) { this._bindToUid = obj.getAttribute('_bindtouid'); } return this._bindToUid },
    hidePanel: function() {
        hidePopUp(this._popUpContainer.id);
    },
    showPanel: function(_bindToUid, sourceElement) {

        //se passo un valore al quale associare succesivamente l'elemento che verrà selezionato cambio, il BindToEntity con quello che gli passo
        //altrimenti rimane invariato e cioè settato in inizializzazione della classe (di solito preso dal parametro query)
        if (_bindToUid != null && _bindToUid != '') {
            this._bindToUid = _bindToUid;
        }
        showPopUp(this._popUpContainer.id);
        this.Refresh(0, sourceElement);

    },
    Bind: function(uids, _toBindUid, _toBindName) {
        if (uids == '00000000-0000-0000-0000-000000000000') {
            this.Unbind(uids, _toBindUid, _toBindName);
            return;
        }
        iWS[this.uid].Bind(uids				//ed imageUid
		, _toBindUid
		, _toBindName
		, this.onSuccessBind, this.onFailedCallback, this.uid);

    },
    Unbind: function(uid, _toUnbindUid, _toUnbindName) {

        iWS[this.uid].Unbind(uid
		, _toUnbindUid
		, _toUnbindName
		, this.onSuccessUnbind, this.onFailedCallback, this.uid);
    },
    onSuccessBind: function(result, context) {

        iObj = iObject[context];
        iObj.hidePanel();
        iObj.set_currentUid(result);
        if (iObj._enabled_showCurrent) {
            iObj.showEntity(result);
        }
        if (iObj._onCommandSuccessReturn != null) { iObj._onCommandSuccessReturn(context); }

    },
    onSuccessUnbind: function(result, context) {

        iObj = iObject[context];
        iObj.hidePanel();
        iObj.set_currentUid('00000000-0000-0000-0000-000000000000');
        if (iObj._enabled_showCurrent) {
            iObj.showEntity(null);
        }
        if (iObj._onCommandSuccessReturn != null) { iObj._onCommandSuccessReturn(context); }
    },
    initializeCommand: function(element, cmds) {
        var all = (cmds == '*');
        _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', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._toUid = obj.getAttribute('_' + _ename.toLowerCase() + 'Uid');
                obj.href = "javascript:iObject[\'" + this.uid + "\'].Bind('" + obj._toUid + "','" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
            }
            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++) {
                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 }
                obj.onchange = function() { iObject[this.getAttribute("_listuid")].Refresh(0); };
            }
            var arr2 = getElementsByKey(element, _ename + '.Filter', 'select');
            for (var i = 0; i < arr2.length; i++) {
                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
                obj.onchange = function() { iObject[this.getAttribute("_listuid")].Refresh(0); };
            }
            this._filters = arr.concat(arr2);
            arr = null;
            arr2 = null;
        }

        if (all || cmds.indexOf('[unbind]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Unbind', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.href = "javascript:iObject[\'" + this.uid + "\'].Unbind(iObject[\'" + this.uid + "\'].get_currentUid(),'" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
            }
            arr = null;
        }

        if (all || cmds.indexOf('[cancel]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Cancel', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj.href = "javascript:iObject[\'" + this.uid + "\'].Bind(iObject[\'" + this.uid + "\'].get_originalUid(),'" + this.get_bindToUid() + "','" + this._bindToEntity + "');";
            }
            arr = null;
        }

        if (all || cmds.indexOf('[showpanel]', 0) >= 0) {
            var 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._bindToUid = this._bindToUid == null ? obj.getAttribute('_bindToUid') : this._bindToUid; //se ho definito il _bindToUid uso quello altrimenti lo recupero dal controllo associato
                obj.href = 'javascript:iObject[\'' + this.uid + '\'].showPanel(\'' + obj._bindToUid + '\',$get(\'' + obj.id + '\'));';
            }
            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;
        }

        if (this.initializeCommand_extender != null) { this.initializeCommand_extender(element, cmds); }

    },
    getFilter: function(_filterName) {
        if (this._filters == null) { return null }
        for (var i = 0; i < this._filters.length; i++) {
            if (this._filters[i].getAttribute("_filterName") == _filterName) { return this._filters[i].value }
        }

    },
    showEntity: function(_currentUid) {
        //* se non specifico l'uid recupero quello degli attributi, altrimenti utilizzo quello corrente e lo setto nell'attributo.
        if (_currentUid == null || _currentUid == '') {
            _currentUid = this.get_currentUid();
        }
        this.set_currentUid(_currentUid);
        this.set_originalUid(_currentUid);
        clientJsonString = this.getClientParameter('detail');

        iWS[this.uid].GetByUidXslt(_currentUid, clientJsonString,
		  this.onSuccessShowEntity, this.onFailedCallback, this.uid);

    },
    onSuccessShowEntity: function(result, context) {
        iobj = iObject[context];
        iobj._currentElementDisplay.innerHTML = result;

    },
    /*aggiorna la lista di selezione*/
    Refresh: function(rowIndex, sourceElement) {
        filter = '';
        if (this._enabled_filter) {
            filter = this._filterFunction(this._filters, rowIndex, sourceElement);
        }
        this._elementIndex.value = rowIndex; //aggiorno l'indice con il valore richiesto
        if (this._progressElement != null) { this._progressElement.style.display = 'block'; } //visualizzo il progress

        //paramtri del client 
        clientJsonString = this.getClientParameter('popUp');

        //chiamo il Ws
        iWS[this.uid].GetXmlXslt(
		filter, clientJsonString
		, this.onSuccessShowPanel, this.onFailedCallback, this.uid);
    },
    onSuccessShowPanel: function(result, context) {
        iobj = iObject[context];
        iobj._popUp_displayContainer.innerHTML = result;
        iobj.initializeCommand(iobj._popUp_displayContainer, '[bind][unbind][hidepanel]');
        //	if(iobj._popUp_commandContainer!=null){
        //		iobj.initializeCommand(iobj._popUp_commandContainer,'[bind][unbind][hidepanel]')
        //	}

    },
    getClientParameter: function(_command) {
        //aggiungo le opzioni
        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 += ',' }
            }
            querystring += ']';
        }

        var options = 0
		+ (this._enabled_paging ? XSLT_ENABLEPAGING : 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) {
            case 'detail':
                xslt = '"XsltFileCustom":"' + ((this._xsltFileCustom_detail == null) ? '' : this._xsltFileCustom_detail) + '",';
                break;
            default:
                xslt = '"XsltFileCustom":"' + ((this._xsltFileCustom_popUp == null) ? '' : this._xsltFileCustom_popUp) + '",';
        }
        clientJsonString =
			  '{"ClientId":"' + this.uid + '",'
			+ '"XsltType":"' + this._xsltType + '",'
			+ xslt
			+ '"Options":"' + options + '",'
			+ querystring
			+ '}';

        return clientJsonString
    },
    onFailedCallback: function(result, context) {
        alert(result.get_message());
    }

};
//Ribo.Cms.JS.EntitySelector.registerClass('Ribo.Cms.JS.EntitySelector', Sys.UI.Control);
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

