$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup blur focus", ".qty, .rate, .amount", calDetail);
    $("body").on("keyup blur focus", ".discperc, .disamt, .vdperc, .vdamt, .cartperc, .cartamt, .cgstperc, .sgstperc , .billamt", 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", ".amount, .rate, .sgstrate, .cgstamt, .sgstamt", caltran);

    function caltran() {
        var tr = $(this).closest("tr");
        var amt = tr.find('.amount').val();


        tr.find('.subtot').val(amt);

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

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


    }

    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('.cgstrate').val(data.cgst);
            tr.find('.sgstrate').val(data.sgst);
            $('.cgstperc').val(data.cgst);
            $('.sgstperc').val(data.sgst);
        }, 'json');
    }


    printLast();

    function printLast() {
        var vouchno = $(".vouchno").val(),
                para = $(".para").val(),
                link = "gst_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 subtotal = $(".subtotal").val(),
                discperc = $(".discperc").val(),
                discamt = (discperc * subtotal) / 100,
                                total = parseFloat(subtotal) - parseFloat(discamt),

                vdperc = $(".vdperc").val(),
                vdamt = (vdperc * total) / 100,
                
                vdtot = total - vdamt,
                
                cartperc = $(".cartperc").val(),
                cartamt = (cartperc * vdtot) / 100,
                                                taxable = parseFloat(total) - parseFloat(vdamt) + parseFloat(cartamt),

                
                cgstperc = $(".cgstperc").val(),
                cgstamt = (cgstperc * taxable) / 100,
                
                sgstperc = $(".sgstperc").val(),
                sgstamt = (sgstperc * taxable) / 100,
//                vattot = parseFloat(carttot) + parseFloat(vatamt),

                billamt = Math.round(parseFloat(taxable) + parseFloat(cgstamt) + parseFloat(sgstamt) + parseFloat(cartamt), 0);

        $(".discamt").val(discamt.toFixed(2));
        $(".total").val(taxable.toFixed(2));
        $(".vdamt").val(vdamt.toFixed(2));
        $(".cartamt").val(cartamt.toFixed(2));
        $(".totcgst").val(cgstamt.toFixed(2));
        $(".totsgst").val(sgstamt.toFixed(2));
        $(".billamt").val(billamt.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('salegst_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: "salegst_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) {

            }
        });
    }

});