$(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,.freeflag,.deemexp", caltran);
    $("body").on("keyup", ".postamt", addpost);
    $("body").on("blur", '.discperc', autoaddrow);
    $("body").on("change", '.freeflag', hideshow);
    $("body").on("click", "#hsubmit", hidesub);
    $("body").on("change", ".cmbparty", getoms);
    $("body").on("click", "#submit ,#cancel", hide_but);

    var canc_flag = $(".canc_flag").val();
    if (canc_flag != '') {
        $("#scancbill").hide();
        $("#hedit").hide();
    }
    
    $("#cancbill").click(function () {
        $("#cancmodel").modal('show');
    });

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

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

//    function deemexp() {
//        if ($('.deemexp').prop("checked") == true) {
//            $('.oms').prop('checked', true);
//        } else {
//            $('.oms').prop('checked', false);
//        }
//    }
//
//    deemexp();


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

    });
//    $('#hedit').click(function(){
//       $('.vouchdt').focus(); 
//    });


    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) {
            $(".cmbparty").select2("open");
        }
    });
    
    function addpost() {
        var gperc = 0;
        if ($('.oms').prop("checked") == true || $('.oms2').val() == 'Yes') {
            $('.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 || $('.oms2').val() == 'Yes') {
                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);
            $('.transporter').val(data.transporter).trigger('change');

        }, 'json');
    }

    function gethsn() {
        var tr = $(this).closest("tr");
        var barcode = tr.find('.barcode').val();
        $.post('get_salegst.php', {barcode: barcode}, function (data) {
//            tr.find('.discperc').val(data.discperc);
            if ($(".oms").prop('checked') || ($(".oms2").val() == 'Yes' )) {
                if (data.igst == '' || data.igst == '0') {
                    tr.find('.igstrate').val('0');
                } else {
                    tr.find('.igstrate').val('0.1');
                }
                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('0.05');
                    tr.find('.sgstrate').val('0.05');
                }
                tr.find('.igstrate').val('0');
            }
        }, 'json');
        caltran();
    }

    function caltran() {
        var cgst5 = 0,
                tot0 = 0,
                tot0a = 0,
                cgst12 = 0,
                cgst18 = 0,
                cgst28 = 0,
                igst1 = 0,
                cgst1 = 0,
                igst5 = 0,
                igst12 = 0,
                igst18 = 0,
                igst28 = 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,
                iamt = 0,
                camt = 0,
                billdiscamt = $('.billdiscamt').val(),
                tottaxble1 = 0;

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

            if ($('.oms').prop("checked") == true || $('.oms2').val() == 'Yes') {
                if (irate == 0) {
                    tot0a = parseFloat(newtax);
                    tot0 += parseFloat(tot0a);
                }
                if (irate == 0.1) {
                    var subtot1 = row.find('.subtot').val();
                    tottaxble1 = parseFloat(tottaxble1) + parseFloat(subtot1);
                }
            } else {
                if (crate == 0) {
                    tot0a = parseFloat(newtax);
                    tot0 += parseFloat(tot0a);
                }
                if (crate == 0.05) {
                    var subtot1 = row.find('.subtot').val();
                    tottaxble1 = parseFloat(tottaxble1) + parseFloat(subtot1);
                }
            }
            $(".tottaxble1").val(tottaxble1);


            var total = parseFloat(iamt) + parseFloat(camt) + parseFloat(camt) + 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(camt);
            row.find('.sgstamt').val(camt);
            igst1 += parseFloat(iamt);
            cgst1 += parseFloat(camt);
        });
        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));
        var totgst1 = parseFloat(cgst1) + parseFloat(cgst1) + parseFloat(igst1);
        $(".tottaxble0").val(tot0.toFixed(2));

        $('.taxableamt').val(subtot.toFixed(2));
        $('.igst1').val(igst1.toFixed(2));
        $('.cgst1').val(cgst1.toFixed(2));
        $('.sgst1').val(cgst1.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);
        $('.totgst1').val(totgst1.toFixed(2));
        $('.totgst5').val(0);
        $('.totgst12').val(0);
        $('.totgst18').val(0);
        $('.totgst28').val(0);
        totbillamt = (parseFloat(subtot) + parseFloat(igst1) + parseFloat(cgst1) + parseFloat(cgst1)).toFixed(2);
//        }
        var totbillamt2 = (totbillamt * 100) / 100;
        var rtotbillamt = Math.round(totbillamt2);
        var rdoff = (rtotbillamt - totbillamt).toFixed(2);
        $(".roundoff").val(rdoff);


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

    }


    function calDetail() {
        var tr = $(this).closest("tr"),
                qty = tr.find(".qty").val(),
                rate = tr.find(".rate").val(),
                amount = (parseFloat(rate) * parseFloat(qty)).toFixed(2),
                subtotal = 0;
        tr.find(".amount").val(amount);
        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.length != 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 detail = ".fetchpart_" + ctr;
        var focusFld = ".focusFld_" + ctr;
        $.post('sale_de_add.php', {ctr: ctr, hide: hide_check, prodtype: prodtype}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
//            $(detail).select2();
            $(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);
    });


});