var isReturned = getQuery("ret") === "1";
var factorSerial = getQuery("code");
var copyCode = getQuery("copycode");
var localProductGroup = [];
var productList = [];
var lstProduct = [];
var messageError = window.top.selectedNotMore;
var reserveId = getQuery("id");
var customerCode = 0;
var customerDesc = "";
var decimalCount = Number(window.top.$("#hfDecimalCount").val());
var currencyName = window.top.$("#hfBaseCurrencyName").val();
var currencyCode = window.top.$("#hfBaseCurrencyCode").val();
var currentYear = window.top.$("#hfCurrentYear").val();

var documentTypeCode = $("#hfDocumentTypeCode").val();
var cashDeskCode = $("#hfCashDeskCode").val();
var customerList = JSON.parse($("#hfCustomerList").val());
var defaultCustomerCode = Number($("#hfDefaultCustomer").val());
var storeCode = Number($("#hfStoreCode").val());
var isOpen = Number($("#hfIsOpen").val()) > 0;

var documentTypeParentCode = Number(getQuery("p"));
var enumDocumentTypeParentCode = {
    codeMoadelSale: 1,
    codeMoadelReturnSale: 10
};
var factorData;
var saleSystemCode = getQuery("systemcode");
var priceListCode = 0;
var enableProductFocus = true;
$("[data-id='currencyName']").text(currencyName);

$(document).ready(function () {
    $("[data-remove]").remove();
    setTimeout(function () { $("#txtProduct").focus() }, 500);
    $(document).on("keydown", function (event) {
        if (event.keyCode === 117) { //F6
            openPosModal();
            event.preventDefault();
        }
        else if (event.keyCode === 120) { //F9
            save();
            event.preventDefault();
        }
        else if (event.keyCode === 107) { //+
            var sender = $(".selected").find(".add-btn");
            if (sender.length > 0) {
                addOrMin(sender, true);
                event.preventDefault();
            }
        }
        else if (event.keyCode === 109) { //+
            var sender = $(".selected").find(".minus-btn");
            if (sender.length > 0) {
                addOrMin(sender, false);
                event.preventDefault();
            }
        }
        else if (event.ctrlKey && event.keyCode === 46) { // ctrl del
            var sender = $(".selected").find(".container-delete");
            if (sender.length > 0) {
                $(sender).click();
                event.preventDefault();
            }
        }
        else if ((event.altKey || event.ctrlKey) && (49 <= event.keyCode && event.keyCode <= 57)) {
            if ($(".selected").length === 0)
                return;
            var productId = $(".selected").attr("data-pid");
            var serial = $(".selected").attr("data-serial");
            var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
            var newCount = (Number($(".selected").find("[data-id='Amount']").text()) + (event.altKey ? -1 : 1) * String.fromCharCode(event.keyCode)).toFixed(model.UnitDecimalCount);
            if (newCount > 0) {
                addOrMinProduct(productId, serial, newCount, false);
                event.preventDefault();
            }
        }
    });
    $(".container-fluid").click(function (e) {
        if ($(e.target).attr("id") &&
            ($(e.target).attr("id").indexOf("txtProduct") !== -1 ||
                $(e.target).attr("id").indexOf("txtCount") !== -1 ||
                $(e.target).attr("id").indexOf("txtCustomer") !== -1
            )) {
            //ignore
        }
        else if ($(e.target).attr("onclick") && $(e.target).attr("onclick").includes('openCounter') || ($(e.target).parent().attr("onclick") && $(e.target).parent().attr("onclick").includes('openCounter'))) {
            //ignore
        }
        else {
            if ($(".searchCustomer")[0].style["display"] === "block") {
                $('.searchCustomer').hide();
                setCustomerAsDefault();
            }
            $('#divCounter').hide();
            $('.searchProduct').hide();
            enableProductFocus = true;
        }
        var focusedElement = $(":focus");
        if (enableProductFocus && !focusedElement.is("input") && !focusedElement.hasClass("lookup-button") && $(".modal").not(":hidden").length === 0)
            setTimeout(function () { $("#txtProduct").focus() }, 500);
    });
    $('.counter').click(function () {
        var textbox = $(this).closest(".counter-container").find(".counter-value");
        var unitDecimalCount = Number(textbox.attr("data-decimalCount"));
        var counter = textbox.val();
        var newValue;
        if ($(this).attr("data-value").trim() === ".") {
            if (counter.includes(".") || unitDecimalCount === 0)
                return;
            newValue = (counter ? numberWithCommas(counter) + "." : ".");
        }
        else {
            if (counter.includes(".")) {
                var currentDecimalCount = counter.split(".")[1].length + 1;
                if (currentDecimalCount > unitDecimalCount)
                    return;
                newValue = numberWithCommas(counter + $(this).attr("data-value").trim(), currentDecimalCount);
            }
            else
                newValue = numberWithCommas(counter + $(this).attr("data-value").trim(), 0);
        }
        textbox.val(newValue);
        setTimeout(function () { $('#txtCounter').focus(); }, 100);
    });
    $("#txtWeightProduct").on("keypress", function (e) {
        if (e.keyCode === 13)
            chooseWeightProduct();
    });
    $("#txtCounter").on("keypress", function (e) {
        if (e.keyCode === 13) {
            sendNumberTo();
            return;
        }
        var decimalCount = $(this).attr("data-decimalCount");
        if (!decimalCount)
            decimalCount = Number(window.top.$('#hfDecimalCount').val());
        if (decimalCount > 0) {
            var dotPos = $(this).val().indexOf(".");
            if (e.keyCode === 46 && decimalCount > 0 && dotPos === -1)
                return true;
            var caratPos = getSelectionStart($(this)[0]);
            if (caratPos > dotPos && dotPos > -1 && ($(this).val().split('.')[1].length > decimalCount - 1)) {
                return false;
            }
        }
        if (!(e.keyCode >= 48 && e.keyCode <= 57))
            return false;
    });
    $("#txtCounter").on("keyup", function (e) {
        var decimalCount = $(this).attr("data-decimalCount");
        $(this).val(numberWithCommas($(this).val()), decimalCount);
    });
    $("#divReturnProduct").on("click", ".data-return", function () {
        var remainAmount = Number($(this).find("[data-id='RemainAmount']").text());
        var productId = $(this).attr("data-pid");
        var serial = $(this).attr("data-serial");
        var model = lstProduct.find(x => x.ProductId === productId && x.ProductSerialNumber === serial);
        if (remainAmount === 0) {
            alert(window.top.amountMoreSavedValue);
            return;
        }
        if (!model) {
            model = factorData.Artikles.find(x => x.ProductId === productId && x.ProductSerialNumber === serial);
        }
        if (model) {
            if (!model.CanReturn) {
                alert(window.top.cantReturnProduct);
                return;
            }
            productSelect(productId, null, model, serial, true);
        }
    });
    $("#divProductContainer").on("click", ".data-product", function () {
        var productId = $(this).attr("data-pid");
        var serial = $(this).attr("data-serial");
        setProductBoxColor($(this));
        showProductShopDetail(productId, serial);
    });
    $("#groupName").on("click", ".menu-item", function () {
        $(".menu-item").removeClass("selected-menu-item");
        $(this).addClass("selected-menu-item");
        setProductGroup($(this).html());
    });
    $("#divProductGroupContainer").on("click", ".product-box", function () {
        var productId = $(this).attr("id").substr(8);
        var model = productList.filter(x => x.Id.split("-")[0] === productId);
        if (model[0].Id.includes("-"))
            openInModal('', "Sale/ShopFeatureSelection?id=" + productId + "&store=" + storeCode, window.top.featureSelection, 550, 400, true)
        else
            productSelect(productId, null, null, false, "");
    });
    $("#divDiscountType").on("click", "label", function () {
        discountTypeChange($(this));
    });
    $('#txtCustomer').bind('keyup', function (e) {
        if (e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40) {
            handleArrowKeys(e.keyCode, "Customer");
        }
        else {
            $(".focused-res").removeClass("focused-res");
            var tag = '';
            var txtCustomer = $('#txtCustomer').val();
            if (txtCustomer.length > 1) {
                var result = customerList.filter(function (item) {
                    return item.Name.includes(txtCustomer) || item.Code.toString().includes(txtCustomer) || (item.NationalCode || "").includes(txtCustomer) || (item.MobileNo || "").includes(txtCustomer);
                });
                $('.searchCustomer').empty();
                if (result.length > 0) {
                    for (var i = 0; i < result.length; i++) {
                        var focused = i === 0 ? 'focused-res' : '';
                        tag += "<div onclick='customerSelectChange(" + result[i].Code + ")' class='col-md-12 col-sm-12 col-xs-12 search-tr " + focused + "' style='padding: 7px;cursor: pointer;'>";
                        tag += '<div class="col-md-3 col-md-3 col-md-3">' + result[i].Code + '</div>';
                        tag += '<div class="col-md-9 col-sm-9 col-xs-9">' + result[i].Name + '</div>';
                        tag += '</div>';
                    }
                }
                else {
                    tag = "<div class='col-md-12' style='height:200px;padding-top:16px'>" + "<div style='text-align:center;padding-top:30px'><img src='../img/notfound.svg' class='svg' style='fill:#037c91;width:64px'  /><div>" + window.top.userNotFound + "</div></div></div>";
                }
                $('.searchCustomer').append(tag).show();
                imgToSvg();
            }
            else {
                $('.searchCustomer').hide();
            }
        }

    });
    $('#txtProduct').bind('keyup', function (e) {
        var i = 0;
        if (e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40) {
            handleArrowKeys(e.keyCode, "Product");
        }
        else {
            $(".focused-res").removeClass("focused-res");
            var tag = '';
            var value = $('#txtProduct').val();
            if (value.length > 1) {
                var list = productList.filter(x=>x.CanSale);
                var result = searchProduct(value.trim(), list);
                var resultBarcode = findProductByBarcode(value.trim());
                var resultSerial = findProductBySerial(value.trim());
                if (resultBarcode.product.length > 0)
                    result = result.concat(resultBarcode.product);
                if (resultSerial.product.length > 0)
                    result = result.concat(resultSerial.product);

                result = result.filter((value, index, self) => self.indexOf(value) === index);
                $('.searchProduct').empty();
                if (result.length > 0) {
                    for (i = 0; i < result.length; i++) {
                        var focused = i === 0 ? 'focused-res' : '';
                        var amount = 0;
                        var serial = "";
                        if (resultBarcode.product.length > 0) {
                            amount = resultBarcode.amount;
                        }
                        if (resultSerial.product.length > 0) {
                            serial = resultSerial.serial;
                        }
                        tag += "<div onclick=productSelect('" + result[i].Id + "'," + (result[i].IsWeightBarcode && amount > 0 ? amount : null) + "," + null + ",false,'" + serial + "') class='col-md-12 col-sm-12 col-xs-12 search-tr " + focused + "' style='padding: 7px;    cursor: pointer;'>";
                        tag += '<div class="col-md-3 col-md-3 col-md-3">' + result[i].Id + '</div>';
                        tag += '<div class="col-md-9 col-sm-9 col-xs-9">' + result[i].Name + '</div>';
                        tag += '</div>';
                    }
                }
                else {
                    tag = "<div class='col-md-12' style='height:200px;padding-top:16px'>" + "<div style='text-align:center;padding-top:30px'><img src='../img/notfound.svg' class='svg' style='fill:#037c91;width:64px'  /><div>" + window.top.productNotFound + "</div></div></div>";
                }
                $('.searchProduct').append(tag).show();
                imgToSvg();
            }
            else {
                $('.searchProduct').hide();
            }
        }
    });

    initial();
});

