$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup change blur focus", ".qty, .rate, .amount", calDetail);
//    $("body").on("keyup blur focus", ".cdperc, .cdamt, .excperc, .excamt, .edperc, .edamt, .shperc, .shamt, .taxperc, .taxamt, .roundoff, .nettotal", calMain);
    $("body").on("keyup", ".ssearch", getSearchData);
    $("body").on("click", ".sload", getSearchData);
    $("body").on("change", ".orderAs, .sortBy", getSearchData);
    $("body").on("change", ".taxcode", getTax);
    $("body").on("focus", ".taxperc", getTax);
    $("body").on("blur", ".invno", chkinvno);
    $("body").on("focus", ".qty", gethsn);
    $("body").on("change", ".party", getgst);
    $("body").on("change keyup blur", ".amount, .discperc, .subtot, .cgstrate, .sgstrate, .igstrate, .totbillamt,.roundoff", caltran);
//    $("body").on("change", ".oms", editoms);

   var addflag = $('.addflag').val();
   if(addflag != 1){
       $('.oms').prop('readonly',true);
   }else{
       $('.oms').prop('readonly',false);
   }

    function gethsn() {
        var tr = $(this).closest("tr");
        var item = tr.find('.itemname').val();
        $.post('gethsncode.php', {item: item}, function (data) {
            tr.find('.hsncode').val(data.hsn);
            if ($(".oms").prop('checked')) {
                tr.find('.igstrate').val(data.igst);

            } else {
                tr.find('.cgstrate').val(data.cgst);
                tr.find('.sgstrate').val(data.sgst);
            }
        }, 'json');
    }
    function getgst() {
        var party = $('.party').val();
        $.post('getgst.php', {party: party}, function (data) {
          $('.vattin').val(data);
        });
    }

