var TotalDebitAmount = 0;
var TotalCreditAmount = 0;

$(function () {



    $(".AmountTxt").on('keyup', function () {

        CalculateTotals();
        var TD = $(this).parent().parent().children()[4];
        var input = $(TD).children()[0];
        if ($(this).val()) {
            input.setAttribute("readonly", true);
        }
        else {
            input.removeAttribute("readonly");
        }
    });

    $(".CreditAmountTxt").on('keyup', function () {

        CalculateTotals();
        var TD = $(this).parent().parent().children()[3];
        var input = $(TD).children()[0];
        if ($(this).val()) {
            input.setAttribute("readonly", true);
        }
        else {
            input.removeAttribute("readonly");
        }

    });

    $('#btnUpdate').on('click', function () {

        var data = {};
        var detailData = [];

        var docDate = $('#DocDate').val();
        var bookID = $('#BookID').val();
        var description = $('#Description').val();
        var referenceVNO = $('#ReferenceVNO').val();
        var voucherNO = $('#VoucherNo').val();

        if (!docDate) {
            $('#DocDate').focus();
            MyAlert('Warning!', 'Doc Date is Required!', 'warning', 'icon-ios-close-outline');
            return false;
        }

        if (!bookID) {
            $('#BookID').focus();
            MyAlert('Warning!', 'Book is Required!', 'warning', 'icon-ios-close-outline');
            return false;
        }

        if (TotalDebitAmount - TotalCreditAmount != 0) {
            MyAlert('Warning!', 'Debit and Credit Amount should Equal!', 'warning', 'icon-ios-close-outline');
            return false;
        }

        var $tblrows = $("#DetailTable tbody tr");
        $tblrows.each(function (index) {

            var Id = $('input[name="GLTransectionDetailDto[' + index + '].Id"]').val();
            var accountID = $('select[name="GLTransectionDetailDto[' + index + '].AccountID"]').val();
            var subAccID = $('select[name="GLTransectionDetailDto[' + index + '].SubAccID"]').val();
            var narration = $('input[name="GLTransectionDetailDto[' + index + '].Narration"]').val();
            var amount = IsNullZero($('input[name="GLTransectionDetailDto[' + index + '].Amount"]').val());
            var creditAmount = IsNullZero($('input[name="GLTransectionDetailDto[' + index + '].CreditAmount"]').val());
            if (!accountID) {
                $('input[name="GLTransectionDetailDto[' + index + '].AccountID"]').focus();
                MyAlert('Warning!', 'Account is Required!', 'warning', 'icon-ios-close-outline');
                return false;
            }
            if (!narration) {
                $('input[name="GLTransectionDetailDto[' + index + '].Narration"]').focus();
                MyAlert('Warning!', 'Narration is Required!', 'warning', 'icon-ios-close-outline');
                return false;
            }


            if (!amount && !creditAmount) {
                $('input[name="GLTransectionDetailDto[' + index + '].Amount"]').focus();
                MyAlert('Warning!', 'Amount is Required!', 'warning', 'icon-ios-close-outline');
                return false;
            }

            detailData.push({
                "Id": Id,
                "AccountID": accountID,
                "SubAccID": subAccID,
                "Narration": narration,
                "Amount": amount,
                "CreditAmount": creditAmount
            });
        });

        data = {
            "Id": $("#Id").val(),
            "DocDate": docDate,
            "BookID": bookID,
            "Description": description,
            "ReferenceVNO": referenceVNO,
            "VoucherNo": voucherNO,
            "GLTransectionDetailDto": detailData
        };

        $.ajax({
            type: 'POST',
            url: '/GLTRHs/Edit',
            data: data,
            success: function (response) {
                if (response.success) {
                    window.location.href = "/GLTRHs/JournalVoucher";
                }
                else {
                    MyAlert("Opps!", response.message, "error", "icon-ios-close-outline");
                }
            }
        });

    });

    $("#BookID").on('change', function () {
        if ($("#BookID").val() != "") {
            $.ajax({
                url: '/GLTRHs/GetNextVoucherNo?bookId=' + $("#BookID").val(),
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    $("#VoucherNo").val(data);
                }
            });
        }
        else {
            $("#VoucherNo").val("");
            $("#DebitAccountId").empty();
        }
    });

    $('.btnremoverow').click(function () {
        if ($('#DetailTable tbody>tr:last').index() + 1 != 2) {
            $(this).closest('tr').remove();
            counter--;
        }
    });


    $('.btnaddrow').click(function () {
        AddNewRow();
        counter++;
        scounter++;
    });

    $(".AccountsDD").on('change', function (e) {
        var AccountID = $(this).val();
        var TD = $(this).parent().parent().children()[1];
        var SubAccount = $(TD).children()[0];
        if (AccountID != "") {
            $.ajax({
                url: '/GLTRHs/GetSubAccounts?AccountID=' + AccountID,
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    var html = "";
                    for (var i = 0; i < data.length; i++) {
                        html += "<option value='" + data[i].Value + "'>" + data[i].Name + "</option>";
                    }
                    $(SubAccount).html(html);
                    SubAccount.focus();
                    if (e.params) {
                        $(SubAccount).val(e.params.data);
                    }
                }
            });
        }
        else {
            $(SubAccount).empty();
        }
    });

})



