$(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('change', '.party', getLogDate);
    $('body').on('blur', '.vouchdt', getLogDate);

    function getLogDate() {
        var party = $(".party").val(),
                vouchdt = $(".vouchdt").val();
        if (party != '' && vouchdt != '') {
            $.get('chk_LogDate.php', {party: party}, function (data) {
                if (data != '0000-00-00') {
                    $(".logdate").val(data);
                    if (vouchdt <= data) {
                        alert('Voucher Date is Less than Log Date');
//                        $(".party").select2("val", "");

                        $(".party").select2("open");

                    }
                }
            });
        }

    }

//    $('body').on('click', '#edit, #delete', checkAutoRecp);
//    
//
//    function checkAutoRecp() {
//        var trnflag = $(".trnflag").val();
//        if (trnflag != "") {
//            alert('Edit / Delete Not Allowed.');
//            location.reload(true);
//        }
//    }

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

        }

    });

    function getRecpNo() {
        var bankname = $("#bankname").val(),
                cashdb = "bankpay",
                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());
        var mbalamt = parseFloat($row.find('.balamt').val());

        var mbilldate = $row.find('.billdate').val();
        var mvouchdt = $('#vouchdt').val();

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

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

        } else {
            var mbillamt = $('#amount').val();

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

            $(".setoff").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    val += parseFloat(this.value);
                }
            });
            if (val > mbillamt) {
                alert("TOTAL SETOFF AMOUNT CANNOT BE GREATER THAN TOTAL AMOUNT");
                $row.find('.setoff').focus();
                $("#save").attr("disabled", "disabled");
            } else {
                $("#totsetoff").val(val);
                $("#save").removeAttr("disabled");

                var totdays = showDays(mvouchdt, mbilldate);
//                            alert(totdays);

                var totremain = mbillamt - 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: "bankpay",
                    pvar: "P",
                    source: "BP"
                }, function (data) {
            $('#data').html(data);

        });
    }

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

//    $('#amount').blur(function () {
//        $(".settotal").show();
//        $("#settmodal").modal("show");
//        billsett();
//    });
//    $(document).keydown(function (event) {
//        //19 for Mac Command+S
//        if (event.keyCode == 27) { // escape key maps to keycode `27`
//            // <DO YOUR WORK HERE>
//            $("#settmodal").hide();
//        }
//
//    });

    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));



        /*        $($(".mark").is(":checked")).each( function() {
         var bamt = parseFloat($(".billamt").val());
         mtot = mtot + bamt;       
         });*/


        /*$(".billamt").each(function() {
         if ($row.find(".mark").is(":checked")) {
         mtot = mtot + parseFloat($row.find(".billamt").val());
         alert(mtot);
         }
         });*/
    }


    $("form").submit(function () {
                                        $("#ssubmit").hide();

        var party = $(".party").val(),
                bankname = $("#bankname").val(),
                vouchdt = $(".vouchdt").val(),
                amount = $(".amount").val(),
                valid = true;

        if (amount <= 0) {
            alert('Amount Cannot Be Zero');
            $("#ssubmit").show();

            return false;
            valid = false;
        }
        if (party == '') {
            alert('Party Cannot Be Empty');
            $("#ssubmit").show();

            return false;
            valid = false;
        }
        if (bankname == '') {
            alert('Bank Name Cannot Be Empty');
            $("#ssubmit").show();

            return false;
            valid = false;
        }
        if (party != '' && vouchdt != '') {
            $.get('chk_LogDate.php', {party: party}, function (data) {
                if (data != '0000-00-00') {
                    $(".logdate").val(data);
                }
            });
        }
        var logdate = $(".logdate").val();
        if (vouchdt <= logdate) {
            alert('VOUCHER DATE IS LESS THAN Log Date');
            return false;
            valid = false;
        }
    });
    $("#close_form").click(function () {
        $("#overlay_form").hide();
//        $("#submit").click();

    });



});