var gridBuilder;
var hasCurrencySystem = window.top.$("#hfCurrencySystem").val() === "1";
var baseCurrencyName = window.top.$("#hfBaseCurrencyName").val();
$(document).ready(function () {
    gridBuilder = $(".grid").gridBuilder();
    gridBuilder.setCaption(getQuery("type") === "1" ? window.top.treasuryReceiveList : window.top.treasuryPaymentList);
    if (getQuery("type") === "1")
        gridBuilder.removeColumn("PaidChequeCode");
    else
        gridBuilder.removeColumn("ReceivedChequeCode");

    gridBuilder.onDblClick(function () {
        edit();
    });
    gridBuilder.onExportClick(function () {
        loadGrid("", { exportExcel: true });
    });
    if (!hasCurrencySystem) {
        gridBuilder.removeColumn("CurrencyName");
    }
    else {
        gridBuilder.setColumnCaption("Price", window.top.amount + "(" + baseCurrencyName + ")");
    }
    loadGrid();
});

function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    ajax({
        gridBuilder: gridBuilder,
        url: "TreasuryApi/GetPayReceivedList",
        data: {
            showOnlyTrs: true,
            mySelf: true,
            trsOperationType: getQuery("type") || -1,
            fromCode: -1,
            toCode: -1,
            filter: gridBuilder.getFilter(),
            sort: gridBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber()
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else
                gridBuilder.loadData(data);
        }
    });
}

function edit() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    openModal(gridBuilder.getCellValue(rowIndex, "code"));
}

function openModal(code) {
    var title = getQuery("type") === "1" ? window.top.registerReceive : window.top.registerPayment;
    var src = 'Treasury/TreasuryPayReceiveSave?isList=1&type=' + getQuery('type') + (code > 0 ? "&code=" + code : "");
    openInTab(src, title, 'img/pages/menu/321.svg', true);
}

function deleteRow() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        var list = [];
        list.push(gridBuilder.getCellValue(rowIndex, "code"));
        ajax({
            loading: true,
            url: "TreasuryApi/DeletePayReceive",
            data: { codeList: list },
            success: function (result) {
                showMsgModal(2, window.top.deletedSuccessfully);
                loadGrid();
            }
        });
    }
}