$(document).ready(function () {

    $('body').on('blur', '.setoff', setoff);

    $('body').on('keyup', '#recd, #discount, #dclaim', calculateRow);

    $('body').on('click', '.mark, #mclaim', setclaim);

    $('body').on('change', '#bankcode', getRecpNo);

    $("body").on("keyup", ".ssearch", getSearchData);

    $("body").on("click", ".sload", getSearchData);

    $("body").on("click", "#search", getSearchData);

    $("#settmodal").on("keyup blur", ".setoff", remark);

    $("body").on("blur", ".flatno", fillName);

    $("body").on("change", "#party", fillFlat);

    $("body").on("change", ".party", getgrpcode);

    $("body").on("blur", ".regnno", getCustname); 
        $("body").on("change", ".recpagnst", chgFilt1);
    
    function chgFilt1() {
        var recpagnst = $(".recpagnst").val();
        if (recpagnst == "U") {
            $("#tour").attr("checked", true);
        }
    }
    


    function getCustname() {
        var regnno = $(".regnno").val();
        var recpagnst = $(".recpagnst").val();

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "getMemNam.php",
            data: {regnno: regnno, recpagnst: recpagnst},
            success: function (response) {
                if (response != "") {
                    var accode = response.accode;

                    $(".party").val(accode).trigger("change");
                }
            },
            error: function (request, textStatus, errorThrown) {
            }
        });
    }

    function getgrpcode() {

        var party = $(".party").val();

        $.post('getgrpcode.php', {party: party}, function (data) {

            $(".grpcode").val(data.grpcode);

        }, 'json');

    }







    $("#viewledger").click(function () {

        var party = $(".party").val(),

                grpcode = $("#grpcode").val(),

                frmdate = $(".zstdate").val(),

                todate = $(".zenddate").val();



        $("#viewledger").attr("href", "ledger_fr.php?party=" + party + "&view=view&frmdate=" + frmdate + "&todate=" + todate + "&grpcd=" + grpcode);

    });



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



    $(".proceed").click(function () {

        $(".secondrymodal").show();

        $(".primarymodal").hide();



        var fdate = $('.mfrmdt').val(),

                tdate = $('.todate').val();



        $('.fdate').val(fdate);

        $('.tdate').val(tdate);

    });



    $("#myModal").on('shown.bs.modal', function () {

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

        $(".primarymodal").show();

    });



    $(".myTable").find('.allchk').change(function () {

        $(".mcheck").prop('checked', $(this).prop('checked'));

    });





    $('.proceed').click(function () {

        var frmdate = $(".fdate").val(),

                todate = $(".tdate").val(),

                accode = $(".accode").val(),

                narr = $(".narr").val(),

                data = {frmdate: frmdate, todate: todate, accode: accode, narr: narr};

        $.ajax({

            type: 'GET',

            dataType: 'html',

            url: 'bankpay_mult.php',

            data: data,

            success: function (response) {

                $(".mprint").empty();

                $(".mprint").html(response);

            },

            error: function (request, textStatus, errorThrown) {

                console.log(errorThrown);

            }

        });

    });















    function fillName() {

        var flatno = $(".flatno").val();

        if (flatno != '') {

            $.post('get_flatno.php', {flatno: flatno}, function (data) {

                $("#party").val(data.accode);

                $("#party").trigger('change');



            }, 'json');

        }

    }

    function fillFlat() {

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

//        if (addflag == 1) {

        if (party != '') {

            $.post('get_party.php', {party: party}, function (data) {

                $(".flatno").val(data.flatno);

//                $(".flatno").trigger('change');



            }, 'json');

        }

    }



    function getRecpNo() {

        var bankname = $("#bankcode").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').val(0);

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

         }

         });*/

    }





//////////////////////////////////////////////Remark Part - Start//////////////////////////////////////////////



    function remark() {

        var myObj = [];

        $(".setoff").each(function () {

            if (this.value != "0") {

                var tr = $(this).closest("tr"),

                        billno = tr.find(".billno").val();

                myObj.push(billno);

            }

        });

        $(".remark2").val(myObj);

    }



//////////////////////////////////////////////Remark Part - Start//////////////////////////////////////////////







//////////////////////////////////////////////Search Part - Start//////////////////////////////////////////////

    $(".snoRecord").hide();



    $(".searchModal").on('shown.bs.modal', function () {

        $(".ssearch").focus();

        $(".ssearch").val("");

        $(".sfield").val("1");

        getSearchData();

    });



    var smrangeFrom = 0,

            smrangeTo = 40;



    function getSearchData(pagination) {



        $(".sloader").show();



        if (pagination == 'prev') {

            if (smrangeFrom > 0) {

                smrangeFrom = (smrangeFrom - 40);

                smrangeTo = (smrangeTo - 40);

            }

        }

        if (pagination == 'next') {

            smrangeFrom = (smrangeFrom + 40);

            smrangeTo = (smrangeTo + 40);

        }



        var series = $(".series").val(),

                para = $(".para").val(),

                ssearch = $(".ssearch").val(),

                sfield = $(".sfield").val(),

                soperator = $(".soperator").val(),

                data = {ssearch: ssearch, sfield: sfield, soperator: soperator, para: para,

                    series: series, rangeFrom: smrangeFrom, rangeTo: smrangeTo},

                values = "";

        $.ajax({

            type: 'GET',

            dataType: 'json',

            url: "bankpay_search.php",

            data: data,

            success: function (response) {

                $.each(response, function () {

                    values += "<tr class='clickable-row' data-href='" + this.action + "'>" +

                            "<td align='left'>" + this.vouchno + "</td>" +

                            "<td align='left'>" + this.vouchdt + "</td>" +

                            "<td align='left'>" + this.cname + "</td>" +

                            "<td align='left'>" + this.amount + "</td>" +

                            "<td align='left'>" + this.name + "</td>" +

                            "<td align='left'>" + this.recpno + "</td>" +

                            "<td align='left'>" + this.chqno + "</td>" +

                            "<td align='left'>" + this.chqdate + "</td>" +

                            "<td align='left'>" + this.rtgsno + "</td>" +

                            "<td align='left'>" + this.narr1 + " " + this.narr2 + "</td>" +

                            "<td align='left'><a href='" + this.action + "'><i class='fa fa-pencil' style='font-size:1.3em;cursor:pointer;'></i></a></td>" +

                            "</tr>";

                });

                $(".sloader").hide();

                $(".sTbody").empty();

                $(".sTbody").html(values);

                if (response) {

                    $(".search-action-bar").show();

                }

            },

            error: function (request, textStatus, errorThrown) {



            }

        });

    }

    $("#search").click(function () {

        getSearchData();

    });

    $(".sprev").click(function () {

        getSearchData('prev');

    });

    $(".sprev").click(function () {

        getSearchData('next');

    });





    //////////////////////////////////////////////Search Part - End  //////////////////////////////////////////////



});