$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup blur", ".qty, .rate", calDetail);
    $("body").on("focus blur", ".barcode, .batch,.qty", gethsn);
    $("body").on("click change", ".oms", gsttr);
    $("body").on("focus blur change", ".vouchdt", getvoucher);
    $("body").on("change blur", ".cmbparty", getgst);
    $("body").on("change keyup blur", ".qty, .rate, .discperc,.discamt,.freeflag,.deemexp", caltran);
    $("body").on("keyup", ".postamt", addpost);
    $("body").on("blur", '.discamt', autoaddrow);
    $("body").on("change", '.freeflag', hideshow);
    $("body").on("click", "#hsubmit", hidesub);
    $("body").on("change", ".cmbparty", getoms);
   $("body").on("click", "#submit ,#cancel", hide_but);


    function hide_but() {
        $("#ssubmit").hide();
        $("#scancel").hide();
    }


    function getoms() {
        var party = $(".cmbparty").val();
        var addflag = $(".addflag").val();
        if (addflag == 1) {
            $.post('chk_oms.php', {party: party}, function (data) {
                if (data == 1) {
                    $(".oms").val(data);
                    $(".oms2").val("Yes");
                } else {
                    $(".oms").val(data);
                    $(".oms2").val("No");
                }
            }, 'json');
        } else {
            var oms = $(".oms").val();

            $.post('chk_oms.php', {party: party}, function (data) {
                if (data == oms) {

                } else {
                    if (oms == '1') {
                        alert("Changed Party should not belong to Maharashtra");
                        $(".party").val("").trigger('change');

                    } else if (oms == '0') {
                        alert("Changed Party should belong to Maharashtra");
                        $(".party").val("").trigger('change');

                    }
                }



            }, 'json');
        }
    }

    $('.hflag').hide();

    function hideshow() {
        if ($('.freeflag').prop("checked") == true) {
            $('.hflag').show();
        } else {
            $('.hflag').hide();
        }
    }

    function hidesub() {
        var party = $('.cmbparty').val(),
                vouchdt = $('.vouchdt').val(),
                paidby = $('.paidby').val(),
                godown = $('.godown').val();

        if (party != '' && vouchdt != '' && paidby != '' && godown != '') {
            $('#hsubmit').hide();
        }
    }

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

    });

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

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

//    $('.oms').focus(function () {
//
//        if (confirm('Is it out of state ?')) {
//            $('.oms').prop("checked", true);
//            $(".cmbparty").focus();
//            $(".cmbparty").select2("open");
//            gsttr();
//        } else {
//            $('.oms').prop("checked", false);
//            $(".cmbparty").focus();
//            $(".cmbparty").select2("open");
//        }
//    });
    $('#addnew').blur(function () {
        $(".staff").select2("open");
    });
    $('.godown').blur(function () {
//        var addflag = $('.addflag').val();
//        if (addflag != 1) {
        $("#party").select2("open");
//        }
    });
//    function openparty(){
//            $(".cmbparty").select2("open");        
//    }
    function addpost() {
        var gperc = 0;
        if ($('.oms').prop("checked") == true) {
            $('.igstrate').each(function () {
                var igstrate = $(this).closest("tr").find(".igstrate").val();
                if (igstrate > parseFloat(gperc)) {
                    gperc = igstrate;
                }
            });
        } else {
            $('.cgstrate').each(function () {
                var cgstrate = $(this).closest("tr").find(".cgstrate").val();
                if (cgstrate > parseFloat(gperc)) {
                    gperc = cgstrate;
                }

            });
        }
        $('.postperc').val(gperc);
        caltran();
    }


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


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


    $(".lrtab").click(function () {
        $(".lrdetail").animate({
            height: 'toggle'
        });
    });
