$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
//    $(".tbody").on("blur", '.rate', autoAddRows);
    $("body").on("keyup change blur click", '.oms,.amount, .subtotal, .litemdisc, .cdicsperc, .cdiscamt, .lessoth, .vatperc, .vatamt, .packing, .netamt', mainbCal);
    $("body").on("focus", '.amount', autoAddRows);


    $("body").on("click change blur", ".oms, .gstperc", gethsn);
    $("body").on("click change blur", ".oms, .gstperc", getGSTPerc);

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

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

        var newval = (mbilamt - amtadj).toFixed(2);
//        alert(newval);
        if (msetoff > newval) {
            $row.find('.setoff').val(0);
//            $row.find('.setoff').focus();
            msetoff = 0;
            alert("SETOFF AMOUNT CANNOT BE GREATER THAN BALANCE AMOUNT");
            $("#save").attr("disabled", "disabled");
            parseFloat($row.find('.balamt').val(mbalamt.toFixed(2)));

        } else {

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



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



            var mamt = $('.netamt').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.toFixed(2));
            }
        }
    }

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


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

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

        });
    }


    $("#submit").hide();

    $("#finishTab").click(function () {
        var ccamt = $('.ccamt').val(),
                party = $('.party').val(),
                cashamt = $('.cashamt').val(),
                bankname = $('#bankname').val(),
                credamt = $('.credamt').val(),
                netamt = $('.netamt').val(),
                totcamt = parseFloat(ccamt) + parseFloat(cashamt) + parseFloat(credamt),
                party = $(".party").val(),
                vouchdt = $(".vouchdt").val(),
                valid = true;

//        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;
//        }


        // if (netamt != totcamt) {
        //     $('.ccamt').val('0');
        //     $('.cashamt').val('0');
        //     $('.credamt').val('0');
        //     $('.cashamt').focus();
        //     alert('Cash, CC , Credit Total Amount Should Be Same As Netamt');
        //     return false;
        //     valid = false;
        // }




        if (party.length <= 0) {
            alert('Karigar Name Cannot Be Empty');
            return false;
            valid = false;
        }

        // if (ccamt > 0) {
        //     if (bankname.length <= 0) {
        //         alert('Bank Name Cannot Be Empty');
        //         return false;
        //         valid = false;
        //     }
        // }

        if (valid) {
            var isValid = true;

            if (isValid) {
                $("#submit").show();
//                $("#submit").click();


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

                $(".settotal").show();
                $("#settmodal").modal("show");
                $("#settmodal").on('shown.bs.modal', function () {
                    $("#setoff_1").focus();
                });
                billsett();

            }
        }
    });


    $(document).keydown(function (event) {
        if (!(String.fromCharCode(event.which).toLowerCase() == 'd' && event.altKey) && !(event.which == 19))
            return true;
        $(".cdicsperc ").focus();
        event.preventDefault();
        return false;
    });

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

    function getGSTPerc() {
        var gstperc = $(".gstperc").val();
//                getdcPerc = 0;

        $.post('getGSTPerc.php', {gstperc: gstperc}, function (data) {

            var mgstperc = data.gstperc,
                    mgst = mgstperc / 2;

            if ($(".oms").prop('checked')) {
                $('.igstperc').val(mgstperc);
                $('.cgstperc').val(0);
                $('.sgstperc').val(0);

            } else {
                $('.cgstperc').val(mgst);
                $('.sgstperc').val(mgst);
                $('.igstperc').val(0);
            }

        }, 'json');
        mainbCal();
    }

    function gethsn() {
//        var tr = $(this).closest("tr");
        var gstperc = $('.gstperc').val(),
                mgst = gstperc / 2;
//        $.post('gethsncode.php', {item: item}, function (data) {
//            tr.find('.hsncode').val(data.hsn);

//        if ($(".oms").prop('checked')) {
//            $('.igstperc').val(gstperc);
//            $('.cgstperc').val(0);
//            $('.sgstperc').val(0);
//
//        } else {
//            $('.cgstperc').val(mgst);
//            $('.sgstperc').val(mgst);
//            $('.igstperc').val(0);
//        }
        mainbCal();
        getGSTPerc();
//        }, 'json');
    }

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

        }
    }

    function remove() {
        $(this).closest("tr").remove();
    }

    function AddRows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;
        $.post('credoth_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }

    function mainbCal() {


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

        $(".subtotal").val(val);

        var subtot = $(".subtotal").val();
//        var litemdisc = $(".litemdisc").val();
        var lessoth = $(".lessoth").val();

        var discperc = $(".cdicsperc").val(),
                cdiscamt = (discperc * subtot) / 100;

        if (isNaN(cdiscamt)) {
            $('.cdiscamt').val("0");
        } else {
            $('.cdiscamt').val(cdiscamt);
        }


        var subtot1 = subtot;

//        var vatperc = $(".vatperc").val(),
//                vatamt = (vatperc * subtot1) / 100;
//
//        if (isNaN(vatamt)) {
//            $('.vatamt').val("0");
//        } else {
//            $('.vatamt').val(vatamt);
//        }



        var taxable = parseFloat(subtot1);

        var cgstperc = parseFloat($(".cgstperc").val());
        var sgstperc = parseFloat($(".sgstperc").val());
        var igstperc = parseFloat($(".igstperc").val());



        var cgstamt = (taxable * cgstperc / 100).toFixed(2);
        var sgstamt = (taxable * sgstperc / 100).toFixed(2);
        var igstamt = (taxable * igstperc / 100).toFixed(2);


        $(".taxamt").val(taxable);
        $(".igstamt").val(igstamt);
        $(".cgstamt").val(cgstamt);
        $(".sgstamt").val(sgstamt);
//        var pack = $(".packing").val();

        var rnet = (parseFloat(taxable) + parseFloat(cgstamt) + parseFloat(sgstamt) + parseFloat(igstamt)).toFixed(2);

        var roundoff = (Math.round(rnet) - rnet).toFixed(2);

        $(".roundoff").val(roundoff);

        var net = parseFloat(rnet) + parseFloat(roundoff);

        if (isNaN(net)) {
            $('.netamt').val("0");
        } else {
            $('.netamt').val(net.toFixed(2));
        }
    }


});