<style type="text/css">
    .amount{
        text-align: right;
    } 
    .btn-group button{
        height:30px;
        padding:3px;
    }
    #content .wrap #grid_content_1 .row-fluid.scRow .row-fluid.scRow .span12.scCol #grid_block_5 .content.np #listDetails tbody #trInfos td .row-fluid .controls-row .span3 {
        font-size: 11px;
        color: #000;
        font-weight: bold;
    }
    .test {
        font-size: 10px;
    }
    .span3 {
        font-size: 10px;
    }
    tbody td { font-size:11px;}
    #content .wrap #grid_content_1 .row-fluid.scRow .row-fluid.scRow .span12.scCol #grid_block_6 .content.np #listCharge tbody #trInfosCharge td .row-fluid .controls-row .span3 {
        font-weight: bold;
    }
</style>
<?php
foreach ($taxmaster as $k => $v) {
    $val = null;
    $val = array_search('NR', (array) $taxmaster[$k]);
    if ($val != null) {
        $nonGstTaxID = $taxmaster[$k]->ID;
        break;
    }
}
?>
<script>

    var gstStatus = true;
            $(document).ready(function(){

    gstStatus = isGstRegistered($('#supplier').attr('data-supplierid'), 'supplier');
            $('select').select2();
            jQuery('.datepicker2').datepicker({
    dateFormat : 'dd-mm-yy',
            changeMonth : true,
            changeYear : true
    });
    }
    );
            function getLatestItemPrice(){
            //var qtyInvoice = parseFloat($("#itemInvoice").attr("data-qtyInvoice"))* $("#idUnitOfMeasure option:selected").attr("data-factor")/$("#idUnitOfMeasure option:selected").attr("data-unitm");
            var prevQty = accounting.unformat($("#itemInvoice").val());
                    var qtyInvoice = (accounting.unformat($("#itemInvoice").attr("data-qtyInvoice")) / accounting.unformat($("#itemInvoice").attr("data-unitm"))) * accounting.unformat($("#itemInvoice").attr("data-factor"));
                    var qtyInvoice = (qtyInvoice * accounting.unformat($("#idUnitOfMeasure option:selected").attr("data-unitm"))) / accounting.unformat($("#idUnitOfMeasure option:selected").attr("data-factor"));
                    $("#itemInvoice").val(accounting.formatNumber(qtyInvoice, 0));
                    var totalItem = (accounting.unformat($("#itemInvoice").attr("data-qtyInvoice")) / accounting.unformat($("#itemInvoice").attr("data-unitm"))) * accounting.unformat($("#itemInvoice").attr("data-factor"));
                    var totalPrice = accounting.unformat($("#itemunitprice").val()) * prevQty;
                    var actualUnitPrice = totalPrice / qtyInvoice;
                    $("#itemunitprice").val(accounting.formatNumber(actualUnitPrice, 5));
                    /* $.ajax({
                     type: "POST",
                     data : {
                     option :'purchase',
                     itemID : $("#itemComboList").val(),
                     datePrice : $("#createdDate").val(),
                     supplierID : $("#supplier").attr("data-supplierID"),
                     umID: $("#idUnitOfMeasure").val(),
                     currencyID: $("#currency").attr('data-curid')
                     },
                     url: "<?php echo base_url() ?>aptransaction/getPrice",
                     success: function(data) {
                     $("#itemunitprice").val(accounting.formatNumber(data,2));
                     }
                     });*/
                    }

    /*	  function getItemDetails(me){
     $("#itemname").val("");
     $("#itemdes").val("");
     $.ajax({
     type: "POST",
     data: "code="+ me.value,
     url: "<?php echo base_url() ?>itemsetup/getItemDetails",
     success: function(data) {
     if(data!="item Not found"){
     var resul = eval ("(" + data + ")");
     $("#itemname").val(resul.description);
     $("#itemdes").val(resul.name);
     $("#itemTax").val(resul.tax);
     }else{
     $("#itemdes").attr("placeholder",data);
     $("#itemname").attr("placeholder",data);
     
     }
     }
     });
     }
     */

    function displaysItemDefaultValue(){
    $("#itemdes").val($("#itemComboList option:selected").attr("data-desc"));
            $("#itemunitprice").val(accounting.formatNumber($("#itemComboList option:selected").attr("data-unitprice"), 2));
            $("#itemTax").val($("#itemComboList option:selected").attr("data-taxPercentage"));
            $("#itemTax").attr("data-taxid", $("#itemComboList option:selected").attr("data-taxid"));
            $("#displayTaxCode").text($("#itemComboList option:selected").attr("data-taxcode"));
            $("#idUnitOfMeasure").select2("val", $("#itemComboList option:selected").attr("data-umid"));
            $("#itemInvoice").val($("#itemComboList option:selected").attr("data-exactQty"));
            $("#itemInvoice").attr("data-qtyInvoice", $("#itemComboList option:selected").attr("data-exactQty"));
            $("#itemqte").val("");
            $("#itemInvoice").val($("#itemComboList option:selected").attr("data-exactQty"));
            $("#itemInvoice").attr("data-qtyInvoice", $("#itemComboList option:selected").attr("data-exactQty"));
            // getLatestItemPrice();
            getItemListOfUM();
    }
    function editRow(me){
    if (!$("#itemComboList").length) {
    var tr = $(me).parent().parent();
            prevUmID = $(tr).find('td:nth-child(4)').attr('data-umid');
            //  alert( $(me).parent().parent().find("td").eq(0).html()); 
            $(tr).replaceWith('<tr><td class="span1">' + $(me).parent().parent().find("td").eq(0).html() + '</td>' +
            '<td class="span1"><select data-lineNo = "' + $(me).parent().parent().find("td").eq(0).html() + '" style="max-width:100%;" data-previewvalue="' + $(me).parent().parent().find("td").eq(1).html() + '" name="itemComboList" id="itemComboList" class="span12" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        $temp = str_replace(array("\n", "\r", "'"), " ", $row->name, $count) . " [" . str_replace(array("\n", "\r", "'"), " ", $row->itemCode, $count) . "]";
        ?>
            '<option data-itemID= "<?php echo $row->itemID; ?>"' +
                    'data-exactQty= "<?php echo $row->exactQty; ?>"' +
                    'data-umCode= "<?php echo $row->unitOfMeasure; ?>"' +
                    'data-defaultCode="<?php echo $row->umCode; ?>"' +
                    'data-defaultUM="<?php echo $row->defaultUM; ?>"' +
                    'data-umID= "<?php echo $row->umID; ?>"' +
                    'data-desc= "<?php echo str_replace(array("\n", "\r", "'"), " ", $row->description, $count); ?>"' +
                    'data-unitPrice= "<?php echo $row->unitPrice; ?>"' +
                    'data-taxid="<?php echo $row->taxID; ?>"' +
                    'data-taxcode="<?php echo $row->code; ?>"' +
                    'data-taxPercentage="<?php echo $row->taxRate; ?>"' +
                    'value="<?php echo $row->invoiceDetailID; ?>"><?php echo $temp; ?>' +
                    '</option>' +
        <?php
    }
}
?>
    '</select>' +
            '</td>' +
            '<td class="span2"><input  id="itemdes" name="itemdes" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(2).html() + '" value="' + $(me).parent().parent().find("td").eq(2).html() + '"></td>' +
            '<td class="span1">' +
            '<select onchange="getLatestItemPrice()" data-previewvalue="' + $(me).parent().parent().find("td").eq(3).html() + '" id="idUnitOfMeasure" class="span12 validate[required]"><option></option></select></td>' +
            '<td class="span1"><input id="itemInvoice"  disabled name="itemInvoice"  class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(4).html() + '" value="' + $(me).parent().parent().find("td").eq(4).html() + '"></td>' +
            '<td class="span1"><input id="itemqte" onkeyup="calculamount()" name="itemqte"  class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(5).html() + '" value="' + $(me).parent().parent().find("td").eq(5).html() + '"></td>' +
            '<td class="span1"><input id="itemunitprice" onkeyup="calculamount()" name="itemunitprice" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(6).html() + '" value="' + $(me).parent().parent().find("td").eq(6).html() + '"></td>' +
            '<td class="span1"><input disabled="disalbed" id="itemAmountET" name="itemAmountET" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(7).html() + '" value="' + $(me).parent().parent().find("td").eq(7).html() + '"></td>' +
            '<td class="span1"><div  class="span12 input-prepend"><input disabled="disalbed" style="max-width: 15px;"  value="' + $(me).attr("data-taxrate") + '" data-taxid="' + $(me).attr("data-taxid") + '" id="itemTax" data-previewvalue="' + $(me).parent().parent().find("td").eq(8).html() + '" onkeyup="calculamount()" onblur="calculamount()" name="itemTax" class="input-mini validate[required, custom[number]]" type="text" placeholder="Tax(%)"><span id="displayTaxCode" style="margin:0;" onclick="taxPopup ()"  class="btn add-on">' + $(me).attr("data-taxcode") + '</span></div></td>' +
            '<td class="span1"><input disabled="disalbed" id="itemTaxAmount" name="itemTaxAmount" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(9).html() + '" value="' + $(me).parent().parent().find("td").eq(9).html() + '"></td>' +
            '<td class="span1"><input disabled="disalbed" id="itemAmountIT" name="itemAmountIT" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(10).html() + '" value="' + $(me).parent().parent().find("td").eq(10).html() + '"></td>' +
            '<td class="span1">' +
            '<button data-invoiceDetailID="' + $(me).attr("data-invoiceDetailID") + '" data-itemid="' + $(me).attr("data-itemid") + '" data-umID="' + $(me).attr("data-umID") + '"  onclick="updateRow(this)" data-taxid="' + $(me).attr("data-taxid") + '"  data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-success-form" type="button"><i class="i-checkmark-3"></i></button>' +
            ' <button data-invoiceDetailID="' + $(me).attr("data-invoiceDetailID") + '" data-itemid="' + $(me).attr("data-itemid") + '" data-umID="' + $(me).attr("data-umID") + '"  id="btnCancel" onclick="cancelEdit(this)" data-taxid="' + $(me).attr("data-taxid") + '"  data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '" data-myid="' + $(me).attr("data-myid") + '"  class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-cross"></i></button></td>' +
            '</tr>'
            );
            $("#itemComboList").val($(me).attr("data-invoiceDetailID"));
            $("#itemComboList").select2();
            // $("#idUnitOfMeasure").val($(me).attr("data-umID"));
            $('#idUnitOfMeasure').select2();
            getItemListOfUM();
            $.each($("#listDetails .select2-container"), function (i, n) {
            $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
                    $(n).prepend($(n).next());
                    $(n).delay(500).queue(function () {
            $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                    $(this).dequeue();
            });
            });
    } else{
    msg (1, "alert", "Please, do save the current details before adding new one");
    }
    }


    function calculamount(){
    if ($("#totalamount").val() == "NaN"){

    $("#totalamount").val("0");
            $("#impotpayable").val("0");
            $("#totalpayable").val("0");
    }
    if (accounting.unformat($("#itemqte").val()) > accounting.unformat($("#itemInvoice").val())){
    $("#itemqte").val("");
            $("#itemqte").attr("style", "background:#F2DEDE;");
    } else{
    $("#itemqte").attr("style", "background:#DFF0D8;");
    }


    var j_itemAmountET = accounting.unformat($("#itemunitprice").val()) * accounting.unformat($("#itemqte").val());
            $("#itemAmountET").val(accounting.formatNumber(j_itemAmountET, 2));
            var j_itemTaxAmount = j_itemAmountET * accounting.unformat($("#itemTax").val()) / 100;
            $("#itemTaxAmount").val(accounting.formatNumber(j_itemTaxAmount, 2));
            $("#itemAmountIT").val(accounting.formatNumber(j_itemTaxAmount + j_itemAmountET, 2));
    }


    function editRowCharge (me){
    var tax = '';
            if (gstStatus){

    tax = '<td class="span2">\
                        <div class="input-prepend">\
                            <input readonly data-taxid="' + $(me).attr("data-taxid") + '" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)" value="' + $(me).attr("data-percent") + '">\
                            <span onclick="taxPopup ()" style="margin-top:0;" id="displayCode" class="btn add-on">' + $(me).attr("data-code") + '</span>\
                        </div>\
                  </td>';
    } else{
    tax = '<td class="span2">\
                        <div class="input-prepend">\
                            <input readonly data-taxid="<?php echo $nonGstTaxID; ?>" value="0" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)">\
                            <span style="margin-top:0;" id="displayCode" class="btn add-on">NR</span>\
                        </div>\
                  </td>';
    }
    var tr = $(me).parent().parent();
            if (!$("#chargeAccount").length) {
    $(tr).replaceWith('<tr>' +
            '<td class="span4"><input disabled data-previewvalue="' + $(me).parent().parent().find("td").eq(0).html() + '"  id="lineNo" name="lineNo"  type="text" class="span12" value="' + $(me).parent().parent().find("td").eq(0).html() + '"></td>' +
            '<td class="span2" ><select data-previewvalue="' + $(me).parent().parent().find("td").eq(1).html() + '" name="chargeAccount" id="chargeAccount" class= "span12 validate[required]"><option></option>' +
<?php
if ($chargeAccount) {
    foreach ($chargeAccount as $row) {
        $temp = str_replace(array("\n", "\r", "'"), " ", $row->acctName, $count);
        ?>
            '<option  value="<?php echo $row->ID; ?>"><?php
        echo substr($row->acctCode, 0, 4) . '-' . substr($row->acctCode, 4, 3) . '-' . substr($row->acctCode, 7) . " | ";
        echo $temp;
        ?></option>' +
        <?php
    }
}
?>
    '</select></td>' +
            '<td class="span4"><input data-previewvalue="' + $(me).parent().parent().find("td").eq(2).html() + '"  id="chargedesc" name="chargedesc"  type="text" class="span12 validate[required]" placeholder="Description" value="' + $(me).parent().parent().find("td").eq(2).html() + '"></td>' +
            '<td class="span1"><input data-previewvalue="' + $(me).parent().parent().find("td").eq(3).html() + '" class="span12" id="chargeAmount" onkeyup="calculChargeAmount()" name="chargeAmount" value="' + $(me).parent().parent().find("td").eq(3).html() + '" class="input-mini validate[required, custom[number]]" type="text" placeholder="Amount"></td>' +
            tax +
            '<td class="span1"> <input data-previewvalue="' + $(me).parent().parent().find("td").eq(5).html() + '" id="chargetaxAmount" value="' + $(me).parent().parent().find("td").eq(5).html() + '"  name="chargetaxAmount" class="span12" type="text" placeholder="Amount"></td>' +
            '<td class="span1"><input data-previewvalue="' + $(me).parent().parent().find("td").eq(6).html() + '" onkeydown="return false;" id="chargeAmountIT" value="' + $(me).parent().parent().find("td").eq(6).html() + '"name="chargeAmountIT" class="span12" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1">' +
            '<button data-myid="' + $(me).attr("data-myid") + '" data-accid="' + $(me).attr("data-accid") + '" data-taxid="' + $(me).attr("data-taxid") + '" onclick = "saveCharge(this)" class="btn-icon btn-mini btn-success-form" type="button"><i class="i-checkmark-3"></i></button>' +
            ' <button data-myid="' + $(me).attr("data-myid") + '" data-accid="' + $(me).attr("data-accid") + '" data-taxid="' + $(me).attr("data-taxid") + '" onclick="delCancelEditCharge(this)" id="btnCancelCharge" class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-cross"></i></button>' +
            '</td>' +
            '</tr>'
            );
            $("#chargeAccount").val($(me).attr("data-accid"));
            $("#chargeAccount").select2();
    } else{
    msg (2, "alert", "Please, do save the current details before adding new one");
    }
    }


    function delCancelEditCharge (me){
    var taxPercent = $("#listTax").val();
            var taxID = $("#listTax").attr('data-taxid');
            var tr = $(me).parent().parent();
            $("#chargeAccount").val($(me).attr("data-accid"));
            $("#listTax").val($(me).attr("data-taxid"));
            $(tr).replaceWith('<tr><td>' + $("#lineNo").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#chargeAccount").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#chargedesc").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#chargeAmount").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#displayCode").text() + " | " + taxPercent + '</td>' +
            '<td class="amount">' + $("#chargetaxAmount").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#chargeAmountIT").attr("data-previewvalue") + '</td>' +
            '<td>' +
            '<button onClick="editRowCharge(this)" data-percent="' + taxPercent + '"  data-code="' + $('#displayCode').text() + '" data-myid="' + $(me).attr("data-myid") + '" data-accid="' + $(me).attr("data-accid") + '" data-taxid="' + taxID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
            ' <button onclick="deleteCompanyCharge(this)" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>' +
            '</td>' +
            '</tr>'
            );
    }

    function cancelEdit(me){
    tr = $(me).parent().parent();
            var dID = $(me).attr("data-itemId");
            $(tr).replaceWith('<tr>' +
            '<td>' + $("#itemComboList").attr("data-lineNo") + '</td>' +
            '<td>' + $("#itemComboList").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#itemdes").attr("data-previewvalue") + '</td>' +
            '<td class="tac">' + $("#idUnitOfMeasure").attr("data-previewvalue") + '</td>' +
            '<td class="tac">' + $("#itemInvoice").attr("data-previewvalue") + '</td>' +
            '<td class="tac">' + $("#itemqte").attr("data-previewvalue") + '</td>' +
            '<td class="tar">' + accounting.formatNumber($("#itemunitprice").attr("data-previewvalue"), 2) + '</td>' +
            '<td class="tar">' + accounting.formatNumber($("#itemAmountET").attr("data-previewvalue"), 2) + '</td>' +
            '<td class="tac">' + $("#itemTax").attr("data-previewvalue") + '</td>' +
            '<td class="tar">' + accounting.formatNumber($("#itemTaxAmount").attr("data-previewvalue"), 2) + '</td>' +
            '<td class="tar">' + accounting.formatNumber($("#itemAmountIT").attr("data-previewvalue"), 2) + '</td>' +
            '<td class="tac">' +
            '<button data-invoiceDetailID="' + $(me).attr("data-invoiceDetailID") + '" data-itemid="' + $(me).attr("data-itemid") + '" data-umID="' + $(me).attr("data-umID") + '"  data-taxid="' + $(me).attr("data-taxid") + '"  data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '" data-myid="' + $(me).attr("data-myid") + '" onClick="editRow(this)" id="' + dID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
            ' <button id="' + dID + '" class="btn-icon btn-mini btn-danger-form" onClick="deleteCompanyDetails(this)"><i class="i-trashcan"></i></button>' +
            '</td>' +
            '</tr>'
            );
            getTotal ();
    }

    function getTotal (){
    var n = $("#listDetails > tbody > tr").length - 2;
            var totalAmount = 0;
            var impot = 0;
            var total = 0;
            for (i = 0; i <= n; i++) {
    totalAmount = totalAmount + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(7)').text()) * 1;
            impot = impot + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(9)').text() * 1);
            total = total + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(10)').text() * 1);
    }


    n = $("#listCharge > tbody > tr").length - 2;
            var totalAmountC = 0;
            var impotC = 0;
            var totalC = 0;
            i = 0;
            for (i = 0; i <= n; i++) {
    totalAmountC = totalAmountC + accounting.unformat($('#listCharge > tbody > tr:eq(' + i + ') > td:eq(3)').text()) * 1;
            impotC = impotC + accounting.unformat($('#listCharge > tbody > tr:eq(' + i + ') > td:eq(5)').text()) * 1;
            totalC = totalC + accounting.unformat($('#listCharge > tbody > tr:eq(' + i + ') > td:eq(6)').text()) * 1;
    }

    $("#totalamount").val(accounting.formatNumber(totalAmount + totalAmountC, 2));
            $("#impotpayable").val(accounting.formatNumber(impot + impotC, 2));
            $("#totalpayable").val(accounting.formatNumber(total + totalC, 2));
    }


    function saveCharge(me) {
    var tr = $(me).parent().parent();
            $.ajax({
            type: "POST",
                    data: {
                    invoiceId :$("#masterId").val(),
                            chargeId : $(me).attr("data-myid"),
                            accountNoID : $("#chargeAccount").val(),
                            itemdescription : $("#chargedesc").val(),
                            amountExcludedTax :  accounting.unformat($("#chargeAmount").val()),
                            taxID : $("#listTax").attr('data-taxid'),
                            taxRate: $("#listTax").val(),
                            taxAmount : accounting.unformat($("#chargetaxAmount").val()),
                            amountIncludedTax : accounting.unformat($("#chargeAmountIT").val())

                    },
                    url: "<?php echo base_url() ?>aptransaction/updDebitNoteCharge",
                    success: function(data) {
                    msg (2, "alert alert-success", "Details successfully updated");
                            var taxPercent = $("#listTax").val();
                            var taxID = $("#listTax").attr('data-taxid');
                            $(tr).replaceWith('<tr><td>' + $("#lineNo").attr("data-previewvalue") + '</td>' +
                            '<td>' + $("#chargeAccount option:selected").text() + '</td>' +
                            '<td>' + $("#chargedesc").val() + '</td>' +
                            '<td class="amount">' + accounting.formatNumber($("#chargeAmount").val(), 2) + '</td>' +
                            '<td>' + $("#displayCode").text() + " | " + taxPercent + '</td>' +
                            '<td class="amount">' + accounting.formatNumber($("#chargetaxAmount").val(), 2) + '</td>' +
                            '<td class="amount">' + accounting.formatNumber($("#chargeAmountIT").val(), 2) + '</td>' +
                            '<td>' +
                            '<button onClick="editRowCharge(this)" data-percent="' + taxPercent + '"  data-code="' + $('#displayCode').text() + '" data-myid="' + $(me).attr("data-myid") + '" data-accid="' + $("#chargeAccount").val() + '" data-taxid="' + taxID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button> ' +
                            ' <button onclick="deleteCompanyCharge(this)" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i</button>' +
                            '</td>' +
                            '</tr>'
                            );
                            getTotal();
                    } });
    }
    function  deleteCompanyCharge(me){
    $('#popupModal').modal('show');
            $("#_popupTitle").html("Confirm delete");
            $("#_popupContent").html("Your about to delete definively this row. <br/> Click on ok to confirm");
            $('#_popupFooter').empty();
            $('#_popupFooter').append('<button class="btn-form btn-success-form" id="detButton">Ok</button>' +
            '<button class="btn-form btn-danger-form" id="canb">Cancel</button>');
            $("#_popupTitle").html("Confirm delete");
            $("#canb").click(function() {
    $('#popupModal').modal('hide');
    });
            $("#detButton").click(function() {
    $('#popupModal').modal('hide');
            $.ajax({
            type: "POST",
                    data: {
                    chargeID :$(me).attr("data-myid"),
                            invoiceId :$("#masterId").val()
                    },
                    url: "<?php echo base_url() ?>aptransaction/deletedebitCharge",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully deleted");
                            delRowInvoice(me);
                            getTotal();
                            $.ajax({
                            type: "POST",
                                    data: {
                                    invoiceId : $("#purchasetransactionId").val(),
                                            totalPayable : $("#totalpayable").val(),
                                            totalTaxAmount :  $("#totalamount").val()
                                    },
                                    url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
                                    success: function(data) {
                                    //update the invoice after delete
                                    }
                            });
                    } });
    });
            getTotal ();
    }

    function updateRow(me){
    // alert($(me).attr("data-myid"));
    $.ajax({
    type: "POST",
            data: {
            invoiceId :$("#masterId").val(),
                    invDetailsId :$(me).attr("data-myid"),
                    itemId : $("#itemComboList option:selected").attr("data-itemID"),
                    invoiceDetailID : $("#itemComboList").val(),
                    itemdescription: $("#itemdes").val(),
                    quantity : $("#itemqte").val(),
                    umid : $("#idUnitOfMeasure").val(),
                    unitPrice: accounting.unformat($("#itemunitprice").val()),
                    amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
                    taxID :  $("#itemTax").attr("data-taxid"),
                    taxRate: $("#itemTax").val(),
                    taxAmount: accounting.unformat($("#itemTaxAmount").val()),
                    amountIncludedTax:accounting.unformat($("#itemAmountIT").val())

            },
            url: "<?php echo base_url() ?>Aptransaction/updateRowDetailDebitNote",
            success: function(data) {
            msg (1, "alert alert-success", "Details successfully updated");
                    var dID = $(me).attr("data-itemId");
                    var tr = $(me).parent().parent();
                    $(tr).replaceWith('<tr>' +
                    '<td>' + $("#itemComboList").attr("data-lineNo") + '</td>' +
                    '<td>' + $("#itemComboList option:selected").text() + '</td>' +
                    '<td>' + $("#itemdes").val() + '</td>' +
                    '<td>' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                    '<td class="tac">' + $("#itemInvoice").val() + '</td>' +
                    '<td class="tac">' + $("#itemqte").val() + '</td>' +
                    '<td class="tar">' + accounting.formatNumber($("#itemunitprice").val(), 2) + '</td>' +
                    '<td class="tar">' + accounting.formatNumber($("#itemAmountET").val(), 2) + '</td>' +
                    '<td class="tac">' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                    '<td class="tar">' + accounting.formatNumber($("#itemTaxAmount").val(), 2) + '</td>' +
                    '<td class="tar">' + accounting.formatNumber($("#itemAmountIT").val(), 2) + '</td>' +
                    '<td class="tac">' +
                    '<button data-invoiceDetailID="' + $("#itemComboList").val() + '" data-itemid="' + $("#itemComboList").val() + '" data-umID="' + $("#idUnitOfMeasure").val() + '"  data-taxid="' + $("#itemTax").attr("data-taxid") + '"  data-taxcode="' + $("#displayTaxCode").text() + '" data-taxrate="' + $("#itemTax").val() + '" data-myid="' + $(me).attr("data-myid") + '" onClick="editRow(this)" id="' + dID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                    ' <button data-myid="' + dID + '" class="btn-icon btn-mini btn-danger-form" onClick="deleteCompanyDetails(this)"><i class="i-trashcan"></i></button>' +
                    '</td>' +
                    '</tr>'
                    );
                    getTotal();
            } });
    }

    function delRowInvoice(me){
    var td = me.parentNode;
            var tr = td.parentNode;
            var tBody = tr.parentNode;
            tBody.removeChild(tr);
            getTotal ();
    }

    function msg(n, type, message){
    $("#msg_div" + n + " p").html(message);
            $("#msg_div").attr("class", "alert " + type);
    }

    function deleteCompanyDetails(me){

    $('#popupModal').modal('show');
            $("#_popupTitle").html("Confirm delete");
            $("#_popupContent").html("Your about to delete definively this row. <br/> Click on ok to confirm");
            $('#_popupFooter').empty();
            $('#_popupFooter').append('<button class="btn-form btn-success-form" id="detButton">Ok</button>' +
            '<button class="btn-form btn-danger-form" id="canb">Cancel</button>');
            $("#_popupTitle").html("Confirm delete");
            $("#canb").click(function() {
    $('#popupModal').modal('hide');
    });
            $("#detButton").click(function() {
    $('#popupModal').modal('hide');
            $.ajax({
            type: "POST",
                    data: {
                    invDetailsId :$(me).attr("data-myid"),
                            invoiceId :$("#masterId").val()
                    },
                    url: "<?php echo base_url() ?>aptransaction/deleteDebitNoteDetail",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully deleted");
                            delRowInvoice(me);
                            $("#calcul").trigger("click");
                    } });
    });
    }

    function taxPopup () {
    $('#popupModal').modal('show');
            $("#_popupTitle").html("Purchase Invoice");
            $("#_popupContent").html('' +
            '<label>Select a tax</label>' +
            '<select style="width:100%;" onclick="calculamount()" name="listTaxPopup" id="listTaxPopup"  class= "validate[required]">' +
<?php
if ($taxmaster) {
    foreach ($taxmaster as $row2) {
        $temp = str_replace(array("\n", "\r", "'"), " ", $row2->name, $count);
        ?>
            '<option data-taxcode="<?php echo $row2->code ?>" value="<?php echo $row2->ID; ?>" data-tax="' + <?php echo $row2->taxPercentage; ?> + '">' +
                    '<?php echo $row2->code . " | " . $row2->taxPercentage . " | ";
        echo $temp;
        ?></option>' +
    <?php }
}
?>
    '</select>');
            $("#listTaxPopup").select2();
            $('#_popupFooter').empty();
            $('#_popupFooter').append('<button class="btn-form btn-success-form" id="confButton">Ok</button>' +
            '<button class="btn-form btn-danger-form" id="canb">Cancel</button>');
            $("#_popupTitle").html("Tax Master");
            $("#canb").click(function() {
    $('#popupModal').modal('hide');
    });
            $("#confButton").click(function() {
    $('#popupModal').modal('hide');
            $("#itemTax,#listTax").attr("data-taxid", $("#listTaxPopup").val());
            $("#itemTax,#listTax").val ($("#listTaxPopup option:selected").attr("data-tax"));
            $("#displayTaxCode,#displayCode").html($("#listTaxPopup option:selected").attr("data-taxcode"));
            calculChargeAmount();
            calculamount();
    });
    }

    function addnewcharge(){

    var tax = '';
            if (gstStatus){
    tax = '<td class="span1">\
                        <div class="input-prepend">\
                            <input readonly data-taxid="" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)" value="">\
                            <span readonly onclick="taxPopup ()" style="margin-top:0;" id="displayCode" class="btn add-on"></span>\
                        </div>\
                  </td>';
    } else{
    tax = '<td class="span2">\
                        <div class="input-prepend">\
                            <input data-taxid="<?php echo $nonGstTaxID; ?>" value="0" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)">\
                            <span style="margin-top:0;" id="displayCode" class="btn add-on">NR</span>\
                        </div>\
                  </td>';
    }

    if (!$("#chargeAccount").length) {
    $('' +
            '<tr><td class="span1">' + ($("#trInfosCharge").attr("data-currentRow") * 1 + 1) + '</td>' +
            '<td class="span2">\n\
        <select name="chargeAccount" id="chargeAccount" class="span12" validate[required]"><option></option>' +
<?php
if ($chargeAccount) {
    foreach ($chargeAccount as $row) {
        $temp = str_replace(array("\n", "\r", "'"), " ", $row->acctName, $count);
        ?>
            '<option value="<?php echo $row->ID; ?>"><?php
        echo $row->acctCode . " | ";
        echo $temp;
        ?></option>' +
        <?php
    }
}
?>
    '</select></td>' +
            '<td class="span4"><input  id="chargedesc" name="chargedesc"  type="text" class="span12 validate[required]" placeholder="Description"></td>' +
            '<td class="span1"><input id="chargeAmount" onkeyup="calculChargeAmount()" name="chargeAmount" class="span12 validate[required, custom[number]]" type="text" placeholder="Amount"></td>' +
            tax +
            '<td class="span1"><input id="chargetaxAmount"  name="chargetaxAmount" class="span12" type="text" placeholder="Amount"></td>' +
            '<td class="span1"><input disabled id="chargeAmountIT" name="chargeAmountIT" class="span12" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1">' +
            '<button title="Save" onclick = "savenewchagerow(this)" class="btn-icon btn-mini btn-success-form" type="button"><span class="i-checkmark-3"></span></button>' +
            ' <button onclick="delRowInvoice(this)" id="btnCancelCharge" title="Cancel" class="btn-icon btn-mini btn-danger-form" type="button"><span class="i-cross"></span></button>' +
            '</td>' +
            '</tr>'
            ).insertBefore("#trInfosCharge");
            $('#chargeAccount').select2();
            $.each($("#listCharge .select2-container"), function (i, n) {
            $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
                    $(n).prepend($(n).next());
                    $(n).delay(500).queue(function () {
            $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                    $(this).dequeue();
            });
            });
    } else{
    msg (2, "alert", "Please, do save the current details before adding new one");
    }
    }

    function calculChargeAmount() {
    var t = accounting.unformat($("#chargeAmount").val()) * accounting.unformat($("#listTax").val()) / 100;
            console.log(t);
            $("#chargetaxAmount").val(accounting.formatNumber(t, 2));
            $("#chargeAmountIT").val(accounting.formatNumber(t + accounting.unformat($("#chargeAmount").val()), 2));
    }

    function savenewchagerow(me){
    $(me).attr("disabled", "disabled");
            $.ajax({
            type: "POST",
                    data: {
                    invoiceId : $("#masterId").val(),
                            accountNoID : $("#chargeAccount").val(),
                            lineNo : $("#trInfosCharge").attr("data-currentRow") * 1 + 1,
                            itemdescription: $("#chargedesc").val(),
                            amountExcludedTax : accounting.unformat($("#chargeAmount").val()),
                            taxID: $("#listTax").attr('data-taxid'),
                            taxAmount: accounting.unformat($("#chargetaxAmount").val()),
                            amountIncludedTax: accounting.unformat($("#chargeAmountIT").val()),
                            totalPayable: accounting.unformat($("#totalpayable").val()) * 1 + accounting.unformat($("#chargeAmountIT").val()),
                            totalTaxAmount : accounting.unformat($("#impotpayable").val()) * 1 + accounting.unformat($("#chargetaxAmount").val()),
                            totalAmount : accounting.unformat($("#totalamount").val()) * 1 + accounting.unformat($("#chargeAmount").val()) * 1

                    },
                    url: "<?php echo base_url() ?>aptransaction/saveNewDebitChargeDetail",
                    success: function(data) {
                    var resul = eval ("(" + data + ")");
                            var taxPercent = $("#listTax").val();
                            var taxID = $("#listTax").attr('data-taxid');
                            console.log(resul.chargeId);
                            $('' +
                                    '<tr><td class="span1">' + ($("#trInfosCharge").attr("data-currentRow") * 1 + 1) + '</td>' +
                                    '<td>' + $("#chargeAccount option:selected").text() + '</td>' +
                                    '<td>' + $("#chargedesc").val() + '</td>' +
                                    '<td class="amount">' + accounting.formatNumber($("#chargeAmount").val(), 2) + '</td>' +
                                    '<td>' + $("#displayCode").text() + " | " + taxPercent + '</td>' +
                                    '<td class="amount">' + accounting.formatNumber($("#chargetaxAmount").val(), 2) + '</td>' +
                                    '<td class="amount">' + accounting.formatNumber($("#chargeAmountIT").val(), 2) + '</td>' +
                                    '<td class="tac">' +
                                    '<button onClick="editRowCharge(this)" data-percent="' + taxPercent + '"  data-code="' + $('#displayCode').text() + '" data-myid="' + resul.chargeId + '" data-accid="' + $("#chargeAccount").val() + '" data-taxid="' + taxID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button> ' +
                                    ' <button onclick="deleteCompanyCharge(this)" data-myid="' + resul.chargeId + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i</button>' +
                                    '</td>' +
                                    '</tr>'
                                    ).insertBefore("#trInfosCharge");
                            $("#trInfosCharge").attr("data-currentRow", $("#trInfosCharge").attr("data-currentRow") * 1 + 1);
                            $("#btnCancelCharge").trigger("click");
                            getTotal ();
                            msg (2, "alert alert-success", "Details successfully saved");
                    }
            }); //end ajax
    }


    function addnewitemrow(){

    if (!$("#itemComboList").length) {
    $('' +
            '<tr><td class="span1">' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
            '<td class="span2"><select style="max-width:100%;" id="itemComboList" class="span12" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        ?>
            '<option data-itemID= "<?php echo $row->itemID; ?>" data-exactQty= "<?php echo $row->exactQty; ?>" data-umCode= "<?php echo $row->unitOfMeasure; ?>" data-umID= "<?php echo $row->umID; ?>" data-desc= "<?php echo str_replace(array("\n", "\r", "'"), " ", $row->description, $count); ?>" data-unitPrice= "<?php echo $row->unitPrice; ?>" \n\
                                                                                    data-taxid="<?php echo $row->taxID; ?>" data-taxcode="<?php echo $row->code; ?>" \n\
                                                                                    data-taxPercentage="<?php echo $row->taxRate; ?>" value="<?php echo $row->invoiceDetailID; ?>"><?php
        echo str_replace(array("\n", "\r", "'"), " ", $row->name, $count)
        . " [" . str_replace(array("\n", "\r", "'"), " ", $row->itemCode, $count) . "]";
        ?></option>' +
        <?php
    }
}
?>
    '</select>' +
            '</td>' +
            '<td class="span2"><input id="itemdes" name="itemdes" class="span12 amount validate[required]" type="text" placeholder="Description"></td>' +
            '<td class="span1">' +
            '<select onchange="getLatestItemPrice()" id="idUnitOfMeasure" class="span12 validate[required]"><option></option>' +
<?php
if ($um) {
    foreach ($um as $rowUm) {
        $code = str_replace(array("\n", "\r", "'"), " ", $rowUm->code);
        ?>
            '<option  value="<?php echo $rowUm->fldid; ?>"><?php
        echo $code;
        ?></option>' +
    <?php
    }
}
?>
    '</select></td>' +
            '<td class="span1"><input id="itemInvoice" disabled name="itemInvoice" class="span10 validate[required,custom[integer]]" type="text" placeholder="Qty Invoice"></td>' +
            '<td class="span1"><input id="itemqte" onkeyup="calculamount()"  name="itemqte" class="span12 amount validate[required,custom[integer]]" type="text" placeholder="Qty return"></td>' +
            '<td class="span1"><input id="itemunitprice" onkeyup="calculamount()" name="itemunitprice" class="span12 validate[required,custom[number]]" type="text" placeholder="Unit Priece"></td>' +
            '<td class="span1"><input disabled="disabled" id="itemAmountET" disabled name="itemAmountET" onkeydown="return false;" class="span12 validate[required]" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1"><div  class="span12 input-prepend"><input disabled="disabled" data-taxid="" id="itemTax" onkeyup="calculamount()" name="itemTax" style="max-width:20px;" class="validate[required, custom[number]]" type="text" placeholder="Tax(%)"><span id="displayTaxCode" onclick="taxPopup ()" style="margin-top:0;" class="btn add-on">....</span></div></td>' +
            '<td class="span1"><input disabled="disabled" id="itemTaxAmount" disabled name="itemTaxAmount" onkeydown="return false;" class="span12 amount" type="text" placeholder="Tax Amount"></td>' +
            '<td class="span1"><input disabled="disabled" id="itemAmountIT" disabled name="itemAmountIT" onkeydown="return false;" class="span12 amount" type="text" placeholder="Amount (Include Tax)"></td>' +
            '<td class="span1">' +
            '<button class="btn-icon btn-mini btn-success-form" onclick="savenewitemrow(this)" type="button"><span class="i-checkmark-3"></span></button>' +
            ' <button id="btnCancel" class="btn-icon btn-mini btn-danger-form" onclick="delRowInvoice(this)" type="button"><span class="i-cross"></span></button>' +
            '</td>' +
            '</tr>'
            ).insertBefore("#trInfos");
            $('#itemComboList').select2();
            $('#idUnitOfMeasure').select2();
            $.each($("#listDetails .select2-container"), function (i, n) {
            $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
                    $(n).prepend($(n).next());
                    $(n).delay(500).queue(function () {
            $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                    $(this).dequeue();
            });
            });
    } else{
    msg (1, "alert", "Please, do save the current details before adding new one");
    }
    }

    function savenewitemrow(me){
    $(me).attr("disabled", "disabled");
            $.ajax({
            type: "POST",
                    data: {
                    invoiceId :$("#masterId").val(),
                            itemID : $("#itemComboList option:selected").attr("data-itemID"),
                            invoiceDetailID : $("#itemComboList").val(),
                            lineNo : $("#trInfos").attr("data-currentRow") * 1 + 1,
                            itemdescription: $("#itemdes").val(),
                            quantity : $("#itemqte").val(),
                            umid : $("#idUnitOfMeasure").val(),
                            unitPrice: accounting.unformat($("#itemunitprice").val()),
                            amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
                            taxID: $("#itemTax").attr("data-taxid"),
                            taxRate: $("#itemTax").val(),
                            taxAmount: accounting.unformat($("#itemTaxAmount").val()),
                            amountIncludedTax:accounting.unformat($("#itemAmountIT").val())

                    },
                    url: "<?php echo base_url() ?>aptransaction/saveNewDebitDetail",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully saved");
                            var resul = eval ("(" + data + ")");
                            $('' +
                                    '<tr>' +
                                    '<td>' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
                                    '<td>' + $("#itemComboList option:selected").text() + '</td>' +
                                    '<td>' + $("#itemdes").val() + '</td>' +
                                    '<td>' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                                    '<td class="tac">' + $("#itemInvoice").val() + '</td>' +
                                    '<td class="tac">' + $("#itemqte").val() + '</td>' +
                                    '<td class="tar">' + accounting.formatNumber($("#itemunitprice").val(), 2) + '</td>' +
                                    '<td class="tar">' + accounting.formatNumber($("#itemAmountET").val(), 2) + '</td>' +
                                    '<td class="tac">' + $("#displayTaxCode").text() + ' | ' + $("#itemTax").val() + '</td>' +
                                    '<td class="tar">' + accounting.formatNumber($("#itemTaxAmount").val(), 2) + '</td>' +
                                    '<td class="tar">' + accounting.formatNumber($("#itemAmountIT").val(), 2) + '</td>' +
                                    '<td class="tac">' +
                                    '<button data-invoiceDetailID="' + $("#itemComboList").val() + '" data-itemid="' + $("#itemComboList").val() + '" data-taxid="' + $("#itemTax").attr("data-taxid") + '"  data-taxcode="' + $("#displayTaxCode").text() + '" data-taxrate="' + $("#itemTax").val() + '" data-myid="' + data.detailID + '" onClick="editRow(this)" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                                    ' <button data-myid="' + resul.detailID + '" class="btn-icon btn-mini btn-danger-form" onClick="deleteCompanyDetails(this)"><i class="i-trashcan"></i></button>' +
                                    '</td>' +
                                    '</tr>'
                                    ).insertBefore("#trInfos");
                            $("#trInfos").attr("data-currentRow", $("#trInfos").attr("data-currentRow") * 1 + 1);
                            $("#btnCancel").trigger("click");
                            $("#calcul").trigger("click");
                    }
            }); //end ajax
    }
    var prevUmID;
            function getItemListOfUM(){
            $("#idUnitOfMeasure").empty();
                    if ($("#itemComboList option:selected").attr("data-umid") > 0 && $("#itemComboList option:selected").attr("data-umCode") != null){
            //  $("#idUnitOfMeasure").select2('destroy'); 
            $("#idUnitOfMeasure").append("<option data-unitm='1' data-factor='1'  value=" + $("#itemComboList option:selected").attr("data-defaultUM") + ">" + $("#itemComboList option:selected").attr("data-defaultCode") + "</option>");
                    $("#idUnitOfMeasure").select2("val", $("#itemComboList option:selected").attr("data-umid"));
            }
            $.ajax({
            type: "POST",
                    data : "unitFrom=" + $("#itemComboList option:selected").attr("data-umID") + "&itemID=" + $("#itemComboList option:selected").attr("data-itemID"),
                    url: "<?php echo base_url() ?>apTransaction/getItemUnitList",
                    success: function(data) {

                    var resul = eval ("(" + data + ")");
                            var n = resul.recordSet.length;
                            var i = 0;
                            var opt = '';
                            for (i = 0; i < n; i++){
                    opt = opt + '<option  value="' + resul.recordSet[i].ID + '" data-unitm="' + resul.recordSet[i].unitm + '" data-factor="' + resul.recordSet[i].factor + '" data-desc ="' + resul.recordSet[i].desc + '">' + resul.recordSet[i].code + '</option>';
                    }
                    $('#idUnitOfMeasure').append(opt);
                            $("#idUnitOfMeasure").select2('val', prevUmID);
                            $('#itemInvoice').attr('data-unitm', $("#idUnitOfMeasure option:selected").attr("data-unitm")).attr('data-factor', $("#idUnitOfMeasure option:selected").attr("data-factor"));
                    }
            });
            }
            
  function updateMaster(){
    if(confirm('Please, confirm update ...')){

        $.ajax({
            type: "POST",
            data: {
                masterId : $("#masterId").val(),
                project : $("#project").val(),
                date : $("#createDate").val(),
                memo : $("#memo").val(),
                formNo : $("#formNo").val()

            },
            url: "<?php echo base_url() ?>Aptransaction/update_purchaseDebitNote_header",
            success: function(data) {
                alertbox ("Details successfully saved",1);
            }
        }); //end ajax
    }
}