//    $('#hedit').click(function () {
//        var addflag = $('.addflag').val();
//        if (addflag != 1) {
//            $('.oms').prop("disabled", true);
//        } else {
//            $('.oms').prop("disabled", false);
//        }
//    });
    function getgst() {
        var party = $('.cmbparty').val();
        $.post('getcustgst.php', {party: party}, function (data) {
            if (data.gstno != 0) {
                $('.gstno').val(data.gstno);
            }
            $('.mobile').val(data.mobile);
        }, 'json');
    }

    function gethsn() {
        var tr = $(this).closest("tr");
        var barcode = tr.find('.barcode').val();
        var editoms = $('#editoms').val();
        $.post('get_salegst.php', {barcode: barcode}, function (data) {
//            tr.find('.discperc').val(data.discperc);
            if ($(".oms").prop('checked') || editoms == 1) {
                if (data.igst == '' && data.igst == 0) {
                    tr.find('.igstrate').val(0);
                } else {
                    tr.find('.igstrate').val(data.igst);
                }
                tr.find('.cgstrate').val(0);
                tr.find('.sgstrate').val(0);
            } else {
                if (data.cgst == '' && data.cgst == 0) {
                    tr.find('.cgstrate').val(0);
                    tr.find('.sgstrate').val(0);
                } else {
                    tr.find('.cgstrate').val(data.cgst);
                    tr.find('.sgstrate').val(data.sgst);
                }
                tr.find('.igstrate').val(0);
            }
        }, 'json');
    }

    function caltran() {
        var cgst5 = 0,
                cgst12 = 0,
                cgst18 = 0,
                cgst28 = 0,
                tot5 = 0,
                tot12 = 0,
                tot18 = 0,
                tot28 = 0,
                igst1 = 0,
                igst5 = 0,
                igst12 = 0,
                igst18 = 0,
                igst28 = 0,
                tot1a = 0,
                tot5a = 0,
                tot12a = 0,
                tot18a = 0,
                tot28a = 0,
                tota = 0,
                cgst5a = 0,
                cgst12a = 0,
                cgst18a = 0,
                cgst28a = 0,
                igst5a = 0,
                igst12a = 0,
                igst18a = 0,
                igst28a = 0,
                totgst5 = 0,
                totgst12 = 0,
                totgst18 = 0,
                totgst28 = 0,
                totbillamt = 0,
                taxable = 0,
                billdiscamt = $('.billdiscamt').val();
//                postamt = $('.postamt').val();

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

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

            $('.tbody').find('tr').each(function () {
                var row = $(this),
                        amt = row.find('.amount').val(),
                        discperc = row.find('.discperc').val(),
                        discount = row.find('.discamt').val();
                if (discperc > 0) {
                    discount = parseFloat(discperc) * parseFloat(amt) / 100;
                }
                var postperc = $('.postperc').val(),
                        rdisc = Math.round(discount * 100) / 100,
                        taxval = parseFloat(amt) - parseFloat(discount),
                        crate = row.find('.cgstrate').val(),
                        postamt = $('.postamt').val(),
                        newtax = 0,
                        irate = row.find('.igstrate').val();
                if ($('.oms').prop("checked") == true) {
                    if (irate > 0) {
                        if (irate == postperc) {
//                            newtax = parseFloat(taxval) + parseFloat(postamt);
                            newtax = parseFloat(taxval) ;
                            $('.postperc').val(0);
                        } else {
                            newtax = parseFloat(taxval);
                        }
                    }
                } else if (crate > 0) {
                    if (crate == postperc) {
//                        newtax = parseFloat(taxval) + parseFloat(postamt);
                        newtax = parseFloat(taxval) ;
                        $('.postperc').val(0);
                    } else {
                        newtax = parseFloat(taxval);
                    }

                } else {
                    newtax = parseFloat(taxval);
                }

                var iamt = parseFloat(newtax) * 0.1 / 100,
                        total = parseFloat(iamt) + parseFloat(newtax),
                        rtotal = Math.round(total * 100) / 100;
                row.find('.subtot').val(newtax);
                row.find('.discamt').val(rdisc);
                row.find('.total').val(rtotal);
                row.find('.igstamt').val(iamt);
                row.find('.cgstamt').val(0);
                row.find('.sgstamt').val(0);
                igst1 += parseFloat(iamt);
            });
            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);
                }
            });
