$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup blur focus", ".qty, .rate, .amount, .discperc, .discount, .vatperc, .vatamt, .total", calDetail);
    $(".tbody").on("keyup blur focus", ".amtoth", calDetailOth);
    $("body").on("keyup blur focus", ".subtotal, .vattot, .totdisc, .billamt", 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(),
            amount      = parseFloat(rate) * parseFloat(qty),
            discperc    = tr.find(".discperc").val(),
            discount    = (discperc * amount)/100,
            vatperc     = tr.find(".vatperc").val(),
            vatamt      = (vatperc * amount)/100,
            total       = parseFloat(amount) - parseFloat(discount),
            subtotal    = 0,
            totvat      = 0,
            totdisc     = 0;

        tr.find(".amount").val(amount);
        tr.find(".discount").val(discount);
        tr.find(".vatamt").val(vatamt);
        tr.find(".total").val(total);

        $(".discount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                totdisc += parseFloat(this.value);
            }
        });
        $(".totdisc").val(totdisc);
        
        $(".vatamt").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                totvat += parseFloat(this.value);
            }
        });
        $(".totvat").val(totvat);
        
        
        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                subtotal += parseFloat(this.value);
            }
        });
        $(".subtotal").val(subtotal);
        
        calMain();
    }
    function calDetailOth() {
        var tr          = $(this).closest("tr"),
            amtoth      = tr.find(".amtoth").val(),
            obillamt    = 0;

        $(".amtoth").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                obillamt += parseFloat(this.value);
            }
        });
        $(".obillamt").val(obillamt);
    }

    function calMain() {
        var subtotal    = $(".subtotal").val(),
            totvat      = $(".totvat").val(),
            totdisc     = $(".totdisc").val(),
            billamt    = parseFloat(subtotal) + parseFloat(totvat)+ parseFloat(totdisc);
    
        $(".billamt").val(billamt.toFixed(2));
    }

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

    function AddRows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;
        $.post('goods_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }

    function AddRowsOth() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;
        $.post('other_add.php', {ctr: ctr, hide: hide_check}, 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(),
            ioperator   = $(".soperator").val(),
            data        = {ssearch: ssearch, sfield: sfield, ioperator: ioperator,
                           rangeFrom: smrangeFrom, rangeTo: smrangeTo},
            values      = "";
        $.ajax({
            type    : 'GET',
            dataType: 'json',
            url     : "debnote_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.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  //////////////////////////////////////////////
    

});