async function initial() {
    if (isOpen) {
        if (!isReturned) {
            await getLocalProductGroupList();
            customerSelectChange(defaultCustomerCode);
            if (copyCode)
                await getFactor();
        }
        else {
            await getFactor();
        }

        await getProductPrices(storeCode);
        if (isReturned || copyCode) {
            await setData(factorData);
        }
        closeLoading();
        $("#divMain").show();

        createProductGroupDiv();
        if (reserveId)
            await getReserveDetails();

        showControl($("#txtCustomer"), $(".searchCustomer"));
        showControl($("#txtProduct"), $(".searchProduct"));
    }
    else {
        closeLoading();
        $("#divMain").show();
    }
}
async function getLocalProductGroupList() {
    await ajax({
        url: "SaleApi/GetLocalProductGroupList",
        success: function (result) {
            localProductGroup = result;
        }
    });
}
async function getFactor() {
    await ajax({
        url: "SaleApi/GetFactor",
        data: { factorSerial: factorSerial || copyCode, documentTypeCode: documentTypeCode, loadArtikles: true, isCopy: copyCode !== ""  },
        success: function (result) {
            factorData = result;
            customerCode = factorData.Header.CustomerCode;
            customerDesc = factorData.Header.CustomerDesc;
            $("#lblFactorDate").text(result.Header.FactorTime + " " + result.Header.FactorDatePersian);
            setJsonValue(factorData.Header, "#divMainFactorInfo");
        }
    });
}