//        taxable = parseFloat(subtot) - parseFloat(billdiscamt);
            taxable = Math.round(parseFloat(subtot));
            $('.taxableamt').val(taxable);
            $('.igst1').val(igst1.toFixed(2));
            $('.totgst1').val(igst1.toFixed(2));
            $('.cgst5').val(0);
            $('.sgst5').val(0);
            $('.igst5').val(0);
            $('.cgst12').val(0);
            $('.sgst12').val(0);
            $('.igst12').val(0);
            $('.cgst18').val(0);
            $('.sgst18').val(0);
            $('.igst18').val(0);
            $('.cgst28').val(0);
            $('.sgst28').val(0);
            $('.igst28').val(0);
            $('.totgst5').val(0);
            $('.totgst12').val(0);
            $('.totgst18').val(0);
            $('.totgst28').val(0);
            totbillamt = parseFloat(taxable) + parseFloat(igst1);
        } else {

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

            var editoms = $("#editoms").val();
            $('.tbody').find('tr').each(function () {
                var row = $(this),
                        amt = row.find('.amount').val(),
                        discperc = row.find('.discperc').val(),
                        discount = row.find('.discamt').val();
                if (discperc > 0) {
                    discount = parseFloat(discperc) * parseFloat(amt) / 100;
                }
                var postperc = $('.postperc').val(),
                        rdisc = Math.round(discount * 100) / 100,
                        taxval = parseFloat(amt) - parseFloat(discount),
                        crate = row.find('.cgstrate').val(),
                        postamt = $('.postamt').val(),
                        newtax = 0,
                        irate = row.find('.igstrate').val();
                if ($('.oms').prop("checked") == true || editoms == 1) {
                    if (irate > 0) {
                        if (irate == postperc) {
//                            newtax = parseFloat(taxval) + parseFloat(postamt);
                            newtax = parseFloat(taxval) ;
                            $('.postperc').val(0);
                        } else {
                            newtax = parseFloat(taxval);
                        }
                    }
                } else if (crate > 0) {
                    if (crate == postperc) {
//                        newtax = parseFloat(taxval) + parseFloat(postamt);
                        newtax = parseFloat(taxval) ;
                        $('.postperc').val(0);
                    } else {
                        newtax = parseFloat(taxval);
                    }

                } else {
                    newtax = parseFloat(taxval);
                }

                var cgstamnt = parseFloat(newtax) * parseFloat(crate) / 100,
                        sgstamnt = parseFloat(newtax) * parseFloat(crate) / 100,
                        iamt = parseFloat(newtax) * parseFloat(irate) / 100,
                        total = parseFloat(cgstamnt) + parseFloat(sgstamnt) + parseFloat(iamt) + parseFloat(newtax),
                        rtotal = Math.round(total * 100) / 100;
                row.find('.subtot').val(newtax);
                row.find('.discamt').val(rdisc);
                row.find('.total').val(rtotal);
                row.find('.cgstamt').val(cgstamnt);
                row.find('.sgstamt').val(sgstamnt);
                row.find('.igstamt').val(iamt);


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



                    if (irate == 5) {
                        tot5a = parseFloat(newtax);
                        tot5 += parseFloat(tot5a);

                    }

                    if (irate == 12) {
                        tot12a = parseFloat(newtax);
                        tot12 += parseFloat(tot12a);

                    }

                    if (irate == 18) {
                        tot18a = parseFloat(newtax);
                        tot18 += parseFloat(tot18a);

                    }
                    if (irate == 28) {
                        tot28a = parseFloat(newtax);
                        tot28 += parseFloat(tot28a);

                    }

                } else {

                    if (crate == 2.5) {
                        tot5a = parseFloat(newtax);
                        tot5 += parseFloat(tot5a);

                    }

                    if (crate == 6) {
                        tot12a = parseFloat(newtax);
                        tot12 += parseFloat(tot12a);

                    }

                    if (crate == 9) {
                        tot18a = parseFloat(newtax);
                        tot18 += parseFloat(tot18a);

                    }
                    if (crate == 14) {
                        tot28a = parseFloat(newtax);
                        tot28 += parseFloat(tot28a);

                    }
                }






                if (crate < 3) {
                    cgst5a = parseFloat(cgstamnt);
                    cgst5 += parseFloat(cgst5a);
                    igst5a = 0;

//                    tot5a = 0;
                } else if (crate < 7) {
                    cgst12a = parseFloat(cgstamnt);
                    cgst12 += parseFloat(cgst12a);
                    igst12a = 0;
//                    tot12a = parseFloat(newtax);
//                    tot12 += parseFloat(tot12a);
//                    tot12a = 0;
                } else if (crate < 10) {
                    cgst18a = parseFloat(cgstamnt);
                    cgst18 += parseFloat(cgst18a);
                    igst18a = 0;
//                    tot18a = parseFloat(newtax);
//                    tot18 += parseFloat(tot18a);
//                    tot18a = 0;
                } else if (crate < 15) {
                    cgst28a = parseFloat(cgstamnt);
                    cgst28 += parseFloat(cgst28a);
                    igst28a = 0;
//                    tot28a = parseFloat(newtax);
//                    tot28 += parseFloat(tot28a);
//                    tot28a = 0;
                }

                if (irate < 7) {
                    igst5a = parseFloat(iamt);
                    igst5 += parseFloat(igst5a);
                    cgst5a = 0;
//                    tot5a = parseFloat(newtax);
//                    tot5 += parseFloat(tot5a);
//                    tot5a = 0;
                } else if (irate < 13) {
                    igst12a = parseFloat(iamt);
                    igst12 += parseFloat(igst12a);
                    cgst12a = 0;
//                    tot12a = parseFloat(newtax);
//                    tot12 += parseFloat(tot12a);
//                    tot12a = 0;

                } else if (irate < 19) {
                    igst18a = parseFloat(iamt);
                    igst18 += parseFloat(igst18a);
                    cgst18a = 0;
//                    tot18a = parseFloat(newtax);
//                    tot18 += parseFloat(tot18a);
//                    tot18a = 0;

                } else if (irate < 29) {
                    igst28a = parseFloat(iamt);
                    igst28 += parseFloat(igst28a);
                    cgst28a = 0;
//                    tot28a = parseFloat(newtax);
//                    tot28 += parseFloat(tot28a);
//                    tot28a = 0;
                }



            });




            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 postage = $('.postamt').val(),
                postage_gst = postage * 0.18,
                igst18_2 = 0,
                cgst18_2 = 0,
                postcgst = 0;
            
            if ($('.oms').prop("checked") == true || editoms == 1) {
                
                igst18_2 = parseFloat(igst18) + parseFloat(postage_gst);

            } else {
                postcgst = postage_gst / 2;

                cgst18_2 = parseFloat(cgst18) + parseFloat(postcgst);
            }


            var tot18_2 = parseFloat(tot18) + parseFloat(postage) ;


            taxable = Math.round(parseFloat(subtot)) + parseFloat(postage);
            $('.taxableamt').val(taxable);

            $(".tottaxble5").val(tot5);
            $(".tottaxble12").val(tot12);
            $(".tottaxble18").val(tot18_2);
            $(".tottaxble28").val(tot28);
            totgst5 = parseFloat(cgst5) + parseFloat(cgst5) + parseFloat(igst5);
            totgst12 = parseFloat(cgst12) + parseFloat(cgst12) + parseFloat(igst12);
            totgst18 = parseFloat(cgst18) + parseFloat(cgst18) + parseFloat(igst18) + parseFloat(postage_gst);
            totgst28 = parseFloat(cgst28) + parseFloat(cgst28) + parseFloat(igst28);

            $('.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_2.toFixed(2));
            $('.sgst18').val(cgst18_2.toFixed(2));
            $('.igst18').val(igst18_2.toFixed(2));
            $('.cgst28').val(cgst28.toFixed(2));
            $('.sgst28').val(cgst28.toFixed(2));
            $('.igst28').val(igst28.toFixed(2));
            $('.totgst5').val(totgst5.toFixed(2));
            $('.totgst12').val(totgst12.toFixed(2));
            $('.totgst18').val(totgst18.toFixed(2));
            $('.totgst28').val(totgst28.toFixed(2));
            $('.igst1').val(0);
            $('.totgst1').val(0);


            totbillamt = parseFloat(taxable) + parseFloat(totgst5) + parseFloat(totgst12) + parseFloat(totgst18) + parseFloat(totgst28) ;
        }

        var totbillamt2 = (totbillamt * 100) / 100;
        var rtotbillamt = Math.round(totbillamt2);

        if ($('.freeflag').prop("checked") == true) {
            $('.freeamount').val(rtotbillamt);
            $(".totbillamt").val(0);
        } else {
            $(".totbillamt").val(rtotbillamt);
            $('.freeamount').val(0);
        }
        calDetail();
    }

    function calDetail() {
        var tr = $(this).closest("tr"),
                qty = tr.find(".qty").val(),
                rate = tr.find(".rate").val(),
                amount = parseFloat(rate) * parseFloat(qty),
                subtotal = 0;
        tr.find(".amount").val(amount);
        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                subtotal += parseFloat(this.value);
            }
        });
        $(".subtotal").val(subtotal);
    }


    $('#addnew').click(function () {
        AddRows();
    });
    function remove() {
        $(this).closest("tr").remove();
        calDetail();
        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 focusFld = ".focusFld_" + ctr;
        $.post('sale_ti_add.php', {ctr: ctr, hide: hide_check, prodtype: prodtype}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(focusFld).focus();
        });
    }


//    ########################Image Uploader##########################

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


});