$(document).ready(function () {
    $('body').on('blur', '.setoff', setoff);
    $("body").off('click').on("click", '.remove', remove);
    $("body").on("keyup change blur focus", ".qty, .rate, .amount,.discperc,.discamt,.vatperc", calDetail);
    $("body").on("keyup change blur focus", ".ldiscperc, .tvatperc, .totdisc, .totadv,.addpack,.addgst", mainCal);
//    $("body").on("focus blur change", ".vouchdt", getvoucher);
//    $("body").on("change blur", ".cmbparty", getgst);
    $("body").on("blur", '.rate', autoaddrow);
    $("body").on("change", '.paidby', chgType);
    $("body").on("keydown", 'td', updown);
    $("body").on("click", "#btn-purchase", showPurModal);

    function showPurModal() {
        var vouchno = $('.vouchno').val();
        var tr = $(this).closest('tr');
        var srno = tr.find(".srno").val();
        var itemname = tr.find(".itemname").val();
        $('.tbody2').html("");
        $.post('purModal_data.php', {vouchno: vouchno, srno: srno, itemname: itemname}, function (data) {
            $('.tbody2').html(data);
            $('#modelWindow').modal('show');

        });

    }

    chgType();
    function chgType() {
        var paidby = $(".paidby").val();
        if (paidby == "C") {
            $(".totadv").attr("readonly", true);
            $(".totadv").val("0");
            mainCal();
        } else {
            $(".totadv").removeAttr("readonly", true);

        }
    }
    function updown() {
        var tr = $(this).closest('tr'),
                newsrno = tr.find(".srno").val(),
                srno = parseFloat(newsrno) - 2,
                curcls = $(this).attr('class');

        $(document).keydown(function (event) {
            if (event.keyCode == 40) { // Down key maps to keycode `40`
                if (curcls == 'p2') {
                    $('#rate_' + newsrno).focus();
                    $('#rate_' + newsrno).select();
                } else if (curcls == 'p1') {
                    $('#qty_' + newsrno).focus();
                    $('#qty_' + newsrno).select();
                }
            }
        });


        $(document).keydown(function (event) {
            if (event.keyCode == 38) { // Up key maps to keycode `38`
                if (curcls == 'p2') {
                    $('#rate_' + srno).focus();
                    $('#rate_' + srno).select();
                } else if (curcls == 'p1') {
                    $('#qty_' + srno).focus();
                    $('#qty_' + srno).select();
                }
            }
        });
    }


    $("#submit").click(function () {
        $("#submit").hide();
    });

    $("form").submit(function () {

        var party = $('.party').val(),
                godown = $('.godown').val(),
                totbillamt = $('.totbillamt').val(),
                valid = true;


        if (party == '') {
            var message = "Party Cannot Be Empty";
            alert(message);
            $("#submit").show();

            return false;
            valid = false;
        }
        if (godown == '') {
            var message = "Godown Cannot Be Empty";
            alert(message);
            $("#submit").show();

            return false;
            valid = false;
        }

        if (parseFloat(totbillamt) <= 0 || totbillamt == '') {
            var message = "Netamt Cannot zero";
            alert(message);
            $("#submit").show();

            return false;
            valid = false;
        }

        if (valid) {
            var isValid = true;

            if (isValid) {
                $("#submit").hide();
                $("#cancel").hide();

            }
        }
    });



    var canc_flag = $(".canc_flag").val();
    if (canc_flag != '') {
        $("#scancbill").hide();
        $("#hedit").hide();

    }


//    $("#hdelete").hide();


    $("#cancbill").click(function () {
        $("#cancmodel").modal('show');
    });

    function autoaddrow() {
        var ctr = $('#items').val();
        var tr = $(this).closest("tr");
        var srno = tr.find(".srno").val();
        if (srno == ctr) {
            AddRows();
        }
    }

    var lrno = $('.lrno').val();
    if (lrno != '') {
        $(".lrdetail").show();
    } else {
        $(".lrdetail").hide();
    }




    $(".lrtab").click(function () {
        $(".lrdetail").animate({
            height: 'toggle'
        });
    });

    function calDetail() {
        var tr = $(this).closest("tr"),
                cartqty = tr.find(".cartqty").val(),
                qty = tr.find(".qty").val(),
                totqty = cartqty * qty,
                rate = tr.find(".rate").val(),
                amount = (rate * qty).toFixed(2),
                discperc = tr.find(".discperc").val(),
                discamt = 0,
                vatperc = tr.find(".vatperc").val(),
                subtot = 0,
                total = 0,
                vat = 0;

        if (discperc > 0) {
            discamt = ((discperc * amount) / 100).toFixed(2);
        } else {
            discamt = tr.find(".discamt").val();
        }
        subtot = amount - discamt;
        if (vatperc > 0) {
            vat = ((vatperc * subtot) / 100).toFixed(2);
        } else {
            vat = 0;
        }
        total = (parseFloat(subtot) + parseFloat(vat)).toFixed(2);
        tr.find(".totqty").val(totqty);
        tr.find(".amount").val(amount);
        tr.find(".discamt").val(discamt);
        tr.find(".vat").val(vat);
        tr.find(".total").val(total);
        var totamt = 0,
                totdisc = 0,
                totvat = 0,
                tottotal = 0,
                totbal = 0,
                totalqty = 0,
                totadv = 0;
        $(".qty").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                totalqty += parseFloat(this.value);
            }
        });
        $(".totalqty").val(totalqty);

        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                totamt += parseFloat(this.value);
            }
        });
