// Necessità del Web Service ~/WS/NewsWS.asmx
// Register the namespace for the control.
Type.registerNamespace('Ribo.Cms.JS');
Ribo.Cms.JS.WorkflowUI = function(workflowName) {
    Ribo.Cms.JS.WorkflowUI._initializeBase(this, workflowName);
};
Ribo.Cms.JS.WorkflowUI._initializeBase = function(obj, workflowName) {
    obj._displayContainer = null;
    obj._filterContainer = null;
    obj._startContainer = null;

    //obj._commandContainer = null;
    obj._workflowId = null;
    obj._workflowName = workflowName;
    obj._workflowStepName = null;

    obj._validateClient = null;
    obj._stepChanged = null;


    obj._parameters = null;
    obj._options = null;
    obj._progressElement = null;
    obj._showStartPage = true;

    obj._commandsElement = new Array();
    obj._commandsElement.length = 0;

    obj._enabled_showRawData = false;
    obj._enabled_progress = true;
    obj._enabled_hideDisplayContainerOnProgress = false;
    obj._validateClient = null;
    obj._validateExtended = null;
    obj._onSuccessWorkflowExtender = null;
    obj._onFailedWorkflowExtender = null;
    obj.uid = workflowName + '_' + iWS.count;
};
Ribo.Cms.JS.WorkflowUI.prototype = {
    _checkSettings: function() {
        if (this._workflowName == null) { alert('Non è stata valorizzata la proprietà this._workflowName'); return false }
        if (this._displayContainer == null) { alert('Non è stata valorizzata la proprietà this._displayContainer'); return false }
        if (this._startContainer == null) { alert('Non è stata valorizzata la proprietà this._startContainer'); return false }
        if (this._enabled_progress) {
            if (this._progressElement == null) { alert('Non è stato specificato il contenitore del progress (this._progressElement)'); return false }
        }

        return true;

    },
    initialize: function(WebService, Object) {
        if (this._checkSettings() == false) { return null }
        _ename = this._workflowName;
        if (WebService == null) { alert('Importare il servizio web per il workflow ' + _ename); return }
        iWS[this.uid] = WebService;
        iWS.count += 1;
        iObject[this.uid] = Object;
        iObject.count += 1;

        this.initializeCommand(this._startContainer, '[start]');

        if (this._showStartPage) { this.start_show(); };

    },
    createOptions: function(element) {
        _ename = this._workflowName;
        // recupero i parametro dall'elemento che indico
        var arr = getElementsByKey(element, _ename + '.Option', 'input');
        var arr2 = getElementsByKey(element, _ename + '.Option', 'select');
        this._options = arr.concat(arr2);
        this._options.getOption = function(key) { iObject[this.uid].getOption(key) };
    },
    createParams: function(element) {
        _ename = this._workflowName;
        // recupero i parametro dall'elemento che indico
        var arr = getElementsByKey(element, _ename + '.Parameter', 'input');
        var arr2 = getElementsByKey(element, _ename + '.Parameter', 'select');
        this._parameters = arr.concat(arr2);
        this._parameters.getParam = function(key) { iObject[this.uid].getParameter(key) };
    },
    createFilters: function(element) {
        _ename = this._workflowName;
        // recupero i parametro dall'elemento che indico
        var arr = getElementsByKey(element, _ename + '.Filter', 'input');
        var arr2 = getElementsByKey(element, _ename + '.Filter', 'select');
        this._filters = arr.concat(arr2);
        this._filters.getParam = function(key) { iObject[this.uid].getFilter(key) };
    },
    //recupera lelemento dato il parametro
    getOption: function(key) {
        if (this._options == null) { this.createOptions(this._displayContainer); }
        if (this._options != null) {
            for (var i = 0; i < this._options.length; i++) {
                if (this._options[i].getAttribute('_optionName') == key);
                { return this._options[i] };
            };
            alert('opzione \'' + key + '\' non trovato.');
        }
    },
    //recupera lelemento dato il parametro
    getParameter: function(key) {
        if (this._parameters == null) { this.createParams(this._displayContainer); }
        if (this._parameters != null) {
            for (var i = 0; i < this._parameters.length; i++) {
                if (this._parameters[i].getAttribute('_parameterName') == key)
                { return this._parameters[i] };
            };
            alert('parametro \'' + key + '\' non trovato.');
        }
    },
    //recupera lelemento dato il parametro
    getFilter: function(key) {
        if (this._filters == null) { this.createFilters(this._filterContainer); }
        if (this._filters != null) {
            for (var i = 0; i < this._filters.length; i++) {
                if (this._filters[i].getAttribute('_filterName') == key)
                { return this._filters[i] };
            };
            alert('Filtro \'' + key + '\' non trovato.');
        }
    },
    filterFunction: function(element, mode) {

        this.createFilters(element);
        // posso valorizzare a seconda del nome
        var value; var toAdd;
        var _json = '';
        for (var i = 0; i < this._filters.length; i++) {
            obj = this._filters[i];
            /****/
            value = this.getValueInput(obj);
            /***/
            //}
            if (mode != 'filter') {
                /*metto solo i valori non nulli*/
                if (value != null) {
                    _json = _json + '"' + obj.getAttribute('_filterName') + '":"' + URLEncode(value) + '",';
                }
            }

        }
        /*aggiungo le opzioni aggiunte con la voce*/
        if (_json != '') {
            _json = '{' + _json.substring(0, _json.length - 1) + '}';
        }
        return _json;
    },
    parameterFunction: function(element, mode) {
        this.createParams(element);
        // posso valorizzare a seconda del nome
        var value; var toAdd;
        var subjson = new Array();
        var _json = '';
        for (var i = 0; i < this._parameters.length; i++) {
            obj = this._parameters[i];
            /****/
            value = this.getValueInput(obj);
            /***/
            if (mode != 'back') {
                if (value != null) {
                    idx_p = obj.getAttribute('_parameterName').indexOf('.');
                    if (idx_p != -1) {
                        key = obj.getAttribute('_parameterName').substring(idx_p, 1);
                        subjson[key] = subjson[key] + '"' + obj.getAttribute('_parameterName').substring(idx_p + 2) + '":"' + URLEncode(value) + '",';
                        subjson[key].key = key;
                    } else {
                        _json = _json + '"' + obj.getAttribute('_parameterName') + '":"' + URLEncode(value) + '",';
                    }
                }
            }

        }
        if (_json != '') {
            var arr_json = '';
            if (subjson != null) {
                for (var i = 0; i < subjson.length; i++) {
                    arr_json = arr_json + '"' + subjson[i].key + '":{' + subjson[i].substring(0, _json.length - 1) + '},';
                }
            }
            _json = '{' + _json.substring(0, _json.length - 1) + arr_json.substring(0, _json.length - 1) + '}';
        }
        return _json;
    },
    optionFunction: function(element, options) {

        this.createOptions(element);
        // creo la stringa a seconda dei parametri
        // posso valorizzare a seconda del nome
        var value; var toAdd;
        var _json = '';
        for (var i = 0; i < this._options.length; i++) {
            obj = this._options[i];
            /****/
            value = this.getValueInput(obj);
            /***/
            if (value != null) {
                _json = _json + '"' + obj.getAttribute('_optionName') + '":"' + value + '",';
            }
        }
        //controllo le altre opzioni passate con il comando next
        if (options != null) {
            for (var i = 0; i < options.length; i++) {
                _json = _json + '"' + options[i].name + '":"' + options[i].value + '",';
            }
        }

        if (_json != '') {
            _json = '{' + _json.substring(0, _json.length - 1) + '}';
        }
        return _json;
    },

    initializeCommand: function(element, cmds) {
        var all = (cmds == '*');
        var _os = 'javascript:iObject[\'' + this.uid + '\']';
        _ename = this._workflowName;
        this._commandsElement = new Array();
        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('[start]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Start', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._startParameter = obj.getAttribute('_startParameter');
                obj.href = _os + ".Start('" + obj._startParameter + "');";
                this._commandsElement[this._commandsElement.length] = obj;
            }
            arr = null;
        }

        if (all || cmds.indexOf('[next]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Next', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._workflowId = obj.getAttribute('_workflowId');
                obj._options = obj.getAttribute('_options');
                obj.onclick = function() { eval(obj.getAttribute('validateClient')) };
                obj.href = _os + ".Next('" + obj._workflowId + "'," + obj._options + ");";
                this._commandsElement[this._commandsElement.length] = obj;
            }
            arr = null;

        }
        if (all || cmds.indexOf('[abort]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Abort', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._workflowId = obj.getAttribute('_workflowId');
                obj.href = _os + ".Abort('" + obj._workflowId + "');";
                this._commandsElement[this._commandsElement.length] = obj;
            }
            arr = null;

        }
        if (all || cmds.indexOf('[filter]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Filter', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._workflowId = obj.getAttribute('_workflowId');
                obj.onclick = function() { eval(obj.getAttribute('validateClient')) };
                obj.href = _os + ".Filter('" + obj._workflowId + "');";
                this._commandsElement[this._commandsElement.length] = obj;
            }
            arr = null;
        }
        if (all || cmds.indexOf('[complete]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Complete', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._workflowId = obj.getAttribute('_workflowId');
                obj._options = obj.getAttribute('_options');
                obj.href = _os + ".Complete('" + obj._workflowId + "'," + obj._options + ");";
                this._commandsElement[this._commandsElement.length] = obj;
            }
            arr = null;
        }
        if (all || cmds.indexOf('[back]', 0) >= 0) {
            var arr = getElementsByKey(element, _ename + '.Back', 'a');
            for (var i = 0; i < arr.length; i++) {
                obj = arr[i];
                obj._workflowId = obj.getAttribute('_workflowId');
                obj.href = _os + ".Back('" + obj._workflowId + "');";
                this._commandsElement[this._commandsElement.length] = obj;
            }
            arr = null;
        }

    },
    Start: function(startParameter) {
        this.progress_show();
        this.start_hide();
        this.time = new Date().getTime();
        settingOptions = '{"ShowRawData":"' + this._enabled_showRawData + '"}';
        if (startParameter == 'null') { startParameter = '' };
        this.lockButton();
        iWS[this.uid].Start(startParameter, settingOptions, this.onSuccess, this.onFailWorkflow, this.uid);
    },
    Next: function(workflowId, options) {
        var _parameters;
        var _currentStep = this.getCurrentStep();
        if (this._onNext != null) { this._onNext(_currentStep, this) }
        if (this.parameterFunction_advanced != null) { _parameters = this.parameterFunction_advanced(_currentStep, 'next'); }
        if (_parameters == null || _parameters == '') {
            _parameters = this.parameterFunction(this._displayContainer, 'next');
        }
        if (_parameters == -1) { return }
        if (!this.validatingInput(this._parameters)) { return }

        _options = this.optionFunction(this._displayContainer, options);
        if (_options == -1) { return }
        if (!this.validatingInput(this._options)) { return }

        if (!this.validating()) { return }
        this.progress_show();
        this.lockButton();
        iWS[this.uid].Next(_parameters, _options, workflowId, this.onSuccess, this.onFailWorkflow, this.uid);
    },
    Filter: function(workflowId) {
        _parameters = this.parameterFunction(this._displayContainer, 'filter');
        if (_parameters == -1) { return }
        if (!this.validatingInput(this._parameters)) { return }

        _options = this.optionFunction(this._displayContainer);
        if (_options == -1) { return }
        if (!this.validatingInput(this._options)) { return }

        _filters = this.filterFunction(this._filterContainer);
        if (_filters == -1) { return }
        if (!this.validatingInput(this._filter)) { return }

        if (!this.validating()) { return }
        this.progress_show();
        this.lockButton();
        iWS[this.uid].Next(_parameters, _options, _filters, workflowId, this.onSuccess, this.onFailWorkflow, this.uid);
    },
    Back: function(workflowId) {
        _parameters = this.parameterFunction(this._displayContainer, 'back');
        this.progress_show();
        this.lockButton();
        iWS[this.uid].Back(_parameters, workflowId, this.onSuccess, this.onFailWorkflow, this.uid);
    },
    Abort: function(workflowId) {
        this.progress_show();
        this.lockButton();
        iWS[this.uid].Abort(workflowId, this._abort, this.onFailWorkflow, this.uid);
    },
    Complete: function(workflowId, options) {
        this.progress_show();
        _parameters = this.parameterFunction(this._displayContainer, 'complete');
        if (!this.validatingInput(this._parameters)) { return }

        _options = this.optionFunction(this._displayContainer, options);
        if (_options == -1) { return }
        if (!this.validatingInput(this._options)) { return }

        this.lockButton();
        iWS[this.uid].Complete(_parameters, _options, workflowId, this.onSuccessWorkflow, this.onFailWorkflow, this.uid);

    },
    onSuccessWorkflow: function(result, context) {

        obj = iObject[context];
        //se contiene uno step failere il wf non è finito ed eseguo
        if (result.indexOf('keys="' + obj._workflowName + '.StepName" value="Failure"', 0) != -1) {
            obj.onSuccess(result, context);
            return
        }

        if (obj._onSuccessWorkflowExtender != null) {
            obj._onSuccessWorkflowExtender(result, context);
        }
        obj._displayContainer.innerHTML = '';
        obj.progress_hide();
        obj.start_show();
    },
    onSuccess: function(result, context) {

        obj = iObject[context];
        obj._displayContainer.innerHTML = result;
        /*svuoto i parametri*/
        obj._parameters = null;
        obj._options = null;
        obj._filters = null;
        //	alert((new  Date().getTime()) - obj.time);
        if (obj._stepChanged != null) { obj._stepChanged(obj.getCurrentStep(), obj) };

        obj.progress_hide();
        obj.unlockButton();
        obj.initializeCommand(obj._displayContainer, '[back][next][abort][start][complete]');

    },
    _abort: function(result, context) {
        obj = iObject[context];
        obj._displayContainer.innerHTML = '';
        if (obj._onFailedWorkflowExtender) { obj._onFailedWorkflowExtender(obj.getCurrentStep(), obj) };
        obj.unlockButton();
        obj.progress_hide();
        obj.start_show();
    },
    onFailWorkflow: function(result, context) {
        alert(result.get_message());
        obj = iObject[context];
        obj._abort(result, context);
    },
    getCurrentStep: function() {
        var elem;
        elem = getElementsByKey(this._displayContainer, _ename + '.StepName', 'input')[0];
        if (elem != null) { return elem.value }
    },
    getWorkflowId: function() {
        var elem;
        elem = getElementsByKey(this._displayContainer, _ename + '.WorkflowId', 'input')[0];
        if (elem != null) { return elem.value } else { alert('Manca l\'input con chiave WorkflowId nel foglio xslt per poter recuperare il workflowId') }
    },
    getValueInput: function(obj) {
        switch (obj.type) {
            case 'radio':
                var group = document.getElementsByName(obj.name);
                value = null;
                for (k = 0; k < group.length; k++) {
                    if (group[k].checked) {
                        value = group[k].value;
                    }
                }
                break;
            case 'checkbox':
                value = obj.checked;
                break;
            default:
                value = (obj.value == '') ? null : obj.value;
                break;

        }
        var _contain_ = obj.getAttribute('_operator');
        if (_contain_ != null && value != '' && value != null) {
            switch (_contain_.toLowerCase()) {
                case 'like':
                    value = '%' + value + '%';
                case 'startwith':
                    value = value + '%';
                case 'endwith':
                    value = '%' + value;
            }
        }
        return value
    },
    validatingInput: function(inputList) {
        for (var i = 0; i < inputList.length; i++) {

            obj = inputList[i];
            value = this.getValueInput(obj);
            var othercheck = null;
            var _curStep = this.getCurrentStep();
            if (this._validateExtended != null)
            { othercheck = this._validateExtended(_curStep, obj) }


            if ((othercheck == null || !othercheck) && !validateField(value, obj)) {
                return false
            }
            if (value != null) {
                if (!validateInput(value)) {
                    return false
                }
            }
        }
        return true
    },
    validating: function() {
        _ename = this._workflowName;
        this._workflowStepName = this.getCurrentStep();
        if (this._workflowStepName == '') { alert('Impossibile validare i dati.inserire un campo hidden con chiave .StepName valorizzato con il nome dello step corrente.'); return false };
        if (this._validateClient != null) { return this._validateClient(this._workflowStepName, this._parameters) };
        return true;

    },
    start_show: function() { this._startContainer.style.display = 'block'; },
    start_hide: function() { this._startContainer.style.display = 'none'; },
    progress_show: function() {
        if (this._enabled_progress) {
            if (this._progressElement != null) { this._progressElement.style.display = 'block'; }
            if (this._enabled_hideDisplayContainerOnProgress) {
                if (this._displayContainer != null) { this._displayContainer.style.display = 'none'; }
            }
        }
    },
    lockButton: function() {
        for (var i = 0; i < this._commandsElement.length; i++) {
            this._commandsElement[i].disabled = true;
        }
    },
    unlockButton: function() {
        for (var i = 0; i < this._commandsElement.length; i++) {
            this._commandsElement[i].disabled = false;
        }
    },
    progress_hide: function() {
        if (this._enabled_progress) {
            if (this._progressElement != null) { this._progressElement.style.display = 'none'; }
            if (this._enabled_hideDisplayContainerOnProgress) {
                if (this._displayContainer != null) { this._displayContainer.style.display = 'block'; }
            }
        }
    }

};


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.WorkflowUI.registerClass('Ribo.Cms.JS.WorkflowUI', Sys.UI.Component);
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


