$(document).ready(function () {
    $('body').on('blur', '.setoff', setoff);
    $('body').on('keyup', '#recd, #discount, #dclaim', calculateRow);
    $('body').on('click', '.mark, #mclaim', setclaim);
    $('body').on('change', '#bankname', getRecpNo);
    $('body').on('blur', '#drawbank', DrwBnkModl);
    $('body').on('blur', '#branch', BrnchModl);
    $('body').on('keyup', '#drawsrch', DrwBnkSrch);
    $('body').on('keyup', '#branchsrch', BrnchSrch);
    $('body').on('click', '.tddrawbank', filval);
    $('body').on('click', '.tdbranch', filvalbrnch);
    $('body').on('change', '.allchk', ChkAll);

    $(".secondrymodal").hide();

    $(".proceed").click(function () {
        $(".secondrymodal").show();
        $(".primarymodal").hide();

        var frecpno = $('.frmrecp').val(),
                trecpno = $('.torecp').val();

        $('.frecpno').val(frecpno);
        $('.trecpno').val(trecpno);
    });

    $("#myModal").on('shown.bs.modal', function () {
        $(".secondrymodal").hide();
        $(".primarymodal").show();
    });

    function ChkAll() {
        if ($(this).prop("checked") == true) {
            $('.mcheck').prop('checked', true);
        } else {
            $('.mcheck').prop('checked', false);
        }
    }

    $('.proceed').click(function () {
        var frmvouch = $('.frmvouch').val(),
                tovouch = $('.tovouch').val(),
                drawbank = $(".drawbank").val(),
                data = {frmvouch: frmvouch, tovouch: tovouch, drawbank: drawbank};
        $.ajax({
            type: 'GET',
            dataType: 'html',
            url: 'bankrecp_mult.php',
            data: data,
            success: function (response) {
                $(".mprint").empty();
                $(".mprint").html(response);
            },
            error: function (request, textStatus, errorThrown) {
                console.log(errorThrown);

            }
        });
    });

    function filval() {
        var tr = $(this).closest('tr'),
                drawname = tr.find('.tddrawbank').text();
        $('#drawbank').val(drawname);
        $(".DrawbnkModal").modal('hide');
        $("#drawbank").focus();
    }
    function filvalbrnch() {
        var tr = $(this).closest('tr'),
                branch = tr.find('.tdbranch').text();
        $('#branch').val(branch);
        $(".BrnchModl").modal('hide');
        $("#branch").focus();
    }

    function DrwBnkModl() {
        var drawbank = $("#drawbank").val();

        if (drawbank === "") {
            $.get('get_draw.php', function (data) {
                $(".DrawbnkModal").modal('show');
                $(".DrawbnkModal").on('shown.bs.modal', function () {
                    $('#drawsrch').focus();
                });
                $('.tbody').html(data);
            });
        }

    }
    
    function BrnchModl() {
        var branch = $("#branch").val();

        if (branch === "") {
            $.get('get_branch.php', function (data) {
                $(".BrnchModl").modal('show');
                $(".BrnchModl").on('shown.bs.modal', function () {
                    $('#branchsrch').focus();
                });
                $('.tbranch').html(data);
            });
        }

    }

    function DrwBnkSrch() {
        var ssearch = $("#drawsrch").val();

        if (ssearch != "") {
            $.get('get_draw.php', {ssearch: ssearch}, function (data) {
                $('.tbody').html(data);
            });
        }
    }
    function BrnchSrch() {
        var ssearch = $("#branchsrch").val();

        if (ssearch != "") {
            $.get('get_branch.php', {ssearch: ssearch}, function (data) {
                $('.tbranch').html(data);
            });
        }
    }


    $(document).keydown(function (event) {

        //19 for Mac Command+S
        if (event.keyCode == 27) { // escape key maps to keycode `27`
            // <DO YOUR WORK HERE>
            $(".BrnchBnkModl").modal('hide');
            $(".DrawbnkModal").modal('hide');
            $("#settmodal").modal('hide');

        }

    });

    $('.school').change(function () {
        var school = $('.school').val();
        $('.ledger').attr('href', 'ledger_fr.php?view&acname=' + school + '&dtype=2');

    });

    function getRecpNo() {
        var bankname = $("#bankname").val(),
                cashdb = "bankrecp",
                vouchno = $("#vouchno").val();

        $.get('getRecpNo.php', {bankname: bankname, cashdb: cashdb, vouchno: vouchno}, function (data) {
            $('.recpno').val(data);

        });
    }
    $(".tranmesg").hide();
    var trnflag = $(".trnflag").val();
    if (trnflag != "") {
        $("#hedit").hide();
        $("#hdelete").hide();
        $(".tranmesg").show();
        $(".trnmsg").val("Edit / Delete Not Allowed For this Receipt");

    }

    function showDays(firstDate, secondDate) {
        var date1 = firstDate;
        var date2 = secondDate.split("-").reverse().join("-");
        var mfirstday = new Date(date1);
        var mlastday = new Date(date2);
        var distance
        if (mfirstday > mlastday) {
            distance = mfirstday.getTime() - mlastday.getTime();
            distance = Math.ceil(distance / 1000 / 60 / 60 / 24);
        } else {
            distance = 0;
        }
        return distance;
    }

    $(".settotal").hide();

    function setoff() {
        var val = 0;
        var $row = $(this).closest("tr");
        var msetoff = parseFloat($row.find('.setoff').val()),
                mbalamt = parseFloat($row.find('.balamt').val()),
                mbilamt = parseFloat($row.find('.billamt').val()),
                amtadj = parseFloat($row.find(".amtadj").val()),
                mbilldate = $row.find('.billdate').val(),
                mvouchdt = $('#vouchdt').val();
        if (isNaN(msetoff)) {
            msetoff = 0;
        }

        if (msetoff > mbalamt && mbalamt < 0) {
            $row.find('.setoff').val(0);
            $row.find('.setoff').focus();
            msetoff = 0;
            alert("SETOFF AMOUNT CANNOT BE GREATER THAN BALANCE AMOUNT");
            $("#save").attr("disabled", "disabled");

        }

        var balance = mbilamt - amtadj - msetoff;
        $row.find(".balamt").val(balance);

        //        var remain = $("#remain").val();



        var mamt = $('#amount').val();

        /*********Total Part************/

        $(".setoff").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val += parseFloat(this.value);
            }
        });

        if (val > mamt) {
            $row.find('.setoff').val(0);
            $row.find('.setoff').focus();
            alert("TOTAL SETOFF AMOUNT CANNOT BE GREATER THAN TOTAL AMOUNT");
            $("#save").attr("disabled", "disabled");
        } else {
            $("#totsetoff").val(val);
            $("#save").removeAttr("disabled");

            var totdays = showDays(mvouchdt, mbilldate);
            var totremain = mamt - val;

            $row.find('.days').val(totdays);
            $("#remain").val(totremain);
        }
    }
    //    function addrows() {
    //
    //        var ctr = $('#items').val();
    //        $.post('billsett.php', {ctr: ctr}, function (data) {
    //            $(data).appendTo('#data');
    //            ctr++;
    //            $('#items').val(ctr);
    //        });
    //    }

    function parseDate(str) {
        var mdy = str.split('/')
        return new Date(mdy[2], mdy[0] - 1, mdy[1]);
    }

    function daydiff(first, second) {
        return (second - first) / (1000 * 60 * 60 * 24)
    }


    //    $('#addnew').click(function () {
    //        addrows();
    //    });


    function billsett() {
        $('#data').empty();
        var accode = $('#party').val();
        var vouchno = $('#vouchno').val();
        var vouchdt = $('#vouchdt').val();
        var amount = $('#amount').val();
        var bankcode = $('#bankcode').val();

        $.get('billsett.php', {
            accode: accode,
            vouchno: vouchno,
            vouchdt: vouchdt,
            amount: amount,
            bank: bankcode,
            dbf: "bankrecp",
            pvar: "R",
            source: "BR"
        }, function (data) {
            $('#data').html(data);
            $('.billflag').val(1);
        });
    }

    $('#billsett').click(function () {
        billsett();
    });

    $('#amount').blur(function () {
        $(".settotal").show();
        $("#settmodal").modal("show");
        billsett();
    });

    $("#settmodal").on('hidden.bs.modal', function () {
        var exam = $('#exam').val();
        $('#bill_table').find('tr').each(function () {
            var row = $(this),
                    setoff = row.find('.setoff').val();

            if (setoff > 0) {
                var texam = row.find('.examcode').val(),
                        billdate = row.find('.billdate').val(),
                        billno = row.find('.billno').val(),
                        billamt = row.find('.billamt').val(),
                        rem = "Bill No." + billno + "   " + "Dated:" + billdate + "   " + "Bill Amt." + billamt;
                if (exam == "") {
                    $('#exam').val(texam).trigger("change");
                }
                $('.remark1').val(rem);
                return false;
            }

        });

    });


    function calculatesetoff() {
        var val = 0;
    }


    function calculateRow() {
        var fintot = 0;
        var subtot = parseFloat($('#recd').val());
        var discount = parseFloat($('#discount').val());
        var claim = parseFloat($('#dclaim').val());

        fintot = subtot + discount + claim;

        if (isNaN(fintot)) {
            $('#amount').val("0");
        } else {
            $('#amount').val(fintot.toFixed(1));
        }
    }

    $("#mclaim").click(function () {
        var code = $("#party").val();
        $.post('get_claim.php', {code: code, var : "R"}, function (data) {
            $('#browdata').html("");
            $('#browdata').append(data);
            $("#overlay_form").fadeIn(1000);
            positionPopup();

        });
    });

    function setclaim() {

        var $row = $(this).closest("tr");
        var vouch = $('#vouchno').val();
        var vouchdt = $('#mvouchdt').val();
        //  var claim   = $('#claim').val();
        var mval = 0;
        var mark = $row.find('.mark');
        //          if($row.find(".mark").is(":checked")) {
        var mtot = 0;
        var cl = parseFloat($("#dclaim").val());
        if ($row.find(".mark").is(":checked")) {
            mtot = cl + parseFloat($row.find(".billamt").val());

        } else {
            mtot = cl - parseFloat($row.find(".billamt").val());
        }
        $("#dclaim").val(mtot.toFixed(2));

    }


});