function CalculateTotals() {
    var $tblrows = $("#DetailTable tbody tr");
    TotalDebitAmount = 0;
    TotalCreditAmount = 0;
    $tblrows.each(function (index) {
        if ($.isNumeric($('input[name="GLTransectionDetailDto[' + index + '].Amount"]').val())) {
            TotalDebitAmount += parseFloat($('input[name="GLTransectionDetailDto[' + index + '].Amount"]').val());
        }

        if ($.isNumeric($('input[name="GLTransectionDetailDto[' + index + '].CreditAmount"]').val())) {
            TotalCreditAmount += parseFloat($('input[name="GLTransectionDetailDto[' + index + '].CreditAmount"]').val());
        }
    });

    $('#DebitAmount').text(TotalDebitAmount);
    $("#TotalDr").val(TotalDebitAmount);

    $('#CreditAmount').text(TotalCreditAmount);
    $("#TotalCr").val(TotalCreditAmount);
    $("#TotalAmount").text(TotalDebitAmount - TotalCreditAmount);

}

function AddNewRow() {

    var counter = $("#DetailTable tbody tr").length;
    var lastIndex = counter - 1;


    $('.AccountsDD').select2("destroy");
    $('#DetailTable tbody>tr:last').clone(true).insertAfter('#DetailTable tbody>tr:last');
    var tr = $('#DetailTable tbody>tr:last');
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__AccountID').attr('name', 'GLTransectionDetailDto[' + counter + '].AccountID').val("");
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__SubAccID').attr('name', 'GLTransectionDetailDto[' + counter + '].SubAccID').val("");
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__Narration').attr('name', 'GLTransectionDetailDto[' + counter + '].Narration').val("");
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__Amount').attr('name', 'GLTransectionDetailDto[' + counter + '].Amount').val("").removeAttr("readonly");
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__CreditAmount').attr('name', 'GLTransectionDetailDto[' + counter + '].CreditAmount').val("").removeAttr("readonly");

    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__AccountID').attr('Id', 'GLTransectionDetailDto_' + counter + '__AccountID');
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__SubAccID').attr('Id', 'GLTransectionDetailDto_' + counter + '__SubAccID');
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__Narration').attr('Id', 'GLTransectionDetailDto_' + counter + '__Narration');
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__Amount').attr('Id', 'GLTransectionDetailDto_' + counter + '__Amount');
    $('#DetailTable tbody>tr:last #GLTransectionDetailDto_' + lastIndex + '__CreditAmount').attr('Id', 'GLTransectionDetailDto_' + counter + '__CreditAmount');


    $('.AccountsDD').select2({
        width: '100%'
    });
}

function LoadAccounts() {
    $.ajax({
        url: '/GLTRHs/GetAccounts',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            var html = "<option value=''>--Select Account--</option>";
            for (var i = 0; i < data.length; i++) {
                html += "<option value='" + data[i].Value + "'>" + data[i].Name + "</option>";
            }

            var $tblrows = $("#DetailTable tbody tr");
            $tblrows.each(function (index) {
                $('select[name="GLTransectionDetailDto[' + index + '].AccountID"]').html(html);
            });
            $('.AccountsDD').select2({
                width: '100%'
            });
        }
    });
}

function GetVoucherDetailForEdit(id) {
    $.ajax({
        url: '/GLTRHs/GetVoucherDetailForEdit?Id=' + id,
        type: 'Get',
        dataType: 'json',
        success: function (data) {
            var $tblrows = $("#DetailTable tbody tr");
            $tblrows.each(function (index) {

                subAccountId = data[index].SubAccID;
                $('select[name="GLTransectionDetailDto[' + index + '].AccountID"]').val(data[index].AccountID).trigger({
                    type: 'change',
                    params: {
                        data: data[index].SubAccID
                    }
                });

            });

        }
    });
}