//     $("body").on("change", ".item", gethsn);


    function editoms() {

        $('.tab').find('tr').each(function () {
            var row = $(this),
                    item = row.find('.itemname').val();
            $.post('gethsncode.php', {item: item}, function (data) {
                row.find('.hsncode').val(data.hsn);
                if ($(".oms").prop('checked')) {
                    row.find('.igstrate').val(data.igst);
                    row.find('.cgstrate').val(0);
                    row.find('.sgstrate').val(0);
                    row.find('.cgstamt').val(0);
                    row.find('.sgstamt').val(0);
                    
                } else {
                    row.find('.cgstrate').val(data.cgst);
                    row.find('.sgstrate').val(data.sgst);
                    row.find('.igstrate').val(0);
                    row.find('.igstamt').val(0);
                }
            }, 'json');
            
            var amt = $('#amount_0').val();
            
            if(amt == 0){
                $(".oms").focus();
            }else{
                $("#amount_0").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);

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

    getImage();

    $(".vouchdt").blur(function () {
        $(".taxcode").select2("open");
    });

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

    var taxcode = $(".taxcode").select2();

    taxcode.on("select2:close", function (e) {
        $(".party").select2("open");
    });

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

    function getTax() {
        var tax = $(".taxcode").val();
        $.ajax({
            type: "POST",
            datatype: "json",
            url: "get_taxperc.php",
            data: {tax: tax},
            success: function (response) {
                if (response.success == true) {
                    $(".taxperc").val(response.perc);
                }
            },
            error: function (request, textStatus, errorThrown) {

            }
        });
    }

//    function calDetail() {
//        var tr = $(this).closest("tr"),
//                qty = tr.find(".qty").val(),
//                rate = tr.find(".rate").val(),
//                amount = parseFloat(rate) * parseFloat(qty),
//                discperc = tr.find(".discperc").val(),
//                discount = (discperc * amount) / 100,
//                total = parseFloat(amount) - parseFloat(discount),
//                subtotal = 0,
//                totdisc = 0;
//
//        tr.find(".amount").val(amount);
//        tr.find(".discount").val(discount);
//        tr.find(".total").val(total);
//
//        $(".discount").each(function () {
//            if (!isNaN(this.value) && this.value.lenght != 0) {
//                totdisc += parseFloat(this.value);
//            }
//        });
//        $(".totdiscamt").val(totdisc);
//
//
//        $(".amount").each(function () {
//            if (!isNaN(this.value) && this.value.lenght != 0) {
//                subtotal += parseFloat(this.value);
//            }
//        });
//        $(".subtotal").val(subtotal);
//
//        calMain();
//    }


    function caltran() {
        var tr = $(this).closest("tr");
        var amt = tr.find('.amount').val(),
                discperc = tr.find('.discperc').val(),
//                roundoff = $(".roundoff").val(),
                cgst5 = 0,
                cgst12 = 0,
                cgst18 = 0,
                cgst28 = 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,
                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);
            }
        });
        $('.taxableamt').val(subtot.toFixed(2));


        $('.tab').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 < 3) {
                cgst5a = parseFloat(cgstamnt);
                cgst5 += parseFloat(cgst5a);
                igst5a = 0;
            } else if (crate < 7) {
                cgst12a = parseFloat(camt);
                cgst12 += parseFloat(cgst12a);
                igst12a = 0;
            } else if (crate < 10) {
                cgst18a = parseFloat(camt);
                cgst18 += parseFloat(cgst18a);
                igst18a = 0;
            } else if (crate < 15) {
                cgst28a = parseFloat(camt);
                cgst28 += parseFloat(cgst28a);
                igst28a = 0;
            }

            if (irate < 7) {
                igst5a += parseFloat(iamt);
                igst5 += parseFloat(igst5a);
                cgst5a = 0;
            } else if (irate < 13) {
                igst12a += parseFloat(iamt);
                igst12 += parseFloat(igst12a);
                cgst12a = 0;
            } else if (irate < 19) {
                igst18a += parseFloat(iamt);
                igst18 += parseFloat(igst18a);
                cgst12a = 0;
            } else if (irate < 28) {
                igst28a += parseFloat(iamt);
                igst28 += parseFloat(igst28a);
                cgst28a = 0;
            }

        });

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

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

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

        var roundoff = $('.roundoff').val();

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


        $(".totbillamt").val(totbillamt.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('purchasegst_add.php', {ctr: ctr, hide: hide_check, prodtype: prodtype}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
            $(focusFld).focus();
            caltran();
        });
    }



    //////////////////////////////////////////////Search Part - Start//////////////////////////////////////////////
    $(".snoRecord").hide();

    $(".searchModal").on('shown.bs.modal', function () {
        $(".ssearch").focus();
        $(".ssearch").val("");
        $(".sfield").val("1");
        getSearchData();
    });

    var smrangeFrom = 0,
            smrangeTo = 40;

    function getSearchData(pagination) {

        $(".sloader").show();

        if (pagination == 'prev') {
            if (smrangeFrom > 0) {
                smrangeFrom = (smrangeFrom - 40);
                smrangeTo = (smrangeTo - 40);
            }
        }
        if (pagination == 'next') {
            smrangeFrom = (smrangeFrom + 40);
            smrangeTo = (smrangeTo + 40);
        }

        var ssearch = $(".ssearch").val(),
                sfield = $(".sfield").val(),
                sortBy = $(".sortBy").val(),
                orderAs = $(".orderAs").val(),
                soperator = $(".soperator").val(),
                data = {ssearch: ssearch, sfield: sfield, sortBy: sortBy, orderAs: orderAs, soperator: soperator,
                    rangeFrom: smrangeFrom, rangeTo: smrangeTo},
        values = "";
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "purchasegst_search.php",
            data: data,
            success: function (response) {
                $.each(response, function () {
                    values += "<tr class='clickable-row' data-href='" + this.action + "'>" +
                            "<td align='left'>" + this.vouchno + "</td>" +
                            "<td align='left'>" + this.name + "</td>" +
                            "<td align='left'>" + this.mobile + "</td>" +
                            "<td align='left'>" + this.billno + "</td>" +
                            "<td align='left'>" + this.vouchdt + "</td>" +
                            "<td align='left'>" + this.nettotal + "</td>" +
                            "<td align='left'>" + this.rem1 + "</td>" +
                            "<td align='left'><a href='" + this.action + "'><i class='fa fa-pencil' style='font-size:1.3em;cursor:pointer;'></i></a></td>" +
                            "</tr>";
                });
                $(".sloader").hide();
                $(".sTbody").empty();
                $(".sTbody").html(values);
                if (response) {
                    $(".search-action-bar").show();
                }
            },
            error: function (request, textStatus, errorThrown) {

            }
        });
    }
    $("#search").click(function () {
        getSearchData();
    });
