/// Author: AustralTek 
/// http://www.australtek.com
/// Copyright: 2009 - 2012

(function () {
    function _IndustrialGridEditableGeneric(object, options) {
        try {
            //Private Members      
            //MYREFERENCE
            var PRIVATEPARAMETERS = null;
            var MYREFERENCES = {
                OBJECTDATA: null
                    , DATA: null
                    , CLICKEDROWINDEX: -1
                    , PREVIOUSSELECTEDINDEX: -1
                    , PREVIOUSSTYLE: ""
                    , SPECIALCOLUMNS: []
                    , MAINTABLE: null
                    , SORTINDEX: -1
                    , SORTMODE: null
                    , SORTCOLUMNTYPE: ""
                    , CHKMAIN: null
                    , ARCHKS: []
                    , CMBPAGING: null
                    , ISREFRESHING: false
                    , PREVIOUSPARAMETERS: null
                    , WIDGETCONTAINER: null
                    , AUTOREFRESH: false
                    , TIMERID: null
                    , REFRESHTIME: 5000
                    , AUTOREFRESHPARAMETERS: null
                    , FILTERWIDGETREFERENCE: null
                    , FIRSTCALL: true
                    , WIDGET: this
                    , EXPORTTYPE: null
                    , CMBGETTINGDATA: false
                    , PrincipalIndex: 0
                    , SelectedRowIndex: -1
                    , PreviousSelectedRow: null
                    , ReadOnly: false
                    , MaxValue: 10000
                    , CLIENTDATACHANGED: false
                    , CLIENTDATABEINGCHANGED: false
                    , WasScrolled: false
                    , MouseOverBGColor: "#FAFAFA"
                    , DropDownItemMouseOverBGColor: "#F0F0F0"
                    , DropDownItemSelectedBGColor: "#F8E894"
                    , DropDownPickersList: []
                    , DRAW: { //internal storage for infinite scroll implementation.
                        COLFORMAT: null
                        , LastRowDrawn: null
                        , times: 0
                    }
                    , CustomConfiguration: {
                        Search: {
                            ColumnsToSearch: []
                            , Enabled: false
                        }
                        , InfiniteScroll: {
                            rowsToDraw: null
                        }
                        , DifferentialRefresh: false
                        , Autosave: {
                            ColumnsToAutosave: []
                            , Enabled: false
                            , AutosaveTimeoutID: null
                            , AutosaveTimeout: 3000 //in milliseconds
                            , UnsavedChanges: false
                        }
                        , ColumnHelpers: {
                            
                        }
                        , DataTypeValidations: []
                    }
            };
            function _Initialize(object, options) {
                try {
                    PRIVATEPARAMETERS = new Core.PrivateParameters(options);
                    MYREFERENCES.ReadOnly = (PRIVATEPARAMETERS.ReadOnly) ? PRIVATEPARAMETERS.ReadOnly : false;
                    if ((PRIVATEPARAMETERS.Events.onPageChange == undefined) || (PRIVATEPARAMETERS.Events.onPageChange == null))
                        PRIVATEPARAMETERS.Events.onPageChange = _ChangePage;
                    PRIVATEPARAMETERS.Events.onAutoRefreshComplete = _AutomaticRefresh;
                    if ((PRIVATEPARAMETERS.Events.onChangeValue == undefined) || (PRIVATEPARAMETERS.Events.onChangeValue == null)) {
                        PRIVATEPARAMETERS.Events.onChangeValue = function () { };
                    }
                    if ((PRIVATEPARAMETERS.Events.onContextMenu == null) || (PRIVATEPARAMETERS.Events.onContextMenu == undefined)) PRIVATEPARAMETERS.Events.onContextMenu = function () { };
                    if (PRIVATEPARAMETERS.Data) {
                        //PRIVATEPARAMETERS.Events.ManualRefresh
                        if (PRIVATEPARAMETERS.Data.ManualRefresh) {
                            if ((PRIVATEPARAMETERS.Events.onManualRefresh == null) || (PRIVATEPARAMETERS.Events.onManualRefresh == undefined)) PRIVATEPARAMETERS.Events.onManualRefresh = _ManualRefresh;
                        }
                        if (PRIVATEPARAMETERS.Data.AutoRefresh) {
                            MYREFERENCES.AUTOREFRESH = true;
                            MYREFERENCES.REFRESHTIME = ((PRIVATEPARAMETERS.Data.AutoRefresh.ElapsedTime) && (IsNumber(PRIVATEPARAMETERS.Data.AutoRefresh.ElapsedTime))) ? PRIVATEPARAMETERS.Data.AutoRefresh.ElapsedTime : MYREFERENCES.REFRESHTIME;
                            MYREFERENCES.FILTERWIDGETREFERENCE = PRIVATEPARAMETERS.Data.AutoRefresh.FilterWidgetReference;
                        }
                    }
                    if (PRIVATEPARAMETERS.Export) {
                        //onExcelExport
                        if ((PRIVATEPARAMETERS.Events.onExcelExport == null) || (PRIVATEPARAMETERS.Events.onExcelExport == undefined)) PRIVATEPARAMETERS.Events.onExcelExport = _DefaultPrint;
                        //onPDFExport
                        if ((PRIVATEPARAMETERS.Events.onPDFExport == null) || (PRIVATEPARAMETERS.Events.onPDFExport == undefined)) PRIVATEPARAMETERS.Events.onPDFExport = _DefaultPrint;
                    }

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.Search.ColumnsToSearch')) {
                        MYREFERENCES.CustomConfiguration.Search.ColumnsToSearch = _getColumnsFromArray(PRIVATEPARAMETERS.Configuration.Search.ColumnsToSearch);
                    }

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.Autosave.Enabled')) {
                        MYREFERENCES.CustomConfiguration.Autosave.Enabled = PRIVATEPARAMETERS.Configuration.Autosave.Enabled;                        
                        Core.Events.Add(window, 'onbeforeunload', _Autosave_BeforeUnload);
                    }

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.Autosave.AutosaveTimeout')) {
                        MYREFERENCES.CustomConfiguration.Autosave.AutosaveTimeout = PRIVATEPARAMETERS.Configuration.Autosave.AutosaveTimeout;
                    }

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.InfiniteScroll.RowsToDraw')) {
                        MYREFERENCES.CustomConfiguration.InfiniteScroll.rowsToDraw = PRIVATEPARAMETERS.Configuration.InfiniteScroll.RowsToDraw;
                    }

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.DifferentialRefresh')) {
                        MYREFERENCES.CustomConfiguration.DifferentialRefresh = PRIVATEPARAMETERS.Configuration.DifferentialRefresh;
                    }

                    object.className += " IndustrialGridEditableContainerGlobal";
                    MYREFERENCES.WIDGETCONTAINER = new IndustrialContainer(object, PRIVATEPARAMETERS);
                    PRIVATEPARAMETERS.Version.Class = "IndustrialGrid";
                    PRIVATEPARAMETERS.Container = MYREFERENCES.WIDGETCONTAINER.GetControl();
                    PRIVATEPARAMETERS.Container.className = "IndustrialGridEditableContainer";
                    Events.Add(PRIVATEPARAMETERS.Container, "onclick", _DocumentClick);
                    Events.Add(PRIVATEPARAMETERS.Container, "onmousedown", _DocumentClick);

                    _ConfigureCustomColumnHelpers();
                    _SetInfiniteScrollingHandlers();

                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ConfigureCustomColumnHelpers() {
                try {
                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.ColumnHelpers')) {
                        var customColumnHelpers = PRIVATEPARAMETERS.Configuration.ColumnHelpers;
                        for (var columnName in customColumnHelpers) {
                            MYREFERENCES.CustomConfiguration.ColumnHelpers[columnName] = { Message: "" };
                            MYREFERENCES.CustomConfiguration.ColumnHelpers[columnName].Message = customColumnHelpers[columnName].Message;
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ConfigureCustomDataTypeValidations() {
                try {
                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.DataTypeValidations')) {
                        var customDataTypeValidations = PRIVATEPARAMETERS.Configuration.DataTypeValidations;
                        MYREFERENCES.CustomConfiguration.DataTypeValidations = customDataTypeValidations; 
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _SetInfiniteScrollingHandlers() {
                try {
                    Core.Events.Add(window, 'onscroll', _InfiniteScrolling_onScroll);
                } catch (Error) {
                }
            }
            function _InfiniteScrolling_onScroll() {
                try {
                    var st = (Core.Object.Eval(window, 'pageYOffset') == true) ? window.pageYOffset : (Core.Object.Eval(window, 'document.documentElement.pageYOffset') == true) ? window.document.documentElement.pageYOffset : 0;
                    if (st > (Core.ElementSize.GetHeight(document) - Core.ElementSize.GetHeight(window) - 300)) {
                        if (MYREFERENCES.CustomConfiguration.InfiniteScroll.rowsToDraw) {
                            _Redraw(PRIVATEPARAMETERS.Container, null, true, { fromRow: MYREFERENCES.DRAW.LastRowDrawn, rowsToDraw: MYREFERENCES.CustomConfiguration.InfiniteScroll.rowsToDraw, redrawHeaders: false });
                            MYREFERENCES.WasScrolled = true;
                        }
                    }
                } catch (Error) { }
            }
            function _ChangePage() {
                try {
                    if (MYREFERENCES.AUTOREFRESH) {
                        MYREFERENCES.FIRSTCALL = true;
                        _AutomaticRefresh();
                    } else _Refresh(MYREFERENCES.PREVIOUSPARAMETERS);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetItemsPerPage() {
                try {
                    return MYREFERENCES.WIDGETCONTAINER.GetItemsPerPage();
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetPageIndex() {
                try {
                    return MYREFERENCES.WIDGETCONTAINER.GetPageIndex();
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _CountItems() {
                return _GetAttributeValue("TotalRows");
            }
            function _SetDetailedError(errorType, detail) {
                try {
                    MYREFERENCES.WIDGETCONTAINER.SetError(errorType, function () { Core.Messages.Alert.Show({ Type: "Error", Message: errorType + ". " + detail }); });
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _AutoRefresh(time, refObjectResults) {
                try {
                    MYREFERENCES.AUTOREFRESH = true;
                    MYREFERENCES.FILTERWIDGETREFERENCE = refObjectResults;
                    MYREFERENCES.REFRESHTIME = ((time) && (IsNumber(time))) ? time : MYREFERENCES.REFRESHTIME;
                    _AutomaticRefresh();
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _CancelAutoRefresh() {
                MYREFERENCES.AUTOREFRESH = false;
            }
            function _AutomaticRefresh() {
                try {
                    if (MYREFERENCES.TIMERID) {
                        clearTimeout(MYREFERENCES.TIMERID);
                        MYREFERENCES.TIMERID = null;
                    }
                    if (MYREFERENCES.AUTOREFRESH) {
                        var t = 1;
                        if (MYREFERENCES.FIRSTCALL) MYREFERENCES.FIRSTCALL = false;
                        else t = MYREFERENCES.REFRESHTIME;
                        MYREFERENCES.TIMERID = setTimeout(function () {
                            MYREFERENCES.AUTOREFRESHPARAMETERS = ((MYREFERENCES.FILTERWIDGETREFERENCE != null) && (MYREFERENCES.FILTERWIDGETREFERENCE.GetResults)) ? MYREFERENCES.FILTERWIDGETREFERENCE.GetResults() : MYREFERENCES.PREVIOUSPARAMETERS;
                            _Refresh(MYREFERENCES.AUTOREFRESHPARAMETERS);
                        }, t);
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ManualRefresh(parameters) {
                try {
                    _Refresh(MYREFERENCES.PREVIOUSPARAMETERS);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ResetParameters() {
                try {
                    MYREFERENCES.WIDGETCONTAINER.SetPageNumber(1);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Refresh(parameters, forceRefresh, customParameters) {
                try {
                    if ((parameters == null) || (parameters.Version == null) || (parameters.Version().indexOf("SQLParameters") == -1)) parameters = new QueryParameters();
                    MYREFERENCES.PREVIOUSPARAMETERS = parameters;
                    MYREFERENCES.SPECIALCOLUMNS = [];
                    if ((parameters != undefined) && (parameters.Legend)) {
                        var animate;
                        if ((parameters.Legend.Animate) || (parameters.Legend.Animate.toString().toUpperCase() == "TRUE")) animate = true;
                        else animate = false;
                        MYREFERENCES.WIDGETCONTAINER.SetLegend(parameters.Legend.Title, animate);
                    } else {
                        MYREFERENCES.WIDGETCONTAINER.SetLegend("Loading...", true);
                    }
                    var url = PRIVATEPARAMETERS.URL + PRIVATEPARAMETERS.Method;
                    var options = {}; options.data = {};
                    if (PRIVATEPARAMETERS.Data.Paging) {
                        MYREFERENCES.WIDGETCONTAINER.AddPagingQueryParameters(parameters);
                    }
                    options.data.DatabaseParameters = PRIVATEPARAMETERS.DatabaseParameters;
                    options.data.JSONFile = PRIVATEPARAMETERS.JSONFile;
                    for (var conParam in PRIVATEPARAMETERS.ConnectionParameters)
                        options[conParam] = PRIVATEPARAMETERS.ConnectionParameters[conParam];

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'DatabaseParameters.Fixed') == true) {
                        var qp;
                        for (var qpi = 0; qpi < PRIVATEPARAMETERS.DatabaseParameters.Fixed.length; qpi++) {
                            qp = PRIVATEPARAMETERS.DatabaseParameters.Fixed[qpi];
                            parameters.AddParameter(qp);
                        }
                    }

                    if ((parameters) && (parameters.Version)) {
                        options.data.DatabaseParameters.QueryParameters = parameters.GetQueryParameters();
                    }

                    else options = (parameters) ? parameters : options;

                    options.data.Namespace = PRIVATEPARAMETERS.Version.Namespace;
                    options.data.Class = PRIVATEPARAMETERS.Version.Class;
                    options.onSuccess = function (requestData) {
                        if ((requestData) && (!requestData.Message)) {
                            data = (Core.Object.Eval(requestData, 'Data')) ? requestData.Data : requestData;
                            MYREFERENCES.WIDGETCONTAINER.DisplayLegend(false);
                            var newDataFormated = _ConvertMatrixToObjectData(data.Columns | data.Fields, data.Matrix, data.Metadata);
                            var oldDataFormated = null;
                            _FillColumnsIndexCollection(newDataFormated.Columns);

                            if ((forceRefresh)
                                || (!MYREFERENCES.DATA)
                                || ((_CompareDatasets(newDataFormated, _ConvertMatrixToObjectData(MYREFERENCES.DATA.Columns | MYREFERENCES.DATA.Fields, MYREFERENCES.DATA.Matrix, MYREFERENCES.DATA.Metadata)) == true)
                                    && (_wasDataChanged() == false) && !MYREFERENCES.WasScrolled)
                                || (!MYREFERENCES.CustomConfiguration.DifferentialRefresh)
                            ) {
                                _Redraw(PRIVATEPARAMETERS.Container, data);

                                MYREFERENCES.CLIENTDATACHANGED = false;
                                MYREFERENCES.WasScrolled = false;
                            } else if (MYREFERENCES.CustomConfiguration.DifferentialRefresh == true) {
                                _differentialRefresh(newDataFormated);
                            }
                            PRIVATEPARAMETERS.Events.onAutoRefreshComplete();

                            if (Core.Object.Eval(customParameters, 'Events.onComplete'))
                                customParameters.Events.onComplete();

                            setTimeout(PRIVATEPARAMETERS.Events.onComplete, 1);
                        }
                        else {
                            MYREFERENCES.OBJECTDATA = null;
                            MYREFERENCES.DATA = null;
                            //if exists error, displayed
                            MYREFERENCES.WIDGETCONTAINER.SetTotalRows(0);
                            if (requestData == null) {
                                MYREFERENCES.WIDGETCONTAINER.DisplayLegend(true);
                                _Clear();
                                PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                                MYREFERENCES.WIDGETCONTAINER.SetLegend("No available Data", false);
                            } else {
                                MYREFERENCES.WIDGETCONTAINER.DisplayLegend(true);
                                _SetDetailedError(requestData, requestData.Message);
                                _Clear();
                                PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                            }
                            setTimeout(PRIVATEPARAMETERS.Events.onComplete, 1);
                        }
                    }
                    options.onFailure = function (message) {
                        PRIVATEPARAMETERS.Events.onFailure(message);
                        PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                        PRIVATEPARAMETERS.Events.onComplete();
                    }
                    if ((url == undefined) || (url == "")) {
                        if ((PRIVATEPARAMETERS.JSONStringFile != undefined) && (PRIVATEPARAMETERS.JSONStringFile != "")) {
                            data = PRIVATEPARAMETERS.JSONStringFile;
                            MYREFERENCES.WIDGETCONTAINER.DisplayLegend(false);
                            _Redraw(PRIVATEPARAMETERS.Container, data);
                            PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                            setTimeout(PRIVATEPARAMETERS.Events.onComplete, 1);
                            return;
                        } else {
                            MYREFERENCES.WIDGETCONTAINER.SetTotalRows(0);
                            MYREFERENCES.WIDGETCONTAINER.SetLegend("No available Data", false);
                            MYREFERENCES.WIDGETCONTAINER.DisplayLegend(true);
                            _Clear();
                            PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                            setTimeout(PRIVATEPARAMETERS.Events.onComplete, 1);
                            return;
                        }
                    }

                    if ((parameters) && (parameters.OnlyRefresh)) {
                        if ((parameters.requestData) && (!parameters.requestData.message)) {
                            data = parameters.requestData;
                            MYREFERENCES.WIDGETCONTAINER.DisplayLegend(false);
                            _Redraw(PRIVATEPARAMETERS.Container, data);
                            PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                            setTimeout(PRIVATEPARAMETERS.Events.onComplete, 1);
                        }
                        else {
                            MYREFERENCES.WIDGETCONTAINER.SetTotalRows(0);
                            MYREFERENCES.WIDGETCONTAINER.SetLegend("No available Data", false);
                            MYREFERENCES.WIDGETCONTAINER.DisplayLegend(true);
                            _Clear();
                            PRIVATEPARAMETERS.Events.onAutoRefreshComplete();
                            setTimeout(PRIVATEPARAMETERS.Events.onComplete, 1);
                        }
                    } else RequestJSON(url, options);

                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _RefreshData(parameters, forceRefresh, customParameters) {
                try {
                    if ((forceRefresh) || ((!(MYREFERENCES.AUTOREFRESH)) || (MYREFERENCES.FIRSTCALL))) {
                        _Refresh(parameters, forceRefresh, customParameters);
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ApplyAttributes(attributes, tr, td) {
                try {
                    var attributes = attributes.split(";");
                    if (attributes.length > 1) {
                        for (var i = 0; i < attributes.length; i++) {
                            var attrib = attributes[i];
                            if (attrib != "") {
                                var key = attributes[i].substring(0, attributes[i].indexOf(":"));
                                var value = attributes[i].substring(attributes[i].indexOf(":") + 1, attributes[i].length);
                                switch (key.toUpperCase()) {
                                    case "TRBCK":
                                        //tr.style.background = value;
                                        for (var j = 0; j < tr.childNodes.length; j++) {
                                            var cell = tr.childNodes[j];
                                            var item; eval("item=" + value);
                                            if (cell) {
                                                if (item.bck) cell.style.backgroundColor = item.bck;
                                                if (item.color) cell.style.color = item.color;
                                            }
                                        }
                                        break;
                                    case "TDBCK":
                                        var item; eval("item=" + value);
                                        if (item.column != undefined) {
                                            var cell = tr.childNodes[item.column];
                                            if (cell) {
                                                if (item.bck) cell.style.backgroundColor = item.bck;
                                                if (item.color) cell.style.color = item.color;
                                            }
                                        }
                                        break;
                                }
                            }
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetSpecialColumns() {
                if (MYREFERENCES.SPECIALCOLUMNS) return MYREFERENCES.SPECIALCOLUMNS;
                else return null;
            }
            function _SetSpecialColumns() {

            }
            function _SelectAllRows() {
                try {
                    var chk = MYREFERENCES.CHKMAIN;
                    var checked = false;
                    checked = chk.checked;
                    if ((MYREFERENCES.MAINTABLE) && (MYREFERENCES.MAINTABLE.childNodes.length > 1)) {
                        var tb = MYREFERENCES.MAINTABLE.childNodes[1];
                        if (tb) {
                            for (var i = 0; i < MYREFERENCES.OBJECTDATA.Rows.length; i++) {
                                MYREFERENCES.OBJECTDATA.Rows[i][0].Checked = checked;
                                row = tb.childNodes[i];
                                if (checked) {
                                    if (row.className.indexOf("Selected") == -1) row.className += "Selected";
                                }
                                else {
                                    row.className = row.className.replace("Selected", "");
                                }
                                row.childNodes[0].childNodes[0].checked = checked;
                            }
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _SelectedRows() {
                try {
                    var retData = [];
                    if (MYREFERENCES.SelectedRowIndex != -1) {
                        var item = {};
                        item.RowIndex = MYREFERENCES.SelectedRowIndex;
                        for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                            eval("item[\"" + MYREFERENCES.OBJECTDATA.Columns[c].Name + "\"] = MYREFERENCES.OBJECTDATA.Rows[MYREFERENCES.SelectedRowIndex][c].Value");
                        }
                        retData.push(item);
                    } else {
                        for (var i = 0; i < MYREFERENCES.OBJECTDATA.Rows.length; i++) {
                            if (MYREFERENCES.OBJECTDATA.Rows[i][0].Checked) {
                                var item = {};
                                item.RowIndex = i;
                                for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                                    if (MYREFERENCES.OBJECTDATA.Columns[c].Type == "normal")
                                        eval("item[\"" + MYREFERENCES.OBJECTDATA.Columns[c].Name + "\"] = MYREFERENCES.OBJECTDATA.Rows[index][c].Value");
                                }
                                retData.push(item);
                            }
                        }
                    }
                    return retData;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _SortRows(e) {
                try {
                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                        var cols = data.Columns | data.Fields;
                        var matrix = data.Matrix;
                        MYREFERENCES.SORTINDEX = target.colIndex;
                        MYREFERENCES.SORTMODE = MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Order;
                        if ((MYREFERENCES.SORTMODE == "none") || (MYREFERENCES.SORTMODE == "desc")) MYREFERENCES.SORTMODE = "asc";
                        else MYREFERENCES.SORTMODE = "desc";
                        for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                            if (MYREFERENCES.OBJECTDATA.Columns[c].Type == "normal") MYREFERENCES.MAINTABLE.childNodes[0].childNodes[0].childNodes[c].childNodes[1].className = "sortingContainer";
                        }
                        if (MYREFERENCES.SORTMODE == "asc") MYREFERENCES.MAINTABLE.childNodes[0].childNodes[0].childNodes[MYREFERENCES.SORTINDEX].childNodes[1].className = "sortingContainerAsc";
                        else MYREFERENCES.MAINTABLE.childNodes[0].childNodes[0].childNodes[MYREFERENCES.SORTINDEX].childNodes[1].className = "sortingContainerDesc";
                        if (PRIVATEPARAMETERS.Events.onSort) {
                            data = PRIVATEPARAMETERS.Events.onSort(MYREFERENCES.SORTMODE, MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Name);
                            MYREFERENCES.OBJECTDATA = _ConvertMatrixToObjectData(data.Columns, data.Matrix, data.Metadata);
                            MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Order = MYREFERENCES.SORTMODE;
                            _QuicklyRefresh();
                        } else {
                            MYREFERENCES.SORTCOLUMNTYPE = (IsNumber(MYREFERENCES.OBJECTDATA.Rows[0][MYREFERENCES.SORTINDEX].Value)) ? "number" : "string";
                            MYREFERENCES.OBJECTDATA.Rows.sort(_Compare);
                            MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Order = MYREFERENCES.SORTMODE;
                            _QuicklyRefresh();
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetSortColumnMode() {
                try {
                    if (((MYREFERENCES.OBJECTDATA == undefined) || (MYREFERENCES.SORTINDEX == -1)) || ((MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Order == "none") || (MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Order == null))) return "";
                    else return "[" + MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Name + "] " + MYREFERENCES.OBJECTDATA.Columns[MYREFERENCES.SORTINDEX].Order;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Compare(row1, row2) {
                try {
                    if (MYREFERENCES.SORTMODE == "asc") {
                        if (MYREFERENCES.SORTCOLUMNTYPE == "string") {
                            return ((row1[MYREFERENCES.SORTINDEX].Value < row2[MYREFERENCES.SORTINDEX].Value) ? -1 : ((row1[MYREFERENCES.SORTINDEX].Value > row2[MYREFERENCES.SORTINDEX].Value) ? 1 : 0))
                        } else return row1[MYREFERENCES.SORTINDEX].Value - row2[MYREFERENCES.SORTINDEX].Value;
                    }
                    else {
                        if (MYREFERENCES.SORTCOLUMNTYPE == "string") {
                            return ((row2[MYREFERENCES.SORTINDEX].Value < row1[MYREFERENCES.SORTINDEX].Value) ? -1 : ((row2[MYREFERENCES.SORTINDEX].Value > row1[MYREFERENCES.SORTINDEX].Value) ? 1 : 0))
                        } else return row2[MYREFERENCES.SORTINDEX].Value - row1[MYREFERENCES.SORTINDEX].Value;
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ConvertMatrixToObjectData(cols, matrix, metadata) {
                try {
                    var od = {};
                    od.Columns = [];
                    od.Rows = [];
                    //add the columns
                    if (PRIVATEPARAMETERS.Data.CheckedColumn) {
                        if (PRIVATEPARAMETERS.Data.CheckedColumn.Allow) {
                            var column = {};
                            column.Name = PRIVATEPARAMETERS.Data.CheckedColumn.ColumnName || PRIVATEPARAMETERS.Data.CheckedColumn.Title;
                            if ((column.Name == undefined) || (column.Name == null)) column.Name = "";
                            column.Type = "checkbox";
                            column.Order = "none";
                            od.Columns.push(column);
                        }
                    }
                    for (var c = 0; c < cols; c++) {
                        var column = {};
                        var text = matrix[c].split("!");
                        column.Name = text[0];
                        column.MappingName = c.toString();
                        column.Type = "normal";
                        if (text.length > 1) {
                            column.Attributes = [];
                            for (var k = 1; k < text.length; k++) column.Attributes.push(text[k]);
                            /* Look for mapping name attribute. */
                            for (var k = 1; k < text.length; k++) {
                                if (text[k].indexOf("mn") != -1) {
                                    column.MappingName = text[k].split(":")[1];
                                    break;
                                }
                            }
                        }
                        column.Order = "none";
                        od.Columns.push(column);
                    }
                    for (var r = cols; r < matrix.length; r += cols) {
                        var Cells = [];
                        if (PRIVATEPARAMETERS.Data.CheckedColumn) {
                            if (PRIVATEPARAMETERS.Data.CheckedColumn.Allow) {
                                cell = {};
                                cell.Type = "checkbox";
                                cell.Checked = false;
                                Cells.push(cell);
                            }
                        }
                        for (var iCell = 0; iCell < cols; iCell++) {
                            cell = {};
                            cell.Type = "normal";
                            cell.Value = matrix[iCell + r];
                            Cells.push(cell);
                        }
                        od.Rows.push(Cells);
                    }
                    return od;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function ColorPicker_Blur(e) {
                try {

                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                        var index = target.ColorPicker;
                        var cp = MYREFERENCES.OBJECTDATA.Rows[index.RowIndex][index.ColIndex].Object;
                        MYREFERENCES.OBJECTDATA.Rows[index.RowIndex][index.ColIndex].Value = cp.toString();
                        MYREFERENCES.OBJECTDATA.Rows[index.RowIndex][index.ColIndex].WasChanged = true;
                        MYREFERENCES.OBJECTDATA.Rows[index.RowIndex].WasChanged = true;

                        MYREFERENCES.CLIENTDATACHANGED = true;
                    }

                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _CheckboxClicked(e) {
                try {
                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                        var index = target.Checkbox;
                        MYREFERENCES.OBJECTDATA.Rows[index.RowIndex][index.ColIndex].Value = (target.checked) ? "1" : "0";
                        MYREFERENCES.OBJECTDATA.Rows[index.RowIndex][index.ColIndex].WasChanged = true;
                        MYREFERENCES.OBJECTDATA.Rows[index.RowIndex].WasChanged = true;

                        MYREFERENCES.CLIENTDATACHANGED = true;

                        //autosave start

                        if (MYREFERENCES.CustomConfiguration.Autosave.Enabled == true) {
                            if (Core.ArrayHelper.IndexOf(MYREFERENCES.CustomConfiguration.Autosave.ColumnsToAutosave, index.ColIndex) != -1) {
                                _Autosave_PerformAutosave();
                            }
                        }

                        //autosave end

                        //preventing the event bubbling.                        

                        var eventFired = (typeof (e) != "undefined") ? e : window.event;

                        if (eventFired && eventFired.stopPropagation) eventFired.stopPropagation();
                        else if (eventFired && eventFired.cancelBubble != undefined) eventFired.cancelBubble = true;
                        else return false;

                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _QuicklyRefresh() {
                try {
                    var t = MYREFERENCES.MAINTABLE;
                    if ((t) && (t.childNodes.length > 1)) {
                        var tb = t.childNodes[1];
                        if ((tb) && (tb.childNodes.length > 0) && ((tb.childNodes.length - 1) == MYREFERENCES.OBJECTDATA.Rows.length)) {
                            for (var index = 0; index < tb.childNodes.length - 1; index++) {
                                var tr = tb.childNodes[index];
                                if ((index + 1) % 2 == 1) tr.className = "odd";
                                else tr.className = "par";
                                var row = MYREFERENCES.OBJECTDATA.Rows[index];
                                for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                                    if (MYREFERENCES.OBJECTDATA.Columns[c].Type == "checkbox") {
                                        tr.childNodes[c].childNodes[0].checked = row[c].Checked;
                                        if (row[c].Checked) tr.className += "Selected";
                                    } else if (MYREFERENCES.OBJECTDATA.Columns[c].Type == "normal") tr.childNodes[c].innerHTML = row[c].Value;
                                }
                            }
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetAttributeValue(Name) {
                try {
                    if (MYREFERENCES.DATA.Attributes != null) for (var i = 0; i < MYREFERENCES.DATA.Attributes.length; i++) if (MYREFERENCES.DATA.Attributes[i].Name == Name) return MYREFERENCES.DATA.Attributes[i].Value;
                    return null;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetDataToExport(exportType) {
                try {
                    //Info.
                    var info = {}; // new PrivateParameters("", "Export");
                    info = PRIVATEPARAMETERS.Version;
                    info.Title = MYREFERENCES.WIDGETCONTAINER.GetTitle();
                    info.DatabaseParameters = PRIVATEPARAMETERS.DatabaseParameters;
                    if ((PRIVATEPARAMETERS.Export) && (PRIVATEPARAMETERS.Export.Source) && (PRIVATEPARAMETERS.Export.Source.toUpperCase() == "LOCALCURRENTVIEW")) {
                        if (exportType == "PDF") {
                            //Get out this if when IndustrialGrid has the GetChunckPDF working, leave Core.Json.Encode only
                            info.Data = {};
                            var json = {};
                            json.HTMLString = Core.Json.Encode(MYREFERENCES.DATA);
                            json.FullPath = "";
                            info.Data = Core.Json.Encode(json);
                        } else info.Data = Core.Json.Encode(MYREFERENCES.DATA);
                    }
                    else if ((PRIVATEPARAMETERS.Export) && (PRIVATEPARAMETERS.Export.Source) && (PRIVATEPARAMETERS.Export.Source.toUpperCase() == "SERVERCURRENTVIEW")) {
                        //Don´t do anything.
                    }
                    else if ((PRIVATEPARAMETERS.Export) && (PRIVATEPARAMETERS.Export.Source) && (PRIVATEPARAMETERS.Export.Source.toUpperCase() == "SENDALL")) {
                        for (var k = 0; k < info.DatabaseParameters.QueryParameters.length; k++) {
                            if (info.DatabaseParameters.QueryParameters[k].Name.toUpperCase() == "PAGESIZE") {
                                info.DatabaseParameters.QueryParameters[k].Value = 0;
                                break;
                            }
                        }
                    }
                    switch (exportType.toUpperCase()) {
                        case "EXCEL":
                            break;
                        case "PDF":
                            var attrib = {};
                            attrib.Orientation = "Portrait"; //Landscape
                            attrib.Type = "HTMLStruct";
                            info.Attributes = attrib;
                            break;
                    }
                    return info;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _DefaultPrint(ExportType) {
                try {
                    MYREFERENCES.EXPORTTYPE = ExportType;
                    switch (MYREFERENCES.EXPORTTYPE.toUpperCase()) {
                        case "EXCEL":
                            var d = new Date();
                            var outputFileName = (PRIVATEPARAMETERS.Export.OutputFileName) ? PRIVATEPARAMETERS.Export.OutputFileName : "Temp_" + d.getFullYear() + "-" + d.getMonth() + "-" + d.getDay() + " " + d.getHours() + "" + d.getMinutes();
                            if (outputFileName.match(".*(\.xls)") == null) outputFileName += ".xls";
                            var ExportOptions = { OutputFileName: outputFileName, ExportType: MYREFERENCES.EXPORTTYPE };
                            var exp = new Export(ExportOptions);
                            //var options = PRIVATEPARAMETERS; options.URL = "/IndustrialDashboard/DALService.svc/ExportTo"; options.FileName = outputFileName;                            
                            //_XlsWidget.SetContent(_GetDataToExport());
                            exp.AddWidget(MYREFERENCES.WIDGET);
                            //Send to export.
                            exp.SendData();
                            break;
                        case "PDF":
                            var d = new Date();
                            var outputFileName = (PRIVATEPARAMETERS.Export.OutputFileName) ? PRIVATEPARAMETERS.Export.OutputFileName : "Temp_" + d.getFullYear() + "-" + d.getMonth() + "-" + d.getDay() + " " + d.getHours() + "" + d.getMinutes();
                            if (outputFileName.match(".*(\.pdf)") == null) outputFileName += ".pdf";
                            var ExportOptions = { OutputFileName: outputFileName, ExportType: MYREFERENCES.EXPORTTYPE };
                            var exp = new Export(ExportOptions);
                            //var options = PRIVATEPARAMETERS; options.URL = "/IndustrialDashboard/DALService.svc/ExportTo"; options.FileName = outputFileName;                            
                            //_XlsWidget.SetContent(_GetDataToExport());
                            exp.AddWidget(MYREFERENCES.WIDGET);
                            //Send to export.
                            exp.SendData();
                            break;
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetComboxoData(procedure, elem) {
                try {
                    if (!MYREFERENCES.CMBGETTINGDATA) {
                        MYREFERENCES.CMBGETTINGDATA = true;
                        var pp = new PrivateParameters();
                        var url = PRIVATEPARAMETERS.URL + PRIVATEPARAMETERS.Method;
                        var options = {}; options.data = {};
                        pp.DatabaseParameters.ConnectionStringName = PRIVATEPARAMETERS.DatabaseParameters.ConnectionStringName;
                        pp.DatabaseParameters.Procedure = procedure;
                        options.data.DatabaseParameters = pp.DatabaseParameters;
                        options.Async = false;
                        options.onSuccess = function (requestData) {
                            if ((requestData) && (!requestData.Message) && (requestData.Table)) elem.Options = requestData.Table;
                            else elem.Options = [];
                            MYREFERENCES.CMBGETTINGDATA = false;
                        }
                        options.onFailure = function (message) {
                            MYREFERENCES.CMBGETTINGDATA = false;
                            elem.Options = [];
                        }
                        RequestJSON(url, options);
                    }

                } catch (Error) {
                    PRIVATEPARAMETERS.Events.onError(Error);
                    MYREFERENCES.CMBGETTINGDATA = false;
                }
            }
            function _GetRowsCount() {
                try {
                    if ((MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows)) return MYREFERENCES.OBJECTDATA.Rows.length;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                return 0;
            }
            function _GetColumnValue(columnName, rowIndex) {
                try {
                    if ((columnName != null) && (rowIndex >= 0) && (rowIndex < MYREFERENCES.OBJECTDATA.Rows.length)) {
                        for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                            if (MYREFERENCES.OBJECTDATA.Columns[c].Name == columnName) return MYREFERENCES.OBJECTDATA.Rows[rowIndex][c].Value;
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _CheckValue(elem, focusout) {
                try {
                    if (elem) {
                        var elem = _GetPrincipal(elem);
                        if ((elem) && (elem.ValueSelect)) {
                            var vs = elem.ValueSelect;
                            var oldValue = null;
                            var newValue = null;
                            var cell = MYREFERENCES.OBJECTDATA.Rows[vs.RowIndex][vs.ColIndex];
                            var row = MYREFERENCES.OBJECTDATA.Rows[vs.RowIndex];
                            if (_PerformCustomChecks(vs) == true) {
                                if (vs.CellValue.value) {
                                    var val = vs.CellValue.value;
                                    newValue = val;
                                    oldValue = cell.Value;
                                    cell.Value = val;
                                    vs.CellValue.value = cell.Value;
                                }
                                if (focusout == true) {
                                }
                                if (newValue != oldValue) {
                                    row.WasChanged = true;
                                    cell.WasChanged = true;
                                    MYREFERENCES.CLIENTDATACHANGED = true;
                                    PRIVATEPARAMETERS.Events.onChangeValue();

                                    //autosave start

                                    if (MYREFERENCES.CustomConfiguration.Autosave.Enabled == true) {
                                        if (Core.ArrayHelper.IndexOf(MYREFERENCES.CustomConfiguration.Autosave.ColumnsToAutosave, vs.ColIndex) != -1) {
                                            _Autosave_PerformAutosave();
                                        }
                                    }

                                    //autosave end
                                }
                            } else {
                                vs.CellValue.value = cell.Value;
                            }
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _PerformCustomChecks(cell) {
                try {
                    var ret = false;
                    var check_datatypes = _CheckDataTypes(cell);
                    var normal_checks = Core.Object.Validate(cell); 
                    
                    if (check_datatypes && normal_checks) {
                        ret = true; 
                    }

                    return ret; 
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _CheckDataTypes(cell) {
                try {
                    var ret = false;
                    var columnName = MYREFERENCES.OBJECTDATA.Columns[cell.ColIndex].Name;
                    var value = cell.CellValue.value;
                    if (Core.Object.Exist(MYREFERENCES.CustomConfiguration.DataTypeValidations, columnName)) {

                        var type = (Core.Object.Exist(MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName], 'Type')) ?
                                    MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName].Type : null;
                        var upper = (Core.Object.Exist(MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName], 'Upper')) ?
                                    MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName].Upper : null;
                        var lower = (Core.Object.Exist(MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName], 'Lower')) ?
                                    MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName].Lower : null;

                        if (type == "numeric") {
                            if (Core.Math.IsNumber(value) || value == "") {
                                ret = true;
                            } else {
                                ret = false;
                            }
                        } else if (type == "string") {
                            ret = true;
                        }

                        if ((value > lower || !lower) &&
                        (value < upper || !upper) && ret) {
                            ret = true;
                        } else {
                            ret = false;
                        }

                    } else {
                        ret = true;
                    }

                    if (ret == false) {
                        var message = (Core.Object.Exist(MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName], 'Message')) ? MYREFERENCES.CustomConfiguration.DataTypeValidations[columnName].Message : "Invalid value";
                        Core.Message.Alert.Show(message);
                    }

                    return ret;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Autosave_PerformAutosave(immediate, callback) {
                try {
                    if (MYREFERENCES.CustomConfiguration.Autosave.AutosaveTimeoutID) clearTimeout(MYREFERENCES.CustomConfiguration.Autosave.AutosaveTimeoutID);

                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.Autosave.Procedure')) {
                        MYREFERENCES.CustomConfiguration.Autosave.UnsavedChanges = true;
                        if (immediate == true) {
                            _SaveData({
                                CustomDataHandlerProcedure: PRIVATEPARAMETERS.Configuration.Autosave.Procedure
                                , CustomDataHandlerCallback: function () { _Autosave_OnComplete(callback); }
                            });
                        } else {
                            MYREFERENCES.CustomConfiguration.Autosave.AutosaveTimeoutID = setTimeout(function () {
                                _SaveData({
                                    CustomDataHandlerProcedure: PRIVATEPARAMETERS.Configuration.Autosave.Procedure
                                    , CustomDataHandlerCallback: function () { _Autosave_OnComplete(callback); }
                                });
                            }, MYREFERENCES.CustomConfiguration.Autosave.AutosaveTimeout);
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Autosave_OnComplete(callback) {
                try {
                    MYREFERENCES.CustomConfiguration.Autosave.UnsavedChanges = false;
                    if (callback instanceof Function) {
                        callback();
                    }
                } catch (Error) { }
            }
            function _Autosave_BeforeUnload() {
                try {
                    /*if (MYREFERENCES.CustomConfiguration.Autosave.UnsavedChanges == true) {
                    _Autosave_PerformAutosave(true);
                    if (MYREFERENCES.CustomConfiguration.Autosave.UnsavedChanges == true) {
                    return ("Some changes have not been saved. Do you want to leave the page and discard your changes?");
                    }
                    }*/
                    if (Core.Object.Exist(window, "_Autosave_BeforeUnloadAutosaveCallback")) {
                        callbackFunction = _Autosave_BeforeUnloadAutosaveCallback;
                    } else {
                        callbackFunction = null;
                    }
                    if (MYREFERENCES.CustomConfiguration.Autosave.UnsavedChanges == true) {
                        _Autosave_PerformAutosave(true, callbackFunction); //add parameter for a callback, send it to main report
                        //inform the user that the changes were saved. 
                        //Global.InfoBar.Show("Saving...");
                        return ("Some changes have not been saved. Do you want to leave the page and discard your changes?");
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Autosave_HasUnsavedChanges() {
                return MYREFERENCES.CustomConfiguration.Autosave.UnsavedChanges;
            }
            function _SetNewValue(value, row, col) {
                try {
                    var cell = MYREFERENCES.OBJECTDATA.Rows[row][col];
                    var changed = false;
                    if (cell.Object && cell.Object.innerHTML == cell.Value) {
                        cell.Object.innerHTML = value;
                        changed = true;
                    } else if (Core.Object.Eval(cell, 'Object.CellValue.value')) {
                        cell.Object.CellValue.value = value;
                        changed = true;
                    }
                    if (changed == true) {
                        cell.WasChanged = true;
                        cell.Value = value;
                        MYREFERENCES.OBJECTDATA.Rows[row].WasChanged = true;
                        MYREFERENCES.CLIENTDATACHANGED = true;
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Redraw(container, data, persistentData, extraParams) {
                try {
                    //MYREFERENCES.CLIENTDATACHANGED = false;
                    //var strNoAvalData = "<p style'font-family:Microsoft Sans Serif ;color:#808080;margin-left:5px;margin-top:10px;'>No available data</p>";
                    //if (((data == null) || (data.Columns == undefined) || (data.Columns == 0)) && persistentData != true) {
                    //    container.innerHTML = strNoAvalData;
                    //    return;
                    //}

                    if (!persistentData) MYREFERENCES.DATA = data;
                    else data = MYREFERENCES.DATA;

                    var cols = data.Columns | data.Fields;
                    var matrix = data.Matrix;

                    if (!persistentData) MYREFERENCES.OBJECTDATA = _ConvertMatrixToObjectData(cols, matrix, data.Metadata);

                    //looking for autosave columns
                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Configuration.Autosave.ColumnsToAutosave') && MYREFERENCES.CustomConfiguration.Autosave.Enabled == true) {
                        MYREFERENCES.CustomConfiguration.Autosave.ColumnsToAutosave = _getColumnsFromArray(PRIVATEPARAMETERS.Configuration.Autosave.ColumnsToAutosave);
                    }
                    //checking for data type validations
                    _ConfigureCustomDataTypeValidations();                    

                    var HasMetaData = false;

                    var colFormat = null;

                    if ((Core.Object.Eval(extraParams, 'redrawHeaders') &&
                     extraParams.redrawHeaders != false) || !(Core.Object.Eval(extraParams, 'redrawHeaders'))) {

                        Core.Object.RemoveAllChildNodes(container);

                        //if ((MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows.length == 0)) {
                        //    container.innerHTML = strNoAvalData;
                        //    return;
                        //}
                        //else container.style.display = "";
                        container.style.display = "";
                        if (PRIVATEPARAMETERS.Data.Paging) {
                            if ((data) && (data.Attributes) && (data.Attributes["TotalRows"] != undefined))
                                MYREFERENCES.WIDGETCONTAINER.SetTotalRows(data.Attributes.TotalRows);
                            else MYREFERENCES.WIDGETCONTAINER.SetTotalRows(0);
                        }
                        var table = document.createElement("table");
                        MYREFERENCES.MAINTABLE = table;
                        table.className = "Grid";
                        container.appendChild(table);
                        table.cellPadding = "0";
                        table.cellSpacing = "0";
                        thead = document.createElement("thead");
                        table.appendChild(thead);
                        tbody = document.createElement("tbody");
                        table.appendChild(tbody);
                        trMainHead = document.createElement("tr");
                        thead.appendChild(trMainHead);
                        trSecHead = document.createElement("tr");
                        thead.appendChild(trSecHead);
                        var textValue; var c; var rCols = 0;
                        var firstCellcolspan = null; //firstcell colspan
                        colFormat = new Array(cols);
                        var colIndex = 0;
                        var tdCmbRef = null;
                        var c;
                        for (c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                            var column = MYREFERENCES.OBJECTDATA.Columns[c];
                            if (column.Type == "checkbox") {
                                tdCmbRef = document.createElement("td");
                                tdCmbRef.colIndex = c;
                                tdCmbRef.className = "CellHeader"
                                                + ((c != 1)
                                                    ? " CellHeaderBorder"
                                                    : "");
                                if (PRIVATEPARAMETERS.Data.CheckedColumn.Title) {
                                    tdCmbRef.innerHTML = PRIVATEPARAMETERS.Data.CheckedColumn.Title;
                                } else {
                                    var chk = document.createElement("input");
                                    chk.type = "checkbox";
                                    //chk.id = "MYREFERENCES.CHKMAIN";
                                    tdCmbRef.appendChild(chk);
                                    MYREFERENCES.CHKMAIN = chk;
                                    Core.Events.Add(chk, "click", _SelectAllRows);
                                }
                                trMainHead.appendChild(tdCmbRef);
                            } else if (column.Type == "normal") {
                                colFormat[c] = {};  // object that holds metathis.data for each column
                                var tvs;
                                var textValue = column.Name;
                                colFormat[c].columnName = textValue;
                                if (column.Attributes) {
                                    for (k = 0; k < column.Attributes.length; k++) {
                                        tvs = MYREFERENCES.OBJECTDATA.Columns[c].Attributes[k];
                                        if (tvs.indexOf("ns") != -1) colFormat[c].noShow = true;  // !ns indicates NO SHOW: don"data show the column
                                        if (tvs.indexOf("he") != -1) colFormat[c].isHeader = true;  // !he indicates header: show it with header style
                                        if (tvs.indexOf("rs") != -1) colFormat[c].rowSpan = true;  // !rs indicates ROWSPAN: join together cells with same values
                                        if (tvs.indexOf("ac") != -1) colFormat[c].alignCenter = true; // !ac indicates ALIGN CENTER
                                        if (tvs.indexOf("al") != -1) colFormat[c].alignLeft = true; // !al indicates ALIGN LEFT
                                        if (tvs.indexOf("ar") != -1) colFormat[c].alignRight = true; // !al indicates ALIGN Right
                                        if (tvs.indexOf("ne") != -1) colFormat[c].NotEditable = true; // !ne not editable
                                        if (tvs.indexOf("id") != -1) colFormat[c].isID = true;
                                        if (tvs.indexOf("colorpicker") != -1) {
                                            column.ColorPicker = {};
                                        }
                                        if (tvs.indexOf("ckb") != -1) {
                                            //colFormat[c].checkbox = true;
                                            column.CheckBox = {};
                                        }
                                        if (tvs.indexOf("cmb") != -1) {
                                            //colFormat[c].combobox = true;
                                            column.ComboBox = {};
                                            column.ComboBox.Procedure = tvs.split(":")[1];
                                            _GetComboxoData(column.ComboBox.Procedure, column.ComboBox);
                                            column.ComboBoxObject = { DOMObject: null, Object: null };
                                            _constructGlobalSelectDDP(column.ComboBox, column.ComboBoxObject);
                                        }
                                        if (tvs.indexOf("vs") != -1) {
                                            //colFormat[c].valueSelect = true;
                                            column.ValueSelect = true;
                                        }
                                        if (tvs.indexOf("wd") != -1) {
                                            colFormat[c].width = tvs.substring(tvs.indexOf("wd") + 3, tvs.length)
                                            if (colFormat[c].width.indexOf("px") == -1) if (colFormat[c].width.indexOf("%") == -1) colFormat[c].width += "px";
                                        }
                                        //if (tvs.indexOf("bck") != -1) colFormat[c].backgroundColor = tvs.substring(tvs.indexOf("bck") + 3, tvs.length);
                                        if (tvs.indexOf("RowAttributes") != -1) colFormat[c].Attributes = true;
                                        if (tvs.indexOf("Special") != -1) colFormat[c].Special = true;
                                        if (tvs.indexOf("color") != -1 && tvs.indexOf("colorpicker") == -1) colFormat[c].color = tvs.substring(tvs.indexOf("color") + 5, 12);
                                        else colFormat[c].colSpan = false;
                                        if (tvs.indexOf("mn") != -1) colFormat[c].mappingName = tvs.split(":")[1]; // !mn column mapping name
                                    }
                                }
                                if (colFormat[c].noShow) continue; // does not print !ns columns (ns = no show)
                                rCols++;
                                if (textValue.indexOf("@") == -1) {
                                    td = document.createElement("td");
                                    td.className = "CellHeader"
                                                + ((c != 1)
                                                    ? " CellHeaderBorder"
                                                    : "");
                                    trMainHead.appendChild(td);
                                    if (colFormat[c].fixedWidth) td.style.width = colFormat[c].fixedWidth + "%"
                                    td.rowSpan = 2;
                                    td.innerHTML = textValue;
                                    colFormat[c].headerPointerTop = td;
                                    colFormat[c].headerPointer = td;
                                    if (tdCmbRef != null) tdCmbRef.rowSpan = 2;
                                } else {
                                    td = document.createElement("td");
                                    td.className = "CellHeader"
                                                + ((c != 1)
                                                    ? " CellHeaderBorder"
                                                    : "");
                                    td.innerHTML = textValue.substring(0, textValue.indexOf("@"));
                                    if (firstCellcolspan != null && firstCellcolspan.innerHTML == td.innerHTML) firstCellcolspan.colSpan += 1;
                                    else {
                                        firstCellcolspan = td;
                                        firstCellcolspan.colSpan = 1;
                                        trMainHead.appendChild(td);
                                    }
                                    colFormat[c].headerPointerTop = td;
                                    td = document.createElement("td");
                                    td.className = "CellHeader"
                                                + ((c != 1)
                                                    ? " CellHeaderBorder"
                                                    : "");
                                    trSecHead.appendChild(td);
                                    td.innerHTML = textValue.substring(textValue.indexOf("@") + 1);
                                    colFormat[c].headerPointer = td;
                                }
                                td.colIndex = c;

                                if (MYREFERENCES.CustomConfiguration.ColumnHelpers[textValue]) {
                                    var tdColHelper = document.createElement('div');
                                    tdColHelper.className = "tdColHelper";
                                    tdColHelper.title = MYREFERENCES.CustomConfiguration.ColumnHelpers[textValue].Message;
                                    td.appendChild(tdColHelper);
                                }

                                if ((PRIVATEPARAMETERS.Data.SortColumn)) {// && ((PRIVATEPARAMETERS.Data.Paging == null) || (PRIVATEPARAMETERS.Data.Paging.PageSize == 0))) {
                                    //td.style.background ="red";
                                    Core.Events.Add(td, "click", _SortRows);
                                    td.style.cursor = "pointer";
                                    var divSorting = document.createElement("div");
                                    divSorting.className = "sortingContainer";
                                    td.appendChild(divSorting);
                                    if ((data.OrderBy != null) && (data.OrderBy != undefined)) {
                                        if (data.OrderBy.indexOf(column.Name) > -1) {
                                            if (data.OrderBy.indexOf("asc") > -1) {
                                                divSorting.className = "sortingContainerAsc";
                                            } else if (data.OrderBy.indexOf("desc") > -1) {
                                                divSorting.className = "sortingContainerDesc";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        var currentClass = "par";

                        if (Core.Object.Eval(PRIVATEPARAMETERS, 'View.RowHover') && PRIVATEPARAMETERS.View.RowHover == true)
                            currentClass = "par mouseHover";

                        MYREFERENCES.DRAW.COLFORMAT = colFormat;
                    }

                    if (!colFormat) colFormat = MYREFERENCES.DRAW.COLFORMAT;

                    var fromRow = 0, rowsToDraw = (!MYREFERENCES.CustomConfiguration.InfiniteScroll.rowsToDraw) ? MYREFERENCES.OBJECTDATA.Rows.length : MYREFERENCES.CustomConfiguration.InfiniteScroll.rowsToDraw;

                    if (Core.Object.Eval(extraParams, 'fromRow'))
                        fromRow = extraParams.fromRow;

                    if (Core.Object.Eval(extraParams, 'rowsToDraw'))
                        rowsToDraw = (extraParams.rowsToDraw == -1) ? MYREFERENCES.OBJECTDATA.Rows.length : extraParams.rowsToDraw;

                    var objectData = (Core.Object.Eval(extraParams, 'CustomObjectData')) ? extraParams.CustomObjectData : MYREFERENCES.OBJECTDATA;

                    var tr;
                    var r;
                    for (r = fromRow; r < objectData.Rows.length && r < (rowsToDraw + fromRow); r++) {

                        tr = document.createElement("tr");

                        tr.IsPrincipalRow = true;
                        tr.Index = r;
                        var hasFooter = false; var firstPar = true;
                        var firstColumnAdded = false;

                        if (Core.Object.Eval(extraParams, 'AddOnTopOf')) {
                            var reference = extraParams.AddOnTopOf;
                            tbody.insertBefore(tr, reference);
                        } else {
                            tbody.appendChild(tr);
                        }

                        tr.id = r;
                        var hlinkCtr = 0; // header counter and to prevent from reading the entire row
                        var rowValue;

                        objectData.Rows[r].WasChanged = (objectData.Rows[r].WasChanged) ? objectData.Rows[r].WasChanged : false;
                        objectData.Rows[r].Display = (Core.Object.Eval(objectData.Rows[r], 'Display')) ? objectData.Rows[r].Display : true;
                        objectData.Rows[r].Object = tr;


                        tr.className = currentClass;
                        for (c = 0; c < objectData.Columns.length; c++) {
                            if ((objectData.Rows[r].Display == true && MYREFERENCES.CustomConfiguration.Search.Enabled == true)
                            || (MYREFERENCES.CustomConfiguration.Search.Enabled == false)
                            ) {
                                if (colFormat[c].isID != null && colFormat[c].isID != undefined) objectData.Rows[r].IDColumn = c;
                                var td = document.createElement("td");
                                //                            td.style.borderTop = borderStyle;
                                td.className = "Cell";
                                if (r != 0) td.className += " CellBorderTop";
                                if (firstColumnAdded == true) td.className += " CellBorderLeft";
                                if (!colFormat[c].noShow) firstColumnAdded = true;
                                td.IsPrincipalColumn = true;
                                td.ColumnIndex = c;
                                td.ColIndex = c;
                                objectData.Rows[r][c].Object = td;
                                objectData.Rows[r][c].WasChanged = (objectData.Rows[r][c].WasChanged) ? objectData.Rows[r][c].WasChanged : false;
                                //if (c < 2) td.style.background = "#FFFFFF";
                                var rowValue = null;
                                var row = objectData.Rows[r];
                                var cell = row[c];
                                var select = null;
                                var spanSelect = null;
                                var selectDDP = null;
                                var checkbox = null;
                                var isColorPicker = null;
                                var checkboxCKX = null;
                                var comboBox = null;
                                var valueSelect = null;
                                var tempValue = parseInt((cell.Value == null) ? 0 : cell.Value, 10);
                                var markError = false;
                                if (!MYREFERENCES.ReadOnly) {
                                    if (objectData.Columns[c].CheckBox) {
                                        //create checkbox
                                        checkbox = objectData.Columns[c].CheckBox;
                                        checkboxCKX = document.createElement("input");
                                        checkboxCKX.type = "checkbox";
                                        checkboxCKX.className = "ckb";
                                        //checkboxCKX.onchange = _CmbChange;
                                        window.Core.Events.Add(checkboxCKX, "click", _CheckboxClicked);
                                        Core.Events.Add(checkboxCKX, "keyup", function (e) {
                                            var evt = (typeof (e) != "undefined") ? e : window.event;
                                            var target = (evt.target) ? evt.target : evt.srcElement;
                                            if (target) {
                                                var kc = evt.keyCode || evt.which;
                                                switch (kc) {
                                                    //case 13:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
                                                    //    evt.className = "InputValue";                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
                                                    //    break;   

                                                    case 13: //enter key
                                                        var inputs = table.getElementsByTagName('input');
                                                        var nextInput = null;
                                                        for (var x = 1; x < inputs.length - 1; x++) {
                                                            var index = Core.ArrayHelper.IndexOf(inputs, target);

                                                            if (index != null && index != undefined && ((index + x) < inputs.length))
                                                                nextInput = inputs[Core.ArrayHelper.IndexOf(inputs, target) + x];

                                                            if (nextInput && !nextInput.disabled && !Core.Object.Exist(nextInput, 'ColorPicker'))
                                                                break;
                                                            else
                                                                nextInput = null;
                                                        }

                                                        if (Core.Object.Validate(nextInput))
                                                            nextInput.focus();

                                                        break;
                                                    case 38: //keyUp

                                                        break;
                                                    case 40: //keyDown
                                                        break;
                                                    case 9: //tab  
                                                        //check focus   
                                                    case 16:
                                                        break;
                                                    default:
                                                        //                                                    _CheckValue(target);
                                                        //                                                    _UpdateHotLengthAndWeightIfIsNecessary(target);
                                                        break;
                                                }
                                            }
                                        });
                                        checkboxCKX.IsPrincipal = true;
                                        checkboxCKX.ColumnIndex = c;
                                        checkboxCKX.ColIndex = c;
                                        checkboxCKX.Checkbox = { RowIndex: r, ColIndex: c };
                                        td.appendChild(checkboxCKX);
                                        objectData.Rows[r][c].Object = checkboxCKX;
                                        cell.Value = (cell.Value == "1") ? cell.Value : "0";
                                    } else if (objectData.Columns[c].ColorPicker) {
                                        var colorpicker = objectData.Columns[c].ColorPicker;
                                        isColorPicker = true;
                                        var cpicker = document.createElement('input');
                                        cpicker.type = "button";
                                        cpicker.style.border = "1px solid #ccc";
                                        cpicker.style.width = "50px";
                                        cpicker.style.height = "20px";
                                        cpicker.ColorPicker = { RowIndex: r, ColIndex: c };
                                        cpicker.style.styleFloat = "left";
                                        objectData.Rows[r][c].Object = new jscolor.color(cpicker, { valueElement: 'null' });
                                        Core.Events.Add(cpicker, 'onblur', ColorPicker_Blur);
                                        td.appendChild(cpicker);
                                    } else if (objectData.Columns[c].ComboBox) {
                                        //create combobox
                                        comboBox = objectData.Columns[c].ComboBox;
                                        select = document.createElement("div");
                                        select.className = "cmb";
                                        spanSelect = document.createElement('span');
                                        spanSelect.className = "spanSelect";
                                        spanSelect.innerHTML = row[c].Value;
                                        select.span = spanSelect;
                                        select.appendChild(spanSelect);
                                        Core.Events.Add(spanSelect, "onclick", _showSelectDDP);
                                        selectDDP = new window.DropDownPicker(
                                        select
                                        , {
                                            ItemsDefaultBackgroundColors: {
                                                MouseOver: MYREFERENCES.DropDownItemMouseOverBGColor
                                                , Selected: MYREFERENCES.DropDownItemSelectedBGColor
                                            }
                                            //Events: { SelectedChanged: [_CmbChange] } 
                                            , ItemPickerType: window.DropDownType
                                        }
                                    );
                                        //select.style.border = "0px solid white";
                                        for (var selIndex = 0; selIndex < comboBox.Options.length; selIndex++) {
                                            selectDDP.AddContent(
                                            new window.ItemPicker.ItemData(comboBox.Options[selIndex].ID, comboBox.Options[selIndex].Value)
                                            , null
                                            , {
                                                //                                                BackgroundColorMouseOver: MYREFERENCES.DropDownItemMouseOverBGColor
                                                //                                                , BackgroundColorSelected: MYREFERENCES.DropDownItemSelectedBGColor
                                            }
                                        );

                                            //                                        var opt = document.createElement("option");
                                            //                                        opt.className = "opt";
                                            //                                        opt.innerHTML = comboBox.Options[selIndex].Value;
                                            //                                        opt.value = comboBox.Options[selIndex].ID;
                                            //                                        select.appendChild(opt);
                                        }
                                        //select.onchange = _CmbChange;
                                        //                                    Core.Events.Add(select, "change", _CmbChange;)
                                        select.IsPrincipal = true;
                                        select.ColumnIndex = c;
                                        select.ColIndex = c;
                                        select.ComboBox = { RowIndex: r, ColIndex: c };
                                        td.appendChild(select);
                                        objectData.Rows[r][c].Object = select;
                                    } else if (objectData.Columns[c].ValueSelect) {
                                        valueSelect = {};
                                        valueSelect.RowIndex = r;
                                        valueSelect.ColIndex = c;
                                        var divContainer = document.createElement("div");
                                        divContainer.className = "ValueSelectContainer";
                                        divContainer.ValueSelect = valueSelect;
                                        divContainer.IsPrincipal = true;
                                        divContainer.ColumnIndex = c;
                                        divContainer.ColIndex = c;
                                        td.appendChild(divContainer);

                                        CellValue = document.createElement("input");
                                        CellValue.RowIndex = r;
                                        CellValue.ColIndex = c;
                                        CellValue.className = "InputValue";
                                        if (colFormat[c].alignCenter == true) CellValue.style.textAlign = "center";
                                        if (colFormat[c].alignLeft == true) CellValue.style.textAlign = "left";
                                        if (colFormat[c].alignRight == true) CellValue.style.textAlign = "right";
                                        Core.Events.Add(CellValue, "click", function (e) {
                                            var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                                            if (target) {
                                                target.className = "InputValue_selected";
                                                if (target.ColIndex && target.RowIndex) MYREFERENCES.OBJECTDATA.Rows[target.RowIndex][target.ColIndex].WasChanged = true;
                                                MYREFERENCES.CLIENTDATABEINGCHANGED = true;
                                            }
                                        });
                                        Core.Events.Add(CellValue, "focus", function (e) {
                                            var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                                            if (target) {
                                                target.className = "InputValue_selected";
                                                if (target.ColIndex && target.RowIndex) MYREFERENCES.OBJECTDATA.Rows[target.RowIndex][target.ColIndex].WasChanged = true;
                                                MYREFERENCES.CLIENTDATABEINGCHANGED = true;
                                                return false;
                                            }
                                        });
                                        Core.Events.Add(CellValue, "blur", function (e) {
                                            var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                                            if (target) {
                                                target.className = "InputValue";
                                                _CheckValue(target, true);
                                                MYREFERENCES.CLIENTDATABEINGCHANGED = false;
                                            }
                                        });
                                        Core.Events.Add(CellValue, "focusout", function (e) {
                                            var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                                            if (target) {
                                                target.className = "InputValue";
                                                _CheckValue(target, true);
                                                MYREFERENCES.CLIENTDATABEINGCHANGED = false;
                                            }
                                        });
                                        Core.Events.Add(CellValue, "keyup", function (e) {
                                            var evt = (typeof (e) != "undefined") ? e : window.event;
                                            var target = (evt.target) ? evt.target : evt.srcElement;
                                            if (target) {
                                                var kc = evt.keyCode || evt.which;
                                                switch (kc) {
                                                    //case 13:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                                                    //    evt.className = "InputValue";                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                                                    //    break;    
                                                    case 13: //enter key
                                                        var inputs = table.getElementsByTagName('input');
                                                        var nextInput = null;
                                                        for (var x = 1; x < inputs.length - 1; x++) {
                                                            var index = Core.ArrayHelper.IndexOf(inputs, target);

                                                            if (index != null && index != undefined && ((index + x) < inputs.length))
                                                                nextInput = inputs[Core.ArrayHelper.IndexOf(inputs, target) + x];

                                                            if (nextInput && !nextInput.disabled && !Core.Object.Exist(nextInput, 'ColorPicker'))
                                                                break;
                                                            else
                                                                nextInput = null;
                                                        }

                                                        if (Core.Object.Validate(nextInput))
                                                            nextInput.focus();

                                                        break;
                                                    case 38: //keyUp
                                                        //                                                    _Up(target);
                                                        //                                                    _UpdateHotLengthAndWeightIfIsNecessary(target);
                                                        PRIVATEPARAMETERS.Events.onChangeValue();
                                                        break;
                                                    case 40: //keyDown
                                                        //                                                    _Down(target);
                                                        //                                                    _UpdateHotLengthAndWeightIfIsNecessary(target);
                                                        PRIVATEPARAMETERS.Events.onChangeValue();
                                                        break;
                                                    case 9: //tab  
                                                        //check focus   
                                                        if (MYREFERENCES.PreviousSelectedRow != null)
                                                            MYREFERENCES.PreviousSelectedRow.className = MYREFERENCES.PreviousSelectedRow.className.replace("Selected", "");
                                                        MYREFERENCES.PreviousSelectedRow = null;
                                                    case 16:
                                                        break;
                                                    default:
                                                        //                                                    _CheckValue(target);
                                                        //                                                    _UpdateHotLengthAndWeightIfIsNecessary(target);
                                                        break;
                                                }
                                            }
                                        });
                                        divContainer.appendChild(CellValue);
                                        valueSelect.CellValue = CellValue;
                                        objectData.Rows[r][c].Object = valueSelect;
                                    } else if (objectData.Columns[c].NotEditable) {
                                        td.style.background = "#F1F2F4";
                                    }
                                }
                                if (cell.Type == "checkbox") { //this is not being used.
                                    td = document.createElement("td");
                                    td.columnType = "chk";
                                    var chk = document.createElement("input");
                                    chk.type = "checkbox";
                                    chk.Index = r;
                                    chk.id = "chk_" + r;
                                    Core.Events.Add(chk, "click", _CheckboxClicked);
                                    objectData.Rows[r][c].Object = chk;
                                    td.appendChild(chk);
                                    tr.appendChild(td);
                                } else if (cell.Type == "normal") {
                                    rowValue = row[c].Value;
                                    if ((comboBox) && (rowValue != null) && (select) && (!MYREFERENCES.ReadOnly)) {
                                        //if (colFormat[c].rowSpan && colFormat[c].fcrs != undefined) colFormat[c].fcrs.className += " nohover";
                                        for (var selIndex = 0; selIndex < comboBox.Options.length; selIndex++) {
                                            if (comboBox.Options[selIndex].Value == rowValue) {
                                                select.selectedIndex = selIndex;
                                                objectData.Rows[r][c].Index = comboBox.Options[selIndex].ID;
                                                objectData.Rows[r][c].Object = select;
                                                break;
                                            }
                                        }
                                    } else if ((rowValue != null) && (checkbox != null)) checkboxCKX.checked = (rowValue && rowValue == 1) ? true : false;
                                    else if ((rowValue != null) && (valueSelect != null)) _ParseCellValue(valueSelect,rowValue);
                                    else if ((rowValue != null) && (isColorPicker == true)) objectData.Rows[r][c].Object.fromString(rowValue);
                                    else if (rowValue != null) _ParseCellValue(td, rowValue); // if it is not undefined/null set the value
                                    else td.innerHTML = "&nbsp;"
                                    if (colFormat[c].width) td.style.width = colFormat[c].width;
                                    if (colFormat[c].alignCenter || !IsNumber(rowValue)) td.style.textAlign = "center";
                                    if (colFormat[c].alignLeft) td.style.textAlign = "left";
                                    if (colFormat[c].alignRight) td.style.textAlign = "right";
                                    if (colFormat[c].isHeader) td.className += " header";
                                    else td.className += " normal";
                                    if (markError) td.className += " error";
                                    td.originalClassName = td.className;
                                    if (colFormat[c].color) td.style.backgroundColor = colFormat[c].color;
                                    if (colFormat[c].Attributes)
                                        _ApplyAttributes(matrix[(r + 1) * cols + c], tr, td);
                                    if (colFormat[c].Special) {
                                        var item = {};
                                        item.elem = td;
                                        item.value = td.innerHTML;
                                        td.innerHTML = "";
                                        if (MYREFERENCES.SPECIALCOLUMNS[objectData.Columns[c].Name] == undefined) MYREFERENCES.SPECIALCOLUMNS[objectData.Columns[c].Name] = [];
                                        MYREFERENCES.SPECIALCOLUMNS[objectData.Columns[c].Name].push(item);
                                    }
                                    /* Check if the cell has some MYREFERENCES.DATA.Metadata value*/

                                    if (MYREFERENCES.DATA.Metadata && MYREFERENCES.DATA.Metadata[r] && MYREFERENCES.DATA.Metadata[r][colFormat[c].columnName] && MYREFERENCES.DATA.Metadata[r][colFormat[c].columnName] != "") {
                                        var s = MYREFERENCES.DATA.Metadata[r][colFormat[c].columnName];
                                        var aq;
                                        try { aq = s.split("!"); }
                                        catch (ex) { }
                                        if (aq) td.className += " " + aq[0];  // set the classnames (Errors, Process Problems or Warnings)
                                        if (aq && aq.length > 1) td.title = aq[1];    // set the tooltip text if any
                                        if (aq && aq[0] == "E") td.innerHTML += "*";
                                        HasMetaData = true;
                                    }
                                    if (colFormat[c].rowSpan && colFormat[c].fcrs != undefined) colFormat[c].fcrs.className += " nohover"; //check column name                                                     
                                    if ((colFormat[c].rowSpan && colFormat[c].fcrs != undefined && colFormat[c].fcrs.innerHTML == td.innerHTML) && (previousStrand == objectData.Rows[r][0].Value)) {
                                        colFormat[c].fcrs.rowSpan += 1; //check column name                                   
                                    } else if (colFormat[c].noShow) { /* do not add the cell */ }
                                    else if (colFormat[c].colSpan && hasFooter) { /*do not add the cell footer*/ }
                                    else {
                                        colFormat[c].fcrs = td;
                                        tr.appendChild(td);
                                        /* set counter to the number of colspan */
                                        if ((hasFooter) && (td.colSpan > 1)) c = td.colSpan;
                                    }
                                }
                            }
                            tr.style.cursor = "pointer";
                            Events.Add(tr, "onclick", _RowClick);
                            Events.Add(tr, "onmouseout", _Rowmouseout);
                            previousStrand = objectData.Rows[r][0].Value;
                        }
                    }

                    MYREFERENCES.DRAW.LastRowDrawn = r;

                    if (Core.Object.Eval(extraParams, 'ReturnObjectData') && extraParams.ReturnObjectData == true)
                        return objectData;

                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _ParseCellValue(cell, value) {
                try {
                    var valueSplit = value.split("[!");
                    var valueToParse = null;

                    if (Core.Object.Eval(cell, 'CellValue.value')) cell.CellValue.value = valueSplit[0];
                    else if (Core.Object.Eval(cell, 'innerHTML')) cell.innerHTML = valueSplit[0];

                    for (var x = 0; x < valueSplit.length; x++) {
                        valueToParse = valueSplit[x];
                        valueToParse = valueToParse.replace("]", "");
                        if (valueToParse.indexOf("loadingIcon") != -1) {
                            if (Core.Object.Eval(cell, 'innerHTML')) {
                                var loadingIcon = document.createElement('div');
                                loadingIcon.className = "cell-loading-icon";
                                cell.appendChild(loadingIcon); 
                            }
                        }
                        if (valueToParse.indexOf("fontColor") != -1) {
                            valueToParse = valueToParse.split(":");
                            if (valueToParse[1]) {
                                if (Core.Object.Eval(cell, 'CellValue.value')) cell.CellValue.style.color = valueToParse[1];
                                if (Core.Object.Eval(cell, 'innerHTML')) cell.style.color = valueToParse[1];
                            }
                        }
                    }
                    
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _MergeDatasetWithCurrentObjectData(newData) {
                try {
                    var c = 0;
                    var r = 0;
                    var row;
                    var oldRowPos = null;
                    for (r = 0; r < newData.Rows.length; r++) {
                        row = newData.Rows[r];
                        oldRowPos = _searchByColumnIDOnCurrentObjectData(row[0].Value);
                        if (oldRowPos != null) {
                            for (c = 0; c < newData.Columns.length; c++) {
                                if (MYREFERENCES.OBJECTDATA.Rows[r][c].WasChanged) {
                                    row[c].Value = MYREFERENCES.OBJECTDATA.Rows[r][c].Value;
                                    row[c].WasChanged = MYREFERENCES.OBJECTDATA.Rows[r][c].WasChanged;
                                }
                            }
                        }
                    }
                    return newData;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _searchByColumnIDOnCurrentObjectData(val) {
                try {
                    var ret = null;
                    for (r = 0; r < MYREFERENCES.OBJECTDATA.Rows.length; r++) {
                        if (MYREFERENCES.OBJECTDATA.Rows[r][0].Value == val) {
                            ret = r;
                            return ret;
                        }
                    }
                    return ret;
                } catch (Error) { }
            }
            function _searchByColumnIDOnNewObjectData(newdata, val) {
                try {
                    var ret = null;
                    for (r = 0; r < newdata.Rows.length; r++) {
                        if (newdata.Rows[r][0].Value == val) {
                            ret = r;
                            return ret;
                        }
                    }
                    return ret;
                } catch (Error) { }
            }
            function _differentialRefresh(newData) {
                try {
                    var c = 0;
                    var r = 0;
                    var row;
                    var oldRowPos = null;
                    var rowsToInsert = { Rows: [], Columns: MYREFERENCES.OBJECTDATA.Columns };
                    for (r = 0; r < newData.Rows.length; r++) {
                        row = newData.Rows[r];
                        oldRowPos = _searchByColumnIDOnCurrentObjectData(row[0].Value);
                        if (oldRowPos != null) {
                            for (c = 0; c < newData.Columns.length; c++) {
                                if (!MYREFERENCES.OBJECTDATA.Rows[oldRowPos][c].WasChanged) {
                                    _differentialRefresh_update(MYREFERENCES.OBJECTDATA.Rows[oldRowPos][c], row[c]);
                                } else {
                                    if (MYREFERENCES.OBJECTDATA.Rows[oldRowPos][c].Value == row[c].Value)
                                        MYREFERENCES.OBJECTDATA.Rows[oldRowPos][c].WasChanged = false;
                                }
                            }
                        } else {
                            rowsToInsert.Rows.push(row);
                        }
                    }
                    if (newData.Rows.length != MYREFERENCES.OBJECTDATA.Rows.length) {
                        var arrRowsDeleted = [];
                        for (r = 0; r < MYREFERENCES.OBJECTDATA.Rows.length; r++) {
                            row = MYREFERENCES.OBJECTDATA.Rows[r];
                            oldRowPos = _searchByColumnIDOnNewObjectData(newData, row[0].Value);
                            if (oldRowPos == null) {
                                if (row.Object) {
                                    MYREFERENCES.MAINTABLE.tBodies[0].removeChild(row.Object);
                                    arrRowsDeleted.push(row[0].Value);
                                }
                            }
                        }
                        for (var x = 0; x < arrRowsDeleted.length; x++) {
                            var indexToDelete = _searchByColumnIDOnCurrentObjectData(arrRowsDeleted[x]);
                            MYREFERENCES.OBJECTDATA.Rows.splice(indexToDelete, 1);
                        }
                    }

                    if (rowsToInsert.Rows.length > 0)
                        _differentialRefresh_insert(rowsToInsert);

                    _differentialRefresh_refreshIndexes();
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _differentialRefresh_insert(objectData) {
                try {
                    _Redraw(PRIVATEPARAMETERS.Container, null, true, { fromRow: 0, rowsToDraw: objectData.Rows.length, redrawHeaders: false, CustomObjectData: objectData, ReturnObjectData: true
                    , AddOnTopOf: (Core.Object.Eval(MYREFERENCES.OBJECTDATA, 'Rows.0.Object')) ? MYREFERENCES.OBJECTDATA.Rows[0].Object : null
                    });
                    MYREFERENCES.OBJECTDATA.Rows = objectData.Rows.concat(MYREFERENCES.OBJECTDATA.Rows);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _differentialRefresh_refreshIndexes() {
                try {
                    //when refreshing OBJECTDATA data, indexes tend to change cause of insertions or deletions.
                    //individual cell index need to be refreshed 
                    //also the last raw drawn used for infinite scrolling
                    var row;
                    var rowsDrawn = 0;
                    for (var r = 0; r < MYREFERENCES.OBJECTDATA.Rows.length; r++) {
                        row = MYREFERENCES.OBJECTDATA.Rows[r];
                        if (Core.Object.Eval(row, 'Object')) {
                            for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                                if (Core.Object.Eval(row[c].Object, 'ColumnIndex') &&
                                    Core.Object.Eval(row[c].Object, 'ColIndex')) {
                                    if (Core.Object.Eval(row[c].Object, 'Checkbox')) {
                                        row[c].Object.Checkbox.RowIndex = r;
                                    }
                                }
                                if (Core.Object.Eval(row[c].Object, 'CellValue')) {
                                    row[c].Object.RowIndex = r;
                                    row[c].Object.CellValue.RowIndex = r;
                                }
                            }
                            //if the Object property is available, it means that
                            //the row is drawn
                            rowsDrawn++;
                        }
                    }
                    if (MYREFERENCES.CustomConfiguration.InfiniteScroll.rowsToDraw) {
                        MYREFERENCES.DRAW.LastRowDrawn = rowsDrawn;
                    }
                } catch (Error) {
                }
            }
            function _differentialRefresh_update(cell, newcellDataObject) {
                try {
                    var changed = false;
                    if (cell.Value != newcellDataObject.Value) {
                        if (cell.Object && cell.Object.innerHTML == cell.Value) {
                            cell.Object.innerHTML = newcellDataObject.Value;
                            changed = true;
                        } else if (Core.Object.Eval(cell, 'Object.CellValue.value')) {
                            cell.Object.CellValue.value = newcellDataObject.Value;
                            changed = true;
                        }
                        if (changed)
                            cell.Value = newcellDataObject.Value;
                    }
                } catch (Error) { }
            }
            function _getColumnsFromArray(columns) {
                try {
                    var col;
                    var retCol = [];
                    if ((MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows.length != 0)) {
                        for (var x = 0; x < MYREFERENCES.OBJECTDATA.Columns.length; x++) {
                            col = MYREFERENCES.OBJECTDATA.Columns[x];
                            if (Core.ArrayHelper.IndexOf(columns, col.Name) != -1) {
                                retCol.push(x);
                            }
                        }
                    }
                    return retCol;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _getColumnsFromObject(obj) {
                try {
                    var col;
                    var retCol = [];
                    var objExtended = null;
                    if ((MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows.length != 0)) {
                        for (var x = 0; x < MYREFERENCES.OBJECTDATA.Columns.length; x++) {
                            col = MYREFERENCES.OBJECTDATA.Columns[x];
                            if (Core.Object.Exist(obj, col.Name) == true) {
                                objExtended = {
                                    Name: col.Name
                                    ,ColIndex: x
                                }
                                Core.Object.Extend(obj[col.Name], objExtended); 
                                retCol.push(objExtended);
                            }
                        }
                    }
                    return retCol;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _searchRows(term, columns) {
                try {
                    var showIt;
                    if ((MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows.length != 0)) {
                        var columnsToSearch = null;
                        if (Core.Object.ValidateArray(columns)) {
                            columnsToSearch = _getColumnsFromArray(columns);
                        } else {
                            columnsToSearch = MYREFERENCES.CustomConfiguration.Search.ColumnsToSearch;
                        }
                        if (Core.Object.ValidateArray(columnsToSearch) && Core.String.ValidateEmpty(term)) {
                            for (var r = 0; r < MYREFERENCES.OBJECTDATA.Rows.length; r++) {
                                var row = MYREFERENCES.OBJECTDATA.Rows[r];
                                showIt = false;
                                for (var ar = 0; ar < columnsToSearch.length; ar++) {
                                    if (row[columnsToSearch[ar]].Value.toUpperCase().indexOf(term) != -1)
                                        showIt = true;
                                }
                                row.Display = showIt;
                            }
                            MYREFERENCES.CustomConfiguration.Search.Enabled = true;
                            _Redraw(PRIVATEPARAMETERS.Container, null, true, { fromRow: 0, rowsToDraw: -1, redrawHeaders: true });
                        } else {
                            MYREFERENCES.CustomConfiguration.Search.Enabled = false;
                            _Redraw(PRIVATEPARAMETERS.Container, null, true);
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }

            function _showSelectDDP(e) {
                try {
                    /*var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                    var elem = _GetPrincipal(target);
                    elem.span.style.display = "none";
                    var ddp = MYREFERENCES.OBJECTDATA.Columns[elem.ColIndex].ComboBoxObject.Object;
                    var domobject = MYREFERENCES.OBJECTDATA.Columns[elem.ColIndex].ComboBoxObject.DOMObject;
                    elem.appendChild(domobject);
                    ddp.SetItemsVisible(true);

                    }*/
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }

            function _constructGlobalSelectDDP(cbOptions, cbContainer) {
                try {
                    cbContainer.DOMObject = document.createElement('div');
                    var selectDDP = new window.DropDownPicker(
                        cbContainer.DOMObject
                        , {
                            ItemsDefaultBackgroundColors: {
                                MouseOver: MYREFERENCES.DropDownItemMouseOverBGColor
                                , Selected: MYREFERENCES.DropDownItemSelectedBGColor
                            }
                            //Events: { SelectedChanged: [_CmbChange] } 
                            , ItemPickerType: window.GridPicker
                            //, Events: { onBlur: 
                        }
                    );
                    //select.style.border = "0px solid white";
                    for (var selIndex = 0; selIndex < cbOptions.Options.length; selIndex++) {
                        selectDDP.AddContent(
                            new window.ItemPicker.ItemData(cbOptions.Options[selIndex].ID, cbOptions.Options[selIndex].Value)
                            , null
                            , {
                                //                                                BackgroundColorMouseOver: MYREFERENCES.DropDownItemMouseOverBGColor
                                //                                                , BackgroundColorSelected: MYREFERENCES.DropDownItemSelectedBGColor
                            }
                        );

                        //                                        var opt = document.createElement("option");
                        //                                        opt.className = "opt";
                        //                                        opt.innerHTML = comboBox.Options[selIndex].Value;
                        //                                        opt.value = comboBox.Options[selIndex].ID;
                        //                                        select.appendChild(opt);
                    }
                    //select.onchange = _CmbChange;
                    //                                    Core.Events.Add(select, "change", _CmbChange);
                    cbContainer.Object = selectDDP;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _RowMouseover(e) {
                try {
                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                        var elem = _GetPrincipalRow(target);
                        if (elem) MYREFERENCES.SelectedRowIndex = elem.Index;
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _DocumentClick(e) {
                try {
                    var allowCM = false;
                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;

                    if (target) {
                        var elem = _GetPrincipalRow(target);
                        var col = _GetPrincipalColumn(target);

                        if ((elem) && (!MYREFERENCES.ReadOnly)) {
                            if (MYREFERENCES.PreviousSelectedRow != null) MYREFERENCES.PreviousSelectedRow.className = MYREFERENCES.PreviousSelectedRow.className.replace("Selected", "");
                            MYREFERENCES.SelectedRowIndex = elem.Index;
                            MYREFERENCES.PreviousSelectedRow = elem;
                            elem.className += "Selected";
                        }
                        else if (MYREFERENCES.PreviousSelectedRow != null) {
                            MYREFERENCES.PreviousSelectedRow.className = MYREFERENCES.PreviousSelectedRow.className.replace("Selected", "");
                            MYREFERENCES.PreviousSelectedRow = null;
                        }

                        if ((col) && (col.ColumnIndex !== undefined) && (!MYREFERENCES.ReadOnly)
                            && ((MYREFERENCES.OBJECTDATA.Columns[col.ColumnIndex].Name != "Size") || (MYREFERENCES.OBJECTDATA.Columns[col.ColumnIndex].Name != "Strand"))) {
                            allowCM = true;
                        }
                    }
                    else if (MYREFERENCES.PreviousSelectedRow != null) {
                        MYREFERENCES.PreviousSelectedRow.className = MYREFERENCES.PreviousSelectedRow.className.replace("Selected", "");
                        MYREFERENCES.PreviousSelectedRow = null;
                    }

                    PRIVATEPARAMETERS.Events.onContextMenu(e, allowCM);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Rowmouseout(e) {
                try {
                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                        var elem = _GetPrincipalRow(target);
                        if (elem) MYREFERENCES.SelectedRowIndex = elem.Index;
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _RowClick(e) {
                try {
                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                    if (target) {
                        var index;
                        var elem = _GetPrincipalRow(target);
                        var col = (target.ColumnIndex != undefined && target.ColumnIndex != null) ? target.ColumnIndex : target.ColIndex;
                        if (elem) {
                            index = MYREFERENCES.SelectedRowIndex = elem.Index;
                            if (PRIVATEPARAMETERS.Data.Selectable) {
                                switch (PRIVATEPARAMETERS.Data.Selectable.toUpperCase()) {
                                    case "SINGLEROW":
                                        _ClearSelection(index, table);
                                        _MarkRowAsSelected(index, table);
                                        break;
                                    case "MULTIROW":
                                        _MarkRowAsSelected(index, table);
                                        break;
                                }
                            }
                            if ((PRIVATEPARAMETERS.Events) && (PRIVATEPARAMETERS.Events.onClick)) PRIVATEPARAMETERS.Events.onClick(index, col);
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            //            function _CmbChange(instanceDOSD, instancePS) {
            //                try {
            //                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
            //                    if (target) {
            //                        var opt = target[target.selectedIndex];
            //                        var elem = _GetPrincipal(target);
            //                        if ((elem) && (opt)) {
            //                            var cell = MYREFERENCES.OBJECTDATA.Rows[elem.ComboBox.RowIndex][elem.ComboBox.ColIndex];
            //                            if (cell) {
            //                                cell.Value = opt.innerHTML;
            //                                cell.Index = opt.value;
            //                            }
            //                        }
            //                    }
            //                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            //            }
            function _GetPrincipal(obj) {
                try {
                    MYREFERENCES.PrincipalIndex++;
                    /* The MYREFERENCES.PrincipalIndex variable is used to stop the recursivity of this function. */
                    if (MYREFERENCES.PrincipalIndex > 20) { MYREFERENCES.PrincipalIndex = 0; return null; }
                    if (obj.IsPrincipal) { MYREFERENCES.PrincipalIndex = 0; return obj; }
                    else if (obj.parentNode) return _GetPrincipal(obj.parentNode);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                MYREFERENCES.PrincipalIndex = 0;
                return null;
            }
            function _GetPrincipalRow(obj) {
                try {
                    MYREFERENCES.PrincipalIndex++;
                    /* The MYREFERENCES.PrincipalIndex variable is used to stop the recursivity of this function. */
                    if (MYREFERENCES.PrincipalIndex > 20) { MYREFERENCES.PrincipalIndex = 0; return null; }
                    if (obj.IsPrincipalRow) { MYREFERENCES.PrincipalIndex = 0; return obj; }
                    else if (obj.parentNode) return _GetPrincipalRow(obj.parentNode);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                MYREFERENCES.PrincipalIndex = 0;
                return null;
            }
            function _GetPrincipalColumn(obj) {
                try {
                    MYREFERENCES.PrincipalIndex++;
                    /* The MYREFERENCES.PrincipalIndex variable is used to stop the recursivity of this function. */
                    if (MYREFERENCES.PrincipalIndex > 20) { MYREFERENCES.PrincipalIndex = 0; return null; }
                    if (obj.IsPrincipalColumn) { MYREFERENCES.PrincipalIndex = 0; return obj; }
                    else if (obj.parentNode) return _GetPrincipalColumn(obj.parentNode);
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                MYREFERENCES.PrincipalIndex = 0;
                return null;
            }
            function _GetRow(index) {
                if (MYREFERENCES.OBJECTDATA) {
                    var item = {};
                    if ((index >= 0) && (index < MYREFERENCES.OBJECTDATA.Rows.length)) {
                        for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                            if (MYREFERENCES.OBJECTDATA.Columns[c].Type == "normal")
                                eval("item[\"" + MYREFERENCES.OBJECTDATA.Columns[c].Name + "\"] = MYREFERENCES.OBJECTDATA.Rows[index][c].Value");
                            else if (MYREFERENCES.OBJECTDATA.Columns[c].Type == "checkbox") eval("item.Checked ='" + MYREFERENCES.OBJECTDATA.Rows[index][c].Checked + "'");
                        }
                    }
                    return item;
                }
            }
            function _SetRow(index, row) {
                try {
                    if (index && row) {
                        if (MYREFERENCES.OBJECTDATA.Rows.length > index) {
                            MYREFERENCES.OBJECTDATA.Rows[index] = row;
                            _QuicklyRefresh();
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetSelectedRowFormated() {
                try {
                    var retData = {};
                    if (MYREFERENCES.SelectedRowIndex != -1) {
                        var item = {};
                        item.RowIndex = MYREFERENCES.SelectedRowIndex;
                        for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                            eval("item[\"" + MYREFERENCES.OBJECTDATA.Columns[c].Name + "\"] = MYREFERENCES.OBJECTDATA.Rows[MYREFERENCES.SelectedRowIndex][c].Value");
                        }
                        retData = { Row: item, Struct: {} };
                    }
                    return retData;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                return null;
            }
            function _ConvertObjectDataToMatrix(data) {
                var retData = { Columns: 0, Matrix: null, Metadata: null, Message: null, Attributes: {}, GetMessageLog: "" };
                try {
                    if (data) {
                        retData.Columns = ((typeof (data.Columns) != "undefined") && (typeof (data.Columns) == "number"))
                                                ? data.Columns
                                                : data.Columns.length;
                        for (var c = 0; c < retData.Columns; c++) {
                            var item = data.Columns[c].Name;
                            if (data.Columns[c].Attributes) {
                                for (var a = 0; a < data.Columns[c].Attributes.length; a++) {
                                    item += "!" + data.Columns[c].Attributes[a];
                                }
                            }
                            if (retData.Matrix == null) retData.Matrix = [];
                            retData.Matrix.push(item);
                        }
                        for (var r = 0; r < data.Rows.length; r++) {
                            for (var c = 0; c < data.Columns.length; c++) {
                                retData.Matrix.push(data.Rows[r][c]["Value"]);
                            }
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                return retData;
            }
            function _GetSimilarRowStruct(cols) {
                try {
                    var rows = [];
                    var add = true;
                    for (var r = 0; r < MYREFERENCES.OBJECTDATA.Rows.length; r++) {
                        for (var c = 0; c < cols.length; c++) {
                            if ((add) && (MYREFERENCES.OBJECTDATA.Rows[r][cols[c].Index].Value != cols[c].Value)) add = false;
                        }
                        if (add) rows.push(MYREFERENCES.OBJECTDATA.Rows[r]);
                        add = true;
                    }
                    return rows;
                } catch (Error) { }
            }
            function _GetMetadata() {
                return ObjectClone(MYREFERENCES.DATA.Metadata);
            }
            function _ClearSelection(index, table) {
                try {
                    if ((table) && (table.childNodes.length > 1)) {
                        var tb = table.childNodes[1];
                        if ((tb) && (tb.childNodes.length - 1 > index)) {
                            var row = tb.childNodes[index];
                            if (MYREFERENCES.PREVIOUSSELECTEDINDEX != -1) {
                                var preRow = tb.childNodes[MYREFERENCES.PREVIOUSSELECTEDINDEX];
                                if (preRow) {
                                    if (PRIVATEPARAMETERS.Data.CheckedColumn) {
                                        if ((PRIVATEPARAMETERS.Data.CheckedColumn.Allow) && (PRIVATEPARAMETERS.Data.CheckedColumn.Selectable)) { }
                                        else preRow.className = MYREFERENCES.PREVIOUSSTYLE;
                                    } else preRow.className = MYREFERENCES.PREVIOUSSTYLE;
                                }
                                MYREFERENCES.PREVIOUSSELECTEDINDEX = -1;
                                MYREFERENCES.PREVIOUSSTYLE = "par";
                            }
                            MYREFERENCES.PREVIOUSSELECTEDINDEX = index;
                            MYREFERENCES.PREVIOUSSTYLE = row.className;
                        }

                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _MarkRowAsSelected(index, table) {
                try {
                    if ((table) && (table.childNodes.length > 1)) {
                        var tb = table.childNodes[1];
                        if ((tb) && (tb.childNodes.length - 1 > index)) {
                            var row = tb.childNodes[index];
                            switch (PRIVATEPARAMETERS.Data.Selectable.toUpperCase()) {
                                case "SINGLEROW":
                                    if (row.className.indexOf("Selected") == -1) {
                                        row.className += "Selected";
                                        if ((MYREFERENCES.OBJECTDATA.Rows[index]) && (MYREFERENCES.OBJECTDATA.Rows[index].length > 0))
                                            MYREFERENCES.OBJECTDATA.Rows[index][0].Checked = true;
                                    }
                                    break;
                                case "MULTIROW":
                                    if (row.className.indexOf("Selected") == -1) {
                                        row.className += "Selected";
                                        if ((MYREFERENCES.OBJECTDATA.Rows[index]) && (MYREFERENCES.OBJECTDATA.Rows[index].length > 0))
                                            MYREFERENCES.OBJECTDATA.Rows[index][0].Checked = true;
                                    }
                                    else {
                                        row.className = row.className.replace("Selected", "");
                                        if ((MYREFERENCES.OBJECTDATA.Rows[index]) && (MYREFERENCES.OBJECTDATA.Rows[index].length > 0))
                                            MYREFERENCES.OBJECTDATA.Rows[index][0].Checked = false;
                                    }
                                    break;
                            }

                            if (PRIVATEPARAMETERS.Data.CheckedColumn) {
                                if ((PRIVATEPARAMETERS.Data.CheckedColumn.Allow) && (PRIVATEPARAMETERS.Data.CheckedColumn.Selectable)) {
                                    var target = ((typeof (e) != "undefined") && (e.target)) ? e.target : window.event.srcElement;
                                    if (target) {
                                        if ((target.type != "checkbox") && (target.id.indexOf("chk") == -1)) {
                                            var checked = !MYREFERENCES.OBJECTDATA.Rows[index][0].Checked;

                                            var tb = MYREFERENCES.MAINTABLE.childNodes[1];
                                            if (tb) {
                                                tb.childNodes[index].childNodes[0].childNodes[0].checked = checked;
                                            }

                                            if (MYREFERENCES.OBJECTDATA.Columns[0].Type == "checkbox") {
                                                MYREFERENCES.OBJECTDATA.Rows[index][0].Checked = checked;
                                                //window.status = "Selected:" + MYREFERENCES.OBJECTDATA.Rows[index][1].Value;
                                            }
                                            if (checked == false) {
                                                row.className = row.className.replace("Selected", "");
                                            }
                                        } else {

                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _RowCount() {
                if ((data != null) && (data != undefined) && (data.Matrix != null)) {
                    return (data.Matrix.length - data.Columns) / data.Columns;
                } else return 0;
            }
            function _SetLegend(legend, animate) {
                MYREFERENCES.WIDGETCONTAINER.SetLegend(legend, animate);
            }
            function _SetTitle(title) {
                MYREFERENCES.WIDGETCONTAINER.SetTitle(title);
            }
            function _GetXMlDocument() {
                var retXML = null;
                var anyChanges = false;
                try {
                    if (MYREFERENCES.OBJECTDATA) {
                        retXML = '<XMLRoot>';
                        for (var r = 0; r < MYREFERENCES.OBJECTDATA.Rows.length; r++) {
                            rowObj = MYREFERENCES.OBJECTDATA.Rows[r];
                            if ((Core.Object.Eval(PRIVATEPARAMETERS, 'Data.SendOnlyChangedData') == true && PRIVATEPARAMETERS.Data.SendOnlyChangedData == true && rowObj.WasChanged == true) || Core.Object.Eval(PRIVATEPARAMETERS, 'Data.SendOnlyChangedData') == false || (Core.Object.Eval(PRIVATEPARAMETERS, 'Data.SendOnlyChangedData') && PRIVATEPARAMETERS.Data.SendOnlyChangedData == false)) {
                                var row = '<Row ';
                                for (var c = 0; c < MYREFERENCES.OBJECTDATA.Columns.length; c++) {
                                    //if (MYREFERENCES.OBJECTDATA.Columns[c].ComboBox) row += Trim(MYREFERENCES.OBJECTDATA.Columns[c].Name).replace(' ', '') + '="' + MYREFERENCES.OBJECTDATA.Rows[r][c].Index + '" ';
                                    //else row += Trim(MYREFERENCES.OBJECTDATA.Columns[c].Name).replace(' ', '') + '="' + MYREFERENCES.OBJECTDATA.Rows[r][c].Value + '" ';
                                    if (MYREFERENCES.OBJECTDATA.Columns[c].ComboBox) row += ((Trim(MYREFERENCES.OBJECTDATA.Columns[c].Name).replace(' ', '')).replace('[', '')).replace(']', '') + '="' + MYREFERENCES.OBJECTDATA.Rows[r][c].Index + '" ';
                                    else row += ((Trim(MYREFERENCES.OBJECTDATA.Columns[c].Name).replace(' ', '')).replace('[', '')).replace(']', '') + '="' + MYREFERENCES.OBJECTDATA.Rows[r][c].Value + '" ';
                                }
                                row += '/>';
                                row = row.replace(/#/g, '');
                                retXML += row;
                                anyChanges = true;
                            }
                        }
                        retXML += '</XMLRoot>';
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
                return (anyChanges == true) ? retXML : null;
            }
            function _SaveData(optionsInit) {
                try {
                    //popup
                    if (true) {
                        var xml = _GetXMlDocument();
                        if (Core.Object.Validate(xml)) {
                            MYREFERENCES.WIDGETCONTAINER.SetLegend('Saving...', true);
                            var pp = new PrivateParameters();
                            var url = PRIVATEPARAMETERS.URL + PRIVATEPARAMETERS.Method;
                            var qp = new QueryParameters();
                            //qp.Add('@HEATNUMBER', 22, MYREFERENCES.HeatNumber);
                            qp.Add('@XML', 25, xml);
                            var options = {}; options.data = {};
                            pp.DatabaseParameters.ConnectionStringName = PRIVATEPARAMETERS.DatabaseParameters.ConnectionStringName;
                            pp.DatabaseParameters.Procedure = (Core.Object.Eval(optionsInit, 'CustomDataHandlerProcedure')) ? optionsInit.CustomDataHandlerProcedure : (PRIVATEPARAMETERS.Procedures.HandleXMLSave) ? PRIVATEPARAMETERS.Procedures.HandleXMLSave : "";
                            pp.DatabaseParameters.QueryParameters = qp.GetQueryParameters();
                            pp.Version.Class = null;
                            options.data.DatabaseParameters = pp.DatabaseParameters;
                            options.Async = false;
                            options.onSuccess = function (requestData) {
                                var ret = null;
                                if ((requestData) && (!requestData.Message) && (requestData.Table) && (requestData.Table[0])) {
                                    if (Core.Object.Eval(requestData, "Table") && requestData.Table.length > 0) {

                                        if (Core.Object.Eval(optionsInit, 'CustomDataHandlerCallback')) {
                                            optionsInit.CustomDataHandlerCallback(requestData.Table);
                                        } else {
                                            _HandleSaveDataReturned(requestData.Table1);
                                        }

                                        //MYREFERENCES.CLIENTDATACHANGED = false;
                                        ret = 2
                                    } else {
                                        ret = 1;
                                    }
                                } else {
                                    //_SetDetailedError('Error Saving. ' + requestData.ErrorType, requestData.Message);
                                }
                                if (Core.Object.Eval(optionsInit, 'Events.onComplete') == true) optionsInit.Events.onComplete(ret);
                                //return ret;
                            }
                            options.onFailure = function (message) {
                                var ret = { CodeID: 'R', Message: null };
                                if (message) ret.Message = message;
                                _SetDetailedError('Error Saving. ', message);
                                return ret;
                            }
                            Core.Json.Request(url, options);
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _HandleSaveDataReturned(data) {
                try {
                    for (var i in data) {
                        //var ob = data[i];
                        //ob;
                        //alert("Error with Tag: " + ob.Name + "\n Message: " + ob.Error);
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _CallCustomXMLHandler(name) {
                try {
                    if (Core.Object.Eval(PRIVATEPARAMETERS, 'Procedures.CustomXMLHandlers')) {
                        if (PRIVATEPARAMETERS.Procedures.CustomXMLHandlers[name] != null &&
                        PRIVATEPARAMETERS.Procedures.CustomXMLHandlers[name] != undefined) {
                            _SaveData(
                                {
                                    CustomDataHandlerProcedure: PRIVATEPARAMETERS.Procedures.CustomXMLHandlers[name].Procedure,
                                    CustomDataHandlerCallback: PRIVATEPARAMETERS.Procedures.CustomXMLHandlers[name].Callback
                                });
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _Clear() {
                try {
                    for (var ddpIndex = 0; ddpIndex < MYREFERENCES.DropDownPickersList.length; ddpIndex++)
                        MYREFERENCES.DropDownPickersList[ddpIndex].Dispose();
                    MYREFERENCES.DropDownPickersList = [];
                    Core.Object.RemoveAllChildNodes(PRIVATEPARAMETERS.Container);
                    PRIVATEPARAMETERS.Container.innerHTML = "";
                    // "<p style=" font-family:Microsoft Sans Serif ;color:#808080;margin-left:5px;margin-top:10px;">No available data</p>";
                    MYREFERENCES.WIDGETCONTAINER.SetTotalRows(0);
                    MYREFERENCES.WIDGETCONTAINER.SetPageNumber(1);
                    MYREFERENCES.DATA = null;
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _SetSelectedIndexRow(index) {
                try {
                    if ((index) && (MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows) && (MYREFERENCES.MAINTABLE) && (PRIVATEPARAMETERS.Data.Selectable.toUpperCase() == "SINGLEROW")) {
                        var table = MYREFERENCES.MAINTABLE;
                        _ClearSelection(index, table);
                        _MarkRowAsSelected(index, table);
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _SetMultiSelectionIndexRow(indexs) {
                try {
                    if ((indexs) && (MYREFERENCES.OBJECTDATA) && (MYREFERENCES.OBJECTDATA.Rows) && (MYREFERENCES.MAINTABLE) && (PRIVATEPARAMETERS.Data.Selectable.toUpperCase() == "MULTIROW")) {
                        var table = MYREFERENCES.MAINTABLE;
                        if (typeof (indexs) == "object") indexs = indexs.split(",");
                        for (var i = 0; o < indexs.length; i++) {
                            _MarkRowAsSelected(indexs[i], table);
                        }
                    }
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _GetPickerControls() {
                try {
                    return MYREFERENCES.WIDGETCONTAINER.GetPickerControls();
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }
            function _AddPicker(widget) {
                MYREFERENCES.WIDGETCONTAINER.AddPicker(widget);
            }
            function _CompareDatasets(newData, oldData) {
                var dataHasChanged = false;
                try {
                    if (!oldData) {
                        dataHasChanged = true;
                    }
                    else {
                        var newColsData = newData.Columns;
                        var oldColsData = oldData.Columns;

                        if (newColsData.length != oldColsData.length) {
                            dataHasChanged = true;
                        }
                        else if (Core.Json.Encode(oldColsData) != Core.Json.Encode(newColsData)) {
                            dataHasChanged = true;
                        }
                        else {
                            var newRowsData = newData.Rows;
                            var oldRowsData = oldData.Rows;

                            if (newRowsData.length != oldRowsData.length) {
                                dataHasChanged = true;
                            } else if (Core.Json.Encode(oldRowsData) != Core.Json.Encode(newRowsData)) {
                                dataHasChanged = true;
                            }
                        }
                    }
                } catch (Error) {
                    dataHasChanged = true;
                    PRIVATEPARAMETERS.Events.onError(Error);
                }
                return dataHasChanged;
            }
            function _FillColumnsIndexCollection(colsData) {
                try {
                    /* Fill. */
                    for (var colName in MYREFERENCES.ColumnsIndexCollection) {
                        MYREFERENCES.ColumnsIndexCollection[colName] = null;

                        for (var colIndex = 0; colIndex < colsData.length; colIndex++) {
                            var colData = colsData[colIndex];

                            if (colName.toUpperCase() == Core.String.Trim(colData.MappingName).toUpperCase()) {
                                MYREFERENCES.ColumnsIndexCollection[colName] = colIndex;
                                break;
                            }
                        }
                    }
                    /* Check if some column was not setted. */
                    var colsNotSetted = "";
                    for (var colName in MYREFERENCES.ColumnsIndexCollection) {
                        if (MYREFERENCES.ColumnsIndexCollection[colName] == null) {
                            colsNotSetted += (colsNotSetted.length == 0)
                                                ? ""
                                                : ","
                                            + colName;
                        }
                    }

                    if (colsNotSetted.length != 0)
                        Core.Messages.Alert.Show({ Type: "Error", Message: "Some columns have not been mapped: " + colsNotSetted });

                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }

            function _wasDataChanged() { try { return (MYREFERENCES.CLIENTDATABEINGCHANGED == true) ? true : MYREFERENCES.CLIENTDATACHANGED; } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); } }

            function _detachAllWindowEvents() {
                try {
                    Core.Events.Remove(window, 'onscroll', _InfiniteScrolling_onScroll); 
                    Core.Events.Remove(window, 'onbeforeunload', _Autosave_BeforeUnload); 
                } catch (Error) { PRIVATEPARAMETERS.Events.onError(Error); }
            }

            _Initialize(object, options);

            /*--------------------------*/
            /*------Public members------*/
            /*--------------------------*/
            this.AutoRefresh = _AutoRefresh;
            this.CancelAutoRefresh = _CancelAutoRefresh;
            this.WasDataChanged = _wasDataChanged;
            this.RefreshData = _RefreshData;
            this.RowCount = _RowCount;
            this.CountItems = _CountItems;
            this.ResetParameters = _ResetParameters;
            this.Clear = _Clear;
            this.AddPicker = _AddPicker;

            this.SetRow = _SetRow;
            this.SetTitle = _SetTitle;
            this.SetLegend = _SetLegend;
            this.SetDetailedError = _SetDetailedError;
            this.SetJSONStringFile = function (string) { if (PRIVATEPARAMETERS) PRIVATEPARAMETERS.JSONStringFile = string; };
            this.SetDatabaseEngine = function (newDatabaseEngine) { DatabaseConnection.SetDatabaseEngine(PRIVATEPARAMETERS, newDatabaseEngine); };
            this.SetConnectionStringName = function (newConnectionStringName) { DatabaseConnection.SetConnectionStringName(PRIVATEPARAMETERS, newConnectionStringName); };
            this.SetTablesCount = function (newTablesCount) { DatabaseConnection.SetTablesCount(PRIVATEPARAMETERS, newTablesCount); };
            this.SetProcedure = function (newProcedure) { DatabaseConnection.SetProcedure(PRIVATEPARAMETERS, newProcedure); };
            this.SetSpecialColumns = _SetSpecialColumns;
            this.SetNewValue = _SetNewValue;

            this.GetRow = _GetRow;
            this.GetDatabaseEngine = function () { return DatabaseConnection.GetDatabaseEngine(PRIVATEPARAMETERS.DatabaseEngine); };
            this.GetConnectionStringName = function () { return DatabaseConnection.GetConnectionStringName(PRIVATEPARAMETERS.ConnectionStringName); };
            this.GetProcedure = function () { return DatabaseConnection.GetProcedure(PRIVATEPARAMETERS.Procedure); };
            this.GetMetadata = _GetMetadata;
            this.GetRowsCount = _GetRowsCount;
            this.GetSpecialColumns = _GetSpecialColumns;
            this.GetSelectedRows = _SelectedRows;
            this.GetItemsPerPage = _GetItemsPerPage;
            this.GetPageIndex = _GetPageIndex;
            this.GetSortColumnMode = _GetSortColumnMode;
            this.GetAttributeValue = _GetAttributeValue;
            this.GetDataToExport = _GetDataToExport;
            this.GetPickerControls = _GetPickerControls;
            this.GetSelectedRowFormated = _GetSelectedRowFormated;
            this.GetXMLDocument = _GetXMlDocument;
            this.SaveData = _SaveData;
            this.Search = _searchRows;
            this.CallCustomXMLHandler = _CallCustomXMLHandler;
            this.DifferentialRefresh = _differentialRefresh;
            this.Autosave = {
                HasUnsavedChanges: _Autosave_HasUnsavedChanges
                , PerformAutosave: _Autosave_PerformAutosave
            }

            this.DetachAllWindowEvents = _detachAllWindowEvents;

        } catch (Error) { }
    }
    window.IndustrialGridEditableGeneric = function (object, options) { return new _IndustrialGridEditableGeneric(object, options); }
})();