async function getProductPrices() {
    await ajax({
        url: "SaleApi/GetProductPrices",
        data: { storeCode: storeCode, documentTypeCode: documentTypeCode, PriceListCode: priceListCode, isShopMode: true },
        success: function (retValue) {
            productList = retValue;
        }
    });
}
async function setData(result) {
    for (var i = 0; i < result.Artikles.length; i++) {
        var product = productList.filter(x => x.Id === result.Artikles[i].ProductId);
        if (product.length > 0) {
            result.Artikles[i]["SecondUnits"] = product[0].SecondUnits;
            result.Artikles[i]["SecondUnits"].push({
                UnitName: product[0].UnitName,
                UnitCode: product[0].UnitCode,
                UnitDecimalCount: product[0].UnitDecimalCount,
                Price: product[0].SalePrice,
                Ratio: 1
            });
            result.Artikles[i]["MainUnitName"] = product[0].UnitName;
            result.Artikles[i].ProductSerialNumber = result.Artikles[i].ProductSerialNumber || "";
            if (product[0].DiscountList.length > 0) {
                result.Artikles[i]["DiscountCode"] = 0;
                result.Artikles[i]["DiscountAmount"] = product[0].DiscountList[0].Discount;
                result.Artikles[i]["DiscountType"] = product[0].DiscountList[0].DiscountType;
                result.Artikles[i]["DiscountName"] = product[0].DiscountList[0].Name;
            }
        }
        result.Artikles[i]["CanReturn"] = result.Artikles[i].ProductCanReturn;
        result.Artikles[i]["Name"] = result.Artikles[i].ProductName;
        result.Artikles[i]["Id"] = result.Artikles[i].ProductId;
        result.Artikles[i]["TaxInPrice"] = false;
        result.Artikles[i]["TaxTypeCode"] = result.Artikles[i].ProductTaxTypeCode;
        result.Artikles[i]["StateSerial"] = result.Artikles[i].ProductStateSerialCode;
        result.Artikles[i]["IsWeightBarcode"] = result.Artikles[i].ProductBarcodeType == 1;
        result.Artikles[i]["SalePrice"] = result.Artikles[i].Price;
        if (factorSerial) {
            var $div = $(".template-return").clone().removeClass("template-return").removeAttr("hidden");
            $div.attr("data-pid", result.Artikles[i].ProductId);
            $div.attr("data-serial", result.Artikles[i].ProductSerialNumber);
            $div.attr("data-max-count", result.Artikles[i].RemainAmount);
            var container = ".data-return[data-pid=" + result.Artikles[i].ProductId + "][data-serial='" + result.Artikles[i].ProductSerialNumber + "']";
            $("#divReturnProduct").append($div);
            setJsonValue(result.Artikles[i], container);
            if (result.Artikles[i].ProductSerialNumber)
                $div.find("[data-id='ProductName']").text(result.Artikles[i].ProductName + " " + result.Artikles[i].ProductSerialNumber);
            if (result.Artikles[i]["MainUnitName"] !== result.Artikles[i].UnitName) {
                var secondUnit = result.Artikles[i]["SecondUnits"].find(x => x.UnitCode === result.Artikles[i].UnitCode);
                $div.find("[data-id='MainUnitNameDesc']").text("(" + (result.Artikles[i].Amount / secondUnit.Ratio) + result.Artikles[i]["MainUnitName"] + ")");
            }
        }
        else {
            await productSelect(result.Artikles[i].ProductId, null, result.Artikles[i], true, result.Artikles[i].ProductSerialNumber);
        }
    }
}
async function productSelect(productId, weight, inputModel, serial, isReturn) {
    var model = inputModel || productList.find(c => c.Id === productId);
    var returnSaleMode = factorSerial !== "";
    weight = (inputModel && !returnSaleMode ? model.Amount : weight);
    serial = serial || "";
    $('#txtWeightProduct').val("");
    if (model.ProductStateSerialCode === 1 && !serial ) {
        var remainAmount = "";
        if (factorSerial) {
            var baseContainer = getBaseDiv(productId, serial);
            var element = baseContainer.find("[data-id='RemainAmount']");
            remainAmount = element.text();
        }
        var url = "Sale/ShopSerialSelection?id=" + productId + "&store=" + storeCode + "&remain=" + remainAmount + "&direct=1" + "&returnSaleMode=" + returnSaleMode + (returnSaleMode ? "&nameKala=" + model.Name + "&nameUnit=" + model.UnitName + "&fi=" + model.SalePrice : "");
        openInModal('', url, window.top.serialSelection, 850, 500, true);
        return;
    }
    if (model.IsWeightBarcode || model.UnitDecimalCount > 0) {
        if (weight)
            await addToTable(productId, model, weight, serial, isReturn);
        else {
            openWeightModal(productId, model.UnitDecimalCount);
        }
    }
    else {
        await addToTable(productId, model, weight || 1, serial, isReturn);
        setTimeout(function () { $("#txtProduct").focus() }, 500);
    }
    $("#txtProduct").val("");
    $('.searchProduct').hide();
}
async function addToTable(productId, product, countWeight, serial) {
    var count = countWeight ? countWeight : 1;
    var selectedProduct = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    if (!selectedProduct) {
        if (factorSerial) {
            if (Number(product.Amount) === 0 || Number(product.Amount) - count <= -1) {
                alert(messageError);
                return;
            }
        }
        pushToSelectedList(product, serial);
        var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
        count = countWeight;
        await createProductDiv(model);
    }
    else {
        count = Number(selectedProduct.Amount) + count;
    }
    addOrMinProduct(productId, serial, count,true);
    $('#lblCount').text("(" + lstProduct.length + ")");
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    var url = "";
    var data = null;

    switch (id) {
        case "cboStore":
            url = "SaleApi/GetStoreList";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
    }
    if (url)
        await ajax({
            url: url,
            data: data,
            success: function (result) {
                $combo.lookupBuilder().bindData(result);
            }
        });
}
async function createProductDiv(product) {
    var $div = $(".template-product").clone().removeClass("template-product").removeAttr("hidden");
    $div.attr("data-pid", product.ProductId);
    $div.attr("data-serial", product.ProductSerialNumber);
    $("#divProductContainer").prepend($div);
    setProductBoxColor($div);
    setJsonValue(product, ".data-product[data-pid=" + product.ProductId + "][data-serial='" + product.ProductSerialNumber + "']");

    $div.find("[data-id='Price']").text(product.MainPrice);
    if (product.ProductSerialNumber)
        $div.find("[data-id='ProductName']").text(product.ProductName + " " + product.ProductSerialNumber);

    if (product.SecondUnitList.length > 1 && product.ProductStateSerialCode !== 1) {
        var unitNameParent = $div.find("[data-id='UnitName']").parent();
        var ul = unitNameParent.next();
        unitNameParent.addClass("dropdown-toggle").attr("data-toggle", "dropdown");
        unitNameParent.find(".caret").show();
        product.SecondUnitList.forEach(function (item) {
            ul.append("<li data-code=" + item.UnitCode + "><a>" + item.UnitName + "</a></li>");
        });
    }
    if (isReturned || product.DiscountCode === 0) {
        $div.find(".container-discount").find(".dropdown").hide();
        $div.find(".container-init-valueadded").hide();
    }
    else {
        $div.find(".container-discount").find(".discount-info").append("<div><label style='font-size:12px;color:#000'><img src='../img/check.svg' class='svg' style='fill:#000000'/>" + product.DiscountName + "</label><label style='font-size:10px;color:#000'>" + window.top.forEach + " " + product.UnitName + " " + product.DiscountAmount + " " + (product.DiscountType === 1 ? " " + window.top.percent : " " + currencyName) + "</label></div><input type='button' value='" + window.top.reApplyTheDiscount + "' class='button-accept re-calculate' style='font-size:10px;display:none' />");
    }

    await getProductShopDetail(product.ProductId);
    imgToSvg();
    if (product.DiscountCode === 0) {
        $div.find(".container-discount").find(".svg").hide();
        $div.find(".container-discount").find(".re-calculate").show();
    }
}
async function getProductShopDetail(productId) {
    var model = lstProduct.find(c => c.ProductId === productId);
    await ajax({
        url: "SaleApi/GetProductShopDetailCurrency",
        data: { productId: productId, storeCode: storeCode, documentTypeCode: documentTypeCode, isShopMode: true },
        success: function (result) {
            model.StoreStock = result.StoreStock;
            model.LastPriceIn = result.LastPriceIn.Fi;
            model.LastPriceOut = result.LastPriceOut.Fi;
            model["LastPriceInCurrencyName"] = result.LastPriceIn.CurrencyName;
            model["LastPriceInDecimalCount"] = result.LastPriceIn.DecimalCount;
            model["LastPriceInCurrencyCode"] = result.LastPriceIn.CurrencyCode;
            model["LastPriceOutCurrencyName"] = result.LastPriceOut.CurrencyName;
            model["LastPriceOutDecimalCount"] = result.LastPriceOut.DecimalCount;
            model["LastPriceOutCurrencyCode"] = result.LastPriceOut.CurrencyCode;
            if (result.LastPriceIn.CurrencyCode > 0 && result.LastPriceIn.CurrencyCode !== Number(currencyCode)) {
                model["LastPriceInBase"] = (result.LastPriceIn.Fi * result.LastPriceIn.CurrencyRate).toFixed(decimalCount);
                model["LastPriceInBaseCurrencyName"] = currencyName;
            }
            if (result.LastPriceOut.CurrencyCode > 0 && result.LastPriceOut.CurrencyCode !== Number(currencyCode)) {
                model["LastPriceOutBase"] = (result.LastPriceOut.Fi * result.LastPriceOut.CurrencyRate).toFixed(decimalCount);
                model["LastPriceOutBaseCurrencyName"] = currencyName;
            }
            showProductShopDetail(productId, model.ProductSerialNumber);
        }
    });
}

