$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $("body").on("focus", '.amount', autoAddRows);
    $("body").on("keyup focus blur click", '.remove, .amount', itemCal);
    $("body").on("keyup focus blur change", '.swchperc, .krshperc, .stperc', calculateTotal);



    $('#addnew').click(function () {
        AddRows(); 
    });
    $('.amount').focus(function () {
        AddRows();
    });

    function autoAddRows() {
        if ($(this).closest("tr").is(":last-child")) {
            AddRows();
        }
    }

    function remove() {
        $(this).closest("tr").remove();
    }

    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('invlumpsum_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }

    function itemCal() {
         var val = tot = 0;

        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val += parseFloat(this.value);
            }
        });
        var tot = parseFloat(val);
        $('.subtotal').val(tot);
//        mainbCal();
        calculateTotal();
    }
    function calculateTotal() {
        var subtotal = $(".subtotal").val(),
                stperc = $(".stperc").val(),
                swchperc = $(".swchperc").val(),
                krshperc = $(".krshperc").val(),
                stamt = 0,
                swchamt = 0,
                krshamt = 0,
                nettotal = 0;

        stamt = stperc * subtotal / 100,
                swchamt = swchperc * subtotal / 100,
                krshamt = krshperc * subtotal / 100,
                nettotal = parseFloat(subtotal) + parseFloat(stamt) + parseFloat(swchamt) + parseFloat(krshamt);
        
        $(".stamt").val(stamt);
        $(".swchamt").val(swchamt);
        $(".krshamt").val(krshamt);
        $(".nettotal").val(nettotal);
    }

});