/**
 * Created by Huzaifa on 9/18/15.
 */

$(document).on('change','#partner_type_id', function() {
    $partner_type_id = $(this).val();
    $.ajax({
        url: $UrlGetPartner,
        dataType: 'json',
        type: 'post',
        data: 'partner_type_id=' + $partner_type_id+'&partner_id='+$partner_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#partner_id').before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                $('#partner_id').select2('destroy');
                $('#partner_id').html(json.html);
                $('#partner_id').select2({width:'100%'});
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

$(document).on('change','#partner_id', function() {
    $partner_id = $(this).val();
    if($partner_id != '') {
        $('#ref_document_type_id').select2('destroy');
        $('#ref_document_type_id').html('<option value="">&nbsp;</option><option value="17">'+$lang['goods_received']+'</option>');
        $('#ref_document_type_id').select2({width: '100%'});
    } else {
        $('#ref_document_type_id').select2('destroy');
        $('#ref_document_type_id').html('');
        $('#ref_document_type_id').select2({width: '100%'});
    }
    $('#ref_document_identity').select2('destroy');
    $('#ref_document_identity').html('<option value="">&nbsp;</option>');
    $('#ref_document_identity').select2({width: '100%'});

});

$(document).on('change','#ref_document_type_id', function() {
    var $partner_type_id = $('#partner_type_id').val();
    var $partner_id = $('#partner_id').val();
    var $ref_document_type_id = $(this).val();
    $.ajax({
        url: $UrlGetRefDocumentNo,
        dataType: 'json',
        type: 'post',
        data: 'ref_document_type_id=' + $ref_document_type_id + '&partner_type_id=' + $partner_type_id + '&partner_id=' + $partner_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#ref_document_id').before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                $('#ref_document_identity').select2('destroy');
                $('#ref_document_identity').html(json.html);
                $('#ref_document_identity').select2({width: '100%'});
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

$(document).on('click','#addRefDocument', function() {
    var $data = {
        partner_type_id : $('#partner_type_id').val(),
        partner_id : $('#partner_id').val(),
        ref_document_type_id : $('#ref_document_type_id').val(),
        ref_document_identity : $('#ref_document_identity').val()
    };

    var $details = [];
    $.ajax({
        url: $UrlGetRefDocument,
        dataType: 'json',
        type: 'post',
        data: $data,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#ref_document_id').before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                $details = json['details'];
                for($i=0;$i<$details.length;$i++) {
                    fillGrid($details[$i]);
                }
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

function fillGrid($obj) {
    $html = '';
    $html += '<tr id="grid_row_'+$grid_row+'" data-row_id="'+$grid_row+'">';
    $html += '<td>';
    $html += '  <a onclick="removeRow(this);" title="Remove" class="btn btn-sm btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="purchase_invoice_details['+$grid_row+'][ref_document_type_id]" id="purchase_invoice_detail_ref_document_type_id_'+$grid_row+'" value="'+$obj['document_type_id']+'" />';
    $html += '<input type="hidden" name="purchase_invoice_details['+$grid_row+'][ref_document_identity]" id="purchase_invoice_detail_ref_document_identity_'+$grid_row+'" value="'+$obj['document_identity']+'" />';
    $html += '<a target="_blank" href="'+$obj['href']+'">'+$obj['document_identity']+'</a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="getProductByCode(this);" type="text" style="min-width: 100px;" class="form-control" name="purchase_invoice_details['+$grid_row+'][product_code]" id="purchase_invoice_detail_product_code_'+$grid_row+'" value="'+$obj['product_code']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<div class="input-group">';
    $html += '<select style="min-width: 100px;" onchange="getProductById(this);" class="form-control select2 product" id="purchase_invoice_detail_product_id_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][product_id]" >';
    $html += '<option value="">&nbsp;</option>';
//    $products.forEach(function($product) {
//        if($product['product_id'] == $obj['product_id']) {
//            $html += '<option value="'+$product.product_id+'" selected="true">'+$product.name+'</option>';
//        } else {
//            $html += '<option value="'+$product.product_id+'">'+$product.name+'</option>';
//        }
//    });
    $html += '</select>';
    $html += '<span class="input-group-btn ">';
    $html += '<button class="btn btn-default btn-flat QSearchProduct" id="QSearchProduct" type="button" data-element="purchase_invoice_detail_product_id_'+$grid_row+'" data-field="product_id">';
    $html += '<i class="fa fa-search"></i>';
    $html += '</button>';
    $html += '</span>';
    $html += '</div>';
    $html += '</td>';
    $html += '<td>';
    $html += '<select class="form-control select2" id="purchase_invoice_detail_warehouse_id_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][warehouse_id]" >';
    $html += '<option value="">&nbsp;</option>';
    $warehouses.forEach(function($warehouse) {
        if($warehouse['warehouse_id'] == $obj['warehouse_id']) {
            $html += '<option value="'+$warehouse.warehouse_id+'" selected="true">'+$warehouse.name+'</option>';
        } else {
            $html += '<option value="'+$warehouse.warehouse_id+'">'+$warehouse.name+'</option>';
        }
    });
    $html += '</select>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateAmount(this)" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][qty]" id="purchase_invoice_detail_qty_'+$grid_row+'" value="'+$obj['qty']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="purchase_invoice_details['+$grid_row+'][unit]" id="purchase_invoice_detail_unit_'+$grid_row+'" value="'+$obj['unit']+'" readonly="true" />';
    $html += '<input type="hidden" class="form-control" name="purchase_invoice_details['+$grid_row+'][unit_id]" id="purchase_invoice_detail_unit_id_'+$grid_row+'" value="'+$obj['unit_id']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" onchange="calculateAmount(this);" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][rate]" id="purchase_invoice_detail_rate_'+$grid_row+'" value="'+$obj['rate']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][amount]" id="purchase_invoice_detail_amount_'+$grid_row+'" value="'+$obj['amount']+'" readonly="true" />';
    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateDiscountAmount(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][discount_percent]" id="purchase_invoice_detail_discount_percent_'+$grid_row+'" value="0" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateDiscountPercent(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][discount_amount]" id="purchase_invoice_detail_discount_amount_'+$grid_row+'" value="0" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][gross_amount]" id="purchase_invoice_detail_gross_amount_'+$grid_row+'" value="'+$obj['amount']+'" readonly="true"/>';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateTaxAmount(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][tax_percent]" id="purchase_invoice_detail_tax_percent_'+$grid_row+'" value="0" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateTaxPercent(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][tax_amount]" id="purchase_invoice_detail_tax_amount_'+$grid_row+'" value="0" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][net_amount]" id="purchase_invoice_detail_net_amount_'+$grid_row+'" value="'+$obj['net_amount']+'" readonly="true" />';
//    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][remarks]" id="purchase_invoice_detail_remarks_'+$grid_row+'" value="" />';
    $html += '</td>';
    $html += '<td><a onclick="removeRow(this);" title="Remove" class="btn btn-sm btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a></td>';
    $html += '</tr>';


    $('#tblPurchaseInvoice tbody').prepend($html);
    $('#purchase_invoice_detail_product_id_'+$grid_row).select2({
        width: '100%',
        ajax: {
            url: $UrlGetProductJSON,
            dataType: 'json',
            type: 'post',
            mimeType:"multipart/form-data",
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 5,
        templateResult: formatRepo, // omitted for brevity, see the source of this page
        templateSelection: formatRepoSelection // omitted for brevity, see the source of this page                }
    });
    $('#purchase_invoice_detail_warehouse_id_'+$grid_row).select2({width: '100%'});
    $grid_row++;
    
    calculateAmount($obj);
}

$(document).on('click','.btnAddGrid', function() {
    $html = '';
    $html += '<tr id="grid_row_'+$grid_row+'" data-row_id="'+$grid_row+'">';
    $html += '<td>';
    $html += '<a title="Duplicate" class="btn btn-xs btn-primary btnAddDuplicate" href="javascript:void(0);"><i class="fa fa-clone"></i></a>&nbsp;';
    $html += '<a title="Add" class="btn btn-xs btn-primary btnAddGrid" href="javascript:void(0);"><i class="fa fa-plus"></i></a>&nbsp;';
    $html += '<a onclick="removeRow(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="purchase_invoice_details['+$grid_row+'][ref_document_type_id]" id="purchase_invoice_detail_ref_document_type_id_'+$grid_row+'" value="" />';
    $html += '<input type="hidden" name="purchase_invoice_details['+$grid_row+'][ref_document_identity]" id="purchase_invoice_detail_ref_document_identity_'+$grid_row+'" value="" />';
    $html += '&nbsp;';
    $html += '</td>';
    $html += '<td>';
    $html += '<select class="form-control select2" id="purchase_invoice_detail_warehouse_id_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][warehouse_id]" >';
    $html += '<option value="">&nbsp;</option>';
    $warehouses.forEach(function($warehouse) {
        $html += '<option value="'+$warehouse.warehouse_id+'">'+$warehouse.name+'</option>';
    });
    $html += '</select>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="getProductByCode(this);" type="text" style="min-width: 100px;" class="form-control" name="purchase_invoice_details['+$grid_row+'][product_code]" id="purchase_invoice_detail_product_code_'+$grid_row+'" value="" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<div class="input-group">';
    $html += '<select style="min-width: 300px;" onchange="getProductById(this);" class="form-control select2" id="purchase_invoice_detail_product_id_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][product_id]" >';
    $html += '<option value="">&nbsp;</option>';
//    $products.forEach(function($product) {
//        $html += '<option value="'+$product.product_id+'">'+$product.name+'</option>';
//    });
    $html += '</select>';
    $html += '<span class="input-group-btn ">';
    $html += '<button class="btn btn-default btn-flat QSearchProduct" id="QSearchProduct" type="button" data-element="purchase_invoice_detail_product_id_'+$grid_row+'" data-field="product_id">';
    $html += '<i class="fa fa-search"></i>';
    $html += '</button>';
    $html += '</span>';
    $html += '</div>';
    $html += '</td>';
//    $html += '<td>';
//    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" id="purchase_invoice_detail_cubic_meter_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][cubic_meter]" value="0" readonly/>';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" id="purchase_invoice_detail_cubic_feet_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][cubic_feet]" value="0" readonly/>';
//    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][container_no]" id="purchase_invoice_detail_container_no_'+$grid_row+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][batch_no]" id="purchase_invoice_detail_batch_no_'+$grid_row+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" class="form-control" id="purchase_invoice_detail_unit_id_'+$grid_row+'" value="" />';
    $html += '<input onchange="calculateAmount(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][qty]" id="purchase_invoice_detail_qty_'+$grid_row+'" value="1" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateTotalCubicFeet(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][total_cubic_meter]" id="purchase_invoice_detail_total_cubic_meter_'+$grid_row+'" value=""/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateTotalCubicMeter(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][total_cubic_feet]" id="purchase_invoice_detail_total_cubic_feet_'+$grid_row+'" value=""/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" onchange="calculateAmount(this);" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][rate]" id="purchase_invoice_detail_rate_'+$grid_row+'" value="0.00" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_amount_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][amount]" value="0.00" readonly="true" />';
    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_ledger_amount_'+$grid_row+'" value="0.00" readonly="true" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_after_ledger_amount_'+$grid_row+'" value="0.00" readonly="true" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_new_rate_'+$grid_row+'" value="0.00" readonly="true" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateDiscountAmount(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][discount_percent]" id="purchase_invoice_detail_discount_percent_'+$grid_row+'" value="0" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateDiscountPercent(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][discount_amount]" id="purchase_invoice_detail_discount_amount_'+$grid_row+'" value="0.00" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_gross_amount_'+$grid_row+'" value="" readonly="true"/>';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateTaxAmount(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][tax_percent]" id="purchase_invoice_detail_tax_percent_'+$grid_row+'" value="0" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateTaxPercent(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][tax_amount]" id="purchase_invoice_detail_tax_amount_'+$grid_row+'" value="0.00" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_net_amount_'+$grid_row+'" value="" readonly="true" />';
//    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="purchase_invoice_details['+$grid_row+'][remarks]" id="purchase_invoice_detail_remarks_'+$grid_row+'" value="" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<a title="Duplicate" class="btn btn-xs btn-primary btnAddDuplicate" href="javascript:void(0);"><i class="fa fa-clone"></i></a>&nbsp;';
    $html += '<a title="Add" class="btn btn-xs btn-primary btnAddGrid" href="javascript:void(0);"><i class="fa fa-plus"></i></a>&nbsp;';
    $html += '<a onclick="removeRow(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '</tr>';


    if($(this).parent().parent().data('row_id')=='H') {
        $('#tblPurchaseInvoice tbody').prepend($html);
    } else {
        $(this).parent().parent().after($html);
    }
    //$('#purchase_invoice_detail_product_id_'+$grid_row).select2({width: '100%'});
    $('#purchase_invoice_detail_product_id_'+$grid_row).select2({
        width: '100%',
        ajax: {
            url: $UrlGetProductJSON,
            dataType: 'json',
            type: 'post',
            mimeType:"multipart/form-data",
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 5,
        templateResult: formatRepo, // omitted for brevity, see the source of this page
        templateSelection: formatRepoSelection // omitted for brevity, see the source of this page                }
    });
    $('#purchase_invoice_detail_warehouse_id_'+$grid_row).select2({width: '100%'});
    $('#purchase_invoice_detail_warehouse_id_'+$grid_row).trigger('change');

    $grid_row++;
});

$(document).on('click','.btnAddDuplicate', function() {
    var $row_id = $(this).parent().parent().data('row_id');
    var $warehouse_id = $('#purchase_invoice_detail_warehouse_id_'+$row_id+' option:selected').val();
    var $product_code = $('#purchase_invoice_detail_product_code_'+$row_id).val();
    var $product_id = $('#purchase_invoice_detail_product_id_'+$row_id+' option:selected').val();
    var $product_name = $('#purchase_invoice_detail_product_id_'+$row_id+' option:selected').text();
    var $cubic_meter = $('#purchase_invoice_detail_cubic_meter_'+$row_id).val();
    var $cubic_feet = $('#purchase_invoice_detail_cubic_feet_'+$row_id).val();
    var $container_no = $('#purchase_invoice_detail_container_no_'+$row_id).val();
    var $batch_no = $('#purchase_invoice_detail_batch_no_'+$row_id).val();
    var $unit_id = $('#purchase_invoice_detail_unit_id_'+$row_id).val();
    var $qty = $('#purchase_invoice_detail_qty_'+$row_id).val();
    var $total_cubic_meter = $('#purchase_invoice_detail_total_cubic_meter_'+$row_id).val();
    var $total_cubic_feet = $('#purchase_invoice_detail_total_cubic_feet_'+$row_id).val();
    var $rate = $('#purchase_invoice_detail_rate_'+$row_id).val();
    var $amount = $('#purchase_invoice_detail_amount_'+$row_id).val();
    var $ledger_amount = $('#purchase_invoice_detail_ledger_amount_'+$row_id).val();
    var $after_ledger_amount = $('#purchase_invoice_detail_after_ledger_amount_'+$row_id).val();
    var $new_rate = $('#purchase_invoice_detail_new_rate_'+$row_id).val();
    var $discount_percent = $('#purchase_invoice_detail_discount_percent_'+$row_id).val();
    var $discount_amount = $('#purchase_invoice_detail_discount_amount_'+$row_id).val();
    var $gross_amount = $('#purchase_invoice_detail_gross_amount_'+$row_id).val();
    var $tax_percent = $('#purchase_invoice_detail_tax_percent_'+$row_id).val();
    var $tax_amount = $('#purchase_invoice_detail_tax_amount_'+$row_id).val();
    var $net_amount = $('#purchase_invoice_detail_net_amount_'+$row_id).val();
    var $remarks = $('#purchase_invoice_detail_remarks_'+$row_id).val();

    $html = '';
    $html += '<tr id="grid_row_'+$grid_row+'" data-row_id="'+$grid_row+'">';
    $html += '<td>';
    $html += '<a title="Duplicate" class="btn btn-xs btn-primary btnAddDuplicate" href="javascript:void(0);"><i class="fa fa-clone"></i></a>&nbsp;';
    $html += '<a title="Add" class="btn btn-xs btn-primary btnAddGrid" href="javascript:void(0);"><i class="fa fa-plus"></i></a>&nbsp;';
    $html += '<a onclick="removeRow(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="purchase_invoice_details['+$grid_row+'][ref_document_type_id]" id="purchase_invoice_detail_ref_document_type_id_'+$grid_row+'" value="" />';
    $html += '<input type="hidden" name="purchase_invoice_details['+$grid_row+'][ref_document_identity]" id="purchase_invoice_detail_ref_document_identity_'+$grid_row+'" value="" />';
    $html += '&nbsp;';
    $html += '</td>';
    $html += '<td>';
    $html += '<select class="form-control select2" id="purchase_invoice_detail_warehouse_id_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][warehouse_id]" >';
    $html += '<option value="">&nbsp;</option>';
    $warehouses.forEach(function($warehouse) {
        if($warehouse_id==$warehouse.warehouse_id) {
            $html += '<option value="'+$warehouse.warehouse_id+'" selected="true">'+$warehouse.name+'</option>';
        } else {
            $html += '<option value="'+$warehouse.warehouse_id+'">'+$warehouse.name+'</option>';
        }
    });
    $html += '</select>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="getProductByCode(this);" type="text" style="min-width: 100px;" class="form-control" name="purchase_invoice_details['+$grid_row+'][product_code]" id="purchase_invoice_detail_product_code_'+$grid_row+'" value="'+$product_code+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<div class="input-group">';
    $html += '<select style="min-width: 100px;" onchange="getProductById(this);" class="form-control select2" id="purchase_invoice_detail_product_id_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][product_id]" >';
    $html += '<option selected="true" value="'+$product_id+'">'+$product_name+'</option>';
    $html += '</select>';
    $html += '<span class="input-group-btn ">';
    $html += '<button class="btn btn-default btn-flat QSearchProduct" id="QSearchProduct" type="button" data-element="purchase_invoice_detail_product_id_'+$grid_row+'" data-field="product_id">';
    $html += '<i class="fa fa-search"></i>';
    $html += '</button>';
    $html += '</span>';
    $html += '</div>';
    $html += '</td>';
//    $html += '<td>';
//    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" id="purchase_invoice_detail_cubic_meter_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][cubic_meter]" value="0" readonly/>';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" id="purchase_invoice_detail_cubic_feet_'+$grid_row+'" name="purchase_invoice_details['+$grid_row+'][cubic_feet]" value="0" readonly/>';
//    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][container_no]" id="purchase_invoice_detail_container_no_'+$grid_row+'" value="'+$container_no+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][batch_no]" id="purchase_invoice_detail_batch_no_'+$grid_row+'" value="'+$batch_no+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" class="form-control" name="purchase_invoice_details['+$grid_row+'][unit_id]" id="purchase_invoice_detail_unit_id_'+$grid_row+'" value="'+$unit_id+'" />';
    $html += '<input onchange="calculateAmount(this)" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][qty]" id="purchase_invoice_detail_qty_'+$grid_row+'" value="'+$qty+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateTotalCubicFeet(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][total_cubic_meter]" id="purchase_invoice_detail_total_cubic_meter_'+$grid_row+'" value="'+$total_cubic_meter+'"/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateTotalCubicMeter(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][total_cubic_feet]" id="purchase_invoice_detail_total_cubic_feet_'+$grid_row+'" value="'+$total_cubic_feet+'"/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateAmount(this)" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][rate]" id="purchase_invoice_detail_rate_'+$grid_row+'" value="'+$rate+'" readonly/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_amount_'+$grid_row+'" value="'+$amount+'" readonly="true" />';
    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_ledger_amount_'+$grid_row+'" value="'+$ledger_amount+'" readonly="true" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_after_ledger_amount_'+$grid_row+'" value="'+$after_ledger_amount+'" readonly="true" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" id="purchase_invoice_detail_new_rate_'+$grid_row+'" value="'+$new_rate+'" readonly="true" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateDiscountAmount(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][discount_percent]" id="purchase_invoice_detail_discount_percent_'+$grid_row+'" value="'+$discount_percent+'" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateDiscountPercent(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][discount_amount]" id="purchase_invoice_detail_discount_amount_'+$grid_row+'" value="'+$discount_amount+'" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][gross_amount]" id="purchase_invoice_detail_gross_amount_'+$grid_row+'" value="'+$gross_amount+'" readonly="true"/>';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateTaxAmount(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][tax_percent]" id="purchase_invoice_detail_tax_percent_'+$grid_row+'" value="'+$tax_percent+'" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input onchange="calculateTaxPercent(this);" type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][tax_amount]" id="purchase_invoice_detail_tax_amount_'+$grid_row+'" value="'+$tax_amount+'" />';
//    $html += '</td>';
//    $html += '<td>';
//    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_invoice_details['+$grid_row+'][net_amount]" id="purchase_invoice_detail_net_amount_'+$grid_row+'" value="'+$net_amount+'" readonly="true" />';
//    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="purchase_invoice_details['+$grid_row+'][remarks]" id="purchase_invoice_detail_remarks_'+$grid_row+'" value="'+$remarks+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<a title="Duplicate" class="btn btn-xs btn-primary btnAddDuplicate" href="javascript:void(0);"><i class="fa fa-clone"></i></a>&nbsp;';
    $html += '<a title="Add" class="btn btn-xs btn-primary btnAddGrid" href="javascript:void(0);"><i class="fa fa-plus"></i></a>&nbsp;';
    $html += '<a onclick="removeRow(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '</tr>';


    $('#tblPurchaseInvoice tbody #grid_row_' + $row_id).after($html);
    $('#purchase_invoice_detail_product_id_'+$grid_row).select2({
        width: '100%',
        ajax: {
            url: $UrlGetProductJSON,
            dataType: 'json',
            type: 'post',
            mimeType:"multipart/form-data",
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 5,
        templateResult: formatRepo, // omitted for brevity, see the source of this page
        templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
    });
    $('#purchase_invoice_detail_warehouse_id_'+$grid_row).select2({width: '100%'});
    $grid_row++;
    calculateRowTotal(this);
});

function getProductById($obj) {
    $product_id = $($obj).val();
    var $row_id = $($obj).parent().parent().parent().data('row_id');
    $.ajax({
        url: $UrlGetProductById,
        dataType: 'json',
        type: 'post',
        data: 'product_id=' + $product_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#grid_row_'+$row_id+' .QSearchProduct i').removeClass('fa-search').addClass('fa-refresh fa-spin');
        },
        complete: function() {
            $('#grid_row_'+$row_id+' .QSearchProduct i').removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-search');
        },
        success: function(json) {
            if(json.success)
            {
                $('#purchase_invoice_detail_product_code_'+$row_id).val(json.product['product_code']);
                $('#purchase_invoice_detail_unit_id_'+$row_id).val(json.product['unit_id']);
                $('#purchase_invoice_detail_cubic_meter_'+$row_id).val(json.product['cubic_meter']);
                $('#purchase_invoice_detail_cubic_feet_'+$row_id).val(json.product['cubic_feet']);
                $('#purchase_invoice_detail_rate_'+$row_id).val(json.product['cost_price']);

                $('#purchase_invoice_detail_rate_'+$row_id).trigger('change');
                $('#purchase_invoice_detail_discount_percent_'+$row_id).trigger('change');
                $('#purchase_invoice_detail_tax_percent_'+$row_id).trigger('change');
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
    calculateAmount($obj);
}

function getProductByCode($obj) {
    $product_code = $($obj).val();
    var $row_id = $($obj).parent().parent().data('row_id');
    $.ajax({
        url: $UrlGetProductByCode,
        dataType: 'json',
        type: 'post',
        data: 'product_code=' + $product_code,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#grid_row_'+$row_id+' .QSearchProduct i').removeClass('fa-search').addClass('fa-refresh fa-spin');
        },
        complete: function() {
            $('#grid_row_'+$row_id+' .QSearchProduct i').removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-search');
        },
        success: function(json) {
            $('#purchase_invoice_detail_product_id_'+$row_id).select2('destroy');
            if(json.success)
            {
                $('#purchase_invoice_detail_unit_id_'+$row_id).val(json.product['unit_id']);
                $('#purchase_invoice_detail_unit_'+$row_id).val(json.product['unit']);
                $('#purchase_invoice_detail_product_id_'+$row_id).html('<option selected="selected" value="'+json.product['product_id']+'">'+json.product['name']+'</option>');
                $('#purchase_invoice_detail_rate_'+$row_id).val(json.product['cost_price']);
                $('#purchase_invoice_detail_cubic_meter_'+$row_id).val(json.product['cubic_meter']);
                $('#purchase_invoice_detail_cubic_feet_'+$row_id).val(json.product['cubic_feet']);

                $('#purchase_invoice_detail_rate_'+$row_id).trigger('change');
                $('#purchase_invoice_detail_discount_percent_'+$row_id).trigger('change');
                $('#purchase_invoice_detail_tax_percent_'+$row_id).trigger('change');
            } else {
                alert(json.error);
                $('#purchase_invoice_detail_unit_id_'+$row_id).val('');
                $('#purchase_invoice_detail_unit_'+$row_id).val('');
                $('#purchase_invoice_detail_product_id_'+$row_id).html('');
                $('#purchase_invoice_detail_rate_'+$row_id).val('0.00');
            }
            $('#purchase_invoice_detail_product_id_'+$row_id).select2({
                width: '100%',
                ajax: {
                    url: $UrlGetProductJSON,
                    dataType: 'json',
                    type: 'post',
                    mimeType:"multipart/form-data",
                    delay: 250,
                    data: function (params) {
                        return {
                            q: params.term, // search term
                            page: params.page
                        };
                    },
                    processResults: function (data, params) {
                        // parse the results into the format expected by Select2
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data, except to indicate that infinite
                        // scrolling can be used
                        params.page = params.page || 1;

                        return {
                            results: data.items,
                            pagination: {
                                more: (params.page * 30) < data.total_count
                            }
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 5,
                templateResult: formatRepo, // omitted for brevity, see the source of this page
                templateSelection: formatRepoSelection // omitted for brevity, see the source of this page                }
            });
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
    calculateAmount($obj);
}

function setProductInformation($obj) {
    var $data = $($obj).data();
    console.log($data);
    var $row_id = $('#'+$data['element']).parent().parent().parent().data('row_id');
    $('#_modal').modal('hide');
    $('#purchase_invoice_detail_product_code_'+$row_id).val($data['product_code']);
    $('#purchase_invoice_detail_cubic_meter_'+$row_id).val($data['cubic_meter']);
    $('#purchase_invoice_detail_cubic_feet_'+$row_id).val($data['cubic_feet']);
    $('#purchase_invoice_detail_unit_id_'+$row_id).val($data['unit_id']);
    $('#purchase_invoice_detail_unit_'+$row_id).val($data['unit']);
    $('#purchase_invoice_detail_rate_'+$row_id).val($data['cost_price']);
    $('#purchase_invoice_detail_product_id_'+$row_id).select2('destroy');
    $('#purchase_invoice_detail_product_id_'+$row_id).html('<option selected="selected" value="'+$data['product_id']+'">'+$data['name']+'</option>');
    $('#purchase_invoice_detail_product_id_'+$row_id).select2({
        width: '100%',
        ajax: {
            url: $UrlGetProductJSON,
            dataType: 'json',
            type: 'post',
            mimeType:"multipart/form-data",
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 5,
        templateResult: formatRepo, // omitted for brevity, see the source of this page
        templateSelection: formatRepoSelection // omitted for brevity, see the source of this page                }
    });
}

function removeRow($obj) {
    //console.log($obj);
    var $row_id = $($obj).parent().parent().data('row_id');
    $('#grid_row_'+$row_id).remove();
    calculateLedger();
    calculateAmount($obj);
}

function calculateTotalCubicFeet($obj) {
    var $rate_type =  $("input[name='rate_type']:checked"). val();
    var $row_id = $($obj).parent().parent().data('row_id');
    var $total_cubic_meter = parseFloat($('#purchase_invoice_detail_total_cubic_meter_' + $row_id).val() || 0.0000000);
     if($rate_type=='LOG') {
        var $total_cubic_feet = parseFloat($total_cubic_meter*27.750).toFixed(4);
     }
     else
     {
        var $total_cubic_feet = parseFloat($total_cubic_meter*35.3147).toFixed(4);  
     }
    $('#purchase_invoice_detail_total_cubic_feet_' + $row_id).val($total_cubic_feet);
    calculateRowTotal($obj);
    calculateAmount($obj);
}

function calculateTotalCubicMeter($obj) {
    var $rate_type =  $("input[name='rate_type']:checked"). val();
    var $row_id = $($obj).parent().parent().data('row_id');
    var $total_cubic_feet = parseFloat($('#purchase_invoice_detail_total_cubic_feet_' + $row_id).val() || 0.0000000);
    if($rate_type=='LOG') {
        var $total_cubic_meter = parseFloat($total_cubic_feet/27.750).toFixed(4);
    } else {
        var $total_cubic_meter = parseFloat($total_cubic_feet/35.3147).toFixed(4);
    }    
    var $total_cubic_meter = parseFloat($total_cubic_feet/35.3147).toFixed(4);
    $('#purchase_invoice_detail_total_cubic_meter_' + $row_id).val($total_cubic_meter);    
    calculateRowTotal($obj);
    calculateAmount($obj);
}

function calculateRowTotal($obj) {
    // var $cubic_meter_master = 0;
    // var $cubic_feet_master = 0;

    // $('#tblPurchaseInvoice tbody tr').each(function() {
    //     var $row_id = $(this).data('row_id');
    //     var $cubic_meter = $('#purchase_invoice_detail_total_cubic_meter_' + $row_id).val() || 0;
    //     var $cubic_feet = $('#purchase_invoice_detail_total_cubic_feet_' + $row_id).val() || 0;

    //     $cubic_meter_master += parseFloat($cubic_meter);
    //     $cubic_feet_master += parseFloat($cubic_feet);
    // });
    // $cubic_meter_master = parseFloat($cubic_meter_master).toFixed(4);
    // $cubic_feet_master = ($cubic_meter_master*35.3147).toFixed(4);
    // $('#total_cubic_meter').val($cubic_meter_master)
    // $('#total_cubic_feet').val($cubic_feet_master)

    var $row_id = $($obj).parent().parent().data('row_id');
    var $amount = parseFloat($('#purchase_invoice_detail_amount_' + $row_id).val());
    var $gross_amount = roundUpto($amount,2);
    var $total_amount = roundUpto($gross_amount,2);
    $('#purchase_invoice_detail_gross_amount_' + $row_id).val($gross_amount.toFixed(0));
    $('#purchase_invoice_detail_total_amount_' + $row_id).val($total_amount.toFixed(0));
    calculateTotal();
    calculateAmount($obj);
}

function calculateTotal() {
    var $item_amount = 0;
    var $item_total = 0;
    var $total_quantity = 0;
    var $total_cubic_meter = 0;
    var $total_cubic_feet = 0;
    $('#tblPurchaseInvoice tbody tr').each(function() {
        var $row_id = $(this).data('row_id');
        var $amount = $('#purchase_invoice_detail_amount_' + $row_id).val();
        var $total_amount = $('#purchase_invoice_detail_total_amount_' + $row_id).val();
        var $quantity = $('#purchase_invoice_detail_qty_' + $row_id).val();
        var $cubic_meter = $('#purchase_invoice_detail_total_cubic_meter_' + $row_id).val();
        var $cubic_feet = $('#purchase_invoice_detail_total_cubic_feet_' + $row_id).val();

        $item_amount += parseFloat($amount);
        $item_total += parseFloat($total_amount);
        $total_quantity += parseFloat($quantity);
        $total_cubic_meter += parseFloat($cubic_meter);
        $total_cubic_feet += parseFloat($cubic_feet);
    });
    $('#total_quantity').val(roundUpto($total_quantity,0));
    $('#total_cubic_meter').val(roundUpto($total_cubic_meter,4));
    //$('#total_cubic_feet').val(roundUpto($total_cubic_meter * 35.3147,4));
    $('#total_cubic_feet').val(roundUpto($total_cubic_feet,4));
    var $net_amount = parseFloat($item_total);
    //console.log($discount_amount, $labour_charges, $misc_charges, $net_amount, $cash_received, $balance_amount);
    $('#item_amount').val(roundUpto($item_amount,2));
    $('#item_total').val(roundUpto($item_total,2));
    $('#net_amount').val(roundUpto($net_amount,2));
}

$(document).on('click','.btnAddLedger', function() {
    $html = '';
    $html += '<tr id="ledger_row_'+$ledger_row+'" data-ledger_row="'+$ledger_row+'">';
    $html += '<td>';
    $html += '<a onclick="removeLedger(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<select class="form-control select2" id="purchase_invoice_ledger_'+$ledger_row+'_coa_id" name="purchase_invoice_ledgers['+$ledger_row+'][coa_id]" >';
    $html += '<option value="">&nbsp;</option>';
    $coas.forEach(function($coa) {
        $html += '<option value="'+$coa.coa_level3_id+'">'+$coa.level3_display_name+'</option>';
    });
    $html += '</select>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateLedger(this);" type="text" style="min-width: 100px;" class="form-control fPdecimal text-right" name="purchase_invoice_ledgers['+$ledger_row+'][debit]" id="purchase_invoice_ledger_'+$ledger_row+'_debit" value="" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateLedger(this);" type="text" style="min-width: 100px;" class="form-control fPdecimal text-right" name="purchase_invoice_ledgers['+$ledger_row+'][credit]" id="purchase_invoice_ledger_'+$ledger_row+'_credit" value="" />';
    $html += '</td>';
    $html += '</tr>';

    $('#tblLedger tbody').prepend($html);
    $('#purchase_invoice_ledger_'+$ledger_row+'_coa_id').select2();
    $ledger_row++;
});


function calculateLedger(obj) {
    var $total_debit = 0;
    var $total_credit = 0;
    var $total_amount = 0;
    var $total_qty = 0;

    $('#tblLedger tbody tr').each(function() {
        var $row_id = $(this).data('ledger_row');
        var $debit = $('#purchase_invoice_ledger_' + $row_id + '_debit').val() || 0;
        var $credit = $('#purchase_invoice_ledger_' + $row_id + '_credit').val() || 0;

        $total_debit += parseFloat($debit);
        $total_credit += parseFloat($credit);
    });

    $('#total_debit').val($total_debit);
    $('#total_credit').val($total_credit);
    var $total_cubic_feet = $('#total_cubic_feet').val();

    $('#tblPurchaseInvoice tbody tr').each(function() {
        var $row_id = $(this).data('row_id');
        var $cubic_feet = $('#purchase_invoice_detail_total_cubic_feet_' + $row_id).val();
        var $qty = $('#purchase_invoice_detail_qty_' + $row_id).val();

        var $amount = parseFloat(($total_debit/$total_cubic_feet) * $cubic_feet) || 0;
        var $rate = parseFloat($amount/$cubic_feet) || 0;
        $('#purchase_invoice_detail_amount_' + $row_id).val(roundUpto($amount,4));
        $('#purchase_invoice_detail_rate_' + $row_id).val(roundUpto($rate,4));

        $total_amount += parseFloat($amount);
        $total_qty += parseFloat($qty);
        //console.log($rate,$amount);
     });

    $('#item_amount').val(roundUpto($total_amount,4));
    $('#total_quantity').val(roundUpto($total_qty,0));
    if($total_credit != $total_debit){
        $('#btnsave').attr('disabled','disabled');
        $('#DebitCreditError').show();
    }
    else{
        $('#btnsave').removeAttr('disabled');
        $('#DebitCreditError').hide();
    }
}


function removeLedger($obj) {
    //console.log($obj);
    var $row_id = $($obj).parent().parent().data('ledger_row');
    console.log($row_id);
    $('#ledger_row_'+$row_id).remove();
    calculateLedger();
    calculateTotal();
}

$(document).on('click','.btnAddExpense', function() {
    $html = '';
    $html += '<tr id="expense_row_'+$expense_row+'" data-expense_row="'+$expense_row+'">';
    $html += '<td>';
    $html += '<a onclick="removeExpense(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<select class="form-control select2" id="purchase_invoice_expense_'+$expense_row+'_inventory_expense_id" name="purchase_invoice_expenses['+$expense_row+'][inventory_expense_id]" >';
    $html += '<option value="">&nbsp;</option>';
    $inventory_expenses.forEach(function($expense) {
        $html += '<option value="'+$expense['inventory_expense_id']+'">'+$expense['name']+'</option>';
    });
    $html += '</select>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateExpense(this);" type="text" style="min-width: 100px;" class="form-control fPdecimal text-right" name="purchase_invoice_expenses['+$expense_row+'][expense_amount]" id="purchase_invoice_expense_'+$expense_row+'_expense_amount" value="" />';
    $html += '</td>';
    $html += '</tr>';

    $('#tblExpense tbody').prepend($html);
    $('#purchase_invoice_expense_'+$expense_row+'_inventory_expense_id').select2();
    $expense_row++;
});

function calculateExpense(obj) {
    var $total_amount = 0;

    $('#tblExpense tbody tr').each(function() {
        var $row_id = $(this).data('expense_row');
        var $amount = $('#purchase_invoice_expense_' + $row_id + '_expense_amount').val() || 0;

        $total_amount += parseFloat($amount);
    });

    $('#total_expense').val($total_amount);
}

function removeExpense($obj) {
    var $row_id = $($obj).parent().parent().data('expense_row');
    $('#expense_row_'+$row_id).remove();
    calculateExpense();
}

function calculateAmount($obj) {
    var $rate_type =  $("input[name='rate_type']:checked"). val();
    var $row_id = $($obj).parent().parent().data('row_id');
    // alert($rate_type);
    var $total_cubic_meter = parseFloat($('#purchase_invoice_detail_total_cubic_meter_' + $row_id).val()) || 0.00;
    var $total_cubic_feet = parseFloat($('#purchase_invoice_detail_total_cubic_feet_' + $row_id).val()) || 0.00;
    var $qty = parseFloat($('#purchase_invoice_detail_qty_' + $row_id).val()) || 0.00;
    var $rate = parseFloat($('#purchase_invoice_detail_rate_' + $row_id).val()) || 0.00;
    if($rate_type=='PCS') {
        var $amount = $qty * $rate;
    } else {
        var $amount = $total_cubic_feet * $rate;
    }
    $amount = roundUpto($amount,2);
    $('#purchase_invoice_detail_amount_' + $row_id).val($amount.toFixed(0));
    calculateTotal();
}
