$(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, .vatoerc, .vatamt , .billamt", calMain);
    $("body").on("keyup", ".ssearch", getSearchData);
    $("body").on("click", ".sload", getSearchData);
    $("body").on("blur", ".qty", checkSize);
    $("body").on("change", ".cashcred", showParty);
    $("body").on("blur", ".mobile", getMobDetails);


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

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

    function getMobDetails() {
        var mobile = $(".mobile").val();
        debugger;
        $.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 = subtotal - discamt,
                
                vdperc = $(".vdperc").val(),
                vdamt = (vdperc * total) / 100,
                vdtot = total - vdamt,
                
                cartperc = $(".cartperc").val(),
                cartamt = (cartperc * total) / 100,
                carttot = parseFloat(vdtot) + parseFloat(cartamt),
                
                vatperc = $(".vatperc").val(),
                vatamt = (vatperc * carttot) / 100,
                vattot = parseFloat(carttot) + parseFloat(vatamt),
                
                billamt = Math.round(parseFloat(vattot)+parseFloat(carttot) +parseFloat(vdtot), 0);

        $(".discamt").val(discamt.toFixed(2));
        $(".total").val(total.toFixed(2));
        $(".vdamt").val(vdamt.toFixed(2));
        $(".cartamt").val(cartamt.toFixed(2));
        $(".vatamt").val(vatamt.toFixed(2));
        $(".billamt").val(billamt.toFixed(2));
    }

    $('#addnew').click(function () {
        AddRows();
    });
    function remove() {
        $(this).closest("tr").remove();
        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('salespare_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: "salespare_search.php",
            data: data,
            success: function (response) {
                $.each(response, function () {
                    values += "<tr class='searchTr'>" +
                            "<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);
                if (m.check == 1) {
                    checkImageAfter()
                    $("#submit").hide();
                } else {
                    $("#submit").show();
                }
            },
            error: function (request, textStatus, errorThrown) {
            }
        });
    }
    $(".imgUploadModal").on("hidden.bs.modal", function () {
        checkImageAfter();
    });

    function checkImageAfter() {
        var vouchno = $("#vouchno").val(),
                series = $("#series").val(),
                data = {vouchno: vouchno, series: series};
        debugger;
        $.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) {

            }
        });
    }

});