$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup blur focus", ".qty, .rate, .total", calDetail);
//    $("body").on("keyup blur focus", ".totqty, .totamt", calMain);
    $("body").on("keyup", ".ssearch", getSearchData);
    $("body").on("click", ".sload", getSearchData);

    function calDetail() {
        var tr          = $(this).closest("tr"),
            qty         = tr.find(".qty").val(),
            rate        = tr.find(".rate").val(),
            total      = parseFloat(rate) * parseFloat(qty),
            totamt    = 0,
            totqty    = 0;

        tr.find(".total").val(total);
        $(".total").each(function () {
            if (!isNaN(this.value) && this.value.lenght !== 0) {
                totamt += parseFloat(this.value);
            }
        });
        $(".totamt").val(totamt);
        
//        calMain();
        
        tr.find(".qty").val(qty);
        $(".qty").each(function () {
            if (!isNaN(this.value) && this.value.lenght !== 0) {
                totqty += parseFloat(this.value);
            }
        });
        $(".totqty").val(totqty);
        
//        calMain();
    }

//    function calMain() {
//        var totamt    = $(".subtotal").val(),
//            cdperc      = $(".cdperc").val(),
//            itemdisc    = $(".itemdisc").val(),
//            cdamt       = (cdperc * subtotal) / 100,
//            total       = subtotal - itemdisc - cdamt ,
//            
//            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 * shtot) / 100,
//            taxtot      = parseFloat(shtot) + parseFloat(taxamt),
//            
//            roundoff    = $(".roundoff").val(),
//            nettotal    = parseFloat(taxtot) + parseFloat(roundoff);
//debugger
//        $(".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();
    }

    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;
        $.post('ordform_add.php', {ctr: ctr, hide: hide_check, prodtype: prodtype}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }
    
    
    
    //////////////////////////////////////////////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(),
            soperator   = $(".soperator").val(),
            data        = {ssearch: ssearch, sfield: sfield, soperator: soperator,
                           rangeFrom: smrangeFrom, rangeTo: smrangeTo},
            values      = "";
        $.ajax({
            type    : 'GET',
            dataType: 'json',
            url     : "ordform_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.vouchdt+ "</td>" +
                              "<td align='left'>" + this.party+ "</td>" +
                              "<td align='left'>" + this.totqty+ "</td>" +
                              "<td align='left'>" + this.totamt+ "</td>" +
                              "<td align='left'>" + this.rem1+ "</td>" +
                              "<td align='left'>" + this.action+ "</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  //////////////////////////////////////////////

});