//        $(".discamt").each(function () {
//            if (!isNaN(this.value) && this.value.lenght != 0) {
//                totdisc += parseFloat(this.value);
//            }
//        });
//        $(".vat").each(function () {
//            if (!isNaN(this.value) && this.value.lenght != 0) {
//                totvat += parseFloat(this.value);
//            }
//        });
        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                tottotal += parseFloat(this.value);
            }
        });
        $(".totamt").val(totamt);

//        $(".tottotal").val(tottotal);
        mainCal();
    }
    function mainCal() {
        var tdiscperc = $(".ldiscperc").val(),
                vatperc = $(".tvatperc").val(),
                amount = $(".totamt").val(),
                addpack = $(".addpack").val(),
                addgst = $(".addgst").val(),
                totadv = $(".totadv").val(),
                discamt = 0, vat = 0,
                totbal = 0;
        if (tdiscperc > 0) {
            discamt = ((tdiscperc * amount) / 100).toFixed(2);
        } else {
            discamt = $(".totdisc").val();
        }
        var subtot = amount - discamt;
        if (vatperc > 0) {
            vat = ((vatperc * subtot) / 100).toFixed(2);
        } else {
            vat = 0;
        }
        var finamt = parseFloat(subtot) + parseFloat(vat) + parseFloat(addpack) + parseFloat(addgst),
                totbal = parseFloat(finamt) - parseFloat(totadv);
        $(".totdisc").val(discamt);
        $(".totvat").val(vat);
        $(".tottotal").val(finamt);
        $(".totbal").val(totbal);

    }


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

    $('#puradd').click(function () {
        AddPurRows();
    });
    function remove() {
        $(this).closest("tr").remove();
        calDetail();
        caltran();
        mainCal();
    }

    function AddRows() {
        var ctr = $('#items').val();
        var prodtype = $('.prodtype').val();
        var addflag = $('.addflag').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var focusFld = ".focusFld_" + ctr;
        ctr++;
        $('#items').val(ctr);
        $.post('saleret_add.php', {ctr: ctr, hide: hide_check, prodtype: prodtype, addflag: addflag}, function (data) {
            $(data).appendTo('.tbody');

            $(focusFld).focus();
        });
    }


    function AddPurRows() {
        var ctr = $('#itemspur').val();
        var focusFld = ".focusFld_" + ctr;
        ctr++;
        $('#itemspur').val(ctr);
        $.post('purModal_add.php', {ctr: ctr}, function (data) {
            $(data).appendTo('.tbody2');
            $(focusFld).focus();
        });
    }

    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) {
            $row.find('.setoff').val(0);
            $row.find('.setoff').focus();
            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 = $('#totbillamt').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);
//                            alert(totdays);

            var totremain = mamt - val;

            $row.find('.days').val(totdays);
            $("#remain").val(totremain);
        }
    }

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

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

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

        });
    }

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

    $('#addpack').blur(function () {
        $(".settotal").show();
        $("#settmodal").modal("show");
        billsett();
        $("#settmodal").on('shown.bs.modal', function () {
            $(".setoff").first().focus();
            $(".setoff").first().select();
        });
    });



});