async function getReserveDetails() {
    await ajax({
        url: "SaleApi/GetReserveDetails",
        data: { code: reserveId, saleSystemCode: saleSystemCode },
        success: function (result) {
            var data = result.Details;
            customerSelectChange(result.Header.CustomerCode);
            data.forEach(function (item) {
                var product = productList.filter(x => x.Id === item.ProductId);
                var unitName;
                if (product[0].UnitCode === item.UnitCode)
                    unitName = product[0].UnitName;
                else if (product[0].SecondUnits.length > 0) {
                    var unit = product.SecondUnits.find(x => x.UnitCode === item.UnitCode);
                    if (unit)
                        unitName = unit.UnitName;
                }
                if (product.length > 0) {
                    item["SecondUnits"] = product[0].SecondUnits;
                    item["Id"] = item.ProductId;
                    item["Name"] = product[0].Name;
                    item["TaxInPrice"] = false;
                    item["TaxTypeCode"] = product[0].TaxTypeCode;
                    item["StateSerial"] = product[0].StateSerial;
                    item["IsWeightBarcode"] = product[0].IsWeightBarcode;
                    item["UnitCode"] = item.UnitCode;
                    item["UnitName"] = unitName;
                    item["Discount"] = item.Discount;
                    item["Tax"] = item.Tax;
                    item["Toll"] = item.Toll;
                    item["Amount"] = item.Amount;
                    item["ProductTax"] = product[0].Tax;
                    item["ProductToll"] = product[0].Toll;
                }
                item["SalePrice"] = item.Price;
                productSelect(item.ProductId, null, item, true);
            });
        }
    });
}
async function refreshLocalProductGroup() {
    $(".product-box").remove();
    $("#groupName").empty();
    await getLocalProductGroupList();
    createProductGroupDiv();
}