//    $(".ssearch").change(function () {
//        getSearchData();
//    });
    $(".sprevious").click(function () {
        getSearchData('prev');
    });
    $(".snext").click(function () {
        getSearchData('next');
    });


    //////////////////////////////////////////////Search Part - End  //////////////////////////////////////////////



    //////////////////////////////////////////////IMAGE UPLOAD - START//////////////////////////////////////////////
    $(".showUpdModal").click(function () {
        $(".imgUploadModal").modal("show");
    });

    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]);
        }
    }
    $(".imgUploadModal").find("#file1").change(function () {
        readIMG(this);
    });

    function getImage() {
        var vouchno = $("#vouchno").val(),
                series = $("#series").val(),
                data = {vouchno: vouchno, series: series};
        $.ajax({
            type: "POST",
            datatype: "json",
            url: "billimg.php",
            data: data,
            success: function (response) {
                $("#preview").attr("src", response.image);
            },
            error: function (request, errorStatus, errorThrown) {

            }
        });
    }

    function _(el) {
        return document.getElementById(el);
    }
    $(".imgUpload").click(function () {
        imgUpload();
    });
    function imgUpload() {
        var file = _("file1").files[0];
        var series = _("series").value;
        var vouchno = _("vouchno").value;
//        alert(file.name+" | "+file.size+" | "+file.type);
        var formdata = new FormData();
        formdata.append("file1", file);
        formdata.append("vouchno", vouchno);
        formdata.append("series", series);
        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", "purImgUpload.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";
    }
    getImage();



    ////////////////////////////////////////////////IMAGE UPLOAD - END  //////////////////////////////////////////////


    //////////////////////////////////////////////PDF UPLOAD - START//////////////////////////////////////////////
    $(".showPdfModal").click(function () {
        $(".pdfUploadModal").modal("show");
    });

//    $(".pdfUploadModal").find("#file2").change(function () {
//        readIMG(this);
//    });
//
    function getPdf() {
        var vouchno = $("#vouchno").val(),
                series = $("#series").val(),
                data = {vouchno: vouchno, series: series};
        $.ajax({
            type: "POST",
            datatype: "json",
            url: "billpdf.php",
            data: data,
            success: function (response) {
                $("#show").show();
                $("#show").attr("href", response.image);
            },
            error: function (request, errorStatus, errorThrown) {

            }
        });
    }

    function _(el) {
        return document.getElementById(el);
    }
    $(".pdfUpload").click(function () {
        pdfUpload();
        getPdf();
    });
    function pdfUpload() {
        var file = _("file2").files[0];
        var series = _("pdfseries").value;
        var vouchno = _("pdfvouchno").value;
//        alert(file.name+" | "+file.size+" | "+file.type);
        var formdata = new FormData();
        formdata.append("file2", file);
        formdata.append("vouchno", vouchno);
        formdata.append("series", series);
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress2", progressHandler, false);
        ajax.addEventListener("load", completeHandler, false);
        ajax.addEventListener("error", errorHandler, false);
        ajax.addEventListener("abort", abortHandler, false);
        ajax.open("POST", "purPdfUpload.php");
        ajax.send(formdata);
    }

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

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

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

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



    ////////////////////////////////////////////////PDF UPLOAD - END  //////////////////////////////////////////////

});