var exportType = '';
var exportTitle = '';
var shiftTab = false;
var enter = false;
var tab = false;
var stopEventCellChange = false;
var DEFULTGRID = "پیش فرض";
var CONS = { accounting: "hesab", noteDocument: "1" };
var saleSystemParent = { pos: 2, shop: 3, trade: 1 };
var enumLockDetail = { trade: "392" };

if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}
translateRowFilterMenu();
$(document).ready(function () {
    $(".system-lookup-control").on("change", ".checkbox-control", function () {
        var resultCode = "";
        var resultText = "";
        var $lookup = $(this).closest(".system-lookup-control");
        $lookup.find("ul li .checkbox-control:checked").each(function (index, item) {
            resultCode += (resultCode !== "" ? "," : "") + $(item).closest("li").attr("data-code");
            resultText += (resultText !== "" ? "," : "") + $(item).closest("li").text();
        });
        $lookup.attr("data-value", resultCode);
        $lookup.find(".text").text(resultText);
        if ($lookup.attr("onselected"))
            eval($lookup.attr("onselected") + "('" + $lookup.attr("id") + "')");
    });
    $(".system-lookup-control").each(function (index, element) {
        if ($(element).attr("data-online") !== "true" && typeof getEventLookupCombo === "function")
            getEventLookupCombo($(element), "");
    });
    $("[multiple]").each(function (index, element) {
        if ($(element).hasClass("demo-default"))
            return;
        getEventLookupCombo($(element), "");
    });
    document.onkeydown = function (event) {
        event = event || window.event;
        if (event.keyCode === 112) //f1 
        {
            window.top.showHelpForm();
            event.preventDefault();
        }
    };
    $(document).click(function (event) {
        if (eval("typeof window.top.closeLeftSideMenu") === "function") {
            window.top.closeLeftSideMenu();
            if ($(".container-help").find(event.target).length === 0)
                window.top.hideSidebar();
        }
    });
    setTimeout(function () {
        $(".grid").each(function (index, grid) {
            var gridBuilder = $(grid).gridBuilder();
            gridBuilder.onCustomizeFieldClick(function (gridId) {
                var columns = gridBuilder.getAllColumns();
                var captions = gridBuilder.getColumnsCaption();
                var widths = gridBuilder.getColumnsWidth();
                var commas = gridBuilder.getColumnsComma();
                var typeArray = gridBuilder.getColumnsType().split(",");
                var images = "";
                gridBuilder.getColumns().split(",").forEach(function (item, index) {
                    if (typeArray[index] === "image") {
                        images += (images.length > 0 ? "," : "") + item;
                    }
                });

                var modelName = $("#" + gridId).attr("data-model");
                var removedColumn = $("#" + gridId).attr("data-removed-column");
                var pageAddress = window.location.pathname.replace(gridBuilder.baseUrl, "").toLowerCase();
                var defaultColumns = gridBuilder.defaultColumns;
                var defaultColumnsWidths = gridBuilder.defaultColumnsWidth;
                var defaultColumnsCaptions = gridBuilder.defaultColumnsCaption;
                var defaultColumnsCommas = gridBuilder.defaultColumnsCommas;
                var defaultColumnsImages = gridBuilder.defaultColumnsImages;
                var defaultColumnArray = defaultColumns.split(",");
                var defaultExtendedColumns = [];
                columns = columns.split(",").filter(x => x).join(",");
                columns.split(",").forEach(function (field) {
                    if (!defaultColumnArray.includes(field))
                        defaultExtendedColumns.push(field);
                });

                var defaultParameters = "defaultColumns=" + defaultColumns + (defaultExtendedColumns.length > 0 ? "," + defaultExtendedColumns.join(",") : "") + "|defaultColumnsCaptions=" + defaultColumnsCaptions + "|defaultColumnsWidths=" + defaultColumnsWidths + "|defaultColumnsCommas=" + defaultColumnsCommas + "|defaultColumnsImages=" + defaultColumnsImages;
                var parameters = "pageAddress=" + pageAddress + "|" + defaultParameters + "|columns=" + columns + "|captions=" + captions + "|widths=" + widths + "|commas=" + commas + "|images=" + images;
                openInModal("", "General/GridCustomizeField?gridId=" + gridId + "&model=" + modelName + "&removed=" + removedColumn, window.top.changeField, 500, 550, true, parameters);
            });
        });
    }, 1000);
    
});