function openPos() {
    var error = checkValidation("#divOpenPos");
    if (error === "") {
        ajax({
            loading: true,
            url: "SaleApi/OpenCashDesk",
            data: {
                storeCode: $("#cboStore").lookupBuilder().getSelectedValue(),
                price: numberNonCommas($('#txtMojodi').val(), 0),
                description: $('#txtOpenPosDesc').val()
            },
            success: function () {
                $('[onclick="openPos()"]').attr('disabled', 'disabled');
                location.reload();
            }
        });
    }
    else {
        showMsgModal(0, error);
    }
}
function getLastReserveNumber() {
    ajax({
        loading: true,
        url: "SaleApi/GetMaxReserveNumber",
        data: { code: saleSystemCode },
        success: function (result) {
            $("#lblCodeReservation").text(result);
        }
    });
}
function addToReserveList() {
    var details = [];
    lstProduct.forEach(function (item) {
        details.push({
            SerialNumber: item.ProductSerialNumber,
            NetPrice: item.NetPrice,
            Discount: item.Discount,
            Tax: item.Tax,
            Toll: item.Toll,
            Amount: item.Amount,
            Price: item.Price,
            UnitCode: item.UnitCode,
            ProductId: item.ProductId
        })
    });
    ajax({
        loading: true,
        url: "SaleApi/AddToReserveList",
        data: { saleSystemCode: saleSystemCode, customerCode: customerCode, customerDesc: customerDesc, description: $("#txtDescription").val(), details: details },
        success: function (result) {
            showMsgModal(2, window.top.waitingListSaved);
            reloadPage();
        }
    });
}
function errorImg(sender, productId) {
    $(sender).hide();
    ajax({
        url: "SaleApi/SaveProductImage",
        data: { productId: productId },
        async: false,
        success: function (result) {
            $(sender).attr("src", "../" + (result ? window.top.productImageUrl + "/" + result + ".jpg" : "img/noimage.png"));
            $(sender).show();
        }
    });
}
function save(ponyModel, roundValue, bankCode, trackingCode) {
    if (factorSerial) {
        insertReturnFactor();
    }
    else {
        var exceptionText = checkValidation("");
        if (customerCode <= 0) {
            showMsgModal(0, window.top.selectClient);
            return;
        }
        if (exceptionText) {
            showMsgModal(0, exceptionText);
            return;
        }
        var trsList = [];
        if (documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelPreInvoice)
            trsList = getNewPonyModel(ponyModel ? ponyModel : null, bankCode || -1, numberNonCommas($("#lblSumNetPrice").text(), 0), trackingCode);

        var header = getJsonValue("#divShop");
        header["FactorSerial"] = -1;
        header["NumberingSave"] = false;
        header["SaleSystemCode"] = saleSystemCode;
        header["CustomerCode"] = customerCode;
        header["CustomerDesc"] = customerDesc;
        header["DocumentTypeCode"] = documentTypeCode;
        header["StoreCode"] = storeCode;
        header["PosSystemCode"] = $("#hfPosCode").val();
        ajax({
            loading: true,
            url: "SaleApi/InsertFactor",
            data: { header: header, artikles: lstProduct, trsArtikles: trsList, roundValue: roundValue || 0 },
            success: function (result) {
                showMsgModal(2, result.Message);
                closeTopModal();
                if (result.PrintAfterSave) {
                    var title = window.top.printDocument;
                    var url = "Report/Default?GrpName=An_SanadN&Inst=" + result.Code + "&SalMali=" + currentYear + "&reportId=" + result.DefaultReportId + "&printAfterSave=" + result.PrintAfterSave;
                    openInModal('', url, title, "", "", false);
                }
                factorSerial = result.Code;
                reloadPage();
            }
        });
    }
}
function savePosParent(bankCode, trackingCode) {
    save(null, 0, bankCode, trackingCode);
}
function insertReturnFactor() {
    var data = [];
    lstProduct.forEach(function (item) {
        data.push({ Amount: item.Amount, ArticleCode: item.ArticleBaseCode, Price: item.MainPrice });
    });
    ajax({
        loading: true,
        url: "SaleApi/InsertReturnFactor",
        data: {
            factorSerial: factorSerial, returnProduct: data, summery: $("#txtSummery").val(), documentTypeCode: 8
        },
        success: function (result) {
            showMsgModal(2, result.Message);
            if (result.PrintAfterSave) {
                var title = window.top.printDocument;
                var url = "Report/Default?GrpName=An_SanadN&Inst=" + result.Code + "&SalMali=" + currentYear;
                openInModal('', url, title, "", "", false);
            }
            reloadPage();
        }
    });
}
function showControl(parentControl, childControl) {
    var offset = parentControl.offset();
    var topOffset = parentControl.offset().top - parentControl.scrollTop();
    var width = parentControl.outerWidth();
    childControl.css({
        position: "absolute",
        top: (topOffset + 32) + "px",
        left: (offset.left) + "px",
        width: width
    });
}
function showProductShopDetail(productId, serial) {
    var model = lstProduct.find(c => c.ProductId === productId);
    $("[data-id='LastPriceIn']").attr("data-decimal-count", model["LastPriceInDecimalCount"]);
    $("[data-id='LastPriceOut']").attr("data-decimal-count", model["LastPriceOutDecimalCount"]);
    if (model["LastPriceInCurrencyCode"] == 0 || model["LastPriceInCurrencyCode"] === Number(currencyCode)) {
        $("[data-id='LastPriceInBase']").hide();
        $("[data-id='LastPriceInBaseCurrencyName']").hide();
    }
    else {
        $("[data-id='LastPriceInBase']").show();
        $("[data-id='LastPriceInBaseCurrencyName']").show();
    }
    if (model["LastPriceOutCurrencyCode"] == 0 || model["LastPriceOutCurrencyCode"] === Number(currencyCode)) {
        $("[data-id='LastPriceOutBase']").hide();
        $("[data-id='LastPriceOutBaseCurrencyName']").hide();
    }
    else {
        $("[data-id='LastPriceOutBase']").show();
        $("[data-id='LastPriceOutBaseCurrencyName']").show();
    }
    $("#divProductShopDetail").attr("data-pid", productId).show();
    setJsonValue(model, "#divProductShopDetail");
}
function createProductGroupDiv() {
    var tag = "";
    var groupName = "";
    for (var i = 0; i < localProductGroup.length; i++) {
        if (localProductGroup[i].GroupName !== groupName) {
            groupName = localProductGroup[i].GroupName;
            var selected = (i === 0 ? "selected-menu-item" : "");
            tag += " <div class='menu-item " + selected + " '>" + localProductGroup[i].GroupName + "</div>";
        }
    }
    $('#groupName').append(tag);
    if (localProductGroup.length > 0)
        setProductGroup(localProductGroup[0].GroupName);
}
function setProductGroup(groupName) {
    $(".product-box").remove();
    var lstProductGroup = localProductGroup.filter(function (item) { return item.GroupName === groupName; })[0].Products;
    var i;
    for (i = 0; i < lstProductGroup.length; i++) {
        var product = productList.find(function (item) { return (item.Id.indexOf("-") > 0 ? item.Id.split("-")[0] : item.Id) === lstProductGroup[i].Id });
        if (product) {
            if (!product.CanSale)
                continue;
            var $div = $(".template-product-group").clone();
            var img = "<img src='../" + window.top.productImageUrl + "/" + lstProductGroup[i].Id + ".jpg' class='product-img' style='background-color: #f8f8f8;height: 100%;' onerror='errorImg(this , \"" + lstProductGroup[i].Id + "\");' />";
            $div.removeClass("template-product-group").removeAttr("hidden");
            $div.addClass("product-box");
            $div.addClass("float-right");
            $div.find("[data-id='ProductName']").text(lstProductGroup[i].Name);
            $div.find(".product-internal-box").prepend(img);
            $div.attr("id", "divGroup" + lstProductGroup[i].Id);
            $("#divProductGroupContainer").append($div);
        }
    }
}
function pushToSelectedList(model, serial) {
    var discountCode = 0;
    var discountAmount = 0;
    var discountType = 0;
    var discountName = "";
    var secondUnitList = [];
    var articleBaseCode = 0;
    var price = Number(model.SalePrice.toFixed(decimalCount));
    if (factorSerial) {
        var baseArticle = factorData.Artikles.find(x => x.ProductId === model.Id && x.ProductSerialNumber === serial);
        price = baseArticle.Price;
        articleBaseCode = baseArticle.Code;
    }
    
    if (model.DiscountList && model.DiscountList.length > 0) {
        discountCode = model.DiscountList[0].Code;
        discountAmount = model.DiscountList[0].Discount;
        discountType = model.DiscountList[0].DiscountType;
        discountName = model.DiscountList[0].Name;
    }
    if (model.Id.indexOf("-") > 0)
        model.SecondUnits = model.SecondUnits.filter(x => x.CodePart === Number(model.Id.split("-")[1]));
    secondUnitList = model.SecondUnits;
    if (secondUnitList.filter(x => x.UnitCode === model.UnitCode).length === 0)
        secondUnitList.push({ UnitName: model.UnitName, UnitCode: model.UnitCode, Price: price, Ratio: 1, UnitDecimalCount: model.UnitDecimalCount });

    var ratio = secondUnitList.find(x => x.UnitCode === model.UnitCode).Ratio;
    var unitCode = Number(model.UnitCode);
    var unitName = model.UnitName;
    var unitDecimalCount = model.UnitDecimalCount;
    if (factorSerial && ratio < 1 && secondUnitList.length > 1) {
        var mainUnit = secondUnitList.find(x => x.Ratio === 1);
        unitCode = mainUnit.UnitCode;
        unitName = mainUnit.UnitName;
        unitDecimalCount = mainUnit.UnitDecimalCount;
        price = Number((price * ratio).toFixed(unitDecimalCount));
        ratio = 1;
    }

    lstProduct.push({
        "ArticleBaseCode": articleBaseCode,
        "Amount": 0,
        "ProductTax": isNaN(Number(model["ProductTax"])) ? Number(model.Tax) : Number(model.ProductTax),
        "ProductToll": isNaN(Number(model["ProductToll"])) ? Number(model.Toll) : Number(model.ProductToll),
        "Tax": 0,
        "Toll": 0,
        "Discount": 0,
        "DiscountCode": discountCode,
        "DiscountAmount": discountAmount,
        "DiscountType": discountType,
        "DiscountName": discountName,
        "Price": price,
        "MainPrice": price,
        "ProductId": model.Id,
        "ProductSerialNumber": serial || "",
        "ProductName": model.Name,
        "ProductTaxInPrice": model.TaxInPrice,
        "ProductTaxTypeCode": model.TaxTypeCode,
        "ProductStateSerialCode": model.StateSerial,
        "UnitCode": unitCode,
        "UnitName": unitName,
        "UnitDecimalCount": unitDecimalCount,
        "SecondUnitList": secondUnitList,
        "Ratio": 1
    });
}
function addOrMinProduct(productId, serial, count, setFirstRow) {
    var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    var $div = $(".data-product[data-pid=" + productId + "][data-serial='" + serial + "']");
    var valueAdded = 0;
    var tax = model.Tax, toll = model.Toll;
    count = count || model.Amount;
    if (factorSerial) {
        var result = setBaseRemainAmount(productId, serial, count);
        if (!result)
            return '';
    }
    model.Amount = count;
    $div.find("[data-id='Amount']").text(count);
    var sumPrice = Number((model.MainPrice * count).toFixed(decimalCount));
    var discount;
    if (factorSerial > 0) {
        discount = calculateBaseDiscount(productId, serial);
    }
    else if (model.DiscountCode) {
        if (Number(model.DiscountType) === 1)
            discount = Number((sumPrice * model.DiscountAmount / 100).toFixed(decimalCount));
        else
            discount = Number((model.DiscountAmount * count / model.Ratio).toFixed(decimalCount));
    }
    else
        discount = model.Discount;


    model.SumPrice = sumPrice;
    model.Discount = discount;
    model.Price = model.MainPrice;
    if (model.ProductTaxTypeCode > 1) {
        if (!model.ProductTaxInPrice || factorSerial) {
            valueAdded = Number((((sumPrice - discount) * (model.ProductTax + model.ProductToll)) / 100).toFixed(decimalCount));
            tax = Number(((sumPrice - discount) * model.ProductTax / 100).toFixed(decimalCount));
            toll = valueAdded - tax;

            model.ValueAdded = valueAdded;
            model.SumPrice = sumPrice;
            model.NetPrice = sumPrice - discount + valueAdded;
        }
        else {
            var price = Number((model.MainPrice * 100 / (100 + model.ProductToll + model.ProductTax)).toFixed(decimalCount));
            var newSumPrice = 0;
            var newDiscount = discount;
            if (discount === 0) {
                netPrice = Number((count * model.MainPrice).toFixed(decimalCount));
                newSumPrice = Number((netPrice * 100 / (100 + model.ProductToll + model.ProductTax)).toFixed(decimalCount));
            }
            else {
                var newSumPrice = Number((count * price).toFixed(decimalCount));
                if (model.DiscountCode)
                    newDiscount = calculateDiscount(productId, newSumPrice, count, serial);
            }

            var newValueAdded = Number(((newSumPrice - newDiscount) * (model.ProductToll + model.ProductTax) / 100).toFixed(decimalCount));
            tax = Number(((newSumPrice - newDiscount) * model.ProductTax / 100).toFixed(decimalCount));
            toll = Number((newValueAdded - tax).toFixed(decimalCount));

            model.ValueAdded = newValueAdded;
            model.SumPrice = newSumPrice;
            model.NetPrice = newSumPrice - discount + newValueAdded;
            model.Price = price;
            model.Discount = newDiscount;
        }
    }
    else {
        model.ValueAdded = tax + toll;
        model.NetPrice = model.SumPrice - model.Discount + model.ValueAdded;
    }
    model.Tax = tax;
    model.Toll = toll;

    $div.find("[data-id='ValueAdded']").text(numberWithCommas(model.ValueAdded));
    $div.find("[data-id='Price']").text(numberWithCommas(model.Price));
    $div.find("[data-id='NetPrice']").text(numberWithCommas(model.NetPrice));
    $div.find("[data-id='Discount']").text(numberWithCommas(model.Discount));

    calculateSum();
    if (setFirstRow)
        setDivAsFirstRow($div);
}
function addOrMin(sender, control)//false min and true add
{
    var $div = $(sender).closest(".data-product");
    var productId = $div.attr("data-pid");
    var serial = $div.attr("data-serial");
    var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    var currentCount = Number($div.find("[data-id='Amount']").text());
    var newCount = Number((control ? currentCount + 1 : currentCount - 1).toFixed(model.UnitDecimalCount));
    if (model.IsWeightBarcode || model.UnitDecimalCount > 0) {
        openWeightModal(productId, model.UnitDecimalCount);
        return;
    }
    if (newCount > 0) {
        if (model.ProductStateSerialCode === 1 && newCount > 1) {
            showMsgModal(0, window.top.limitProductCount);
            return;
        }
        addOrMinProduct(productId, serial, newCount, false);
    }
    $('#lblCount').text("(" + lstProduct.length + ")");
}
function calculateSum() {
    var allSumPrice = 0;
    var allSumValueAdded = 0;
    var allSumDiscount = 0;
    lstProduct.forEach(function (item) {
        allSumPrice += item.SumPrice;
        allSumValueAdded += item.ValueAdded;
        allSumDiscount += item.Discount;
    });
    $("#lblSumPrice").text(numberWithCommas(allSumPrice));
    $("#lblSumValueAdded").text(numberWithCommas(allSumValueAdded));
    $("#lblSumDiscount").text(numberWithCommas(allSumDiscount));
    $("#lblSumNetPrice").text(numberWithCommas(allSumPrice - allSumDiscount + allSumValueAdded));
}
function calculateDiscount(productId, sumPrice, count, serial) {
    var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    var discount = 0;
    var discountValue = model.DiscountAmount;
    var discountType = model.DiscountType;
    if (discountValue === 0 && model.Discount > 0) {
        var factorModel = factorData.Artikles.find(c => c.Code === model.ArticleBaseCode);
        discountValue = Number((factorModel.Discount / factorModel.Amount).toFixed(decimalCount));
        discountType = 0;
    }
    count = count / model.Ratio;
    discount = (discountType === 1 ? discountValue * Number((sumPrice / 100).toFixed(decimalCount)) : discountValue * count);
    return discount;
}
function calculateBaseDiscount(productId, serial) {
    var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    var discount = 0;
    var factorModel = factorData.Artikles.find(c => c.Code === model.ArticleBaseCode);
    if (factorModel.Discount > 0) {
        if (factorModel.Amount === model.Amount)
            return factorModel.Discount;
        discount = Number((factorModel.Discount / factorModel.Amount).toFixed(decimalCount));
        var baseUnit = model.SecondUnitList.find(x => x.UnitCode === factorModel.UnitCode);
        discount = discount * baseUnit.Ratio
    }
    return discount * model.Amount / model.Ratio;
}
function findProductByBarcode(value) {
    var list = productList.filter(function (item) { return item.Barcodes.filter(x => x.Barcode.toLowerCase() === value.toLowerCase()).length > 0 });
    var amount = 0;
    if (list.length === 0) {
        var barcode = value.substring(0, value.length - 6);
        if (barcode !== "") {
            list = productList.filter(function (item) { return item.Barcodes.filter(x => x.Barcode.toLowerCase() === barcode.toLowerCase()).length > 0 });
            if (list.length === 1) {
                amount = value.substring(value.indexOf(barcode) + barcode.length, value.length - 1);
                if (list[0].IsWeightBarcode) {
                    amount = amount.substring(0, 2) + "." + amount.substring(2);
                }
            }
        }
    }
    else {
        if (!list[0].IsWeightBarcode)
            amount = 1;
    }
    return { product: list, amount: Number(amount) }
}
function findProductBySerial(value) {
    var list = productList.filter(function (item) { return item.SerialList.filter(x => x.SerialNumber.toLowerCase() === value.toLowerCase() && x.Count > 0).length > 0 });
    return { product: list, serial: Number(value) }
}
function searchProduct(search,list) {
    var result = list;
    var searchArr = search.trim().split(" ");
    for (i = 0; i < searchArr.length; i++) {
        result = result.filter(function (item) {
            return item.Name.toLowerCase().indexOf(searchArr[i].toString().toLowerCase()) >= 0 || item.Id.toString().indexOf(searchArr[i]) === 0;
        });
    }
    return result;
}
function customerSelectChange(code) {
    var customerModel = customerList.find(x => x.Code === code);
    if (customerModel) {
        customerCode = customerModel.Code;
        customerDesc = customerModel.Name;
        $("#txtCustomer").val(customerDesc);
        $("#txtMobileNo").val(customerModel.MobileNo);
        $(".searchCustomer").hide();
    }
    getPriceList();
}
function deleteAll() {
    var rows = $(".data-product").not(":hidden").find(".container-delete");
    for (var i = 0; i < rows.length; i++) {
        deleteRow(rows[i]);
    }
}
function deleteRow(sender) {
    var $div = $(sender).closest(".data-product");
    var productId = $div.attr("data-pid");
    var serial = $div.attr("data-serial");
    var $divSerial = $(".data-product[data-pid=" + productId + "][data-serial='" + serial + "']");
    if (factorSerial) {
        setBaseRemainAmount(productId, serial, 0);
    }
    if ($divSerial.length > 1) {
        lstProduct = lstProduct.filter(function (item) { return item.ProductId === productId || item.ProductSerialNumber === serial; });
        lstProduct.splice(0, 1)
    } else {
        lstProduct = lstProduct.filter(function (item) { return item.ProductId !== productId || item.ProductSerialNumber !== serial; });
    }
    calculateSum();
    $('#lblCount').text("(" + lstProduct.length + ")");
    $div.remove();
}
function sendNumberTo() {
    var value = numberNonCommas($('#txtCounter').val(), 0);
    var isGeneralDiscount = $("#divCounter").attr("data-general-discount");
    var isPercent = $("#divCounter").attr("data-discounttype") === "1";
    if (isGeneralDiscount) {
        if (isPercent && value > 100) {
            showMsgModal(0, window.top.invalidDiscount);
            return;
        }
        var allSumPrice = numberNonCommas($("#lblSumPrice").text(), 0);
        if (isPercent)
            value = Number((value * allSumPrice / 100).toFixed(decimalCount));
        var newPrice = allSumPrice - value;
        if (newPrice <= 0) {
            showMsgModal(0, window.top.invalidDiscount);
            return;
        }
        $("#divCounter").hide();
        generalDiscount(value);
    }
    else {
        var productId = $("#divCounter").attr("data-product");
        var serial = $("#divCounter").attr("data-serial");
        var fieldName = $("#divCounter").attr("data-field");
        if (fieldName === "Amount" && isReturned) {
            var maxCount = Number(getBaseDiv(productId).attr("data-max-count"));
            if (value > maxCount) {
                alert(window.top.amountMoreSavedValue);
                return;
            }
        }
        else if (fieldName === "Discount") {
            var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
            if (isPercent && value > 100) {
                showMsgModal(0, window.top.invalidDiscount);
                return;
            }
            if (isPercent)
                value = Number((value * model.SumPrice / 100).toFixed(decimalCount));
            var newPrice = model.SumPrice - value;
            if (newPrice <= 0) {
                showMsgModal(0, window.top.invalidDiscount);
                return;
            }
        }
        $("#divCounter").hide();
        setManualValue(productId, serial, fieldName, value);
    }
    enableProductFocus = true;
    setTimeout(function () { $("#txtProduct").focus() }, 500);
}
function setProductBoxColor($div) {
    $(".data-product").not(":hidden").find(".container-amount").css({ "background-color": "##eceff1" });
    $(".data-product").not(":hidden").find(".container-header").css({ "background-color": "##f5f5f5" });
    $(".data-product").not(":hidden").find(".container-row").css({ "background-color": "#fff" });
    $(".data-product").removeClass("selected");
    $div.find(".container-amount").css({ "background-color": "#d3edff" });
    $div.find(".container-header").css({ "background-color": "#bbd7ea" });
    $div.find(".container-row").css({ "background-color": "#deebf5" });
    $div.addClass("selected");
}