</script>


<div id="content"> 
    <div class="wrap">
        <div class="head">
            <div class="info">
                <!--<h1><?php echo element('compName', $this->session->userdata('logged_in')) ?> [ 
<?php echo element('compNo', $this->session->userdata('logged_in')) ?> ]</h1>-->
                <ul class="breadcrumb">
                    <li><a href='<?php echo base_url() . "home" ?>'><?php echo $this->lang->line('dashboard') ?></a> <span class="divider">-</span></li>
                    <li><a href='<?php echo base_url() . "gl/home" ?>'> <?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
                    <li class="active"><?php echo $this->lang->line('titleDebitNote') ?></li>
                </ul>
            </div>

            <div class="search">
                <form action="<?php echo base_url() ?>admin/search" method="post">
                    <input name="search_text" type="text" placeholder="search..."/>                                
                    <button type="submit"><span class="i-magnifier"></span></button>
                </form>
            </div>        

        </div><!-- head --> 
        <div class="content" id="grid_content_1">

<?php
$memo = "";
if ($pInvoice) {

    foreach ($pInvoice as $rowIn) {
        $memo = $rowIn->memo;
        ?> 
                    <div class="block">
                        <div class="head">
                            <h2><strong><?php echo $this->lang->line('title') ?></strong></h2>
                        </div><!-- head -->
                        <div class="content">
                            <div class="row-fluid scRow">                            
                                <div class="span6 scCol">
                                    <div class="block" id="grid_block_1">
                                        <div class="controls-row">
                     
                                        <div class="span3"><?php echo $this->lang->line('formNo') ?></div>
                                        <div class="span4">
                                            <input class="span12 validate[required]" id="formNo" name="formno" value='<?php echo $rowIn->frmNo; ?>' style="color:red;"   type="text" placeholder="Form number ...">
                                        </div>
                                        <div class="span4">
                                            <input class="span12" type="text" value="<?php echo str_pad($rowIn->serialNo, 8, '0', STR_PAD_LEFT);  ?>" placeholder="Serial" disabled="disabled">
                                        </div>
                                    </div> <!-- row -->
                                        
                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('supplier') ?></div>
                                            <div class="span8">
                                                <input type="hidden" id="masterId" value="<?php echo $rowIn->ID; ?>" />
                                                <input id="supplier" data-supplierID="<?php echo $rowIn->supplierID ?>" type="text" disabled="disabled" value="<?php echo $rowIn->supplierName; ?>" class="span12" />
                                            </div>
                                        </div> <!-- row -->
                                        
                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('date') ?></div>
                                            <div class="span8">
                                                <input id="createDate" type="text" class="datepicker2 validate[required] financhk span12" value="<?php echo date("d-m-Y", strtotime($rowIn->debitNoteDate)); ?>" class="span12" />
                                            </div>
                                        </div> <!-- row -->
                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('project') ?></div>
                                            <div class="span8">
                                                <select id="project" class="span12">
                                                    <option></option>
        <?php
        if ($project != '') {
            foreach ($project as $Prow) {
                ?>
                                                            <option <?php if ($Prow->ID == $rowIn->projectID) echo "selected" ?> value="<?php echo $Prow->ID; ?>"><?php echo $Prow->project_name; ?></option>
            <?php }
        }
        ?>
                                                </select>
                                            </div>
                                        </div> <!-- row -->
                                    </div><!-- grid block 1-->
                                </div><!-- scCol -->

                                <div class="span6 scCol">
                                    <div class="block" id="grid_block_3">
                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('invoiceNo') ?></div>
                                            <div class="span8">
                                                <input type="text" disabled="disabled" value="<?php echo $rowIn->IformNo; ?>" class="span12" />

                                            </div>
                                        </div> 
                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('supplierInvoiceNo') ?></div>
                                            <div class="span8">
                                                <input type="text" disabled="disabled" value="<?php echo $rowIn->supplierInvoiceNo; ?>" class="span12" />

                                            </div>
                                        </div> 

                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('currency') ?></div>
                                            <div class="span8">
                                                <input type="text" id="currency" data-curid="<?php echo $rowIn->currencyID; ?>" disabled="disabled" value="<?php echo $rowIn->fldcurr_code; ?>" class="span12" />

                                            </div><!-- span -->
                                        </div><!-- control row -->
                                        <div class="controls-row">
                                            <div class="span3"><?php echo $this->lang->line('exchangeRate') ?></div>
                                            <div class="span8">
                                                <input type="text" disabled="disabled" value="<?php echo number_format($rowIn->exchangeRate, 5); ?>" class="span12 tar" />

                                            </div><!-- span -->
                                        </div><!-- control row -->
                                    </div><!-- content -->
                                </div><!-- content -->
                            </div><!-- grid block 1-->
                        </div><!-- scCol -->
                        <div class="row-fluid scRow">                            
                            <div class="span12 scCol">
                                <textarea placeholder="<?php echo $this->lang->line('memo') ?>"  id="memo" class="span12"><?php echo $memo; ?></textarea>
                            </div>
                        </div>

                        <div class="footer">
                            <div class="side fr">
                                <div class="btn-group">
                                    <button  onclick="updateMaster()" class="btn-form btn-success-form" type="button" title="<?php echo $this->lang->line('submit') ?>">
        <?php echo $this->lang->line('update') ?></button>
                                </div><!-- btn group -->      
                            </div><!-- side fr -->      
                        </div><!-- footer -->  
                    </div><!-- row-fluid scRow-->
    <?php }
}
?>

            <div class="row-fluid scRow">                            
                <div class="span12 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="head">


                            <ul class="fr buttons">
                                <li><a class="block_toggle collapsed" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
                                        <span class="i-arrow-down-3"></span></a></li>
                            </ul>
                            <ul class="buttons fr">
                                <li><a href="#trInfos" onclick="addnewitemrow()" title="Add New"><span class="i-plus-2"></span></a></li>
                            </ul>
                            <h2><?php echo $this->lang->line('items'); ?></h2>
                        </div><!-- head -->
                        <div class="content np">
                            <table id="listDetails" cellpadding="0" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th><?php echo $this->lang->line('item') ?></th>
                                        <th><?php echo $this->lang->line('itemDesc') ?></th>
                                        <th><?php echo $this->lang->line('um') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('qtyInvoice') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('quantityReturn') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amountExcludeTax') ?></th>
                                        <th><?php echo $this->lang->line('tax') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('taxAmount') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amountIncludeTax') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
