var openingCorrespondant = 0;
var openingMoain = 0;
var openingTafsil = 0;
var getOpeningCheque = false;
var cboAccountSelectionCriteria = null;
var stopEvent = false;
var dataTable = [];
var listUsedNumberCheque = [];
var trsType = -1;
var insertId = 1;
var updateId = 0;
var operationRow = 'ADD';
var trsOperationType = Number(getQuery("type"));
var isReceive = trsOperationType === 1;
var isPay = trsOperationType === 2;
var code = getQuery("code");
var id = 0;

var baseDecimalCount = Number(window.top.$('#hfDecimalCount').val());
var baseCurrencyCode = window.top.$("#hfBaseCurrencyCode").val();
var baseCurrencyName = window.top.$("#hfBaseCurrencyName").val();

$(document).ready(function () {
    initial();
});
function initial() {
    $("#txtSummeryHeader").focus();
    if (code) {
        getPayReceive();
    }
    else {
        getMaxCode();
    }
    if (isReceive) {
        $("#cboCashBank1").lookupBuilder().onChanged(function () {
            var value = $("#cboCashBank1").lookupBuilder().getSelectedValue();
            if (value) {
                var isPos = Number(value.split("|")[2]) >= 3;
                var serverIp = value.split("|")[3];
                $("#btnSendToPos").prop("disabled", !isPos).attr("data-server-ip", serverIp);
            }
        });
    }
}
function getPayReceive() {
    ajax({
        loading: true,
        url: "TreasuryApi/GetPayReceive",
        data: { code: code },
        success: function (result) {
            $("#txtDate").val(result.Header.DateLocal);
            $("#txtCodeAtfSanad").val(result.Header.ReferenceCode);
            $("#txtSummeryHeader").val(result.Header.Summery);
            if (result.Articles.length > 0) {
                var articles = result.Articles;
                for (var i = 0; i < articles.length; i++) {
                    articles[i].BasePrice = articles[i].Price;
                    articles[i].Price = articles[i].CurrencyCode !== Number(baseCurrencyCode) ? articles[i].CurrencyPrice : articles[i].Price;
                    setArticle(articles[i]);
                    dataTable.push(articles[i]);
                    insertId = articles[i].Index;
                }
                insertId++;
                var types = dataTable.map(function (d) { return d['TrsType']; });
                types = $.grep(types, function (item, index) {
                    return index == $.inArray(item, types);
                });
                for (var j = 0; j < types.length; j++) {
                    fetchData(types[j]);
                    $('#tblData' + types[j]).show();
                    $('#tblData' + types[j]).closest(".container-save").show();
                }
            }
        }
    });
}
function getMaxCode() {
    ajax({
        loading: true,
        url: "TreasuryApi/GetMaxTrsDocumentCode",
        success: function (result) {
            $("#txtCodeAtfSanad").val(result);
            $("#divMessageEmptyPage").show().css({ "height": "calc(100vh - 150px)" });
            $("#paylist").attr("style", "display:none !important;" + $("#paylist").attr("style"));
        }
    });
}

function addToTable() {
    if (trsType !== -1) {
        var error = checkValidation("#tabFirst");
        if (error === '') {
            $('#btnAddPayRec').show();
            setData();
            $('#tblData' + trsType).show();
        }
        else {
            showMsgModal(0, error);
        }
    }
    else {
        showMsgModal(0, window.top.selectTransactionType);
    }
}

function chooseState(state) {
    cboAccountSelectionCriteria = null;
    trsType = Number(state);
    if (trsType !== 4) {
        $("#cboAccount" + trsType).lookupBuilder().setSelectedValue("");
        $("#cboCashBank" + trsType).lookupBuilder().setSelectedValue("");
    }
    displayCardAdd(state, true);
}

function backToInitMode() {
    $('#btnAddToTable' + trsType).val(window.top.addtoList);
    $($('#btnAddToTable' + trsType).prev()[0]).show();
    operationRow = 'ADD';
    updateId = 0;
}

function closePanelAdd(type) {

    emptyControls();
    backToInitMode();
    $('#btnAddPayRec').show();
    showHidePayPanel(false, type);
}

function getSaveFormElement(typeId) {
    var element = null;
    switch (typeId) {
        case 0:
            element = $('#paycash-save');
            break;
        case 1:
            element = $('#payBank-save');
            break;
        case 2:
            element = $('#payCheque-save');
            break;
        case 4:
            element = $('#income-save');
            break;
    }
    return element;
}

