var gridBuilder;
var hfSanadType = 'close';
var errorStr = "";
var hasCurrencySystem = window.top.$("#hfCurrencySystem").val() === "1";
var baseCurrencyName = window.top.$('#hfBaseCurrencyName').val();
var accHeader;
$(document).ready(function () {
    gridBuilder = $("#gridDocument").gridBuilder();
    if (!hasCurrencySystem) {
        gridBuilder.removeColumn("CurrencyDebit,CurrencyCredit,CurrencyName,CurrencyRate");
    }
    else {
        gridBuilder.setColumnCaption("Debit", window.top.debit + " (" + baseCurrencyName + ")");
        gridBuilder.setColumnCaption("Credit", window.top.debit + " (" + baseCurrencyName + ")");
    }
    $(".main-title").click(function () {
        gridBuilder.clearRows();
        $('.main-title').removeClass("selected-tab-title");
        $(this).addClass("selected-tab-title");
        switch ($('.selected-tab-title').attr('data-id')) {
            case '1':
                $('#level1').show();
                $('#divTab1').show();
                $('#level2').hide();
                $('#level3').hide();
                $('#divTab3').hide();
                $('#divTab2').hide();
                hfSanadType = 'close';
                changeRequired("cboMoain", true);
                break;
            case '2':
                $('#level2').show();
                $('#level1').hide();
                $('#level3').hide();
                $('#divTab3').hide();
                $('#divTab1').hide();
                $('#divTab2').show();
                hfSanadType = 'end';
                changeRequired("cboMoain", false);
                break;
            case '3':
                $('#level3').show();
                $('#divTab3').show();
                $('#divTab2').hide();
                $('#level1').hide();
                $('#level2').hide();
                $('#divTab1').hide();
                hfSanadType = 'start';
                changeRequired("cboMoain", false);
                break;
        }
    });
    $('#btnCalculate').click(function () {
        $('#btnSave').css('display', 'inline-block');
    });
    $('#btnSave').click(function () {
        $('#btnTransferToAccounting').css('display', 'inline-block');
    });

});
function loadGrid(gridId, objectParameter, state) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    ajax({
        loading: true,
        url: "AccountingApi/" + (state === 1 ? "GetClosingAccDocument" : "GetOpeningAccDocument"),
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else {
                gridBuilder.loadData(data);
            }
        }
    });
}
function getEventLookupCombo($combo, search, code) {
    ajax({
        url: "AccountingApi/GetMoainList",
        async: false,
        data: {
            checkActive: true,
            search: search,
            selectedCode: code,
            pageNo: 1
        },
        success: function (result) {
            $combo.lookupBuilder().bindData(result);
        }
    });
}
function getDocumentTypeCode(name) {
    var code;
    switch (name) {
        case "start":
            code = 2;
            break;
        case "close":
            code = 3;
            break;
        case "end":
            code = 4;
            break;
    }
    return code;
}

async function save() {
    var exceptionText = checkValidation('');
    if (exceptionText === '') {
        var articles = gridBuilder.getDataArray()["data"];
        if (articles.length === 0)
            alert(window.top.dataEmpty);
        else if (!isFullDate($('#txtDate').val()))
            showMsgModal(0, window.top.dateCorrectly);
        else {
            showLoading();
            await getNewDocument();
            await saveDocument(articles);
            closeLoading();
        }
    }
    else
        showMsgModal(0, window.top.fillMarked);
}
async function getNewDocument() {
    await ajax({
        loading: false,
        url: 'AccountingApi/GetNewDocument',
        success: function (retValue) {
            accHeader = retValue;
        }
    });
}
async function saveDocument(articles) {
    accHeader['CodeSanadState'] = 2;
    accHeader['DocumentStateCode'] = 2;
    accHeader['CodeSanadStateMain'] = 2;
    accHeader["DocumentTypeCode"] = getDocumentTypeCode(hfSanadType);
    accHeader["Summery"] = $("#txtDecription").val();
    accHeader["DocumentDateLocal"] = $("#txtDate").val();
    await ajax({
        loading:false,
        url: 'AccountingApi/InsertDocument',
        data: { header: accHeader, articles: articles, printAfter: false, jump: false, attachment: [] },
        success: function (result) {
            showMsgModal(2, result.FinalMessage);
            location.reload();
        }, error: function (error) {
            showMsgModal(0, error.responseJSON.Message);
            errorStr = error.ErrorCode;
        }
    });
}
function openModal(frmName) {
    var title;
    var src;
    if (frmName === 'chooseAccount') {
        var moain = $("#cboMoain").lookupBuilder().getSelectedValue();
        if (moain) {
            title = window.top.temporaryResidual;
            src = "Accounting/ChooseAccount?code=" + moain;
            openInModal('', src, title, "", "");
        }
        else {
            alert(window.top.annualPerformance);
        }
    }
    else if (frmName === 'InvoiceSave') {
        var artikles = gridBuilder.getDataArray()["data"];
        if (artikles.length > 0) {
            title = window.top.accountingDocument;
            src = "Accounting/InvoiceSave?yearclose=1&type=" + hfSanadType;
            openInModal('', src, title, "", "");
        }
        else {
            alert(window.top.transferAccounting);
        }
    }
}
function refreshGrid(value) {
    if (value !== "clear")
        gridBuilder.loadData(eval(value));
}
function getData() {
    var data = gridBuilder.getDataArray()["data"];
    return { data: data, error: errorStr};
}



