$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup change blur focus", ".qty, .rate, .amount", calDetail);
    $("body").on("blur", ".invno", chkinvno);
    $("body").on("focus", ".qty,.oms", gethsn);
    $("body").on("change", ".party", getgst);
    $("body").on("change keyup blur", ".qty, .rate,.totbillamt,.discperc,.roundoff,freightperc,packing,courier, .pretottcs, .tcsperc, .tcsamt", caltran);
    $("body").on("click change", ".oms", gsttr);
    $("body").on("blur change", ".vouchdt", getvoucher);
    $("body").on("blur ", ".discperc", autoadd);
//    $("body").on("click", "#submit ,#cancel", hide_but);

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

            }
        }
    });

//    function hide_but() {
//        $("#ssubmit").hide();
//        $("#scancel").hide();
//    }
    $(".showUploader").click(function () {
        $("#imageUpload").modal('show');
        $("#imageno").prop("disabled", false);
    });

    function _(el) {
        return document.getElementById(el);
    }

    $("#uploadbtn").click(function () {
        imageUpload();
    });



    function imageUpload() {
        var file = _("file1").files[0];
        var vouchno = _("vouchno").value;
        var source = _("source").value;
//        var imageno = _("imageno").value;
//        alert(file.name+" | "+file.size+" | "+file.type);
        var formdata = new FormData();
        formdata.append("file1", file);
        formdata.append("vouchno", vouchno);
        formdata.append("source", source);
//        formdata.append("imageno", imageno);
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", progressHandler, false);
        ajax.addEventListener("load", completeHandler, false);
        ajax.addEventListener("error", errorHandler, false);
        ajax.addEventListener("abort", abortHandler, false);
        ajax.open("POST", "upload_image.php");
        ajax.send(formdata);
    }


    function progressHandler(event) {
        _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
        var percent = (event.loaded / event.total) * 100;
        _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
    }

    function completeHandler(event) {
        _("status").innerHTML = event.target.responseText;
        _("progressBar").value = 0;
//        setTimeout(function(){ GetImage(); },3000);
    }

    function errorHandler(event) {
        _("status").innerHTML = "Upload Failed";
    }

    function abortHandler(event) {
        _("status").innerHTML = "Upload Aborted";
    }

    function readIMG(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#preview').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imageUpload").find("#file1").change(function () {
        readIMG(this);
    });

    $(".showUploader").click(function () {
        $("#imageUpload").modal('show');
        $("#imageno").prop("disabled", false);
    });

    $(".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();
        }
    }

    $('.oms').focus(function () {
        var oms = $('.oms').val();
        if (oms == 1) {
            $('.oms').prop("checked", true);
            $(".godown").focus();
            gsttr();
        } else {
            $('.oms').prop("checked", false);
            $(".godown").focus();
        }
    });

    $('.paidby').blur(function () {
        $(".debitac").select2("open");
    });

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

    function gsttr() {
        $('.tbody').find('tr').each(function () {
            var row = $(this),
                    cgstrate = row.find('.cgstrate').val(),
                    igstrate = row.find('.igstrate').val(),
                    igstamt = row.find('.igstamt').val(),
                    cgstamt = row.find('.cgstamt').val();
            if ($('.oms').prop("checked") == true) {
                if (igstrate == 0) {
                    var nigstrt = cgstrate * 2,
                            nigstamt = cgstamt * 2;
                    row.find('.igstrate').val(nigstrt);
                    row.find('.igstamt').val(nigstamt);
                    row.find('.cgstrate').val(0);
                    row.find('.cgstamt').val(0);
                    row.find('.sgstrate').val(0);
                    row.find('.sgstamt').val(0);
                }
            } else {
                if (cgstrate == 0) {
                    var ncgstrt = igstrate / 2,
                            ncgstamt = igstamt / 2;
                    row.find('.cgstrate').val(ncgstrt);
                    row.find('.cgstamt').val(ncgstamt);
                    row.find('.sgstrate').val(ncgstrt);
                    row.find('.sgstamt').val(ncgstamt);
                    row.find('.igstrate').val(0);
                    row.find('.igstamt').val(0);
                }
            }
        });
        caltran();
    }

    function getvoucher() {
        var date = new Date($(".vouchdt").val()),
                month = (date.getMonth() + 1).toString(),
                vouchno = $('.vouchno').val(),
                party = $('.party').val(),
                voucher = '0' + month + vouchno;

        $('.monno').val(month);
        $('.voucher').val(voucher);
    }

    $('#hedit').click(function () {
        var addflag = $('.addflag').val();
        if (addflag != 1) {
            $('.oms').prop("disabled", true);
        } else {
            $('.oms').prop("disabled", false);
        }
    });

    function gethsn() {
        var tr = $(this).closest("tr");
        var itemname = tr.find('.itemname').val();
        var type = $('.type').val();
        $.post('gethsncode.php', {itemname: itemname, type: type}, function (data) {
//            tr.find('.hsncode').val(data.hsn);
//            tr.find('.discperc').val(data.discperc);
            if ($(".oms").prop('checked')) {
                tr.find('.igstrate').val(data.gstperc);
                tr.find('.cgstrate').val(0);
                tr.find('.sgstrate').val(0);

            } else {
                tr.find('.cgstrate').val(data.cgstperc);
                tr.find('.sgstrate').val(data.sgstperc);
                tr.find('.igstrate').val(0);
            }
        }, 'json');
    }

    function getgst() {
        var party = $('.party').val();
        $.post('getrawpur.php', {party: party, mvar: "G"}, function (data) {
            $('.gstno').val(data);
        });
        $.post('getrawpur.php', {party: party, mvar: "O"}, function (data) {
            $('.oms').val(data);
            if (data == 1) {
                $('.oms').prop("checked", true);
                $(".godown").focus();
                gsttr();
            } else {
                $('.oms').prop("checked", false);
                $(".godown").focus();
            }
        });


    }


    function calDetail() {
        var tr = $(this).closest("tr"),
                qty = tr.find(".qty").val(),
                rate = tr.find(".rate").val(),
                amount = parseFloat(rate) * parseFloat(qty);

        tr.find(".amount").val(amount);

    }


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



    function caltran() {
        var tr = $(this).closest("tr");
        var amt = tr.find('.amount').val(),
                discperc = tr.find('.discperc').val(),
                cgst3 = 0,
                cgst5 = 0,
                cgst12 = 0,
                cgst18 = 0,
                cgst28 = 0,
                igst3 = 0,
                igst5 = 0,
                igst12 = 0,
                igst18 = 0,
                igst28 = 0,
                cgst3a = 0,
                cgst5a = 0,
                cgst12a = 0,
                cgst18a = 0,
                cgst28a = 0,
                igst3a = 0,
                igst5a = 0,
                igst12a = 0,
                igst18a = 0,
                igst28a = 0,
                totgst3 = 0,
                totgst5 = 0,
                totgst12 = 0,
                totgst18 = 0,
                totgst28 = 0,
                totbillamt = 0,
                discount = (discperc * amt) / 100;
        tr.find('.discamt').val(discount);
        var taxval = parseFloat(amt) - parseFloat(discount);
        tr.find('.subtot').val(taxval);

        var cgstrate = tr.find('.cgstrate').val(),
                sgstrate = tr.find('.sgstrate').val(),
                igstrate = tr.find('.igstrate').val(),
                cgstamnt = parseFloat(taxval) * parseFloat(cgstrate) / 100,
                sgstamnt = parseFloat(taxval) * parseFloat(sgstrate) / 100,
                igstamnt = parseFloat(taxval) * parseFloat(igstrate) / 100,
                total = Math.round(parseFloat(cgstamnt) + parseFloat(sgstamnt) + parseFloat(igstamnt) + parseFloat(taxval));

        tr.find('.cgstamt').val(cgstamnt.toFixed(2));
        tr.find('.sgstamt').val(sgstamnt.toFixed(2));
        tr.find('.igstamt').val(igstamnt.toFixed(2));
        tr.find('.total').val(total);

        var grosstot = 0,
                discamt = 0,
                subtot = 0;


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

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

        $('.totdiscamt').val(discamt.toFixed(2));

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

//        var freightperc = $('.frieghtperc').val,
//                packing = $('.packing'),
//                courier = $('.courier'),
//               freightamt = freightperc * subtot / 100,
//               taxable = parse(freightamt) + parse(packing) + parse(courier);
//        
//        $('.taxableamt').val(taxable.toFixed(2));
        $('.taxableamt').val(subtot.toFixed(2));


        var tottaxble3 = 0,
                tottaxble5 = 0,
                tottaxble12 = 0,
                tottaxble18 = 0,
                tottaxble28 = 0;

        $('.tbody').find('tr').each(function () {
            var row = $(this),
                    crate = row.find('.cgstrate').val(),
                    camt = row.find('.cgstamt').val(),
                    irate = row.find('.igstrate').val(),
                    iamt = row.find('.igstamt').val();

            if (crate == 1.5) {
                cgst3a = parseFloat(camt);
                cgst3 += parseFloat(cgst3a);
                igst3a = 0;
            } else if (crate == 2.5) {
                cgst5a = parseFloat(camt);
                cgst5 += parseFloat(cgst5a);
                igst5a = 0;
            } else if (crate == 6) {
                cgst12a = parseFloat(camt);
                cgst12 += parseFloat(cgst12a);
                igst12a = 0;
            } else if (crate == 9) {
                cgst18a = parseFloat(camt);
                cgst18 += parseFloat(cgst18a);
                igst18a = 0;
            } else if (crate == 14) {
                cgst28a = parseFloat(camt);
                cgst28 += parseFloat(cgst28a);
                igst28a = 0;
            }


            if (irate == 3) {
                igst3a = parseFloat(iamt);
                igst3 += parseFloat(igst3a);
                cgst3a = 0;
            } else if (irate == 5) {
                igst5a = parseFloat(iamt);
                igst5 += parseFloat(igst5a);
                cgst5a = 0;
            } else if (irate == 12) {
                igst12a = parseFloat(iamt);     // the problem was here += used previously that is why it was adding iamt in igst12a
                igst12 += parseFloat(igst12a);
                cgst12a = 0;
            } else if (irate == 18) {
                igst18a = parseFloat(iamt);
                igst18 += parseFloat(igst18a);
                cgst18a = 0;
            } else if (irate == 28) {
                igst28a = parseFloat(iamt);
                igst28 += parseFloat(igst28a);
                cgst28a = 0;
            }


            if ($('.oms').prop("checked") == true) {

                if (irate == 3) {
                    var subtot3 = row.find('.subtot').val();
                    tottaxble3 = parseFloat(tottaxble3) + parseFloat(subtot3);
                }
                if (irate == 5) {
                    var subtot5 = row.find('.subtot').val();
                    tottaxble5 = parseFloat(tottaxble5) + parseFloat(subtot5);
                }

                if (irate == 12) {
                    var subtot12 = row.find('.subtot').val();
                    tottaxble12 = parseFloat(tottaxble12) + parseFloat(subtot12);
                }

                if (irate == 18) {
                    var subtot18 = row.find('.subtot').val();
                    tottaxble18 = parseFloat(tottaxble18) + parseFloat(subtot18);
                }
                if (irate == 28) {
                    var subtot28 = row.find('.subtot').val();
                    tottaxble28 = parseFloat(tottaxble28) + parseFloat(subtot28);
                }

            } else {

                if (crate == 1.5) {
                    var subtot3 = row.find('.subtot').val();
                    tottaxble3 = parseFloat(tottaxble3) + parseFloat(subtot3);
                }
                if (crate == 2.5) {
                    var subtot5 = row.find('.subtot').val();
                    tottaxble5 = parseFloat(tottaxble5) + parseFloat(subtot5);
                }

                if (crate == 6) {
                    var subtot12 = row.find('.subtot').val();
                    tottaxble12 = parseFloat(tottaxble12) + parseFloat(subtot12);
                }

                if (crate == 9) {
                    var subtot18 = row.find('.subtot').val();
                    tottaxble18 = parseFloat(tottaxble18) + parseFloat(subtot18);
                }
                if (crate == 14) {
                    var subtot28 = row.find('.subtot').val();
                    tottaxble28 = parseFloat(tottaxble28) + parseFloat(subtot28);
                }
            }

            $(".tottaxble3").val(tottaxble3);
            $(".tottaxble5").val(tottaxble5);
            $(".tottaxble12").val(tottaxble12);
            $(".tottaxble18").val(tottaxble18);
            $(".tottaxble28").val(tottaxble28);
        });

        totgst3 = parseFloat(cgst3) + parseFloat(cgst3) + parseFloat(igst3);
        totgst5 = parseFloat(cgst5) + parseFloat(cgst5) + parseFloat(igst5);
        totgst12 = parseFloat(cgst12) + parseFloat(cgst12) + parseFloat(igst12);
        totgst18 = parseFloat(cgst18) + parseFloat(cgst18) + parseFloat(igst18);
        totgst28 = parseFloat(cgst28) + parseFloat(cgst28) + parseFloat(igst28);

        $('.cgst3').val(cgst3.toFixed(2));
        $('.sgst3').val(cgst3.toFixed(2));
        $('.igst3').val(igst3.toFixed(2));

        $('.cgst5').val(cgst5.toFixed(2));
        $('.sgst5').val(cgst5.toFixed(2));
        $('.igst5').val(igst5.toFixed(2));

        $('.cgst12').val(cgst12.toFixed(2));
        $('.sgst12').val(cgst12.toFixed(2));
        $('.igst12').val(igst12.toFixed(2));



        $('.cgst18').val(cgst18.toFixed(2));
        $('.sgst18').val(cgst18.toFixed(2));
        $('.igst18').val(igst18.toFixed(2));

        $('.cgst28').val(cgst28.toFixed(2));
        $('.sgst28').val(cgst28.toFixed(2));
        $('.igst28').val(igst28.toFixed(2));

        $('.totgst3').val(totgst3.toFixed(2));
        $('.totgst5').val(totgst5.toFixed(2));
        $('.totgst12').val(totgst12.toFixed(2));
        $('.totgst18').val(totgst18.toFixed(2));
        $('.totgst28').val(totgst28.toFixed(2));

        totbillamt = parseFloat(subtot) + parseFloat(totgst3) + parseFloat(totgst5) + parseFloat(totgst12) + parseFloat(totgst18) + parseFloat(totgst28);

        var roundoff = $('.roundoff').val();
        if (roundoff != '') {
            roundoff = roundoff;
        } else {
            roundoff = 0;
        }

        var tcsperc = $(".tcsperc").val(),
                pretottcs = parseFloat(totbillamt) + parseFloat(roundoff),
                pretottcs = Math.round(pretottcs),
                tcsamt = (tcsperc * pretottcs) / 100,
                totamt = Math.round(parseFloat(pretottcs) + parseFloat(tcsamt));


        $(".pretottcs").val(pretottcs);
        $(".totbillamt").val(totamt);
        $(".tcsamt").val(tcsamt.toFixed(2));
    }


    $('#addnew').click(function () {
        AddRows();
        caltran();
    });
    function remove() {
        $(this).closest("tr").remove();
        caltran();
    }

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




});