<?php
$t_amountExcludedTax = 0;
$t_taxAmount = 0;
$t_amountIncludedTax = 0;
$lastrow = 0;
if ($pdetails && $pInvoice) {
    foreach ($pdetails as $row) {

        if ($lastrow < $row->lineNo)
            $lastrow = $row->lineNo;

        $t_amountExcludedTax += $row->amountExcludedTax;
        ;
        $t_taxAmount+= $row->taxAmount;
        $t_amountIncludedTax += $row->amountIncludedTax;
        ?>
                                            <tr>
                                                <td><?php echo $row->lineNo; ?></td>
                                                <td><?php echo $row->name . " [" . $row->itemCode . "]"; ?></td>
                                                <td><?php echo $row->description; ?></td>
                                                <td class="tac" data-umid="<?php echo $row->umID; ?>"><?php echo $row->unitOfMeasure; ?></td>
                                                <td class="tac"><?php echo $row->qytInvoice; ?></td>
                                                <td class="tac"><?php echo $row->quantity; ?></td>
                                                <td class="tar"><?php echo number_format($row->unitPrice, 2); ?></td>
                                                <td class="tar"><?php echo number_format($row->amountExcludedTax, 2); ?></td>
                                                <td class="tac"><?php echo $row->code . " | " . $row->taxRate; ?></td>
                                                <td class="tar"><?php echo number_format($row->taxAmount, 2); ?></td>
                                                <td class="tar"><?php echo number_format($row->amountIncludedTax, 2); ?></td>
                                                <td class="tac">
                                                    <button data-invoiceDetailID="<?php echo $row->invoiceDetailID; ?>"  data-taxcode="<?php echo $row->code; ?>" data-umID ="<?php echo $row->umID; ?>" data-taxrate="<?php echo $row->taxRate; ?>"
                                                            data-taxid="<?php echo $row->taxID; ?>" onClick="editRow(this)" data-myid="<?php echo $row->ID; ?>" data-itemid="<?php echo $row->itemid; ?>" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button> 
                                                    <button onClick="deleteCompanyDetails(this)" data-myid="<?php echo $row->ID; ?>" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>
                                                </td>
                                            </tr>
    <?php } ?>
                                        <tr data-currentRow="<?php echo $lastrow; ?>" id="trInfos">
                                            <td colspan="12">
                                                <div id="msg_div1" class="alert alert-info">


                                                    <h4><?php echo $this->lang->line('lastMessage') ?></h4>
                                                    <p style="padding-top:10px;"><?php echo $this->lang->line('noMessage') ?></p>
                                                </div>
                                            </td>

                                        </tr>                               
<?php } else {
    ?>

                                        <tr data-currentRow="<?php echo $lastrow; ?>" id="trInfos">
                                            <td colspan="12">
                                                <div id="msg_div1" class="alert alert-info">


                                                    <h4><?php echo $this->lang->line('lastMessage') ?></h4>
                                                    <p style="padding-top:10px;"><?php echo $this->lang->line('message1') ?></p>
                                                </div>
                                            </td>

                                        </tr>
<?php } ?>
                                </tbody>
                            </table>     
                        </div><!-- content -->
                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->

            <div class="row-fluid scRow">                            
                <div class="span12 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="head">

                            <ul class="buttons fr">
                                <li><a class="block_toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
                                        <span class="i-arrow-down-3"></span></a></li>
                            </ul>
                            <ul class="buttons fr">
                                <li><a href="javascript:" onclick="addnewcharge()" title="Add New"><span class="i-plus-2"></span></a></li>
                            </ul>

                            <h2><?php echo $this->lang->line('charge') ?></h2>
                        </div><!-- head -->
                        <div class="content np">
                            <table id="listCharge" cellpadding="0" cellspacing="0" width="100%">
                                <thead>
                                    <tr><th>#</th>
                                        <th><?php echo $this->lang->line('account') ?></th>
                                        <th><?php echo $this->lang->line('description') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amount') ?></th>
                                        <th><?php echo $this->lang->line('tax') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('taxAmount') ?></th>
                                        <th class="tar"><?php echo $this->lang->line('amountIncludeTax') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