String.prototype.replaceAll = function (search, replacement) {
    return this.replace(new RegExp(search, "g"), replacement);
};
$(document).on("keydown", ".panel-grid", function (event) {
    var id = $(this).find("table").attr("id");
    var grid = eval(id);
    if (!grid.allowBatchEditing) {
        if (event.ctrlKey && event.keyCode === 65) {
            grid.SelectAllRowsOnPage();
            event.preventDefault();
        }
    }
});

function redirectUrl(url, target, token) {
    if (!url)
        url = window.location.href;
    if (!token)
        token = window.top.$("#hfSid").val();
    if (!target)
        target = "_self";

    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("action", url);
    form.setAttribute("target", target);

    var hfSid = document.createElement("input");
    hfSid.setAttribute("name", "result");
    hfSid.setAttribute("value", "X-User-Token=" + (token || ""));

    form.appendChild(hfSid);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function openInTab(url, title, iconUrl, closeAfterLoading, parameters) {
    window.top.openInTab(url, title, iconUrl, closeAfterLoading, parameters);
}
function openInModal(iconUrl, url, title, width, height, closeAfterLoading, parameters) {
    window.top.openInModal(iconUrl, url, title, width, height, closeAfterLoading, parameters);
}
function closeTopModal() {
    closeLoading();
    window.top.closeTopModal();
}
function closeCurrentTab() {
    closeLoading();
    window.top.closeCurrentTab();
}
function closeCurrentModal(id) {
    closeLoading();
    window.top.closeCurrentModal(id);
}
function refreshParent(method) {
    return window.top.refreshParent(method);
}
function refreshParentList(method) {
    return window.top.refreshParentList(method);
}
function refreshParentDetail(method) {
    return window.top.refreshParentDetail(method);
}

function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', o.value.length);
        if (r.text == '') return o.value.length;
        return o.value.lastIndexOf(r.text);
    } else return o.selectionStart;
}
function translateRowFilterMenu() {
    //$(".grid-filter div[data-filter='equals'] div:last-child").text(window.top.equals);
    //$(".grid-filter div[data-filter='not-equal'] div:last-child").text(window.top.doesntEqual);
    //$(".grid-filter div[data-filter='starts-with'] div:last-child").text(window.top.beginsWith);
    //$(".grid-filter div[data-filter='ends-with'] div:last-child").text(window.top.endsWith);
    //$(".grid-filter div[data-filter='contains'] div:last-child").text(window.top.contains);
    //$(".grid-filter div[data-filter='not-contains'] div:last-child").text(window.top.doesntContain);
    //$(".grid-filter div[data-filter='less'] div:last-child").text(window.top.less);
    //$(".grid-filter div[data-filter='less-equal'] div:last-child").text(window.top.lessEqual);
    //$(".grid-filter div[data-filter='greater'] div:last-child").text(window.top.greater);
    //$(".grid-filter div[data-filter='greater-equal'] div:last-child").text(window.top.greaterEqual);


    //$(".grid .grid-header .grid-title .grid-title-count").text(window.top.item + ":");
    //$(".grid .grid-footer span:not([class])").text(window.top.from);
    //$(".grid .grid-footer input[type='text']").attr("placeholder", window.top.goto);

    lookupBuilderGlobal.dictionary.item = window.top.item;
    lookupBuilderGlobal.dictionary.search = window.top.search;
    gridBuilderGlobal.dictionary.item = window.top.item;
    gridBuilderGlobal.dictionary.equal = window.top.equals;
    gridBuilderGlobal.dictionary.notEqual = window.top.doesntEqual;
    gridBuilderGlobal.dictionary.startWith = window.top.beginsWith;
    gridBuilderGlobal.dictionary.endWith = window.top.endsWith;
    gridBuilderGlobal.dictionary.contain = window.top.contains;
    gridBuilderGlobal.dictionary.notContain = window.top.doesntContain;
    gridBuilderGlobal.dictionary.less = window.top.less;
    gridBuilderGlobal.dictionary.lessEqual = window.top.lessEqual;
    gridBuilderGlobal.dictionary.greater = window.top.greater;
    gridBuilderGlobal.dictionary.greaterEqual = window.top.greaterEqual;
    gridBuilderGlobal.dictionary.viewSelected = window.top.showChoices;
    gridBuilderGlobal.dictionary.viewAll = window.top.showAll;
    gridBuilderGlobal.dictionary.deleteSelected = window.top.deleteChoices;
    gridBuilderGlobal.dictionary.selected = window.top._select;
    gridBuilderGlobal.dictionary.goto = window.top.goto;
    gridBuilderGlobal.dictionary.from = window.top.from;
    gridBuilderGlobal.dictionary.insertKeyForNewRow = window.top.insertKeyForNewRow;
    gridBuilderGlobal.dictionary.newRow = window.top.newRow;
    gridBuilderGlobal.dictionary.changeField = window.top.changeField;
    gridBuilderGlobal.dictionary.autoAlignColumns = window.top.autoAlignColumns;
    gridBuilderGlobal.dictionary.getExcelSample = window.top.getExcelSample;
    gridBuilderGlobal.dictionary.excelOutput = window.top.excelOutput;
    gridBuilderGlobal.dictionary.importFromExcel = window.top.importFromExcel;
    gridBuilderGlobal.dictionary.fileOutputOffline = window.top.fileOutputOffline;
    gridBuilderGlobal.dictionary.fileInputOffline = window.top.fileInputOffline;
    gridBuilderGlobal.dictionary.manageTags = window.top.manageTags;
    commonGlobal.dictionary.doDelete = window.top.doDelete;
    commonGlobal.dictionary.completeFillMarked = window.top.fillMarked;
    commonGlobal.dictionary.warning = window.top.warning;
    commonGlobal.dictionary.copyText = window.top.copyText;
    commonGlobal.dictionary.code = window.top.code;
    commonGlobal.dictionary.description = window.top.desc;
    commonGlobal.dictionary.close = window.top.close;
    commonGlobal.dictionary.makeSureYourSystemConnectedToNetwork = window.top.makeSureYourSystemConnectedToNetwork;
    commonGlobal.dictionary.contactSystemAdministrator = window.top.contactSystemAdministrator;
}
function checkIsNumberDev(s, e, manualDecimalCount) {
    var specialKeys = new Array();
    specialKeys.push(8); //backspace
    specialKeys.push(9); //Tab
    specialKeys.push(13); //enter
    specialKeys.push(16); //shiftKey
    specialKeys.push(17); //ctrlKey
    specialKeys.push(27); //escape
    specialKeys.push(38); //up
    specialKeys.push(40); //down
    specialKeys.push(45); //insert
    specialKeys.push(46); //delete

    if (specialKeys.indexOf(e.htmlEvent.keyCode) === -1) {

        var decimalCount = 0;
        if (manualDecimalCount && manualDecimalCount !== '') {
            decimalCount = Number(manualDecimalCount);
        }
        else if (s.displayFormat === '{0:n' + window.top.$('#hfDecimalCount').val() + '}')
            decimalCount = Number(window.top.$('#hfDecimalCount').val());

        if (decimalCount > 0) {
            var sender = s.GetInputElement();
            var dotPos = $(sender).val().indexOf(".");
            if ((e.htmlEvent.keyCode === 110 || e.htmlEvent.keyCode === 190) && dotPos === -1)
                return true;

            var caratPos = getSelectionStart($(sender)[0]);
            if (caratPos > dotPos && dotPos > -1 && ($(sender).val().split('.')[1].length > decimalCount - 1)) {
                ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
            }
        } else {
            specialKeys.push(110); // . numLock
            specialKeys.push(190); // .
        }
        if (!(e.htmlEvent.keyCode >= 48 && e.htmlEvent.keyCode <= 57) &&
            !(e.htmlEvent.keyCode >= 96 && e.htmlEvent.keyCode <= 105) &&
            !(e.htmlEvent.keyCode >= 112 && e.htmlEvent.keyCode <= 123)) {
            ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        }
    }
}
function isNumeric(value) {
    value = value.toString().trim();
    return Number(value).toString() === value;
}
function isNullOrEmptyQuery(name, url) {
    return getQuery(name, url) == '';
}
var wordifyfa = function (num, level) {
    'use strict';
    if (num === null) {
        return "";
    }
    num = Number(numberNonCommas(num).toString().split('.')[0]);
    // convert negative number to positive and get wordify value
    if (num < 0) {
        num = num * -1;
        return window.top.negative + wordifyfa(num, level);
    }
    if (num === 0) {
        if (level === 0) {
            return window.top.zero;
        } else {
            return "";
        }
    }
    var result = "";
    var yekan = [window.top.one, window.top.two, window.top.three, window.top.four, window.top.five, window.top.six, window.top.seven, window.top.eight, window.top.nine];
    var dahgan = [window.top.twenty, window.top.thirty, window.top.forty, window.top.fifty, window.top.sixty, window.top.seventy, window.top.eighty, window.top.ninety];
    var sadgan = [window.top.hundred, window.top.twoHundred, window.top.threeHundred, window.top.fourHundred, window.top.fiveHundred, window.top.sixHundred, window.top.sevenHundred, window.top.eightHundred, window.top.nineHundred];
    var dah = [window.top.ten, window.top.eleven, window.top.twelve, window.top.thirteen, window.top.fourteen, window.top.fifteen, window.top.sixteen, window.top.seventeen, window.top.eighteen, window.top.nineteen];

    if (level > 0) {
        result += " " + (window.top.isLeftToRight ? "" : window.top.and) + " ";
        level -= 1;
    }

    if (num < 10) {
        result += yekan[num - 1] + " ";
    } else if (num < 20) {
        result += dah[num - 10] + " ";
    } else if (num < 100) {
        result += dahgan[parseInt(num / 10, 10) - 2] + wordifyfa(num % 10, level + 1) + " ";
    } else if (num < 1000) {
        result += sadgan[parseInt(num / 100, 10) - 1] + wordifyfa(num % 100, level + 1) + " ";
    } else if (num < 1000000) {
        result += wordifyfa(parseInt(num / 1000, 10), level) + window.top.thousand + wordifyfa(num % 1000, level + 1) + " ";
    } else if (num < 1000000000) {
        result += wordifyfa(parseInt(num / 1000000, 10), level) + window.top.million + wordifyfa(num % 1000000, level + 1) + " ";
    } else if (num < 1000000000000) {
        result += wordifyfa(parseInt(num / 1000000000, 10), level) + window.top.milliard + wordifyfa(num % 1000000000, level + 1) + " ";
    } else if (num < 1000000000000000) {
        result += wordifyfa(parseInt(num / 1000000000000, 10), level) + window.top.trilliard + wordifyfa(num % 1000000000000, level + 1) + " ";
    }
    return result;

};
var wordifyRials = function (num) {
    return wordifyfa(num, 0) + " " + window.top.rial;
};
function isDate(value) {
    var currVal = value;
    if (currVal == '')
        return false;

    var rxDatePattern = /^(\d{2})(\/)(\d{2})(\/)(\d{2})$/;
    var dtArray = currVal.match(rxDatePattern);

    if (dtArray == null)
        return false;

    var dtMonth = dtArray[3];
    var dtDay = dtArray[5];
    var dtYear = dtArray[1];


    if (dtMonth < 1 || dtMonth > 12)
        return false
    else if (dtDay < 1 || dtDay > 31)
        return false;

    return true;
}
function isFullDate(value) {
    var currVal = value;
    if (currVal == '')
        return false;
    var rxDatePattern = /^(\d{4})(\/)(\d{2})(\/)(\d{2})$/;
    var dtArray = currVal.match(rxDatePattern);
    if (dtArray == null)
        return false;
    var dtMonth = dtArray[3];
    var dtDay = dtArray[5];
    var dtYear = dtArray[1];
    if (dtMonth < 1 || dtMonth > 12)
        return false
    else if (dtDay < 1 || dtDay > 31)
        return false;
    return true;
}
function validatePass(value) {
    //return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\W\d]{6,}$/.test(value);
    return value.length > 3;
}
function JsonToArray(data) {
    var key;
    var dataArray = [];
    for (key in data) {
        if (data.hasOwnProperty(key)) {
            dataArray.push({ key: key, value: data[key] });
        }
    }
    return dataArray;
}
function checkIsNumber(s, e, manualDecimalCount) {

    var specialKeys = new Array();
    specialKeys.push(8); //backspace
    specialKeys.push(9); //Tab
    specialKeys.push(13); //enter
    specialKeys.push(16); //shiftKey
    specialKeys.push(17); //ctrlKey
    specialKeys.push(27); //escape
    specialKeys.push(38); //up
    specialKeys.push(40); //down
    specialKeys.push(45); //insert
    specialKeys.push(46); //delete
    specialKeys.push(115); //f4


    if (specialKeys.indexOf(e.keyCode) === -1 && !(e.ctrlKey && e.keyCode === 65)) {
        var decimalCount = 0;
        if (manualDecimalCount && manualDecimalCount !== '') {
            decimalCount = Number(manualDecimalCount);
        }
        else
            decimalCount = Number(window.top.$('#hfDecimalCount').val());

        if (decimalCount > 0) {
            var sender = s;
            var dotPos = $(sender).val().indexOf(".");
            if ((e.keyCode === 110 || e.keyCode === 190) && dotPos === -1)
                return true;

            var caratPos = getSelectionStart($(sender)[0]);
            if (caratPos > dotPos && dotPos > -1 && ($(sender).val().split('.')[1].length > decimalCount - 1)) {
                e.preventDefault();
            }
        } else {
            specialKeys.push(110); // . numLock
            specialKeys.push(190); // .
        }
        if (!(e.keyCode >= 48 && e.keyCode <= 57) &&
            !(e.keyCode >= 96 && e.keyCode <= 105) &&
            !(e.keyCode >= 112 && e.keyCode <= 123)) {
            e.preventDefault();
        }
    }

}
function exportExcel(dataSet, columns, captions, isEmptyExport) {
    var data = JSON.parse(JSON.stringify(dataSet));

    if (!isEmptyExport && (!data || data.length === 0))
        return;
    if (data && data.length > 0) {
        var deletedFields = "";
        var columnsArr = columns.split(",");
        for (var field in data[0]) {
            if (!columnsArr.includes(field))
                deletedFields += "delete this." + field + "; ";
        }
        if (deletedFields)
            $(data).each(function () { eval(deletedFields); });
    }
    var json = data ? JSON.stringify(data) : null;
    ajax({
        url: "GeneralApi/ExportExcel",
        data: {
            json: json,
            columns: columns,
            captions: captions,
        },
        success: function (fileUrl) {
            var link = document.createElement("a");
            link.download = "export.xlsx";
            link.href = fileUrl;
            link.click();
            $(link).remove();
        }
    });
}
function setValueNonRaiseEvent(gridBuilder, rowIndex, fieldName, value) {
    stopEventCellChange = true;
    gridBuilder.setCellValue(rowIndex, fieldName, value);
    stopEventCellChange = false;
}
function importXml(gridId, base64) {
    var gridBuilder = $("#" + gridId).gridBuilder();
    var data = {};
    data["Base64"] = base64;
    data["Columns"] = gridBuilder.getColumns();
    data["Captions"] = gridBuilder.getColumnsCaption();
    ajax({
        gridBuilder: gridBuilder,
        url: "GeneralApi/ImportXml",
        data: data,
        success: function (json) {
            var data = JSON.parse(json);
            var dataSet = gridBuilder.mappingRows(data);
            gridBuilder.loadData(dataSet);
        }
    });
}
Array.prototype.groupByJson = function (properties) {
    return [...Object.values(this.reduce((accumulator, object) => {
        const key = JSON.stringify(properties.map((x) => object[x] || null));
        if (!accumulator[key])
            accumulator[key] = [];
        accumulator[key].push(object);
        return accumulator;
    }, {}))];
};
function refreshPicSrc(img, src) {
    $(".picture-img").html("<img src='" + src + "' />");
}
function changeRequired(id, state) {
    if (state) {
        $("#" + id + " .lookup-button").addClass("validation");
        $("#" + id).attr("data-required", "true");
    }
    else {
        $("#" + id + " .lookup-button").removeClass("validation");
        $("#" + id).removeAttr("data-required");
    }
}
function setComboCaption(id, text) {
    $("#" + id + "_dropdown .has-float-label span").text(text);
    $("#lbl_" + id).text(text);
}
