$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup blur focus", ".qty, .rate, .amount", calDetail);
    $("body").on("change keyup blur", ".rate,.amount, .discperc, .subtot, .cgstrate, .sgstrate, .cgstamt, .sgstamt, .totbillamt", calMain);
    $("body").on("keyup", ".ssearch", getSearchData);
    $("body").on("click", ".sload", getSearchData);
    $("body").on("change", ".orderAs, .sortBy", getSearchData);
    $("body").on("blur", ".qty", checkSize);
    $("body").on("change", ".cashcred", showParty);
    $("body").on("blur", ".mobile", getMobDetails);
    $("body").on("focus", ".rate", gethsn);
    $("body").on("change keyup blur", ".rate,.amount, .discperc, .subtot, .cgstrate, .sgstrate, .igstrate, .cgstamt, .sgstamt, .igstamt,.totbillamt,.roundoff", caltran);


    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);
            tr.find('.discperc').val(data.discperc);
            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 caltran() {
        var tr = $(this).closest("tr");
        var amt = tr.find('.amount').val(),
                discperc = tr.find('.discperc').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.toFixed(2));
        var taxval = parseFloat(amt) - parseFloat(discount);
        tr.find('.subtot').val(taxval.toFixed(2));

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


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


        $(".totbillamt").val(totbillamt.toFixed(2));
    }



    printLast();

    function printLast() {
        var vouchno = $(".vouchno").val(),
                para = $(".para").val(),
                link = "salegstdtl_print.php?vouchno=" + vouchno + "&" + para;

        $.ajax({
            type: "POST",
            datatype: "json",
            data: {vouchno: vouchno},
            url: "print_last.php",
            success: function (response) {
                if (response.success == true) {
                    window.open(link, "_blank");
                }
            },
            error: function (request, errorThrown, textStatus) {

            }
        });
    }

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

    $(".location").blur(function () {
        $(".staff").select2("open");
    });

    function getMobDetails() {
        var mobile = $(".mobile").val();

        $.ajax({
            type: "POST",
            datatype: "json",
            data: {mobile: mobile},
            url: "getMobDetail.php",
            success: function (response) {
                $(".cashcred").val(response.cashcred).trigger("change");
                $(".cashcred").select2("open");
                if (response.cashcred != "S") {
                    $(".txtparty").val(response.partyname)
                } else {
                    $(".cmbparty").val(response.accode).trigger("change")
                }
                $(".location").val(response.location);
                $(".rem1").val(response.rem1);
                $(".rem2").val(response.rem2);
                $(".vattin").val(response.vattin);
                $(".csttin").val(response.csttin);
            },
            error: function (request, errorThrown, textStatus) {

            }
        });
    }




    showParty();
    function showParty() {
        var cashcred = $(".cashcred").val();

        if (cashcred != "S") {
            $(".cmbparty").select2();
            $(".cmbparty").select2("destroy");
            $(".cmbparty").hide();
            $(".txtparty").show();
            $(".txtparty").attr("required", true);
            $(".cmbparty").attr("required", false);
        } else {
            $(".cmbparty").show();
            $(".cmbparty").select2();
            $(".cmbparty").attr("required", true);
            $(".txtparty").attr("required", false);
            $(".txtparty").hide();
        }
    }

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

    function calMain() {
        var tr = $(this).closest("tr");
        var amt = tr.find('.amount').val(),
                discperc = tr.find('.discperc').val(),
                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(),
                cgstamnt = parseFloat(taxval) * parseFloat(cgstrate) / 100,
                sgstamnt = parseFloat(taxval) * parseFloat(sgstrate) / 100,
                total = Math.round(parseFloat(cgstamnt) + parseFloat(sgstamnt) + parseFloat(taxval));

        tr.find('.cgstamt').val(cgstamnt);
        tr.find('.sgstamt').val(sgstamnt);
        tr.find('.total').val(total);

        var grosstot = 0,
                discamt = 0,
                subtot = 0,
                cgstamt = 0,
                sgstamt = 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));

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

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




        var totbillamt = Math.round(parseFloat(subtot) + parseFloat(cgstamt) + parseFloat(sgstamt));


        $(".totbillamt").val(totbillamt.toFixed(2));
    }

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

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



    //////////////////////////////////////////////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 series = $(".series").val(),
                para = $(".para").val(),
                ssearch = $(".ssearch").val(),
                sfield = $(".sfield").val(),
                sortBy = $(".sortBy").val(),
                orderAs = $(".orderAs").val(),
                ioperator = $(".soperator").val(),
                data = {ssearch: ssearch, sfield: sfield, sortBy: sortBy, orderAs: orderAs, ioperator: ioperator, para: para,
                    series: series, rangeFrom: smrangeFrom, rangeTo: smrangeTo},
        values = "";
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "salegstdtl_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.billamt + "</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();
    });
    $(".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: "getImage.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", "imgUpload.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  //////////////////////////////////////////////

    function checkSize() {
        var tr = $(this).closest("tr"),
                size = tr.find(".size").val(),
                data = {size: size};

        $.ajax({
            type: "GET",
            datatype: "JSON",
            url: "checkSize.php",
            data: data,
            success: function (response) {
                var m = jQuery.parseJSON(response);
                $(".sizeCheckField").val(m.check);
                if (m.check == 1) {
                    checkImageAfter();
                    $("#submit").hide();
                } else {
                    $("#submit").show();
                }
            },
            error: function (request, textStatus, errorThrown) {
            }
        });
    }
    $(".imgUploadModal").on("hidden.bs.modal", function () {
        var check = $(".sizeCheckField").val();
        if (check == "1") {
            checkImageAfter();
        }
    });

    function checkImageAfter() {
        var vouchno = $("#vouchno").val(),
                series = $("#series").val(),
                data = {vouchno: vouchno, series: series};

        $.ajax({
            type: "POST",
            datatype: "json",
            url: "checkImage.php",
            data: data,
            success: function (response) {
                if (response.success == true) {
                    $("#submit").show();
                } else {
                    $("#submit").hide();
                }
            },
            error: function (request, errorStatus, errorThrown) {

            }
        });
    }

});