$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup blur focus", ".qty, .rate, .amount, .discperc, .discount, .total", 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);
    var salelock = $(".salelock").val();
    if (salelock != "0000-00-00" && salelock != "") {
        $("#hadd").hide();
        $("#hedit").hide();
        $("#hdelete").hide();
        $("#scancbill").hide();
    }

    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);
            }
        });
        $(".itemdisc").val(totdisc);


        $(".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(),
                cdperc = $(".cdperc").val(),
                itemdisc = $(".itemdisc").val(),
                
                
                cdamt = (cdperc * (subtotal-itemdisc)) / 100,
                total = subtotal - itemdisc - cdamt,
                
                totamt = $(".totamt").val(),
                
                excperc = $(".excperc").val(),
                excise = (excperc * total) / 100,
                exctot = total + excise,
                
                edperc = $(".edperc").val(),
                edcessamt = (edperc * total) / 100,
                edtot = exctot + edcessamt,
                
                shprec = $(".shprec").val(),
                shcessamt = (shprec * total) / 100,
                shtot = edtot + shcessamt,
                
                taxperc = $(".taxperc").val(),
                taxamt = (taxperc * total) / 100,
                taxtot = parseFloat(shtot) + parseFloat(taxamt),
                
                roundoff = $(".roundoff").val(),
                nettotal = parseFloat(taxtot) + parseFloat(roundoff);
        $(".cdamt").val(cdamt.toFixed(2));
        $(".totamt").val(total.toFixed(2));
        $(".excise").val(excise.toFixed(2));
        $(".edcessamt").val(edcessamt.toFixed(2));
        $(".shcessamt").val(shcessamt.toFixed(2));
        $(".taxamt").val(taxamt.toFixed(2));
        $(".nettotal").val(nettotal.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('purchase_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 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: "purchase_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  //////////////////////////////////////////////

});