require("../vendors/jquery-ui.min.js")
var toastr = require("../vendors/toastr.js")

module.exports = function (options) {
    var resizeTable = function () {
        setTimeout(function () {
            $('.ko-tbl th:not(.checkbox-col, .stateSwitch-ty, .label-ty)').resizable({
                handles: 'w',
                minWidth: 100,
                _h: "resizable-_h-t",
                start: function (event, ui) {
                    //var table = $(event.target).closest("table");
                    //table.css("table-layout", "auto");
                },
                stop: function (event, ui) {
                    $(event.target).css("left", 0);
                    kocnx().changeColWidth(event.target);
                    //var table = $(event.target).closest("table");
                    //table.css("table-layout", "fixed");
                },
                resize: function (event, ui) {
                    $(event.target).css("left", 0);
                }
            });
        }, 200);
    }
    var confirmDeleteAlert = function (message, callback, withCancelBtn) {
        var yes = getLocalizedText("yesConfirm");
        var no = getLocalizedText("noConfirm");
        var buttons = [
            { text: yes, type: "danger", value: true },
            { text: no, type: "default", value: false }
        ];
        if (withCancelBtn) {
            var cancel = getLocalizedText("cancelConfirm");
            buttons.push({ text: cancel, type: "success", value: undefined });
        }
        confirmBox.run({
            text: message,
            buttons: buttons
        }, function (res) {
            callback(res);
        });
    };
    var confirmTableTemplateAlert = function (message, callback, withCancelBtn) {
        var yes = getLocalizedText("yesConfirm");
        var no = getLocalizedText("noConfirm");
        var buttons = [
            { text: yes, type: "success", value: true },
            { text: no, type: "danger", value: false }
        ];
        if (withCancelBtn) {
            var cancel = getLocalizedText("cancelConfirm");
            buttons.push({ text: cancel, type: "warning", value: undefined });
        }
        confirmBox.run({
            text: message,
            buttons: buttons
        }, function (res) {
            callback(res);
        });
    };
    var confirmChooseAlert = function (message, callback) {
        confirmBox.run({
            text: message, buttons: [
                { text: "اعمال", type: "success", value: true },
                { text: "لغو", type: "danger", value: false },
                { text: "انصراف", type: "default", value: undefined }
            ]
        }, function (res) {
            callback(res);
        });
    };
    var warningToast = function (message) {
        toastr.options = {
            "newestOnTop": false,
            "positionClass": "toast-bottom-left",
            "closeButton": false,
            "toastClass": "animated fadeInDown"
        };
        toastr.options.rtl = true;
        toastr.warning(message);
    }
    var successToast = function (message) {
        toastr.options = {
            "newestOnTop": false,
            "positionClass": "toast-bottom-left",
            "closeButton": false,
            "toastClass": "animated fadeInDown"
        };
        toastr.options.rtl = true;
        toastr.success(message);
    }
    var failToast = function (message) {
        toastr.options = {
            "newestOnTop": false,
            "positionClass": "toast-top-left",
            "closeButton": false,
            "toastClass": "animated fadeInDown"
        };
        toastr.options.rtl = true;
        toastr.error(message);
    }
    var findControllerName = function (name) {
        var value = 0;
        for (var i = 0; i < controllerNames.length; i++) {
            if (controllerNames[i].enText.toLowerCase() === name.toLowerCase())
                value = controllerNames[i].value;
        }
        return value;
    }
    var getEnumText = function (values, id) {
        var value = null;
        $.each(values, function (i, p) {
            if (p.value === id)
                value = p.text;
        });
        return value;
    }
    var getEnumEnText = function (values, id) {
        var value = null;
        $.each(values, function (i, p) {
            if (p.value === id)
                value = p.enText;
        });
        return value;
    }
    var getEnumItem = function (values, id) {
        var value = null;
        $.each(values, function (i, p) {
            if (p.value === id)
                value = p;
        });
        return value;
    }
    var getEnumItemByText = function (values, text) {
        var value = null;
        $.each(values, function (i, p) {
            if (p.enText === text)
                value = p;
        });
        return value;
    }
    var kocnx = function () {
        var wrapper = $("#ko_wrapper");
        if (wrapper) {
            var context = ko.contextFor(wrapper[0]);
            if (context)
                return context.$data;
        }
    }
    var countBackNumberZero = function (str) {
        var count = 0;
        for (var i = 0; i < str.length; i++) {
            var target = str.substring(i, i + 1);
            if (target === "0")
                count++;
            else {
                return count;
            }
        }
        return count;
    }
    var isNumeric = function (obj) {
        return !jQuery.isArray(obj) && (obj - parseFloat(obj) + 1) >= 0;
    }
    var abd = function (a, n) {
        n = (n + "").replace("9", "").replace("0", "");
        n = n.split("");
        var s = "";
        n.forEach(x => {
            var p = Number(x);
            const ab = a[p - 1];
            s += ab;
        });
        return s;
    }
    var getExtension = function (value) {
        if (!value)
            return "";
        var filename = value.replace(/^.*[\\\/]/, "");
        return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
    }
    var getApiMessage = function (key) {
        var item = apiMessages[key];
        if (item === undefined || item === "")
            item = clientMessages[key];
        if (item === undefined || item === "")
            item = cmdMessages[key];
        var text = item[locale] || item['default'] || "";
        return text;
    }
    var generateUuid = function () {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }
    var getLocalizedText = function (binding, subDomain) {
        var domain = window.resDomain;
        if (typeof domain === "undefined") {
            throw "res domain is empty";
        }

        if (typeof locale === "undefined") {
            throw "ko.localationbinding.getLocalizedText: locale object is not defined";
        }

        if (Object.prototype.toString.call(binding) === '[object String]') {
            binding = { key: binding };
        }
        if (!binding)
            var y = 2;
        var key = binding.key;

        var item = commonRes[key];

        if (!item) {
            item = reportgenRes[key];
        }
        if (!item) {
            item = findModelRes(key, domain);
        }
        if (!item) {
            item = findPageRes(key, domain, subDomain);
        }
        if (!item) {
            item = tabNameRes[key];
        }
        if (!item) {
            var x = 2;
        }


        var text = item[locale] || item['default'] || "";
        if (binding.params) {
            for (var replaceKey in binding.params) {
                if (binding.params.hasOwnProperty(replaceKey)) {
                    var replacement = binding.params[replaceKey];
                    if (typeof replacement === "function") {
                        replacement = ko.utils.unwrapObservable(replacement());
                    }
                    text = text.replace("#" + replaceKey, replacement);
                }
            }
        }

        return text;
    }
    var findModelRes = function (key, domain) {
        switch (domain) {
            case "ActionLog":
            case "Access":
            case "Company":
            case "GroupPeriod":
            case "Consolidate":
            case "OnlineUser":
            case "DynamicTable":
            case "CompanyInfo":
            case "DynamicDocument":
                return window[domain.toLowerCase() + "ModelRes"][key];
            case "Period":
                var periodVal = periodModelRes[key];
                if (periodVal === null || periodVal === undefined)
                    periodVal = comparativeperiodsModelRes[key];

                if (periodVal === null || periodVal === undefined)
                    periodVal = periodhistoryModelRes[key];

                return periodVal;
            case "User":
                var userVal = userModelRes[key];
                if (userVal === null || userVal === undefined)
                    userVal = usercontentModelRes[key];
                return userVal;
            case "Tree":
                var treeVal = treeModelRes[key];
                if (treeVal === null || treeVal === undefined)
                    treeVal = valuepartsModelRes[key];
                return treeVal;
            case "Balancesheet":
                var val = balancesheetModelRes[key];
                if (val === null || val === undefined)
                    val = balancesheetcontentModelRes[key];
                return val;
            case "Mapping":
                var valMapping = mappingtreeModelRes[key];
                if (valMapping === null || valMapping === undefined)
                    valMapping = mappingDataModelRes[key];
                if (valMapping === null || valMapping === undefined)
                    valMapping = substituteNodeModelRes[key];
                if (valMapping === null || valMapping === undefined)
                    valMapping = mappingruleModelRes[key];
                if (valMapping === null || valMapping === undefined)
                    valMapping = mappingruledataModelRes[key];


                return valMapping;
            case "BalanceReport":
                var valBalancereport = balancereportModelRes[key];
                if (valBalancereport === null || valBalancereport === undefined)
                    valBalancereport = reportbalancedataModelRes[key];
                if (valBalancereport === null || valBalancereport === undefined)
                    valBalancereport = totalbalancereportModelRes[key];
                if (valBalancereport === null || valBalancereport === undefined)
                    valBalancereport = reportbalancedatadetailsModelRes[key];
                return valBalancereport;
            case "TableTemplate":
                var valTableTemplate = tabletemplateModelRes[key];
                if (valTableTemplate === null || valTableTemplate === undefined)
                    valTableTemplate = tabletemplatepreviewModelRes[key];
                if (valTableTemplate === null || valTableTemplate === undefined)
                    valTableTemplate = treeInfoModelRes[key];
                if (valTableTemplate === null || valTableTemplate === undefined)
                    valTableTemplate = tableModelRes[key];
                return valTableTemplate;
            case "Magazine":
                var valMagazine = magazineModelRes[key];
                if (valMagazine === null || valMagazine === undefined)
                    valMagazine = savemagazineModelRes[key];
                if (valMagazine === null || valMagazine === undefined)
                    valMagazine = magazinePreviewPageRes[key];
                return valMagazine;
            case "AdjustmentDocument":
                var valadjustmentdocument = adjustmentdocumentModelRes[key];
                if (valadjustmentdocument === null || valadjustmentdocument === undefined)
                    valadjustmentdocument = adjustmentdocumentitemModelRes[key];
                return valadjustmentdocument;
        }
        return null;
    }
    var findPageRes = function (key, domain, subDomain) {
        switch (domain) {
            case "CompanyInfoData":
            case "CompanyInfo":
                var companyInfoData = companyinfoPageRes[key];
                if (companyInfoData === null || companyInfoData === undefined)
                    companyInfoData = companyInfoDataPageRes[key];
                return companyInfoData;
            case "ActionLog":
                return actionlogPageRes[key];
            case "Company":
                return companyPageRes[key];
            case "Period":
                var period = periodPageRes[key];
                if (period === null || period === undefined)
                    period = periodHistoryPageRes[key];
                if (period === null || period === undefined)
                    period = periodGroupHistoryPageRes[key];
                return period;
            case "Tree":
                return treePageRes[key];
            case "User":
                var userVal = userPageRes[key];
                if (userVal === null || userVal === undefined)
                    userVal = usercontentPageRes[key];
                return userVal;
            case "Access":
                return accessPageRes[key];
            case "Balancesheet":
                var val = balancesheetPageRes[key];
                if (val === null || val === undefined)
                    val = balancesheetContentPageRes[key];
                return val;
            case "Mapping":
                var valMapping;
                switch (subDomain) {
                    case "MappingRule":
                        valMapping = mappingrulePageRes[key];
                        break;
                    case "SubstituteNode":
                        valMapping = substitutenodePageRes[key];
                        break;
                    default:
                        valMapping = mappingTreePageRes[key];
                        if (valMapping === null || valMapping === undefined)
                            valMapping = mappingDataPageRes[key];
                        if (valMapping === null || valMapping === undefined)
                            valMapping = substitutenodePageRes[key];
                        if (valMapping === null || valMapping === undefined)
                            valMapping = mappingrulePageRes[key];
                        break;
                }
                return valMapping;
            case "BalanceReport":
                var valBalanceReport = balancereportFilterRes[key];
                if (valBalanceReport === null || valBalanceReport === undefined)
                    valBalanceReport = balancereportPageRes[key];
                if (valBalanceReport === null || valBalanceReport === undefined)
                    valBalanceReport = totalBalanceReportPageRes[key];

                if (valBalanceReport === null || valBalanceReport === undefined)
                    valBalanceReport = reportBalanceDataPageRes[key];
                return valBalanceReport;
            case "TableTemplate":
                var valTableTemplate = tabletemplatePageRes[key];
                if (valTableTemplate === null || valTableTemplate === undefined)
                    valTableTemplate = tableStructurePageRes[key];
                if (valTableTemplate === null || valTableTemplate === undefined)
                    valTableTemplate = reportgenRes[key];
                return valTableTemplate;
            case "Magazine":
                var valMagazine = magazinePageRes[key];
                if (valMagazine === null || valMagazine === undefined)
                    valMagazine = savemagazinePageRes[key];
                return valMagazine;
            case "AdjustmentDocument":
                var valadjustmentdocument = adjustmentdocumentPageRes[key];
                if (valadjustmentdocument === null || valadjustmentdocument === undefined)
                    valadjustmentdocument = adjustmentdocumentitemPageRes[key];
                return valadjustmentdocument;
            case "GroupPeriod":
                return groupperiodPageRes[key];
            case "Consolidate":
                return consolidatePageRes[key];
            case "DynamicTable":
                var valdynamictable = dynamictablePageRes[key];
                if (valdynamictable === null || valdynamictable === undefined)
                    valdynamictable = dynamictabledataPageRes[key];
                return valdynamictable;
            case "DynamicDocument":
                return dynamicdocumentPageRes[key];
            case "OnlineUser":
                return onlineuserPageRes[key];
        }
        return null;
    }
    var createOneDepthLines = function (item) {
        ko.utils.arrayFilter(item.children(), function (child) {
            child.createlines();
        });
    };
    var toggleChildren = function (item) {
        if (item.childrenShow() === false) {
            item.childrenShow(true);
            createOneDepthLines(item);
        } else {
            item.childrenShow(false);
        }
    }
    var fixLabelsSize = function () {
        var list = $(".control-label");
        if (list && list.length)
            for (var i = 0; i < list.length; i++) {
                var target = list[i];
                var size = calDim($(target).text(), "11px", "Iransans", "400");
                $(target).css("width", (size[1] + 5) + "px");
            }
    }
    var setSd = function (object) {
        localStorage.setItem("sd", JSON.stringify(object));
    }
    var getSd = function () {
        var object = localStorage.getItem('sd');
        if (object !== null && object !== undefined && object !== "") {
            return JSON.parse(object);
        }
        return null;
    }
    var setUd = function (object) {
        localStorage.setItem("ud", JSON.stringify(object));
    }
    var getUd = function () {
        var object = localStorage.getItem('ud');
        if (object !== null && object !== undefined && object !== "") {
            return JSON.parse(object);
        }
        return null;
    }
    var toggleParent = function () {
        var a = getUd();
        var b = getSd();
        return { a: [a.ur.usr_cks, a.cmp.cmp_cks, a.prd.prd_cks, b.sys_dt_rf, a.sys_date_trs, a.ur.avt_bg, b.cks_sys_bg, a.prd.col_lt], b: a.cmp.log_cl_cks };
    }
    var getTvm = function () {
        var a = toggleParent();
        var b = abd(a.a, a.b);
        if (b) {
            return b;
        }
        return null;
    }
    var backToLogin = function () {
        var pathName = "";
        if (window.location.pathname)
            pathName = "?returnUrl=" + window.location.pathname;
        window.location.href = "/account/login" + pathName;
    }
    var isNullOrEmpty = function (model) {
        if (model === null || model === undefined) {
            return true;
        }
        return false;
    }
    var isEmpty = function (model) {
        if (model === null || model === undefined || model === "") {
            return true;
        }
        return false;
    };
    var isBigger = function (number, cond) {
        return number !== null && number !== undefined && number > cond;
    }
    var any = function (model) {
        if (model !== null && model !== undefined && model.length > 0) {
            return true;
        }
        return false;
    }
    var errorListHandler = function (list) {
        for (var j = 0; j < list.length; j++) {
            var target = list[j];
            if (target["selfDescriptive"] && target.selfDescriptive === true) {
                failToast(target.description);
            } else {
                var text = getApiMessage(target.code);
                text = completeError(text, target);
                failToast(text);
            }
        }
    };
    var warningListHandler = function (list) {
        for (var j = 0; j < list.length; j++) {
            var target = list[j];
            if (target["selfDescriptive"] && target.selfDescriptive === true) {
                failToast(target.description);
            } else {
                var text = getApiMessage(target.code);
                text = completeError(text, target);
                warningToast(text);
            }
        }
    };
    var successListHandler = function (list) {
        for (var j = 0; j < list.length; j++) {
            var target = list[j];
            var text = getApiMessage(target.code);
            text = completeError(text, target);
            successToast(text);
        }
    }
    var formatTextIfNull = function (text, sign) {
        var outIfNull = sign;
        if (outIfNull === null || outIfNull === undefined)
            outIfNull = "-";
        if (text === null || text === undefined || text === "undefined" || text === "null"
            || text === "" || text === 0 || text === '0')
            return outIfNull;
        if ($.isNumeric(text)) {
            return formatNumber(text, false);
        }
        return text;
    }
    var emptyTextIfNull = function (text, sign) {
        var outIfNull = sign;
        if (outIfNull === null || outIfNull === undefined)
            outIfNull = "";
        if (text === null || text === undefined || text === "undefined" || text === "null"
            || text === "" || text === 0 || text === '0')
            return outIfNull;
        return text;
    }
    var setAppSetting = function (data) {
        var cast = JSON.parse(data);
        for (var p in cast) {
            if (cast.hasOwnProperty(p)) {
                var target = cast[p];
                localStorage.setItem(target.Key, target.Value);
            }
        }
    }
    var getAppSetting = function (key) {
        var value = localStorage.getItem(key);
        if (value === null || value === undefined || value === "") {
            return null;
        }
        return value;
    }
    var toggleDisableSections = function (signalMappingStructureDisable) {
        var context = kocnx();
        var isExistPeriod = context.periodItem() !== null && context.periodItem() !== undefined;
        var isExistMappingStructure = context.currentMappingEnabled();
        var isCompany = context.loginCompanyType() === 1;

        if (isExistPeriod) {
            $(".trees-dis-menu a").attr("href", "/trees");
            $(".operation-dis-menu a").attr("href", "/operation");
            $(".reports-dis-menu a").attr("href", "/reports");
            $(".notes-dis-menu a").attr("href", "/notes");
            $(".operation-dis-menu").addClass("operation-menu");
            $(".reports-dis-menu").addClass("reports-menu");
            $(".notes-dis-menu").addClass("notes-menu");
            $(".operation-menu").removeClass("operation-dis-menu");
            $(".reports-menu").removeClass("reports-dis-menu");
            $(".notes-menu").removeClass("notes-dis-menu");
            $(".trees-menu").removeClass("trees-dis-menu");


            if (!isCompany) {
                $('a[href="#Company-t"]').parent().removeClass("disabledTab");

                return;
            }
            if (isExistMappingStructure) {

                $('a[href="#Mapping-t"]').parent().removeClass("disabledTab");
                $('a[href="#Balancesheet-t"]').parent().removeClass("disabledTab");
                $('a[href="#AdjustmentDocument-t"]').parent().removeClass("disabledTab");
            }
            if (!isExistMappingStructure || signalMappingStructureDisable === true) {
                $('a[href="#Mapping-t"]').parent().addClass("disabledTab");
                $('a[href="#Balancesheet-t"]').parent().addClass("disabledTab");
                $('a[href="#AdjustmentDocument-t"]').parent().addClass("disabledTab");

                var path = window.location.pathname.toLowerCase().split("?");
                if (path[0] !== "") {
                    var array = path[0].split("/");
                    array = $.grep(array, function (n) {
                        return n !== ""
                    });
                    if (array.length > 0) {
                        if ("reports".indexOf(array[0]) !== -1 || "notes".indexOf(array[0]) !== -1) {
                            window.location.href = "/operation";
                        }
                        if ("operation".indexOf(array[0]) !== -1) {
                            $('a[href="#Balancesheet-t"]').trigger('click');
                        }
                    }
                }
            }
        } else {
            $(".trees-menu a").attr("href", "#");
            $(".operation-menu a").attr("href", "#");
            $(".reports-menu a").attr("href", "#");
            $(".notes-menu a").attr("href", "#");

            $(".trees-menu").addClass("trees-dis-menu");
            $(".operation-menu").addClass("operation-dis-menu");
            $(".reports-menu").addClass("reports-dis-menu");
            $(".notes-menu").addClass("notes-dis-menu");
            $(".trees-dis-menu").removeClass("trees-menu");
            $(".operation-dis-menu").removeClass("operation-menu");
            $(".reports-dis-menu").removeClass("reports-menu");
            $(".notes-dis-menu").removeClass("notes-menu");
            if (!isCompany) {
                $('a[href="#Company-t"]').parent().addClass("disabledTab");
            }

        }
    }
    var buildTree = function (list) {
        var idFieldName = 'id';
        var parentKeyFieldName = 'pi';
        var fieldNameForChildren = 'children';
        var rootElements = [];
        var lookup = {};
        list.forEach(function (flatItem) {
            var itemId = flatItem[idFieldName];
            lookup[itemId] = flatItem;
            flatItem[fieldNameForChildren] = [];
        });
        list.forEach(function (flatItem) {
            var parentKey = flatItem[parentKeyFieldName];
            if (parentKey !== null) {
                var parentObject = lookup[flatItem[parentKeyFieldName]];
                if (parentObject) {
                    parentObject[fieldNameForChildren].push(flatItem);
                } else {
                    rootElements.push(flatItem);
                }
            } else {
                rootElements.push(flatItem);
            }
        });
        return rootElements;
    };
    var numberToAlphabet = function (num) {
        if (num) {
            for (var ret = '', a = 1, b = 26; (num -= a) >= 0; a = b, b *= 26) {
                ret = String.fromCharCode(parseInt((num % b) / a) + 65) + ret;
            }
            return ret;
        }
    }
    var alphabetToNumber = function (alfabet) {
        if (alfabet) {
            var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;

            for (i = 0, j = alfabet.length - 1; i < alfabet.length; i += 1, j -= 1) {
                result += Math.pow(base.length, j) * (base.indexOf(alfabet[i]) + 1);
            }
            return result;
        }
    }
    var getIcon = function (key) {
        if (key === null || key === undefined)
            return '';
        var array = {
            Create: {
                fa: 'create.png'
            },
            create: {
                fa: 'create.png'
            },
            Edit: {
                fa: 'edit.png'
            },
            edit: {
                fa: 'edit.png'
            },
            Delete: {
                fa: 'delete.png'
            },
            delete: {
                fa: 'delete.png'
            },
            Cancel: {
                fa: 'cancel.png'
            },
            Refresh: {
                fa: 'refresh.png'
            },
            Copy: {
                fa: 'copy.png'
            },
            Paste: {
                fa: 'paste.png'
            },
            Cut: {
                fa: 'cut.png'
            },
            Up: {
                fa: 'up.png'
            },
            Down: {
                fa: 'down.png'
            },
            RoleUser: {
                fa: 'access.png'
            },
            ChangePassword: {
                fa: 'password.png'
            },
            Comparatives: {
                fa: 'comparatives.png'
            },
            ClosePeriod: {
                fa: 'closeperiod.png'
            },
            OpenPeriod: {
                fa: 'openperiod.png'
            },
            SendPeriod: {
                fa: 'period-send.png'
            },
            TakebackPeriod: {
                fa: 'period-takeback.png'
            },
            Archive: {
                fa: 'archive.png'
            },
            UnArchive: {
                fa: 'unarchive.png'
            },
            Calculator: {
                fa: 'calculator.png'
            },
            ExportExcel: {
                fa: 'exportexcel.png'
            },
            ImportExcel: {
                fa: 'importexcel.png'
            },
            Key: {
                fa: 'key.png'
            },
            Sort: {
                fa: 'sort.png'
            },
            Save: {
                fa: 'save.png'
            },
            TreeCreate: {
                fa: 'treecreate.png'
            },
            ValueEdit: {
                fa: 'valueedit.png'
            },
            ExportPdf: {
                fa: 'exportpdf.png'
            },
            storePdf: {
                fa: 'storePdf.png'
            },
            ExportHtml: {
                fa: 'export_html.png'
            },
            ReportDesign: {
                fa: 'reportdesign.png'
            },
            FileList: {
                fa: 'filelist.png'
            },
            SelectRow: {
                fa: 'selectrow.png'
            },
            Preview: {
                fa: 'preview.png'
            },
            PageContent: {
                fa: 'pagecontent.png'
            },
            Statement: {
                fa: 'statement.png'
            },
            StatementOption: {
                fa: 'statementoption.png'
            },
            PercentOwnership: {
                fa: 'percentownership.png'
            },
            Consolidate: {
                fa: 'consolidate.png'
            },
            DocsEnable: {
                fa: 'docs-enable.png'
            },
            DocsDisable: {
                fa: 'docs-disable.png'
            },
            DocsConfirm: {
                fa: 'docs-confirm.png'
            },
            DocsTemporary: {
                fa: 'docs-temporary.png'
            },
            DocEnable: {
                fa: 'doc-enable.png'
            },
            DocDisable: {
                fa: 'doc-disable.png'
            },
            DocConfirm: {
                fa: 'doc-confirm.png'
            },
            DocTemporary: {
                fa: 'doc-temporary.png'
            },
            AccountingNature: {
                fa: 'account-statement.png'
            },
            EraseCell: {
                fa: 'cell_style-erase.png'
            },
            MergeCells: {
                fa: 'cells_merge.png'
            },
            Help: {
                fa: 'help.png'
            },
            CalculateToday: {
                fa: 'calculatortoday.png'
            },
            CalculateDate: {
                fa: 'calculatordate.png'
            },
            ImportFile: {
                fa: 'import_from_database.png'
            },
            ExportFile: {
                fa: 'export_to_database.png'
            },
            CalculateDocument: {
                fa: 'calculatordocment.png'
            },
            CalculateDocumentDelete: {
                fa: 'calculatedocument-delete.png'
            },
            StockBuy: {
                fa: 'buy.png'
            },
            StockSell: {
                fa: 'sell.png'
            },
            ListDelete: {
                fa: "list-delete.png"
            },
            DatabaseLink: {
                fa: "database-link.png"
            },
            NodeReport: {
                fa: "node-report.png"
            },
            ReportDownload: {
                fa: "report-preview.png"
            },
            MappingOn: {
                fa: "link-add2.png"
            },
            MappingOff: {
                fa: "link-delete2.png"
            },
            AcceptTreeChange: {
                fa: "tree-ok.png"
            },
            RejectTreeChange: {
                fa: "tree-delete2.png"
            },
            AcceptTable: {
                fa: "tree-new.png"
            },
            Info: {
                fa: "info.png"
            },
            ResetConsolidate: {
                fa: "buildings-update.png"
            },
            UnlockUser: {
                fa: "unlock-user.png"
            },
            UnlockTemplate: {
                fa: "security_unlock.png"
            },
            ModalResult: {
                fa: "report_open-new.png"
            },
            Returned: {
                fa: "returned.png"
            },
            FormMaker: {
                fa: "form.png"
            },
            CloseThis: {
                fa: "closethis.png"
            },
            CloseAll: {
                fa: "closeall.png"
            },
            CloseAllButThis: {
                fa: "closeallbutthis.png"
            },
            CloseRight: {
                fa: "closeright.png"
            },
            CloseLeft: {
                fa: "closeleft.png"
            },
            ExportExcels: {
                fa: "exporttexcels.png"
            },
        };
        var item = array[key];
        return item["fa"];
    }
    var int2Hex = function (i) {
        var h = i.toString(16);
        if (h.length == 1) {
            h = '0' + h;
        }
        return h;
    };
    var st2Hex = function (s) {
        return int2Hex(Number(s));
    };
    var toHex3 = function (c) {
        if (c.length > 10) { // IE9
            var p1 = 1 + c.indexOf('('),
                p2 = c.indexOf(')'),
                cs = c.substring(p1, p2).split(',');
            return ['#', st2Hex(cs[0]), st2Hex(cs[1]), st2Hex(cs[2])].join('');
        } else {
            return c;
        }
    };
    var cleanArray = function (actual) {
        var newArray = new Array();
        for (var i = 0; i < actual.length; i++) {
            if (actual[i]) {
                newArray.push(actual[i]);
            }
        }
        return newArray;
    }
    var jsonToStyle = function (item) {
        var style = "";
        if (item.textColor && item.textColor !== "")
            style += "color: " + item.textColor + ";";
        if (item.backColor)
            style += "background-color: " + item.backColor + ";";
        if (item.textAlign)
            style += "text-align: " + item.textAlign + ";";
        if (item.textBold)
            style += "font-weight: bold;";
        if (item.borderStyle)
            style += "border-style: " + item.borderStyle + ";";
        if (item.borderWidth)
            style += "border-width: " + item.borderWidth + ";";
        if (item.borderColor)
            style += "border-color: " + item.borderColor + ";";
        if (item.textFontFamily)
            style += "font-family: " + item.textFontFamily + ";";
        if (item.textFontSize)
            style += "font-size: " + item.textFontSize + ";";
        return style;
    }
    var template = function (tpl, args) {
        var keys = Object.keys(args),
            fn = new Function(...keys,
                'return ` ' + tpl.replace(/`/g, '\\ ` ') + '`');
        return fn(...keys.map(x =>
            " " + args[x]
        )
        );
    };
    var arrayToObject = function (list) {
        var object = {};
        for (var i = 0; i < list.length; i++) {
            object[list[i].key] = list[i].value;
        }
        return object;
    };
    var completeError = function (message, error) {
        if (message.indexOf("$") === -1)
            return message;
        return template(message, arrayToObject(error.keyValues));
    };
    var formatNumber = function (number, removeSign) {
        var decimalPart,
            numberPart;
        number = ko.isObservable(number) ? number() : number;
        if (number === null || number === undefined)
            return 0;
        if (number.toString().indexOf(".") !== -1) {
            numberPart = number.toString().split(".")[0];
            decimalPart = number.toString().split(".")[1];
            if (removeSign)
                return numberPart.toString().replace('-', '').replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "." + decimalPart;
            else
                return numberPart.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "." + decimalPart;

        } else {
            if (removeSign)
                return number.toString().replace('-', '').replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            else
                return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
    };
    var isNumberNegative = function (number) {
        number = number.toString();
        if (isNullOrEmpty(number) || number === "" || number === "0" || number.indexOf("-") === -1)
            return false;
        return true;
    }
    var timeAgo = function (date) {
        if (ko.isObservable(date)) {
            if (date() !== null && date() !== undefined && date() !== "")
                return $.timeago(date());
            else
                return "--";
        } else {
            if (date !== null && date !== undefined && date !== "")
                return $.timeago(date);
            else
                return "--";
        }
    }
    var anyFilters = function (filters) {
        if (any(filters)) {
            var hasActiveFilter = false;
            for (var i = 0; i < filters.length; i++) {
                if (!isNullOrEmpty(filters[i].source) || (filters[i].type && filters[i].type === "text"))
                    hasActiveFilter = true;
            }
            return hasActiveFilter;
        }
        return false;
    }
    var pixelToMm = function (val) {
        return (val * 0.2645833333);
    };
    var shortString = function (text, limit) {
        text = ko.isObservable(text) ? text() : text;
        if (!isNullOrEmpty(text)) {
            if (text.length < limit)
                return text;
            return text.substr(0, limit - 3) + "...";
        }
        return "";
    }
    var getWidth = function (element) {
        try {
            return element.getBoundingClientRect().width;

        } catch (e) {
            return 0;
        }
    }
    var getHeight = function (element) {
        try {
            return element.getBoundingClientRect().height;

        } catch (e) {
            return 0;
        }
    }
    var getLogoType = function (name) {
        name = name.trim();
        name = name.replace("شرکت", "");
        name = name.replace("گروه", "");
        name = name.trim().substring(0, 1);
        if (name !== null && name !== undefined && name !== "")
            return name;
        return "آ";
    }
    var generateTotalTableCaption = function (context) {
        var phrase = "";
        phrase += (((context.pageNumber() - 1) * context.pageSize()) + 1);
        if (context.total() < 1)
            phrase = 0;
        phrase += " تا ";
        var last = (context.pageSize() * context.pageNumber());
        if (last > context.total())
            phrase += context.total();
        else
            phrase += last;

        phrase += " از " + context.total() + " رکورد";

        return phrase;
    }
    var splitStringList = function (str, seprator) {
        if (isNullOrEmpty(str) || str === "")
            return [];
        if (isNullOrEmpty(seprator) || seprator === "")
            seprator = ",";
        var splites = str.split(seprator);
        splites = cleanArray(splites);
        return splites;
    }
    var concatStringList = function (list, seprator) {
        if (!list && list.length === 0)
            return "";
        var phrase = "";
        for (var i = 0; i < list.length; i++) {
            if (list.length === i + 1) {
                phrase += list[i];
            } else {
                phrase += (list[i] + ",");
            }
        }
        return phrase;
    }
    var contains = function (set, val) {
        var res = false;
        for (var i = 0; i < set.length; i++) {
            if (set[i] === val)
                res = true;
        }
        return res;
    }
    var splitMulti = function (str, tokens) {
        var tempChar = tokens[0];
        for (var i = 1; i < tokens.length; i++) {
            str = str.split(tokens[i]).join(tempChar);
        }
        str = str.split(tempChar);
        return str;
    }
    var escapeRegExp = function (str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
    var replaceAll = function (str, find, replace) {
        if (isNullOrEmpty(str) || str === "")
            return str;
        return str.replace(new RegExp(find, 'g'), replace);
    }
    var tdOutput = function (record, col, parents) {
        var value, className, span = "<span>";
        switch (col.type) {
            case "enum":
                value = getEnumText(window[col.name + 's'], record[col.name]());
                if (value === null && col['enumSourceName']) {
                    value = getEnumText(window[col['enumSourceName']], record[col.name]());
                }
                if (value === null && col['enumSourceName'] === null) {
                    value = "-";
                }
                span = "<span>" + value + "</span>";
                return span;
            case "template":
                value = record[col.name]();
                span = "<div class='awcheckbox awcheckbox-success awcheckbox-inline'><input type='checkbox' checked='"
                    + value + "' id='" + col.name + record.id() + "'><label for='" + col.name + record.id() + " ></label></div>";

                return span;
            case "label":
                var item = getEnumItem(window[col.name + 's'], record[col.name]());
                switch (item.color) {
                    case "green":
                        className = 'label label-success';
                        break;
                    case "red":
                        className = 'label label-danger';
                        break;
                    case "orange":
                        className = 'label label-warning';
                        break;
                    case "blue":
                        className = 'label label-info';
                        break;
                    case "navy":
                        className = 'label label-primary';
                        break;
                    case "gray":
                        className = 'label label-default';
                        break;
                    case "none":
                        className = 'label label-none';
                        break;
                    case "":
                        className = 'label label-none';
                        break;
                }
                span = "<span class='" + className + "'>" + item.text + "</span>";
                return span;
            case "timeago":
                span = "<span>" + timeAgo(record[col.name]) + "</span>";
                return span;
            case "pdatetime":
                span = "<span style='unicode-bidi: plaintext;'>" +
                    dateHelper.formatPersianDateTime(record[col.name]) +
                    "</span>";
                return span;
            case "pdate":
                span = "<span>" + dateHelper.formatPersianDate(record[col.name]) + "</span>";
                return span;
            case "money-abs":
                value = formatValue(record, col);
                span = "<span data-original-title='" +
                    formatNumber(Math.abs(value), true) +
                    "'>" +
                    formatNumber(Math.abs(value), true) +
                    "</span>";
                return span;
            case "money":
                value = formatValue(record, col);
                span = "<span data-original-title='" +
                    formatNumber(value, true) +
                    "'>" +
                    formatNumber(value, true) +
                    "</span>";
                return span;
            case "smoney":
                value = formatValue(record, col);
                span = "<span data-original-title='" +
                    formatNumber(value, false) +
                    "'>" +
                    formatNumber(value, false) +
                    "</span>";
                return span;
            case 'stringdrag':
                value = formatValue(record, col);
                var id = ko.isObservable(record['id']) ? record['id']() : record['id'];
                span = "<span class='template-item ui-draggable ui-draggable-handle' data-id='" +
                    id +
                    "'>" +
                    value +
                    "</span>";
                return span;
            case "lstring":
                value = formatValue(record, col);
                span = "<span  style='unicode-bidi: plaintext;'>" + value + "</span>";
                return span;
            case "string":
                value = formatValue(record, col);
                return "<span style='unicode-bidi: plaintext;'>" + value + "</span>";
            case "stateSwitch":
                var div;
                if (record[col.name]() === true || record[col.name]() === 1) {
                    div = '<div class="onoffswitch" style="margin-right: 20px;">' +
                        '<input type="checkbox" name="state" checked="checked" class="onoffswitch-checkbox">' +
                        '<label class="onoffswitch-label"></label></div>';
                } else {
                    div = '<div class="onoffswitch" style="margin-right: 20px;">' +
                        '<input type="checkbox" name="state" class="onoffswitch-checkbox">' +
                        '<label class="onoffswitch-label"></label></div>';
                }
                return div;
            case "file":
                var index = Number(col.name);
                value = record[index];
                if (!value)
                    return "";
                value = getFileIcon(value);
                var title = ko.isObservable(record[index]) ? record[index]() : record[index];
                var div = '<a class="file-download-item" title="' + title + '" data-order="' + index + '"><img class="icon-image-xsmall selectable" style="vertical-align: middle;" src="' + value + '"/><a/>';
                return div;
                break;
            case "bool":
                value = formatValue(record, col);
                if (value)
                    span = "<span  style='unicode-bidi: plaintext;'>بایگانی شده</span>";
                else
                    span = "<span  style='unicode-bidi: plaintext;'>-</span>";
                return span;
                break;
        }
    }
    var getVm = function (parents) {
        if (parents[1]["isVisibleColumn"])
            return parents[1];
        return parents[2];
    }
    var formatValue = function (record, col) {
        var value = ko.isObservable(record[col.name]) ? record[col.name]() : record[col.name];
        if (value === null || value === "null" || value === undefined)
            return "-";
        return value;
    }
    var clearNumber = function (num) {
        if (!num)
            return undefined;
        return replaceAll(num, ",", "");
    }
    var calDim = function (val, fontSize, fontFamily, fontWeight) {
        var test = document.getElementsByClassName("test-el")[0];
        test.style.fontSize = fontSize;
        test.style.fontFamily = fontFamily;
        test.style.fontWeight = fontWeight;
        test.innerText = val;
        var height = test.clientHeight + 1;
        var width = test.clientWidth + 1;
        test.innerText = "";
        return [height, width];
    }
    var fixItemHeight = function (id) {
        var ul = document.getElementById(id);
        if (!ul)
            return;
        var liList = $(ul).find("li");
        var height = 0;
        if (liList && liList.length > 0) {
            for (var i = 0; i < liList.length; i++) {
                var li = liList[i];
                height += $(li).height();
            }
            if (height > 210 || liList.length > 7) {
                $(ul).height("210px");
            } else {
                $(ul).height((height + 22) + "px");
            }
        } else {
            $(ul).height("10px");
        }
    }
    var createRandomNumber = function () {
        var min = Math.ceil(1);
        var max = Math.floor(999999999);
        return Math.floor(Math.random() * (max - min) + min);
    }
    var isEnglishKeyboard = function (input) {
        var rtlChars = '\u0600-\u06FF';
        rtlChars += '\u0750-\u077F';
        rtlChars += '\uFB50-\uFDFF';
        rtlChars += '\uFE70-\uFEFF';
        var controlChars = '\u0000-\u0020';
        controlChars += '\u2000-\u200D';
        var reRTL = new RegExp('^[' + controlChars + ']*[' + rtlChars + ']');
        var reControl = new RegExp('^[' + controlChars + ']*$');
        var value = input;

        if (value === undefined)
            return false;

        if (value.match(reRTL)) {
            return false;
        } else if (value.match(reControl)) {
            return false;
        } else {
            return true;
        }
    }
    var multiSplit = function (str, delimiter) {
        if (!(delimiter instanceof Array))
            return str.split(delimiter);
        if (!delimiter || delimiter.length == 0)
            return [str];
        var hashSet = new Set(delimiter);
        if (hashSet.has(""))
            return str.split("");
        var lastIndex = 0;
        var result = [];
        for (var i = 0; i < str.length; i++) {
            if (hashSet.has(str[i])) {
                result.push(str.substring(lastIndex, i));
                lastIndex = i + 1;
            }
        }
        result.push(str.substring(lastIndex));
        return result;
    }
    var shortName = function (name, num) {
        if (!num)
            num = 35;
        if (name.length < num)
            return [name, false];
        return [name.substr(0, num - 3) + "...", true];
    }
    var shortValue = function (val) {
        return val.replace("-", "");
    }
    var abs = function (val) {
        return val.replace("-", "");
    }
    var getPosition = function (el) {
        var rect = el.getBoundingClientRect(),
            scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
            scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        var l, t, w, h, sw, sh, sbw, sbh;
        if (el == document.body) {
            l = 0;
            t = 0;
            w = document.body.clientWidth || document.documentElement.clientWidth || window.innerWidth;//don't change this order
            h = document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight; //don't change this order
            sw = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
            sh = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
            sbw = (document.documentElement.clientWidth - document.body.offsetWidth); //16
            sbh = (document.documentElement.clientHeight - document.body.offsetHeight); //16
        } else {
            l = rect.left + scrollLeft;
            t = rect.top + scrollTop;
            w = rect.right - rect.left;
            h = rect.bottom - rect.top;
            sw = el.scrollWidth;
            sh = el.scrollHeight;
            sbw = el.offsetWidth - el.clientWidth; //17
            sbh = el.offsetHeight - el.clientHeight; //17
        }
        return {
            left: l, top: t
            , width: w, height: h
            , right: l + w
            , bottom: t + h
            , scrollLeft: scrollLeft
            , scrollTop: scrollTop
            , scrollWidth: sw
            , scrollHeight: sh
        };
    };
    var periodSelectRowTemplate = function (item) {
        var temp = '<div>' +
            '<span class="item-title">' +
            '<span class="item-name">' +
            item.text +
            '</span></span>' +
            '<ul class="item-meta">' +
            '<li class="item-type">' +
            getEnumText(periodTypes, item.periodType) +
            " - " +
            getEnumText(periodStates, item.periodState) +
            " - " +
            getEnumText(auditStates, item.auditState);

        if (item.description)
            temp += '<i class="dmn-info fa fa-info-circle" title="' + item.description + '"></i>';

        temp += '</li></ul></div>';
        return temp;
    };
    var tagSelectRowTemplate = function (item) {
        var temp = '<div style="padding: 3px;">' +
            '<span class="item-title">' +
            '<span class="item-name">' +
            item.text +
            '</span>' +
            '</span>' +
            '<div class="label label-primary2 remove-tag" style="float: left;padding-top: 4px;background-color: #ccc;">حذف</div>' +
            '</div>';
        return temp;
    };
    var activeTooltip = function (onlyVisible) {
        if (!onlyVisible) {
            var elements = $('[title]');
            $(elements).tooltip({ placement: 'top' });
        } else {
            $('[title]:visible').tooltip({ placement: 'top' });
        }
    };
    var removeDragLabel = function () {
        var div = document.getElementById('drag-label');
        div.style.display = "none";
    };
    var toBase64 = function (file, callback) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            callback(reader.result);
        };
        reader.onerror = function (error) {
            callback(undefined);
        };
    }
    var stringHasAlphabet = function (str) {
        var index;
        var res = false;
        var english = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+<>?|\\/";
        for (index = str.length - 1; index >= 0; --index) {
            var x = str.substring(index, index + 1);
            if (english.indexOf(x) > 0) {
                res = true;
            }
        }

        for (var i = 0, len = str.length; i < len; i++) {
            var target = str[i];
            if (/[^\u0600-\u06FF\s]/g.test(target) === false) {
                res = true;
            }
        }
        return res;
    }
    var prop1Class = function (data) {
        switch (data.items[0]['t']) {
            case "rdo":
            case "chk":
                return 'col-xs-12';
            case "tsp":
                if (data.items.length === 1)
                    return 'form-full-line form-full-tuchpin-line col-xs-12';
                if (data.items.length > 1)
                    return 'form-line form-tuchpin-line  col-xs-6';
                break;

            default:
                if (data.items.length === 1)
                    return 'form-full-line col-xs-12';
                if (data.items.length > 1)
                    return 'form-line col-xs-6';
        }
    };
    var prop2Class = function (data) {
        switch (data.items[1]['t']) {
            case "rdo":
            case "chk":
                return 'col-xs-6';
            case "tsp":
                return 'form-line form-tuchpin-line  col-xs-6';
            default:
                return 'form-line col-xs-6';
        }
    };
    var hasSpecialChar = function (str) {
        if (!str)
            return false;
        var res = false;
        for (var i = 0; i < str.length; i++) {
            if (/^[!@#\$%\^\&*\)\(+=._-]+$/g.test(str[i]))
                res = true;
        }
        return res;
    };
    var adjustModalPosition = function (width, minWidth) {
        var mb = $(".modal-box");
        mb.css("width", width);
        var screenWidth = $("body").width();
        var modalWidth = mb.width()
        var rest = (screenWidth - (modalWidth + 65)) / 2;
        mb.css("left", rest + "px");
        if (minWidth)
            mb.css("min-width", minWidth);
    }
    var getFileIcon = function (fileName) {
        var value = ko.isObservable(fileName) ? fileName() : fileName;
        var ext = getExtension(value);
        var base = "/App/src/images/ico/";
        switch (ext.toLowerCase()) {
            case "txt":
                return base + "file_text.png";
            case "xlsx":
            case "xls":
                return base + "file_excel.png";
            case "html":
                return base + "file_html.png";
            case "csv":
                return base + "file_csv.png";
            case "pdf":
                return base + "file_pdf.png";
            case "png":
            case "jpg":
            case "jpeg":
                return base + "file_image.png";
            case "":
                return "";
            default:
                return base + "file_txt.png";

        }
    }
    var normalizeAmpersand = function (phrase) {
        if (isEmpty(phrase))
            return "";
        if (typeof phrase !== "string" || phrase.indexOf("&&") === -1)
            return phrase;
        return replaceAll(phrase, "&&", "\\u0026\\u0026");
    }
    var findMinMaxCells = function (list) {
        let minCol = Math.min(...list.map(item => item.col));
        let minRow = Math.min(...list.map(item => item.row));
        let maxCol = Math.max(...list.map(item => item.col));
        let maxRow = Math.max(...list.map(item => item.row));
        let minCell = list.filter(item => item.col === minCol && item.row === minRow)[0];
        let maxCell = list.filter(item => item.col === maxCol && item.row === maxRow)[0];

        return [minCell.address, maxCell.address];
    }
    var analyzeCells = function (list) {
        let minCol = Math.min(...list.map(item => item.col));
        let minRow = Math.min(...list.map(item => item.row));
        var canShowChartOffline = list.filter(a => !isNullOrEmpty(a.value)).length;
        var series = list.filter(item => item.row === minRow && item.col !== minCol);// columns name
        var categories = list.filter(item => item.col === minCol && item.row !== minRow);// rows name
        var columns = series.map(function (v) {
            return { label: v.text, address: v.address };
        });
        var rows = categories.map(function (v) {
            return { label: v.text, address: v.address };
        });

        return [columns, rows, canShowChartOffline];
    }
    var downloadFile = function (code) {
        var url = "/reports/downloadfile?code=" + code;
        window.open(url);
    }
    var clearHtmlTag = function (str) {
        if (isEmpty(str))
            return "";
        return str.replace(/<\/?[^>]+(>|$)/g, "");
    }
    var createNodeTooltip = function (str) {
        var list = str.split('|');
        var ul = _hh.createTag({
            name: "ul",
            attach: false,
            className: "none-style",
            styles: "direction: rtl;"
        });
        for (var i = 0; i < list.length; i++) {
            var li = _hh.createTag({
                name: "li",
                parent: ul,
                styles: "font-size: 10px; font-weight: 400;"
            });
            var divRow = _hh.createTag({
                name: "div",
                parent: li,
                className: "row m-b-m"
            });
            var div = _hh.createTag({
                name: "div",
                parent: divRow,
                className: "col-lg-12",
                styles: "margin-top: 11px;"
            });
            _hh.createTag({
                name: "span",
                parent: div,
                text: (i + 1) + '- '
            });
            _hh.createTag({
                name: "span",
                parent: div,
                text: list[i]
            });
        }
        return ul;
    }
    var changeAft = function (val) {
        if (val)
            document.getElementsByName("__RequestVerificationToken")[0].value = val;
    }

    return {
        changeAft: changeAft,
        createNodeTooltip: createNodeTooltip,
        clearHtmlTag: clearHtmlTag,
        downloadFile: downloadFile,
        findMinMaxCells: findMinMaxCells,
        analyzeCells: analyzeCells,
        normalizeAmpersand: normalizeAmpersand,
        getFileIcon: getFileIcon,
        adjustModalPosition: adjustModalPosition,
        hasSpecialChar: hasSpecialChar,
        prop2Class: prop2Class,
        prop1Class: prop1Class,
        stringHasAlphabet: stringHasAlphabet,
        toBase64: toBase64,
        findControllerName: findControllerName,
        setSd: setSd,
        getSd: getSd,
        abs: abs,
        abd: abd,
        shortValue: shortValue,
        shortName: shortName,
        periodSelectRowTemplate: periodSelectRowTemplate,
        emptyTextIfNull: emptyTextIfNull,
        isEnglishKeyboard: isEnglishKeyboard,
        getPosition: getPosition,
        createRandomNumber: createRandomNumber,
        fixItemHeight: fixItemHeight,
        calDim: calDim,
        removeDragLabel: removeDragLabel,
        clearNumber: clearNumber,
        tdOutput: tdOutput,
        formatValue: formatValue,
        replaceAll: replaceAll,
        splitMulti: splitMulti,
        escapeRegExp: escapeRegExp,
        contains: contains,
        concatStringList: concatStringList,
        splitStringList: splitStringList,
        generateTotalTableCaption: generateTotalTableCaption,
        getLogoType: getLogoType,
        getWidth: getWidth,
        getHeight: getHeight,
        shortString: shortString,
        pixelToMm: pixelToMm,
        timeAgo: timeAgo,
        formatNumber: formatNumber,
        isNumberNegative: isNumberNegative,
        anyFilters: anyFilters,
        completeError: completeError,
        jsonToStyle: jsonToStyle,
        cleanArray: cleanArray,
        toHex3: toHex3,
        getIcon: getIcon,
        alphabetToNumber: alphabetToNumber,
        numberToAlphabet: numberToAlphabet,
        setAppSetting: setAppSetting,
        getAppSetting: getAppSetting,
        initResizeTable: resizeTable,
        errorListHandler: errorListHandler,
        warningListHandler: warningListHandler,
        successListHandler: successListHandler,
        formatTextIfNull: formatTextIfNull,
        isNumeric: isNumeric,
        isNullOrEmpty: isNullOrEmpty,
        isEmpty: isEmpty,
        isBigger: isBigger,
        multiSplit: multiSplit,
        tagSelectRowTemplate: tagSelectRowTemplate,
        any: any,
        confirmDeleteAlert: confirmDeleteAlert,
        confirmTableTemplateAlert: confirmTableTemplateAlert,
        confirmChooseAlert: confirmChooseAlert,
        successToast: successToast,
        failToast: failToast,
        warningToast: warningToast,
        getEnumText: getEnumText,
        getEnumEnText: getEnumEnText,
        getEnumItemByText: getEnumItemByText,
        kocnx: kocnx,
        getVm: getVm,
        countBackNumberZero: countBackNumberZero,
        getExtension: getExtension,
        getApiMessage: getApiMessage,
        generateUuid: generateUuid,
        getLocalizedText: getLocalizedText,
        findModelRes: findModelRes,
        findPageRes: findPageRes,
        getEnumItem: getEnumItem,
        toggleChildren: toggleChildren,
        fixLabelsSize: fixLabelsSize,
        setUd: setUd,
        getUd: getUd,
        getTvm: getTvm,
        backToLogin: backToLogin,
        toggleDisableSections: toggleDisableSections,
        buildTree: buildTree,
        activeTooltip: activeTooltip
    };
}();


Array.prototype.remove = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === val) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
}