$(document).ready(function() {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup change blur focus", ".qty, .rate, .amount,.discperc,.discamt,.vatperc,.pcscart,.cartqty", calDetail);
    $("body").on("blur", ".invno", chkinvno);
    $("body").on("blur ", ".discamt", autoadd);
    $(".itemgrp").hide();
    $("body").on("blur ", ".barcode", CreateProd);
    $("body").on("blur", ".mbarcode", checkmbarcode);
    $("body").on("blur", ".mprodname", checkmprodname);
    $("body").on("click", ".saveent", saveProduct);

    $("body").on("blur", ".invno", ChkinvnoDupli);

    function ChkinvnoDupli() {
        var invno = $('.invno').val();
        var party = $('.party').val();
        if (invno) {
            $.get('check_invnoDupli.php', { invno: invno, party: party }, function(data) {
                if (parseFloat(data) > 0) {
                    $('.invno').val("");
                    $('.invno').focus();
                    alert("Invoice No. Already Exist On Voucher No. " + data);
                }
            });
        }
    }

    function saveProduct() {
        // Show loading animation
        var tr = $(this).closest("tr");

        $("#loadingIndicator").show();

        var mbarcode = $(".mbarcode").val(),
            mprodname = $(".mprodname").val(),
            mpkg = $(".mpkg").val();

        if (mbarcode == "") {
            alert("Barcode Cannot Be Empty");
            $("#loadingIndicator").hide();
            return;
        }
        if (mprodname == "") {
            alert("Product Cannot Be Empty");
            $("#loadingIndicator").hide();
            return;
        }

        $.post("saveProduct.php", {
            mbarcode: mbarcode,
            mprodname: mprodname,
            mpkg: mpkg
        }, function(data) {
            // Hide loading animation
            $("#loadingIndicator").hide();

            if (data > 0) {
                alert("Product Created.");
                $(".PurchCreateModal").modal("hide");
            } else {
                alert("Failed to Create Product.");
            }
        }).fail(function() {
            $("#loadingIndicator").hide();
            alert("Error occurred during saving.");
        });
    }


    function checkmbarcode() {
        var barcode = $('.mbarcode').val();
        if (barcode) {
            $.get('check_prodModal.php', { barcode: barcode }, function(data) {
                if (parseFloat(data) > 0) {
                    $('.mbarcode').val("");
                    $('.mbarcode').focus();
                    alert("Barcode Already Exist");
                }
            });
        }
    }

    function checkmprodname() {
        var prodname = $('.mprodname').val();
        if (prodname) {
            $.get('check_prodModal.php', { prodname: prodname }, function(data) {
                if (parseFloat(data) > 0) {
                    $('.mprodname').val("");
                    $('.mprodname').focus();
                    alert("Product Name Already Exist");
                }
            });
        }
    }

    function CreateProd() {
        var tr = $(this).closest("tr"),
            barcode = tr.find(".barcode").val().toUpperCase(), // convert to uppercase
            itemname = tr.find(".itemname").val();

        if (itemname === '' && barcode === 'NEW') { // match uppercase 'NEW'
            $(".PurchCreateModal").modal("show");
            $('.PurchCreateModal').on('shown.bs.modal', function() {
                $('.mbarcode').focus(); // replace with your class or ID
            });

        }
    }


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

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


        if (party == '') {
            var message = "Party Cannot Be Empty";
            alert(message);
            return false;
            valid = false;
        }

        if (parseFloat(totbillamt) <= 0 || totbillamt == '') {
            var message = "Netamt Cannot zero";
            alert(message);
            return false;
            valid = false;
        }

        if (valid) {
            var isValid = true;

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

            }
        }
    });

    $(".party").change(function() {
        var invno = $(".invno").val(),
            file = $(".file").val(),
            party = $(".party").val();
        $.post('chk_invo.php', { invno: invno, party: party, file: file }, function(data) {
            if (data.s == 1) {
                alert('These Invoice Already Exist For Voucher  ' + data.vouchno);
                $(".invno").val('');
                $(".invno").focus();

            }
        }, 'json');
    });

    function autoadd() {
        if ($(this).closest('tr').is(":last-child")) {
            AddRows();
        }
    }

    $('.invno').blur(function() {
        $('.party').select2("open");
    });


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

        if (discperc > 0) {
            discamt = ((discperc * amount) / 100).toFixed(2);
        } else {
            discamt = tr.find(".discamt").val();
        }
        subtot = amount - discamt;

        total = (subtot).toFixed(2);
        tr.find(".qty").val(qty);
        tr.find(".amount").val(amount);
        tr.find(".discamt").val(discamt);
        tr.find(".total").val(total);

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

    }


    function chkinvno() {
        var invno = $('.invno').val();
        var party = $(".party").val();
        if (invno.length > 0) {
            $.post('check_inv_dtl.php', { invno: invno, party: party }, function(data) {
                if (data == 'success') {
                    alert('This Bill No. For This Party Already Exist');
                    $('.invno').val('');
                    $('.invno').focus();
                }
            });
        }
    }

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

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


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

            //            $(detail).select2();
            $(focusFld).focus();
            //            caltran();
        });
    }




});