<?php
$t_amountExcludedTaxC = 0;
$t_taxAmountC = 0;
$t_amountIncludedTaxC = 0;
$lastrow = 0;
if ($charge && $pInvoice) {

    foreach ($charge as $row) {
        if ($lastrow < $row->lineNo)
            $lastrow = $row->lineNo;
        $t_amountExcludedTax += $row->amountExcludedTax;
        ;
        $t_taxAmount+= $row->taxAmount;
        $t_amountIncludedTax += $row->amountIncludedTax;
        ?>
                                            <tr> <td><?php echo $row->lineNo; ?></td>
                                                <td><?php echo substr($row->acctCode, 0, 4) . '-' . substr($row->acctCode, 4, 3) . '-' . substr($row->acctCode, 7) . ' | ' . $row->acctName; ?></td>
                                                <td><?php echo $row->itemdescription; ?></td>
                                                <td  class="amount"><?php echo number_format($row->amountExcludedTax, 2); ?></td>
                                                <td><?php echo $row->code . ' | ' . $row->taxPercentage; ?></td>
                                                <td  class="amount"><?php echo number_format($row->taxAmount, 2); ?></td>
                                                <td  class="amount"><?php echo number_format($row->amountIncludedTax, 2); ?></td>
                                                <td class="tac">
                                                    <button onClick="editRowCharge(this)" data-code="<?php echo $row->code; ?>" data-percent="<?php echo $row->taxPercentage; ?>" data-taxid="<?php echo $row->taxId ?>" data-accid= "<?php echo $row->accountNoID ?>" data-myid="<?php echo $row->myid; ?>" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button> <button onClick="deleteCompanyCharge(this)" data-myid="<?php echo $row->myid; ?>" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>
                                                </td>
                                            </tr>
        <?php }
    ?>
                                        <tr data-currentRow="<?php echo $lastrow; ?>" id="trInfosCharge">
                                            <td colspan="8">
                                                <div id="msg_div2" class="alert alert-info">


                                                    <h4><?php echo $this->lang->line('lastMessage') ?></h4>
                                                    <p style="padding-top:10px;"><?php echo $this->lang->line('noMessage') ?></p>
                                                </div>
                                            </td>
                                        </tr>                                  
<?php } else {
    ?>
                                        <tr data-currentRow="<?php echo $lastrow; ?>" id="trInfosCharge">
                                            <td colspan="8">
                                                <div id="msg_div2" class="alert alert-info">


                                                    <h4><?php echo $this->lang->line('lastMessage') ?></h4>
                                                    <p style="padding-top:10px;"> No charges found ...</p>
                                                </div>
                                            </td>
                                        </tr>
<?php } ?>
                                </tbody>
                            </table>     
                        </div><!-- content -->
                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->

            <div class="row-fluid scRow">
                <div class="span7 scCol">
                    <div class="block" id="grid_block_4">

                    </div>
                </div>
                <div class="span5 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="content np">
                            <div class="controls-row">

                                <div class="span3"><?php echo $this->lang->line('totalAmount') ?></div>
                                <div class="span8">
                                    <input id="totalamount" value="<?php echo number_format($t_amountExcludedTax, 2) ?>" class="span12 amount" type="text" placeholder="0" disabled="disabled" >
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span3"><?php echo $this->lang->line('importDutyPayable') ?></div>
                                <div class="span8">
                                    <input value="<?php echo number_format($t_taxAmount, 2) ?>" id="impotpayable" class="span12 amount" type="text" disabled="disabled"  placeholder="0">
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span3"><?php echo $this->lang->line('totalPayable') ?></div>
                                <div class="span8">
                                    <input value="<?php echo number_format($t_amountIncludedTax, 2) ?>" id="totalpayable" disabled="disabled"  class="span12 amount" type="text" placeholder="0">
                                </div>
                            </div><!-- row control -->
                            <div class="footer">
                                <div class="side fr">
                                    <div class="btn-group">
                                        <!--<button id="calcul" onclick="getTotal()" class="btn btn-mini btn-warning" type="button"> 
                        <i class="icon-ok-circle"></i><?php echo $this->lang->line('calTotal') ?></button>-->
                                    </div><!-- btn group -->      
                                </div><!-- side fr -->      
                            </div><!-- footer -->   
                        </div>    
                    </div><!-- grid block 1-->
                </div><!-- scCol -->
            </div><!-- row-fluid scRow-->
        </div><!-- grid 1 -->
    </div><!-- wrap -->
</div><!-- content -->