function setManualValue(productId, serial, name, value) {
    var $parentDiv = $(".data-product[data-pid=" + productId + "][data-serial='" + serial + "']");
    var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    var newCount = null;
    switch (name) {
        case "Discount":
            model.DiscountCode = 0;
            model.Discount = value;
            break;
        case "UnitName":
            var secondUnit = model.SecondUnitList.filter(x => x.UnitCode === Number(value));
            model.UnitCode = secondUnit[0].UnitCode;
            model.MainPrice = secondUnit[0].Price;
            model.Ratio = secondUnit[0].Ratio;
            model.UnitName = secondUnit[0].UnitName;
            model.UnitDecimalCount = secondUnit[0].UnitDecimalCount;
            value = model.UnitName;
            break;
        case "Amount":
            newCount = value;
            break;
    }
    $parentDiv.find("[data-id='" + name + "']").text(value).show();
    addOrMinProduct(productId, serial, newCount, false);
}
function setCustomerAsDefault() {
    customerCode = defaultCustomerCode;
    var defaultCustomer = customerList.filter(x => x.Code === customerCode);
    if (defaultCustomer.length > 0) {
        customerDesc = $("#txtCustomer").val() + " " + "(" + defaultCustomer[0].Name + ")";
    }
    $("#txtCustomer").val(customerDesc);
}
function handleArrowKeys(keyCode, type) {
    if (keyCode === 13) {
        eval($('.focused-res').attr("onclick"));
        if (type === "Product")
            $("#txt" + type).val("");
        $(".search" + type).hide();
    }
    else if (keyCode === 38 || keyCode === 40) {
        var divs = $(".search-tr, .add-tr");
        var selectionDiv = $(".focused-res");
        var next = "";
        var previous = "";
        var scroll = 0;
        for (i = 0; i < divs.length; i++) {
            scroll += parseInt($(divs[i]).css('height'));
            if (divs[i] === selectionDiv[0]) {
                previous = divs[i - 1];
                next = divs[i + 1];
                break;
            }
        }
        switch (keyCode) {
            case 38:
                if (previous) {
                    $(selectionDiv[0]).removeClass('focused-res');
                    $(previous).addClass('focused-res');
                    $(".search" + type).animate({
                        scrollTop: scroll - 40 - parseInt($(selectionDiv[0]).css('height'))
                    }, 100);
                }
                break;
            case 40:
                if (next) {
                    $(selectionDiv[0]).removeClass('focused-res');
                    $(next).addClass('focused-res');
                    $(".search" + type).animate({
                        scrollTop: scroll
                    }, 100);
                }
                break;

        }
    }
}
function unitChange(e) {
    var li = $(e.target).parent();
    var productDiv = $(li).closest(".data-product");
    var productId = productDiv.attr("data-pid");
    var serial = productDiv.attr("data-serial");
    setManualValue(productId, serial, "UnitName", $(li).attr("data-code"));
}
function backspace() {
    var decimalCount = $('#txtCounter').attr("data-decimalCount");
    var value = numberNonCommas($('#txtCounter').val(), decimalCount);
    $('#txtCounter').val(numberWithCommas(value.toString().substring(0, value.toString().length - 1), decimalCount));
}
function openCounter(sender, dataId) {
    //if (dataId)
    //    sender = $(sender).find("[data-id='" + dataId + "']");
    var fieldName = dataId || $(sender).attr("data-id");
    var productDiv = $(sender).closest(".data-product");
    var productId = productDiv.attr("data-pid");
    var serial = productDiv.attr("data-serial");
    var counterDecimalCount = decimalCount;
    var model = lstProduct.find(x => x.ProductId === productId && x.ProductSerialNumber === serial);
    var top;
    var left;

    if (fieldName === "Amount") {
        if (model.IsWeightBarcode || model.UnitDecimalCount > 0) {
            openWeightModal(productId, model.UnitDecimalCount);
            return;
        }
        if (model.ProductStateSerialCode == 1) {
            showMsgModal(0, window.top.limitProductCount);
            return;
        }
        var tempElement = productDiv.find("[data-id='Price']");
        top = tempElement.offset().top - tempElement.scrollTop() + 46;
        left = productDiv.offset().left + productDiv.width() - 200;
        $(".container-counter").addClass("col-lg-12 col-md-12 col-sm-12 col-xs-12");
        $(".container-counter").removeClass("col-lg-9 col-md-9 col-sm-9 col-xs-9");
        $("#divDiscountType").hide();
    }
    else {
        var parentElement = $(sender).closest(".container-" + fieldName.toLowerCase());
        left = parentElement.offset().left + parentElement.width() - 190;
        top = $(sender).offset().top - $(sender).scrollTop() + 46;
        $(".container-counter").removeClass("col-lg-12 col-md-12 col-sm-12 col-xs-12");
        $(".container-counter").addClass("col-lg-9 col-md-9 col-sm-9 col-xs-9");
        $("#divDiscountType").show();
    }

    $("#divCounter").css({
        position: "absolute",
        top: top + "px",
        left: left + "px",
        width: '200px'
    });
    $("#divCounter").attr("data-product", productId);
    $("#divCounter").attr("data-serial", serial);
    $("#divCounter").attr("data-field", fieldName);
    $("#divCounter").attr("data-general-discount", "");
    if (fieldName === "Amount") {
        counterDecimalCount = model.UnitDecimalCount;
    }
    $('#txtCounter').val('').attr("data-decimalCount", counterDecimalCount);
    if (counterDecimalCount === 0)
        $("#divCounter").find("[data-value='.']").css({ "color": "#aaa", "cursor": "default" });
    else
        $("#divCounter").find("[data-value='.']").css({ "color": "#333", "cursor": "pointer" });
    $('#txtCounter').val("");
    $("#divCounter").removeClass("bottom-triangle").show();
    enableProductFocus = false;
    setTimeout(function () { $('#txtCounter').focus(); }, 100);
}
function chooseWeightProduct() {
    enableProductFocus = true;
    var productId = $('#divWeightedProductModal').attr("data-product");
    var weight = numberNonCommas($('#txtWeightProduct').val());
    var model = lstProduct.find(c => c.ProductId === productId);
    var maxCount = Number(getBaseDiv(productId).attr("data-max-count"));
    if (weight === 0) {
        showMsgModal(0, window.top.chooseCorrectValue);
        return;
    }
    if (weight > maxCount) {
        showMsgModal(0, window.top.selectedNotMore);
        return;
    }
    $('#divWeightedProductModal').modal("hide");
    setTimeout(function () { $("#txtProduct").focus() }, 500);
    if (model) {
        setBaseRemainAmount(productId, "", 0);
        model.Amount = 0;
    }
    productSelect(productId, weight);
}
function getNewPonyModel(list, bankCode, price,trackingCode) {
    var newList = [];
    if (list === null) {
        newList.push({
            Price: price,
            CashDeskCode: bankCode === -1 ? cashDeskCode : -1,
            BankCode: bankCode,
            TrsType: bankCode === -1 || bankCode === null ? 0 : 1,
            TrsOperationType: factorSerial !== "" ? 2 : 1,
            TrackingCode: bankCode === -1 ? "" : trackingCode
        });
    }
    else {
        list.forEach(function (item) {
            newList.push({
                Price: item.Mablagh,
                CashDeskCode: item.CodeSandog,
                BankCode: item.CodeBank,
                TrackingDate: item.Date_Paygri,
                TrackingCode: item.Code_Paygri,
                ChequeBookCode: item.Code_Dastachak,
                Summery: item.Sumery,
                TrsType: item.Trs_Type,
                TelEtc: item.TelEtc,
                TrsOperationType: item.CodeNoeAmaliyat === -1 ? ($('#HiddenStateInOut').val() === "-1" ? 1 : 2) : item.CodeNoeAmaliyat
            });
        });
    }
    return newList;
}
function openShopCategory() {
    openInModal('', 'Sale/ShopCategeryProduct?codeAnbar=' + storeCode, window.top.makingProductGroup);
}
function openReserveModal() {
    $('#reserveModal').modal();
    getLastReserveNumber();
}
function openPosModal() {
    var price = numberNonCommas($("#lblSumNetPrice").text());
    if (price > 0)
        openInModal('', 'Treasury/POSClearing?price=' + price, window.top.posPayed, 600, 390);
    else
        showMsgModal(0, window.top.invalidPrice);
}
function openShopProduct(sender) {
    var productId = $(sender).closest("#divProductShopDetail").attr("data-pid");
    if (!productId)
        return;
    openInModal('', 'Sale/ShopProduct?pid=' + productId, window.top.productSpecifications, '1000', '');
}
function openPony() {
    var title = window.top.clearingForm;
    var width = "1000";
    var src = "Sale/Pony?state=-1&tarafH=" + ($('#txtCustomer').val().trim() || window.top.miscellaneousCustomer) + "&tarafHCode=" + customerCode + "&date=&amount=" + numberNonCommas($("#lblSumNetPrice").text()) + "&sanadType=" + documentTypeCode + "&codeSanad=" + factorSerial + "&currencyCode=" + currencyCode + "&currencyName=" + currencyName + "&currencyDecimalCount=" + decimalCount + "&type=pos";
    openInModal('', src, title, width, "", false);
}