async function showHidePayPanel(showSaveForm, formID, isInsertMode) {
    var count = dataTable.length;
    formID = formID === undefined ? -1 : formID;
    for (var i = 0; i <= 4; i++) {
        if (i === 3)
            continue;
        var parentDiv = $("#tblData" + i).closest(".container-save");
        if ($("#tblData" + i + " > tbody > tr").length === 0) {
            $("#tblData" + i).hide();
            parentDiv.hide();
        }
        else
            parentDiv.show();
    }
    if (formID !== -1) {
        var element = getSaveFormElement(formID);
        if (showSaveForm) {
            element.show();
            element.closest(".container-save").show();
            element[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
        else {
            element.hide();
        }
    }
    if (count > 0 || showSaveForm) {
        $('#divMessageEmptyPage').attr("style", "display: none !important;");
        $("#paylist").show();
        var cboCurrency = $("#cboArz" + trsType);
        if (cboCurrency.length > 0 && isInsertMode) {
            await cboCurrency.lookupBuilder().setSelectedValue(baseCurrencyCode);
        }
    }
    else {
        $("#divMessageEmptyPage").show().css({ "height": "calc(100vh - 150px)" });
        $("#paylist").hide();
        $('#btnAddPayRec').show();
    }
}

function setArticle(article) {
    var newData = {};
    newData.CodeAccount = article.CodeAccount ? article.CodeAccount : ((isReceive ? article.FromMoainCode : article.ToMoainCode) + "/" + article.CustomerCode);
    newData.AccountName = article.CustomerName + "/" + (isReceive ? article.FromMoainName : article.ToMoainName)
    newData.ToMoainCode = isReceive ? article.ToMoainCode : article.FromMoainCode;
    newData.ToMoainName = isReceive ? article.ToMoainName : article.FromMoainName;
    newData.FromMoainCode = isReceive ? article.FromMoainCode : article.ToMoainCode;
    newData.FromMoainName = isReceive ? article.FromMoainName : article.ToMoainName;
    newData.ToTafsilCode = isReceive ? article.ToTafsilCode : article.FromTafsilCode;
    newData.ToTafsilName = isReceive ? article.ToTafsilName : article.FromTafsilName;
    newData.FromTafsilCode = isReceive ? article.FromTafsilCode : article.ToTafsilCode;
    newData.FromTafsilName = isReceive ? article.FromTafsilName : article.ToTafsilName;
    newData.ToCostCenterCode = isReceive ? article.ToCostCenterCode : article.FromCostCenterCode;
    newData.ToCostCenterName = isReceive ? article.ToCostCenterName : article.FromCostCenterName;
    newData.FromCostCenterCode = isReceive ? article.FromCostCenterCode : article.ToCostCenterCode;
    newData.FromCostCenterName = isReceive ? article.FromCostCenterName : article.ToCostCenterName;
    newData.ToProjectCode = isReceive ? article.ToProjectCode : article.FromProjectCode;
    newData.ToProjectName = isReceive ? article.ToProjectName : article.FromProjectName;
    newData.FromProjectCode = isReceive ? article.FromProjectCode : article.ToProjectCode;
    newData.FromProjectName = isReceive ? article.FromProjectName : article.ToProjectName;

    article.CodeAccount = newData.CodeAccount;
    article.AccountName = newData.AccountName;
    article.ToMoainCode = newData.ToMoainCode;
    article.ToMoainName = newData.ToMoainName;
    article.FromMoainCode = newData.FromMoainCode;
    article.FromMoainName = newData.FromMoainName;
    article.ToTafsilCode = newData.ToTafsilCode;
    article.ToTafsilName = newData.ToTafsilName;
    article.FromTafsilCode = newData.FromTafsilCode;
    article.FromTafsilName = newData.FromTafsilName;
    article.ToCostCenterCode = newData.ToCostCenterCode;
    article.ToCostCenterName = newData.ToCostCenterName;
    article.FromCostCenterCode = newData.FromCostCenterCode;
    article.FromCostCenterName = newData.FromCostCenterName;
    article.ToProjectCode = newData.ToProjectCode;
    article.ToProjectName = newData.ToProjectName;
    article.FromProjectCode = newData.FromProjectCode;
    article.FromProjectName = newData.FromProjectName;
}

function fetchData(typeId) {
    var tag = "";
    var price = 0;
    var sumPrice = 0;
    for (var i = 0; i < dataTable.length; i++) {
        if (dataTable[i].TrsType === typeId) {
            tag += "<tr id=" + dataTable[i].Index + "_" + typeId + ">";
            switch (typeId) {
                case 0: case 1:
                    tag +=
                        "<td>" + dataTable[i].AccountName + "</td>" +
                        "<td>" + numberWithCommas(dataTable[i].Price) + " " + dataTable[i].CurrencyName + "</td>" +
                        "<td>" + ((typeId === 0 ? dataTable[i].CashDeskName : dataTable[i].BankName) || "") + "</td>" +
                        "<td>" + (dataTable[i].TrackingCode || "") + "</td>" +
                        "<td>" + (dataTable[i].FromProjectName || "") + "</td>" +
                        "<td>" + (dataTable[i].FromCostCenterName || "") + "</td>";
                    break;
                case 2:
                    var chequeTypeName = window.top.normal;
                    if (dataTable[i].ChequeType === 2)
                        chequeTypeName = window.top.assurance;
                    else if (dataTable[i].ChequeType === 3)
                        chequeTypeName = window.top.opening;
                    tag +=
                        "<td>" + dataTable[i].AccountName + "</td>" +
                        "<td>" + numberWithCommas(dataTable[i].Price) + " " + dataTable[i].CurrencyName + "</td>" +
                        "<td>" + ((isReceive ? dataTable[i].BankName : dataTable[i].ChequeBookName) || "") + "</td>" +
                        "<td>" + (dataTable[i].TrackingCode || "") + "</td>" +
                        "<td>" + (dataTable[i].TrackingDate || "") + "</td>" +
                        "<td>" + (chequeTypeName) + "</td>" +
                        "<td>" + (dataTable[i].FromProjectName || "") + "</td>" +
                        "<td>" + (dataTable[i].FromCostCenterName || "") + "</td>";
                    break;
                case 4:
                    tag +=
                        "<td>" + (dataTable[i].CostIncomeName || "") + "</td>" +
                        "<td>" + (dataTable[i].FromTafsilName || "") + "</td>" +
                        "<td>" + (dataTable[i].FromCostCenterName || "") + "</td>" +
                        "<td>" + (dataTable[i].FromProjectName || "") + "</td>" +
                        "<td>" + (dataTable[i].ToMoainName || "") + "</td>" +
                        "<td>" + (dataTable[i].ToTafsilName || "") + "</td>" +
                        "<td>" + numberWithCommas(dataTable[i].Price) + "</td>";
                    break;
            }
            tag += "<td title='" + (dataTable[i].Summery || "") + "'>" + (dataTable[i].Summery || "") + " <span data-toggle='tooltip' data-placement='bottom' title='" + (dataTable[i].Summery || "") + "'></span></td></tr>";
            price += dataTable[i].Price;
        }
        sumPrice += Number(dataTable[i].BasePrice.toString().replace(/\,/g, ''));
    }

    $('#lblReceivedCollection').text(numberWithCommas(sumPrice));
    $("#bodyData" + typeId).empty();
    $('#bodyData' + typeId).append(tag);

    var element = getSaveFormElement(typeId);
    if (element && element != -1)
        element.hide();

    $('#bodyData' + typeId + ' tr').hover(function () {
        $("#divEditDelete").show();
        showControl($(this), $("#divEditDelete"));
        id = $(this).attr("id").split("_")[0];
        $("#divEditRow").attr("onclick", "editRow(" + id + ")");
        $("#divDeleteRow").attr("onclick", "deleteRow(" + id + ")");

    }, function () {
        $("#divEditDelete").hide();
    });
    $('#divEditDelete').hover(function () {
        $("#divEditDelete").show();
    }, function () {
        $("#divEditDelete").hide();
    });
}

function setData() {
    var $cboTafsil = $("#cboTafsil" + trsType);
    var $cboCostCenter = $("#cboCostCenter" + trsType);
    var $cboProject = $("#cboProject" + trsType);
    var $cboAccount = $("#cboAccount" + trsType);
    var $cboCash = $("#cboCashBank" + trsType);
    var $cboArz = $("#cboArz" + trsType);
    var $cboReciptTo = $("#cboReciptTo");
    var $cboTafsil42 = $("#cboTafsil42");
    var $cboProject42 = $("#cboProject42");
    var $cboCostCenter42 = $("#cboCostCenter42");
    var accountNames = $cboAccount.length > 0 ? $cboAccount.lookupBuilder().getSelectedText().split("/") : "";
    var price = $("#txtPrice" + trsType).val().toString().replace(/\,/g, '');
    var currencyRate = $("#txtNerkh" + trsType).length === 0 ? "1" : $("#txtNerkh" + trsType).val();
    var item = {
        Index: operationRow === 'ADD' ? insertId : updateId,
        AccountName: $cboAccount.length > 0 ? $cboAccount.lookupBuilder().getSelectedText() : "",
        FromMoainName: accountNames.length > 0 ? accountNames[0] : "",
        CustomerCode: getCodeTarafHesab(),
        CustomerName: accountNames.length > 0 && accountNames[1] ? accountNames[1] : "",
        CodeAccount: $cboAccount.length > 0 && $cboAccount.lookupBuilder().getSelectedValue() ? $cboAccount.lookupBuilder().getSelectedValue() : -1,
        CashDeskName: $cboCash.length > 0 ? $cboCash.lookupBuilder().getSelectedText() : "",
        CashDeskCode: getBankCode("cashDesk"),
        Summery: $('#txtSummery' + trsType).val(),
        Price: price,
        CurrencyCode: $cboArz.length > 0 ? $cboArz.lookupBuilder().getSelectedValue().split("|")[0] : baseCurrencyCode,
        CurrencyName: $cboArz.length > 0 ? $cboArz.lookupBuilder().getSelectedText() : baseCurrencyName,
        CurrencyRate: currencyRate,
        BasePrice: price * (currencyRate.replace(/\,/g, '') || 1),
        ChequeBookCode: getCodeDastachak(),
        ChequeBookName: getChequeBookName(),
        BankCode: getBankCode("bank"),
        BankName: getBankName(),
        TrackingCode: getTrackingCode(),
        TrackingDate: getTrackingDate(),
        FromMoainCode: getFromMoainCode(),
        ChequeType: getCheckType(),
        TelEtc: "",
        CostIncomeCode: getCodeHazinehDaramad(),
        CostIncomeName: getNameHazinehDaramad(),
        FromCostCenterCode: $cboCostCenter.length > 0 && $cboCostCenter.lookupBuilder().getSelectedValue() ? $cboCostCenter.lookupBuilder().getSelectedValue() : -1,
        FromCostCenterName: $cboCostCenter.length > 0 ? $cboCostCenter.lookupBuilder().getSelectedText() : "",
        FromProjectCode: $cboProject.length > 0 && $cboProject.lookupBuilder().getSelectedValue() ? $cboProject.lookupBuilder().getSelectedValue() : -1,
        FromProjectName: $cboProject.length > 0 ? $cboProject.lookupBuilder().getSelectedText() : "",
        FromTafsilCode: $cboTafsil.length > 0 && $cboTafsil.lookupBuilder().getSelectedValue() ? $cboTafsil.lookupBuilder().getSelectedValue() : -1,
        FromTafsilName: $cboTafsil.length > 0 ? $cboTafsil.lookupBuilder().getSelectedText() : "",
        NameBankMoain: $cboReciptTo.length > 0 ? $cboReciptTo.lookupBuilder().getSelectedText() : "",
        ToTafsilCode: $cboTafsil42.length > 0 && $cboTafsil42.lookupBuilder().getSelectedValue() ? $cboTafsil42.lookupBuilder().getSelectedValue() : -1,
        ToProjectCode: $cboProject42.length > 0 && $cboProject42.lookupBuilder().getSelectedValue() ? $cboProject42.lookupBuilder().getSelectedValue() : -1,
        ToCostCenterCode: $cboCostCenter42.length > 0 && $cboCostCenter42.lookupBuilder().getSelectedValue() ? $cboCostCenter42.lookupBuilder().getSelectedValue() : -1,
        ToMoainCode: getToMoainCode(),
        TrsType: trsType,
        TrsOperationType: trsOperationType,
        Code: -1,
        CodeSanadS: -1,
        ToMoainName: $cboReciptTo ? $cboReciptTo.lookupBuilder().getSelectedText() : "",
        CodeMoainHazinehDaramad: getCodeMoainHazinehDaramad(),
        CodeMoain_Mo: $cboReciptTo ? $cboReciptTo.lookupBuilder().getSelectedValue() : -1,
        ToTafsilName: $("#cboTafsil42").length > 0 ? $("#cboTafsil42").lookupBuilder().getSelectedText() : "",
    };
    if (isPay && trsType === 2)
        listUsedNumberCheque.push({ "numberCheque": item.TrackingCode, "dastehCheque": item.ChequeBookCode });

    if (operationRow === 'ADD') {
        dataTable.push(item);
        insertId++;
    }
    else if (operationRow === 'EDIT') {
        var editItem = dataTable.find(item => item.Index === updateId);
        item.Code = editItem.Code;
        dataTable[$.inArray(editItem, dataTable)] = item;
        backToInitMode();
    }
    emptyControls();
    fetchData(trsType);
    displayCardAdd(-1);
    return true;
}

function deleteRow(itemId) {
    if (confirm(window.top.confirmMsg)) {
        var deleteRowData = dataTable.find(item => item.Index === itemId);
        var typeId = deleteRowData.TrsType;
        dataTable.splice($.inArray(deleteRowData, dataTable), 1);
        if (isPay && typeId === 2) {
            var item = listUsedNumberCheque.find(c => c.numberCheque == deleteRowData.numberCheque && dastehCheque == deleteRowData.ChequeBookCode);
            if (item) {
                listUsedNumberCheque.splice($.inArray(item, listUsedNumberCheque), 1);
                cboNumberCheque.AddItem(deleteRowData.numberCheque, deleteRowData.numberCheque);
            }
        }
        fetchData(typeId);
        backToInitMode();
        showHidePayPanel(false, -1);
    }
}

function displayCardAdd(state, isInsertMode) {
    state = state === undefined ? -1 : state;
    if (state !== -1)
        $('#btnAddPayRec').hide();
    showHidePayPanel(true, state, isInsertMode);
}

async function cboChequeBookChange() {
    if (stopEvent)
        return;
    await getEventLookupCombo($("#cboNumberCheque"), "", "");
}

function saveChangeFinal() {
    var codeAtf = $('#txtCodeAtfSanad').val();
    if (codeAtf.length > 12) {
        showMsgModal(0, window.top.docNumberCharacter);
        return;
    }
    if ($('#txtDate').val() === '') {
        showMsgModal(0, window.top.enterDate);
        return;
    }
    if (dataTable.length === 0) {
        showMsgModal(0, window.top.noTransaction);
        return;
        //addToTable();
    }

    var newData = [];
    dataTable.forEach(function (item) {
        if (item.CodeAccount && item.CodeAccount.length > 0) {
            item.CodeAccount = item.CodeAccount.split("|")[0];
            item.CustomerCode = Number(item.CodeAccount.split("/")[1]);
            item.CurrencyRate = numberNonCommas(item.CurrencyRate || 1);
        }
        newData.push({
            CustomerCode: item.CustomerCode,
            CurrencyCode: item.CurrencyCode,
            CurrencyRate: item.CurrencyRate,
            CashDeskCode: item.CashDeskCode,
            CostIncomeCode: item.CostIncomeCode,
            ChequeBookCode: item.ChequeBookCode,
            ChequeBankName: isPay ? item.ChequeBookName : item.BankName,
            ChequeType: item.ChequeType,
            BankCode: item.BankCode,
            Price: item.Price,
            Summery: item.Summery,
            TrackingDate: item.TrackingDate,
            TrackingCode: item.TrackingCode,
            TelEtc: item.TelEtc,
            TrsType: item.TrsType,
            TrsOperationType: item.TrsOperationType,
            ToMoainCode: isReceive ? item.ToMoainCode : item.FromMoainCode,
            FromMoainCode: isReceive ? item.FromMoainCode : item.ToMoainCode,
            ToTafsilCode: isReceive ? item.ToTafsilCode : item.FromTafsilCode,
            FromTafsilCode: isReceive ? item.FromTafsilCode : item.ToTafsilCode,
            ToCostCenterCode: isReceive ? item.ToCostCenterCode : item.FromCostCenterCode,
            FromCostCenterCode: isReceive ? item.FromCostCenterCode : item.ToCostCenterCode,
            ToProjectCode: isReceive ? item.ToProjectCode : item.FromProjectCode,
            FromProjectCode: isReceive ? item.FromProjectCode : item.ToProjectCode,
            Code: item.Code
        });
    });

    ajax({
        loading: true,
        url: "TreasuryApi/InsertPayReceive",
        data: {
            documentNumber: codeAtf.length === 0 ? "-1" : codeAtf,
            date: $('#txtDate').val(),
            summery: $('#txtSummeryHeader').val(),
            trsArtikles: newData,
            code: getQuery('code') !== '' ? getQuery("code") : -1
        },
        success: function (result) {
            cboAccountSelectionCriteria = null;
            showMsgModal(2, result.Message);
            var modalId = window.top.$('.gheyas-modal').last().attr('id');
            clearPage();

            for (var i = 0; i <= 4; i++) {
                if (i === 3)
                    continue;
                var parentDiv = $("#tblData" + i).closest(".container-save");
                $("#tblData" + i + " > tbody > tr").remove();
                $("#tblData" + i).hide();
                parentDiv.hide();
            }

            $('#btnSabtDaramad').show();
            $('#btnAddPayRec').show();

            if (result.IsPrint)
                print(result.Code, result.CurrentYear);
            if (getQuery('code') !== '') {
                closeCurrentModal(modalId);
            }
        }
    });
}

function clearPage() {
    emptyControls();
    $('#txtSummeryHeader').val('');
    dataTable = [];
    displayCardAdd();
    $('#lblReceivedCollection').text('0');
    listUsedNumberCheque = [];
    getMaxCode();
}

function showControl(parentControl, childControl) {
    var offset = parentControl.offset();
    var topOffset = parentControl.offset().top - parentControl.scrollTop();
    var width = parentControl.width();
    childControl.css({
        position: "absolute",
        top: (topOffset + 2) + "px",
        left: window.top.isLeftToRight ? (Number($("#header").width()) + Number($("#detail").width())) - 60 + "px" : "unset",
        right: !window.top.isLeftToRight ? (Number($("#header").width()) + Number($("#detail").width())) - 60 + "px" : "unset"
    });
}

function print(code, saleMali) {
    var title = window.top.printDocument;
    var src = "Report/Default?GrpName=FormTrsSanad&SalMali=" + saleMali + "&Inst=" + code;
    openInModal('', src, title, "", "", false);
}

function convertToLetters() {
    var currencyElement = $("#cboArz" + trsType);
    var currencyCode = currencyElement.length > 0 ? currencyElement.lookupBuilder().getSelectedValue() : baseCurrencyCode;
    if (currencyCode.includes("|"))
        currencyCode = currencyCode.split("|")[0];
    if (Number(currencyCode) === 98) {
        var currencyName = currencyElement.length > 0 ? currencyElement.lookupBuilder().getSelectedText() : baseCurrencyName;
        var price = $('#txtPrice' + trsType).val();
        $('#lblAmountletters' + trsType).text(price !== '' ? wordifyfa(numberNonCommas(price), 0) + ' ' + currencyName : '---');
    }
    else {
        $('#lblAmountletters' + trsType).parent().hide();
    }
}

function openFormChequCash() {
    var title = window.top.checksListAtCash;
    var height = "";
    var width = "900";
    var src = "Treasury/ChequeCashdeskList";
    openInModal("", src, title, width, height);
}

function getRemainder(codeType) {
    if ($("#cboAccount" + codeType).lookupBuilder().getSelectedValue()) {
        var account = $("#cboAccount" + codeType).lookupBuilder().getSelectedValue();
        var costCenter = $("#cboCostCenter" + codeType).lookupBuilder().getSelectedValue();
        var project = $("#cboProject" + codeType).lookupBuilder().getSelectedValue();
        var accountCode = account.split("|")[0];

        ajax({
            loading: true,
            url: "TreasuryApi/GetRemainder",
            data: {
                moainCode: Number(accountCode.split("/")[0]),
                customerCode: Number(accountCode.split("/")[1]),
                costCenterCode: costCenter || -1,
                projectCode: project || -1
            },
            success: function (result) {
                $("#remainder" + codeType).text(numberWithCommas(Math.abs(result), baseDecimalCount) + "  " + baseCurrencyName + " " + (result !== 0 ? result > 0 ? window.top.debit : window.top.credit : ""));
            }
        });
    }
}

async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr("id");
    var url = "";
    var data = {};
    var $parent;
    var moainCode = -1;
    switch (id) {
        case "cboTafsil4":
            url = "AccountingApi/GetTafsilList";
            moainCode = $("#cboTypeIncome").lookupBuilder().getSelectedValue().split("/")[1];
            if (!moainCode)
                return;
            data = { MoainCode: moainCode, Level: 21, Search: search, PageNo: 1, SelectedCode: code };
            break;
        case "cboTafsil42":
            url = "AccountingApi/GetTafsilList";
            moainCode = $("#cboReciptTo").lookupBuilder().getSelectedValue();
            if (!moainCode)
                return;
            data = { MoainCode: $("#cboReciptTo").lookupBuilder().getSelectedValue(), level: 21, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCostCenter4":
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboTypeIncome").lookupBuilder().getSelectedValue().split("/")[1], level: 20, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCostCenter42":
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboReciptTo").lookupBuilder().getSelectedValue(), level: 20, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboProject4":
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboTypeIncome").lookupBuilder().getSelectedValue().split("/")[1], level: 22, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboProject42":
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboReciptTo").lookupBuilder().getSelectedValue(), level: 22, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboArz0": case "cboArz1": case "cboArz2":
            url = "GeneralApi/GetCurrencyList";
            data = { search: search, pageNo: 1 };
            break;
        case "cboAccount0": case "cboAccount1": case "cboAccount2":
            url = "TreasuryApi/GetCustomerMoainList";
            data = { search: search, pageNo: 1, selectedCode: code, SelectionCriteria: cboAccountSelectionCriteria };
            break;
        case "cboCashBank0": case "cboCashBank2":
            url = "TreasuryApi/GetCashDeskList";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCashBank1":
            url = "TreasuryApi/GetBankAccountList";
            data = { bank: (!isReceive || null), filter: search, pageNo: 1, selectedCode: code };
            break;
        case "cboProject0": case "cboProject1": case "cboProject2":
            $parent = $("#cboAccount" + id.substr(10)).lookupBuilder();
            moainCode = trsType === 4 ? $parent.getSelectedValue().split('/')[1] : trsType === 42 ? $parent.getSelectedValue() : Number($parent.getSelectedValue().split('/')[0]);
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: moainCode, level: 22, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCostCenter0": case "cboCostCenter1": case "cboCostCenter2":
            $parent = $("#cboAccount" + id.substr(13)).lookupBuilder();
            moainCode = trsType === 4 ? $parent.getSelectedValue().split('/')[1] : trsType === 42 ? $parent.getSelectedValue() : Number($parent.getSelectedValue().split('/')[0]);
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: moainCode, level: 20, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboTypeIncome":
            data = { isReceive: getQuery("type") === "1" };
            url = "TreasuryApi/GetCostIncomeTypeList";
            break;
        case "cboCheckBank":
            url = "TreasuryApi/GetBankList";
            break;
        case "cboReciptTo":
            url = "TreasuryApi/GetBankCashDeskList";
            break;
        case "cboChequeBook":
            var currencyElement = $("#cboArz" + trsType);
            var currencyCode = currencyElement.length > 0 ? currencyElement.lookupBuilder().getSelectedValue() : baseCurrencyCode;
            if (currencyCode.includes("|"))
                currencyCode = currencyCode.split("|")[0];
            url = "TreasuryApi/GetChequeListCombo";
            data = { CurrencyCode: currencyCode };
            break;
        case "cboNumberCheque":
            var selectedValue = $("#cboChequeBook").lookupBuilder().getSelectedValue();
            if (!selectedValue)
                return;
            data = { code: selectedValue.split("/")[0], search: search, selectedCode: code };
            url = "TreasuryApi/GetChequeNumbers";
            break;

    }
    if (url === "")
        return;
    await ajax({
        url: url,
        async: false,
        data: data,
        success: function (result) {
            if (id === "cboAccount0" || id === "cboAccount1" || id === "cboAccount2") {
                $.each(result, function () {
                    this.Code = this.Code + "|" + this.CurrencyCode + "|" + this.CurrencyDecimalCount + "|" + this.CurrencyName + "|" + this.ChildCountTafsil + "|" + this.ChildCountCostCenter + "|" + this.ChildCountProject + "|" + this.Level + "|" + this.TafsilCode;
                });
            }
            else if (id === "cboCashBank0" || id === "cboCashBank2") {
                $.each(result, function () {
                    this.Code = this.Code + "|" + this.CashMoainCode;
                });
            }
            else if (id === "cboCashBank1") {
                $.each(result, function () {
                    this.Code = this.Code + "|" + this.CashMoainCode + "|" + this.PosType + "|" + this.ServerIp;
                });
            }
            else if (id === "cboNumberCheque") {

                var updateRowId = operationRow !== "ADD" ? updateId : "";
                var data = dataTable.filter(x => x.TrsType === 2 && Number(x.ChequeBookCode) === Number($("#cboChequeBook").lookupBuilder().getSelectedValue().split("/")[0]));
                if (updateRowId) {
                    var item = dataTable.filter(x => x.Index === updateRowId)[0];
                    data = data.filter(x => x.Index !== item.Index);
                }
                result = result.filter(x => !data.includes(x));
            }
            else if (id === "cboCheckBank") {
                $.each(result, function () {
                    this.Code = this.Name;
                });
            }
            else if (id.includes("cboArz")) {
                $.each(result, function () {
                    this.Code = this.Code + "|" + this.DecimalCount;
                });
            }
            $combo.lookupBuilder().bindData(result);
            if (id === "cboNumberCheque" && Number(code) <= 0 && result.length > 0) {
                $combo.lookupBuilder().setSelectedValue(result[0].Code)
            }
        }
    });

}

function cboTypeIncomeChange(id) {
    var codeMoain = -1;
    var isMoghabel = false;
    var selectedValue = $("#" + id).lookupBuilder().getSelectedValue();
    if (selectedValue === "")
        return;
    if (id === "cboTypeIncome")
        codeMoain = $("#" + id).lookupBuilder().getSelectedValue().split("/")[1];
    else {
        codeMoain = $("#" + id).lookupBuilder().getSelectedValue();
        isMoghabel = true;
    }

    if ($("#cboTafsil42").length > 0)
        $("#cboTafsil42").lookupBuilder().setSelectedValue("");
    if ($("#cboCostCenter42").length > 0)
        $("#cboCostCenter42").lookupBuilder().setSelectedValue("");
    if ($("#cboProject42").length > 0)
        $("#cboProject42").lookupBuilder().setSelectedValue("");

    ajax({
        loading: true,
        url: "AccountingApi/GetCostCenterProject",
        data: { moainCode: codeMoain },
        success: function (result) {
            var tafsilCount = result.Tafsil.length;
            var ProjectCount = result.ProjectCenter.length;
            var CostCount = result.CostCenter.length;
            if (tafsilCount === 0) {
                $("#cboTafsil4" + (isMoghabel ? "2" : "")).lookupBuilder().setEnabled(false);
                $("#cboTafsil4" + (isMoghabel ? "2" : "")).lookupBuilder().setSelectedValue("");
                toggleRequired("cboTafsil4" + (isMoghabel ? "2" : ""), 1, null, null, false);
            }
            else {
                $("#cboTafsil4" + (isMoghabel ? "2" : "")).lookupBuilder().setEnabled(true);
                toggleRequired("cboTafsil4" + (isMoghabel ? "2" : ""), 1, null, null, true);
            }

            if (ProjectCount === 0) {
                $("#cboProject4" + (isMoghabel ? "2" : "")).lookupBuilder().setEnabled(false);
                $("#cboProject4" + (isMoghabel ? "2" : "")).lookupBuilder().setSelectedValue("");
                toggleRequired("cboProject4" + (isMoghabel ? "2" : ""), 1, null, null, false);
            }
            else {
                $("#cboProject4" + (isMoghabel ? "2" : "")).lookupBuilder().setEnabled(true);
                toggleRequired("cboProject4" + (isMoghabel ? "2" : ""), 1, null, null, true);
            }

            if (CostCount === 0) {
                $("#cboCostCenter4" + (isMoghabel ? "2" : "")).lookupBuilder().setEnabled(false);
                $("#cboCostCenter4" + (isMoghabel ? "2" : "")).lookupBuilder().setSelectedValue("");
                toggleRequired("cboCostCenter4" + (isMoghabel ? "2" : ""), 1, null, null, false);
            }
            else {
                $("#cboCostCenter4" + (isMoghabel ? "2" : "")).lookupBuilder().setEnabled(true);
                toggleRequired("cboCostCenter4" + (isMoghabel ? "2" : ""), 1, null, null, true);
            }
        }
    });
}
function toggleRequired(id, type, currencyCode, rate, state) {
    if (type === 0) {
        if (Number(currencyCode) !== Number(baseCurrencyCode))
            $("#txtNerkh" + trsType.toString()).prop("disabled", false).attr("data-required", "true").addClass("validation").val(numberWithCommas(rate));
        else
            $("#txtNerkh" + trsType.toString()).prop("disabled", true).attr("data-required", "false").removeClass("validation").val(1);
        convertToLetters();
    }
    else {
        if (state) {
            $("#" + id + " .lookup-button").addClass("validation");
            $("#" + id).attr("data-required", "true");
        }
        else {
            $("#" + id + " .lookup-button").removeClass("validation");
            $("#" + id).removeAttr("data-required");
        }
    }
}

async function editRow(itemId) {
    operationRow = 'EDIT';
    updateId = Number(itemId);
    var item = dataTable.find(item => item.Index === updateId);
    trsType = item.TrsType;
    displayCardAdd(trsType);

    $('#btnAddToTable' + trsType).val(window.top._editRegister);
    $($('#btnAddToTable' + trsType).prev()[0]).hide();

    if (trsType !== 4) {
        if ($("#cboArz" + trsType).length > 0) {
            stopEvent = true;
            await $("#cboArz" + trsType).lookupBuilder().setSelectedValue(item.CurrencyCode);
            toggleRequired(null, 0, item.CurrencyCode, item.CurrencyRate);
            stopEvent = false
        }
        await $("#cboAccount" + trsType).lookupBuilder().setSelectedValue(item.CodeAccount);
        $("#cboProject" + trsType).lookupBuilder().setSelectedValue(item.FromProjectCode === -1 ? "" : item.FromProjectCode);
        $("#cboCostCenter" + trsType).lookupBuilder().setSelectedValue(item.FromCostCenterCode === -1 ? "" : item.FromCostCenterCode);

        $('#txtPrice' + trsType).val(numberWithCommas(item.Price));
        convertToLetters();
        $('#txtSummery' + trsType).val(item.Summery);
    }

    switch (trsType) {
        case 0:
            $('#txtTrackNumber').val(item.TrackingCode);
            $("#cboCashBank0").lookupBuilder().setSelectedValue(item.CashDeskCode);
            break;
        case 1:
            $('#txtCodePaygri').val(item.TrackingCode);
            $("#cboCashBank1").lookupBuilder().setSelectedValue(item.BankCode);
            break;
        case 2:
            if (isReceive) {
                $('#txtCheckNumber').val(item.TrackingCode);
                $('#txtOccureDate1').val(item.TrackingDate);
                $('#cboCheckBank').lookupBuilder().setSelectedValue(item.BankName);
                $('#cboCheckType1').val(item.ChequeType);
                $('#cboCashBank2').lookupBuilder().setSelectedValue(item.CashDeskCode);
            }
            else {
                stopEvent = true;
                await $('#cboChequeBook').lookupBuilder().setSelectedValue(item.ChequeBookCode + '/' + item.BankCode);
                stopEvent = false;
                await $("#cboNumberCheque").lookupBuilder().setSelectedValue(item.TrackingCode);
                $('#txtOccureDate').val(item.TrackingDate);
                $('#cboCheckType').val(item.ChequeType.toString());

            }
            $('#txtTel').val(item.TelEtc);
            break;
        case 4:
            var fromMoainCode = item.CodeMoainHazinehDaramad ? item.CodeMoainHazinehDaramad : item.FromMoainCode;
            var toMoainCode = item.CodeMoain_Mo ? item.CodeMoain_Mo : item.ToMoainCode;
            await $('#cboTypeIncome').lookupBuilder().setSelectedValue(item.CostIncomeCode + '/' + fromMoainCode);
            $('#cboTafsil4').lookupBuilder().setSelectedValue(item.FromTafsilCode);
            $('#cboCostCenter4').lookupBuilder().setSelectedValue(item.FromCostCenterCode);
            $('#cboProject4').lookupBuilder().setSelectedValue(item.FromProjectCode);
            $('#txtSummery4').val(item.Summery);
            $('#txtPrice4').val(item.Price);

            await $('#cboReciptTo').lookupBuilder().setSelectedValue(toMoainCode);
            $('#cboTafsil42').lookupBuilder().setSelectedValue(item.ToTafsilCode);
            $('#cboCostCenter42').lookupBuilder().setSelectedValue(item.ToCostCenterCode);
            $('#cboProject42').lookupBuilder().setSelectedValue(item.ToProjectCode);
            convertToLetters();
            break;
    }
}

function getCostCenterProject(senderId) {
    var $combo = $("#" + senderId);
    var selectedValue = $combo.lookupBuilder().getSelectedValue();
    if (selectedValue === "")
        return;
    var moainSelectedItem = selectedValue.split("|");
    var codeMoain = trsType === 4 ? $combo.lookupBuilder().getSelectedValue().split('/')[1] : trsType === 42 ? $combo.lookupBuilder().getSelectedValue() : Number(moainSelectedItem[0].split('/')[0]);
    if ($combo.lookupBuilder().getSelectedValue().indexOf("|") > 0) {
        var childCountM = moainSelectedItem[5];
        var childCountP = moainSelectedItem[6];
        if (codeMoain === 0) {
            if ($("#cboProject" + trsType).length > 0) {
                $("#cboProject" + trsType).lookupBuilder().setEnabled(false);
                $("#cboProject" + trsType).lookupBuilder().setSelectedValue("");
                toggleRequired("cboProject" + trsType, 1, null, null, false);
            }
            if ($("#cboCostCenter" + trsType).length > 0) {
                $("#cboCostCenter" + trsType).lookupBuilder().setEnabled(false);
                $("#cboCostCenter" + trsType).lookupBuilder().setSelectedValue("");
                toggleRequired("cboCostCenter" + trsType, 1, null, null, false);
            }
        }
        else {
            if ($("#cboProject" + trsType).length > 0) {
                if (childCountP > 0) {
                    $("#cboProject" + trsType).lookupBuilder().setEnabled(true);
                    $("#cboProject" + trsType).lookupBuilder().setSelectedValue("");
                    toggleRequired("cboProject" + trsType, 1, null, null, true);
                }
                else {
                    $("#cboProject" + trsType).lookupBuilder().setEnabled(false);
                    $("#cboProject" + trsType).lookupBuilder().setSelectedValue("");
                    toggleRequired("cboProject" + trsType, 1, null, null, false);
                }
            }
            if ($("#cboCostCenter" + trsType).length > 0) {
                if (childCountM > 0) {
                    $("#cboCostCenter" + trsType).lookupBuilder().setEnabled(true);
                    $("#cboCostCenter" + trsType).lookupBuilder().setSelectedValue("");
                    toggleRequired("cboCostCenter" + trsType, 1, null, null, true);
                }
                else {
                    $("#cboCostCenter" + trsType).lookupBuilder().setEnabled(false);
                    $("#cboCostCenter" + trsType).lookupBuilder().setSelectedValue("");
                    toggleRequired("cboCostCenter" + trsType, 1, null, null, false);
                }
            }
        }
    }
    else {

        var item = dataTable.find(item => item.Index === updateId);
        if (!item)
            return;
        if ($("#cboCostCenter" + trsType).length > 0) {
            if (item.FromCostCenterCode > 0) {
                $("#cboCostCenter" + trsType).lookupBuilder().setEnabled(true);
                toggleRequired("cboCostCenter" + trsType, 1, null, null, true);
            }
            else {
                $("#cboCostCenter" + trsType).lookupBuilder().setEnabled(false);
                toggleRequired("cboCostCenter" + trsType, 1, null, null, false);
            }
        }
        if ($("#cboProject" + trsType).length > 0) {
            if (item.FromProjectCode > 0) {
                $("#cboProject" + trsType).lookupBuilder().setEnabled(true);
                toggleRequired("cboProject" + trsType, 1, null, null, true);
            }
            else {
                $("#cboProject" + trsType).lookupBuilder().setEnabled(false);
                toggleRequired("cboProject" + trsType, 1, null, null, false);
            }
        }
    }

    $(".remainder").text("");
}

function getBankCode(type) {
    if (trsType === 4)
        return -1;
    else if (trsType === 1) {
        if (type === "bank")
            return $('#cboCashBank1').lookupBuilder().getSelectedValue() !== null ? $('#cboCashBank1').lookupBuilder().getSelectedValue().split("|")[0] : -1;
        else
            return -1;
    }
    else if (trsType === 0) {
        if (type === "bank") {
            return -1;
        }
        else {
            return $('#cboCashBank0').lookupBuilder().getSelectedValue() !== null ? $('#cboCashBank0').lookupBuilder().getSelectedValue().split("|")[0] : -1;
        }
    }
    else if (trsType === 2) {
        if (isReceive) {
            if (type === "bank")
                return -1;
            //return $("#cboCheckBank").lookupBuilder().getSelectedValue();
            else
                return $('#cboCashBank2').lookupBuilder().getSelectedValue() !== null ? $('#cboCashBank2').lookupBuilder().getSelectedValue().split("|")[0] : -1;

        }
        else if (type === "bank")
            return $('#cboChequeBook').lookupBuilder().getSelectedValue() !== null ? $('#cboChequeBook').lookupBuilder().getSelectedValue().split('/')[1] : -1;
        else
            return -1;
    }
    else
        return -1;
}

function getBankName() {
    if (trsType === 4)
        return $('#cboTafsil42').lookupBuilder().getSelectedText();
    else if (trsType === 1)
        return $('#cboCashBank1').lookupBuilder().getSelectedText();
    else if (trsType === 0)
        return $('#cboCashBank0').lookupBuilder().getSelectedText();
    else if (trsType === 2 && isReceive)
        return $('#cboCheckBank').lookupBuilder().getSelectedText();
    else
        return '';
}

function getCodeDastachak() {
    return isPay && trsType === 2 && $("#cboChequeBook").lookupBuilder().getSelectedValue() !== null ? Number($("#cboChequeBook").lookupBuilder().getSelectedValue().split('/')[0]) : -1;
}

function getChequeBookName() {
    return isPay && trsType === 2 ? $("#cboChequeBook").lookupBuilder().getSelectedText() : '';
}

function getFromMoainCode() {
    if (trsType === 4)
        return $("#cboTypeIncome").lookupBuilder().getSelectedValue() !== null ? $("#cboTypeIncome").lookupBuilder().getSelectedValue().split('/')[1] : -1;
    else {
        return $("#cboAccount" + trsType).lookupBuilder().getSelectedValue() !== null ? $("#cboAccount" + trsType).lookupBuilder().getSelectedValue().split('/')[0] : -1;

    }
}

function getToMoainCode() {
    if (trsType === 4)
        return $("#cboReciptTo").lookupBuilder().getSelectedValue() !== null ? $("#cboReciptTo").lookupBuilder().getSelectedValue() : -1;
    else {
        if (isReceive)
            return $("#cboCashBank" + trsType).lookupBuilder().getSelectedValue().split("|")[1];
        else
            return -1;
    }

}

function getTrackingCode() {
    if (trsType === 0)
        return $('#txtTrackNumber').val();
    else if (trsType === 1)
        return $('#txtCodePaygri').val();
    else if (trsType === 2) {
        if (isReceive)
            return $('#txtCheckNumber').val();
        else
            return $('#cboNumberCheque').lookupBuilder().getSelectedValue();
    }
    return '';
}

function getTrackingDate() {
    if (trsType === 2)
        if (isReceive)
            return $('#txtOccureDate1').val();
        else
            return $('#txtOccureDate').val();
    else
        return '';
}

function getCheckType() {
    if (trsType === 2)
        if (isReceive)
            return $('#cboCheckType1').val() || -1;
        else
            return $('#cboCheckType').val() || -1;
    else
        return 0;
}

function getCodeTarafHesab() {
    return trsType !== 4 && $("#cboAccount" + trsType).lookupBuilder().getSelectedValue() !== null ? Number($("#cboAccount" + trsType).lookupBuilder().getSelectedValue().split("|")[0].split('/')[1]) : -1;
}

function getCodeHazinehDaramad() {
    return trsType === 4 && $('#cboTypeIncome').lookupBuilder().getSelectedValue() !== null ? Number($('#cboTypeIncome').lookupBuilder().getSelectedValue().split('/')[0]) : -1;
}

function getCodeMoainHazinehDaramad() {
    return trsType === 4 && $('#cboTypeIncome').lookupBuilder().getSelectedValue() !== null ? Number($('#cboTypeIncome').lookupBuilder().getSelectedValue().split('/')[1]) : -1;
}

function getNameHazinehDaramad() {
    return trsType === 4 && $('#cboTypeIncome').lookupBuilder().getSelectedValue() !== null ? $('#cboTypeIncome').lookupBuilder().getSelectedText() : '';
}

async function onCurrencyChanged(sender) {
    var value = eval(sender + "Builder").getSelectedValue();
    if (value === "")
        return;
    value = value.split("|");
    $("#txtPrice" + trsType).attr("data-decimalcount", value[1]);
    if (stopEvent)
        return;
    var rate = 1;
    if (Number(value[0]) !== Number(baseCurrencyCode)) {
        await ajax({
            loading: true,
            url: 'SaleApi/GetCurrencyRate',
            data: { currencyCode: value[0], date: $("#txtDate").val() },
            success: function (retValue) {
                rate = retValue.PriceInReal;
            }
        });
    }
    toggleRequired(null, 0, Number(value[0]), rate);
}

async function emptyControls() {
    $('#txtPrice' + trsType).val('');
    $('#txtTrackNumber').val('');
    $('#txtCodePaygri').val('');
    $('#txtOccureDate').val('');
    $('#txtOccureDate1').val('');
    $('#txtCheckNumber').val('');
    $('#txtSummery' + trsType).val('');
    $("#txtNerkh" + trsType).val('');
    $("#lblAmountletters" + trsType).text('');



    if ($("#cboArz" + trsType).length > 0)
        await $("#cboArz" + trsType).lookupBuilder().setSelectedValue("");
    if ($("#cboChequeBook").length > 0)
        $("#cboChequeBook").lookupBuilder().setSelectedValue("");
    if ($("#cboAccount" + trsType).length > 0)
        $("#cboAccount" + trsType).lookupBuilder().setSelectedValue("");

    if ($("#cboCostCenter" + trsType).length > 0)
        $("#cboCostCenter" + trsType).lookupBuilder().setSelectedValue("");
    if ($("#cboCostCenter42").length > 0)
        $("#cboCostCenter42").lookupBuilder().setSelectedValue("");

    if ($("#cboProject" + trsType).length > 0)
        $("#cboProject" + trsType).lookupBuilder().setSelectedValue("");
    if ($("#cboProject42").length > 0)
        $("#cboProject42").lookupBuilder().setSelectedValue("");

    if ($("#cboCashBank" + trsType).length > 0)
        $("#cboCashBank" + trsType).lookupBuilder().setSelectedValue("");

    if (trsType === 2) {
        if ($("#cboChequeBook").length > 0)
            $("#cboChequeBook").lookupBuilder().setSelectedValue("");
        if ($("#cboNumberCheque").length > 0)
            $("#cboNumberCheque").lookupBuilder().setSelectedValue("");
        if ($("#cboCheckBank").length > 0)
            $("#cboCheckBank").lookupBuilder().setSelectedValue("");
        $("#cboCheckType").val(1);
    }

    if (trsType === 4) {
        if ($("#cboTypeIncome").length > 0)
            $("#cboTypeIncome").lookupBuilder().setSelectedValue("");
        if ($("#cboTafsil4").length > 0)
            $("#cboTafsil4").lookupBuilder().setSelectedValue("");
        if ($("#cboReciptTo").length > 0)
            $("#cboReciptTo").lookupBuilder().setSelectedValue("");
        if ($("#cboTafsil42").length > 0)
            $("#cboTafsil42").lookupBuilder().setSelectedValue("");
        if ($("#cboTafsil42").length > 0)
            $("#cboTafsil42").lookupBuilder().setSelectedValue("");
    }


}

function getProjectCostCenter(code, codeProject, codeCostCenter, codeTafsil) {

    var cboProject = $("#cboProject" + trsType);
    var cboCostCenter = $("#cboCostCenter" + trsType);
    var cboTafsil = $("#cboTafsil" + trsType);

    ajax({
        loading: true,
        url: "AccountingApi/GetCostCenterProject",
        data: { moainCode: type === 4 ? code.split('/')[1] : code },
        async: false,
        success: function (result) {
            var costCenter = result.CostCenter;
            var projectCenter = result.ProjectCenter;
            var tafsil = result.Tafsil;
            if ($('#cboProject').length === 1) {
                $('#cboProject').lookupBuilder().setSelectedValue("");
                for (var i = 0; i < projectCenter.length; i++) {
                    $('#cboProject').lookupBuilder().AddItem(projectCenter[i].Name, projectCenter[i].Code);
                }

                if (codeProject !== -1)
                    $('#cboProject').lookupBuilder().setSelectedValue(codeProject);

                if (projectCenter.length !== 0)
                    $('#cboProject').attr("disabled", "");
                else
                    $('#cboProject').attr("disabled", "disable");
            }

            if ($('#cboCostCenter').length > 0) {
                $('#cboCostCenter').lookupBuilder().setSelectedValue("");
                for (var j = 0; j < costCenter.length; j++) {
                    $('#cboCostCenter').lookupBuilder().AddItem(costCenter[j].Name, costCenter[j].Code);
                }

                if (codeCostCenter !== -1)
                    $('#cboCostCenter').lookupBuilder().setSelectedValue(codeCostCenter);
                if (projectCenter.length !== 0)
                    $('#costCenter').attr("disabled", "");
                else
                    $('#costCenter').attr("disabled", "disable");
            }

            $('#cboTafsil').lookupBuilder().setSelectedValue("");
            for (var k = 0; k < tafsil.length; k++) {
                $('#cboTafsil').lookupBuilder().AddItem(tafsil[k].Name, tafsil[k].Code);
            }
            cboTafsil.EndUpdate();

            if (codeTafsil !== -1)
                $('#cboTafsil').lookupBuilder().setSelectedValue(codeTafsil);

        }
    });
}
async function cboChequeTypeChange(sender) {
    var value = Number($(sender).val());
    if (value === 3) {
        if (!getOpeningCheque) {
            await getAccConfig();
            if (openingMoain <= 0) {
                showMsgModal(0, window.top.noOpeningAcc);
                $(sender).val(1);
                return;
            }
            await getOpeningCorrespondant();
        }
        if (openingMoain <= 0) {
            showMsgModal(0, window.top.noOpeningAcc);
            $(sender).val(1);
        }
        else {
            cboAccountSelectionCriteria = openingMoain + (openingCorrespondant ? "/" + openingCorrespondant : "");
            $("#cboAccount2").lookupBuilder().setSelectedValue(cboAccountSelectionCriteria);
        }
    }
    else {
        cboAccountSelectionCriteria = null;
        $("#cboAccount2").lookupBuilder().setSelectedValue("");
    }
}
async function getAccConfig() {
    await ajax({
        loading: true,
        url: "GeneralApi/GetConfigArray",
        data: { NameList: ["Eftetahiyeh_HesabTafsil", "Eftetahiyeh_Moein"] },
        success: function (result) {
            openingMoain = Number(result[1].Value);
            openingTafsil = Number(result[0].Value);
            getOpeningCheque = true;
        }
    });
}
async function getOpeningCorrespondant() {
    await ajax({
        loading: true,
        url: "GeneralApi/GetCustomerByTafsilCode",
        data: { Code: openingTafsil },
        success: function (result) {
            openingCorrespondant = (result ? Number(result.Code) : 0);
        }
    });
}
function openPosModal() {
    var price = numberNonCommas($("#txtPrice1").val());
    var bank = $("#cboCashBank1").lookupBuilder().getSelectedValue();
    if (price <= 0) {
        showMsgModal(0, window.top.invalidPrice);
        return;
    }
    if (!bank)
        return;

    openInModal('', 'Treasury/POSClearing?price=' + price + "&bank=" + bank.split("|")[0]+"&dis=1", window.top.posPayed, '600', '390');
}
function savePosParent(bankCode, trackingCode) {
    $("#txtCodePaygri").val(trackingCode);
    closeTopModal();
    addToTable();
}