function refreshPageWhenReserve(id) {
    var herf = window.location.href;
    if (herf.indexOf('&id') >= 0)
        herf = window.location.href.substr(0, window.location.href.indexOf('id') - 1);
    herf = herf + "&id=" + id;
    redirectUrl(herf);
}
function reloadPage() {
    if (copyCode) {
        var herf = window.location.href;
        var a = herf.split("&");
        a[0] = a[0].replace("copycode=" + copyCode, "code=" + factorSerial);
        redirectUrl(a.join("&"));
    }
    else
        location.reload();
}
function discountTypeChange(sender) {
    $("#divCounter").attr("data-discounttype", sender.attr("data-percent") ? 1 : 0);
    sender.parent().find("label").css({ "border": "none" });
    sender.css({ "border": "1px solid #2f83d6" });
}
function generalDiscount(value) {
    var allSumPrice = numberNonCommas($("#lblSumPrice").text(), 0);
    if (allSumPrice === 0)
        return;
    var sumDiscount = 0;
    lstProduct.forEach(function (item) {
        var newDiscount = Number((item.SumPrice * value / allSumPrice).toFixed(decimalCount));
        sumDiscount += newDiscount;
        item.Discount = newDiscount;
        item.DiscountCode = 0;
        addOrMinProduct(item.ProductId, item.ProductSerialNumber, null, false);
    });
    var remained = value - sumDiscount;
    if (remained > 0) {
        var lastItem = lstProduct[lstProduct.length - 1];
        lastItem.Discount = lastItem.Discount + remained;
        addOrMinProduct(lastItem.ProductId, lastItem.ProductSerialNumber, null, false);
    }
}
function openCounterGeneralDiscount() {
    var element = $("#lblSumDiscount");
    var left = element.offset().left + element.width() - 190;
    var top = element.offset().top - element.scrollTop() - $("#divCounter").height() - 45;
    toggleDiscountType(true);
    $("#divCounter").addClass("bottom-triangle").attr("data-general-discount", "1");
    $("#divCounter").css({
        position: "absolute",
        top: top + "px",
        left: left + "px",
        width: '200px'
    });
    $('#txtCounter').val("");
    $("#divCounter").show();
    enableProductFocus = false;
    setTimeout(function () { $('#txtCounter').focus(); }, 400);
}
function toggleDiscountType(state) {
    if (state)
        $("#divDiscountType").show();
    else
        $("#divDiscountType").hide();
    $(".container-counter").addClass(state ? "col-lg-9 col-md-9 col-sm-9 col-xs-9" : "col-lg-12 col-md-12 col-sm-12 col-xs-12");
    $(".container-counter").removeClass(state ? "col-lg-12 col-md-12 col-sm-12 col-xs-12" : "col-lg-9 col-md-9 col-sm-9 col-xs-9");
}
function getPriceList() {
    ajax({
        url: "GeneralApi/GetCustomerPriceList",
        loading: false,
        data: { CustomerCode: customerCode },
        success: function (result) {
            if (result.length > 1) {
                $(".container-price-list").empty();
                result.forEach(function (item, i) {
                    var div = $(".price-list-template").clone().removeClass("price-list-template").removeAttr("hidden");
                    div.find("input").val(item.Code).attr("id", "rdo" + i);
                    div.find("label").text(item.Name).attr("for", "rdo" + i);
                    $(".container-price-list").append(div);
                });
                $(".container-price-list").find("[value=" + priceListCode + "]").prop("checked", true);
                $("#priceListModal").modal();
            }
            else if (priceListCode > 0) {
                setPriceList();
            }
        }
    });
}
async function setPriceList() {
    showLoading();
    priceListCode = 0;
    await getProductPrices(storeCode);
    reCalculatePrice();
    closeLoading();
    $("#divPriceList").hide();
    $("#lblPriceListName").text("");
}
async function changePriceList() {
    priceListCode = Number($("[name='rdoPriceList']:checked").val());
    $("#lblPriceListName").text($("[name='rdoPriceList']:checked").next().text());
    $("#divPriceList").show();
    showLoading();
    await getProductPrices(storeCode);
    reCalculatePrice();
    closeLoading();
    $('#priceListModal').modal('toggle');
    setTimeout(function () { $("#txtProduct").focus() });
}
function openPriceListModal() {
    $(".container-price-list").find("[value=" + priceListCode + "]").prop("checked", true);
    $("#priceListModal").modal();
}
function reCalculatePrice() {
    lstProduct.forEach(function (item) {
        var model = productList.find(c => c.Id === item.ProductId);
        var price = Number(model.SalePrice.toFixed(decimalCount));
        var secondUnitList = model.SecondUnits;
        if (!secondUnitList.some(x => x.UnitCode === model.UnitCode))
            secondUnitList.push({ UnitName: model.UnitName, UnitCode: model.UnitCode, Price: price, Ratio: 1, UnitDecimalCount: model.UnitDecimalCount });

        item.SecondUnitList = secondUnitList;
        if (item.UnitCode != model.UnitCode) {
            var unit = item.SecondUnitList.find(x => x.UnitCode === item.UnitCode);
            if (unit)
                price = unit.Price;
        }
        item.MainPrice = price;
        item.DiscountCode = 0;
        item.Discount = 0;
        addOrMinProduct(item.ProductId, item.ProductSerialNumber, null, false);
    });
}
function setDivAsFirstRow(div) {
    setTimeout(function () {
        var firstDiv = div.clone();
        div.parent().prepend(firstDiv);
        div.remove();
    }, 500);
    setProductBoxColor(div);
}
function setBaseRemainAmount(productId, serial, count) {
    var baseContainer = getBaseDiv(productId, serial);
    if (baseContainer.length === 0)
        return true;
    var element = baseContainer.find("[data-id='RemainAmount']");
    var model = lstProduct.find(c => c.ProductId === productId && c.ProductSerialNumber === serial);
    var maxCount = Number(element.text()) + (model.Amount);
    var newValue = (maxCount - count).toFixed(model.UnitDecimalCount);
    if (newValue < 0) {
        alert(messageError);
        return false;
    }
    element.text(newValue);
    return true;
}
function getBaseDiv(productId, serial) {
    var baseContainer = $(".data-return[data-pid=" + productId + "][data-serial='" + (serial || "") + "']");
    return baseContainer;
}
function openWeightModal(productId,unitDeciamlCount) {
    enableProductFocus = false;
    $('#divWeightedProductModal').attr("data-product", productId);
    $('#divWeightedProductModal').modal();
    $("#txtWeightProduct").attr("data-decimalCount", unitDeciamlCount);
    setTimeout(function () { $('#txtWeightProduct').focus(); }, 700);
}






