<style type="text/css">
    .amount{
        text-align: right !important;
    }

    .quantity {
        text-align: center !important;
    }

    .input-prepend span, input-prepend button{
        height:18px;
        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('OS',(array) $taxmaster[$k]);  
        if($val != null){
            $nonGstTaxID = $taxmaster[$k]->ID;
            break;
        }
    }
?>
<script>
    var gstStatus = true;
    $(document).ready(function(){
        gstStatus = isGstRegistered(<?php echo element('compID', $this->session->userdata('logged_in')); ?>,'company');
        console.log(gstStatus);
    $('select').select2();
            $.each($(".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();
            });
            });
            jQuery('.datepicker2').datepicker({
    dateFormat : 'dd-mm-yy',
            changeMonth : true,
            changeYear : true
    });
    });
    
    function getLatestItemPrice(){
        $("#itemqte").val("");
     $.ajax({
            type: "POST",
            data : {
                option :'sale',
                itemID : $("#itemList").val(),
                datePrice : $("#createDate").val(),
                customerID : $("#customerID").attr("data-customerID")
            },
            url: "<?php echo base_url() ?>artransaction/getPrice",
            success: function(data) {
                $("#itemunitprice").val(accounting.formatNumber(data,2));
            }
      });
    }

            var lisItem = "";
            function refreshItemList(selectedItem){
            if ($("#location").attr("data-ispopulated") !== "true"){
            $.ajax({
            type: "POST",
                    data : "idLocation=" + $("#location").attr("data-idLocation"),
                    url: "<?php echo base_url() ?>artransaction/getItemList",
                    success: function(data) {
                    var result = eval ("(" + data + ")");
                            if (result.status == "success"){
                    var n = result.recordSet.length;
                            var i = 0;
                            var opt = '' +
                            '<option></option>';
                            for (i = 0; i < n; i++) {
                    opt = opt + '<option data-umCode="' + result.recordSet[i].umCode + '" data-umid="' + result.recordSet[i].unitOfMeasureID + '" data-desc="' + result.recordSet[i].description + '" data-taxid="' + result.recordSet[i].outputTaxID + '" data-taxpercentage="' + result.recordSet[i].outputTaxPercentage + '" data-taxcode="' + result.recordSet[i].outputTaxCode + '"\n\
                        data-salesprice="' + result.recordSet[i].salesPrice + '" data-qty="' + result.recordSet[i].quantity + '" value="' + result.recordSet[i].ID + '">' + result.recordSet[i].itemCode + ' | ' + result.recordSet[i].name + '</option>';
                    }
                    $('#itemList').empty();
                            $('#itemList').append(opt);
                            lisItem = opt;
                            $("#location").attr("data-ispopulated", "true");
                            $("#itemList").val(selectedItem);
                            $('#itemList').select2();
                            getItemListOfUM();
                    }
                    }
            });
            } else {
            $('#itemList').empty();
                    $('#itemList').append(lisItem);
                    $("#location").attr("data-ispopulated", "true");
                    $("#itemList").val(selectedItem);
                    $('#itemList').select2();
            }
            }

    function displaysItemDefaultValue(){

    if (document.getElementById("saleItemInList" + $("#itemList").val()) !== null){
    $("#itemList").val("");
            msg (1, "alert", "This item has already been inserted ...");
    }
    //alert($("#itemList option:selected").attr("data-desc"));
            $("#itemdesc").val($("#itemList option:selected").attr("data-desc"));
            $("#itemunitprice").val(accounting.formatNumber($("#itemList option:selected").attr("data-salesprice"), 2));
            $("#itemTax").val($("#itemList option:selected").attr("data-taxpercentage"));
            $("#itemTax").attr("data-taxid", $("#itemList option:selected").attr("data-taxid"));
            $("#displayTaxCode").text($("#itemList option:selected").attr("data-taxcode"));
          getLatestItemPrice ();
            
            getItemListOfUM();
    }

    function editRow(me){
    //  alert( $(me).parent().parent().find("td").eq(0).html()); 
    if (!$("#itemList").length) {
    if(gstStatus){
      var tax = '<td class="span1">\
                    <div  class="span12 input-prepend">\
                        <input disabled="disabled" style="width:15px;" data-previewvalue= "' + $(me).attr("data-taxcode") + ' | ' + $(me).attr("data-taxrate") + '"  value="' + $(me).attr("data-taxrate") + '" data-taxid="' + $(me).attr("data-taxid") + '" id="itemTax" onkeyup="calculamount()" onblur="calculamount()" name="itemTax" class="input-mini validate[required, custom[number]]" type="text" placeholder="Tax(%)">\
                        <span id="displayTaxCode" style="margin-top:0;" onclick="taxPopup ()"  class="btn add-on">' + $(me).attr("data-taxcode") + '</span>\
                    </div>\
                </td>';
    }else{
      var tax = '<td class="span1">\
                    <div  class="span12 input-prepend">\
                        <input disabled="disabled" style="width:15px;" data-previewvalue= "OS | 0"  value="0" data-taxid="<?php echo $nonGstTaxID; ?>" id="itemTax" onkeyup="calculamount()" onblur="calculamount()" name="itemTax" class="input-mini validate[required, custom[number]]" type="text" placeholder="Tax(%)">\
                        <span id="displayTaxCode" style="margin-top:0;"  class="btn add-on">OS</span>\
                    </div>\
                </td>';
    }
    var tr = $(me).parent().parent();
            $(tr).replaceWith('<tr><td>' + $(me).parent().parent().find("td").eq(0).html() + '</td>' +
            '<td class="span5"><select onchange="displaysItemDefaultValue()" data-lineNo="' + $(me).parent().parent().find("td").eq(0).html() + '"  data-previewvalue="' + $(me).parent().parent().find("td").eq(1).html() + '" name="itemList" data-ispopulated="false" id="itemList" class="span12"><option></option>' +
            '</select></td>' +
            '<td><input type="text" class="span12" data-previewvalue="' + $(me).parent().parent().find("td").eq(2).html() + '" value ="' + $(me).parent().parent().find("td").eq(2).html() + '" id="itemdesc" /></td>' +
            '<td class="span1">' +
                        '<select onchange="getLatestItemPrice()" data-previewvalue="' + $(me).parent().parent().find("td").eq(3).html() + '" id="idUnitOfMeasure" class="span12 validate[required]">' +
                        '</select></td>'+
            '<td class="span1"><input id="itemqte"  onkeyup="calculamount()" onkeyup="calculamount()" name="itemqte"  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="itemunitprice" onkeyup="calculamount()" onchange="calculamount()" name="itemunitprice" 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="itemAmountET" name="itemAmountET" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(6).html() + '" value="' + $(me).parent().parent().find("td").eq(6).html() + '"></td>' +
            tax+
            '<td class="span1"><input disabled="disabled" onkeyup="calculamount()" onchange="calculamount()" id="itemTaxAmount" name="itemTaxAmount" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(8).html() + '" value="' + $(me).parent().parent().find("td").eq(8).html() + '"></td>' +
            '<td class="span1"><input onkeyup="calculamount()" onchange="calculamount()" id="itemAmountIT" name="itemAmountIT" 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">' +
            '<button data-itemID="' + $(me).attr("data-itemID") + '" onclick="updateRow(this)" data-locationID="' + $(me).attr("data-locationID") + '"  data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '" data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '" class="btn-icon btn-mini btn-success-form" type="button"><i class="i-checkmark-3"></i></button>' +
            ' <button data-itemID="' + $(me).attr("data-itemID") + '"  id="btnCancel" data-locationID="' + $(me).attr("data-locationID") + '" data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '" onclick="cancelEdit(this)" data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '"  class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-cross"></i></button></td>' +
            '</tr>');
            refreshItemList($(me).attr("data-itemID"));
           
            $('#idUnitOfMeasure').select2();
            getItemListOfUM();
             }else{
                                                msg (1,"alert","Please, do save the current details before adding new one");
                                                } 
    }

    function calculamount(){

    if ($("#itemTax").attr("data-taxid") == "") {
    //taxPopup ();
    }
    //check qty
    var currentQty =  accounting.unformat($("#itemqte").attr("data-previewvalue"));
    var qtyMax = currentQty + accounting.unformat($("#itemList option:selected").attr("data-qty")*$("#idUnitOfMeasure option:selected").attr("data-factor")/$("#idUnitOfMeasure option:selected").attr("data-unitm"));
            if ($("#itemqte").val() * 1 > qtyMax || $("#itemqte").val() < 1){
    $("#itemqte").attr("style", "background:#F2DEDE;");
            $("#itemqte").val("");
            msg (1, "alert", "The quantity available of this item is :" + qtyMax + " " + $("#idUnitOfMeasure option:selected").text() 
                    + "<br> The current quantity should more than 0 and less than " + qtyMax + " " + $("#idUnitOfMeasure option:selected").text());
    } else{
    $("#itemqte").attr("style", "background:#DFF0D8;");
            $("#itemqte").val($("#itemqte").val() * 1);
            msg (1, "alert alert-info", "...");
            if (isNaN($("#itemqte").val()))
            $("#itemqte").val("");
    }
    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 calculChargeAmount() {
    var t = accounting.unformat($("#chargeAmount").val()) * accounting.unformat($("#listTax").val()) / 100;
            $("#chargetaxAmount").val(accounting.formatNumber(t, 2));
            $("#chargeAmountIT").val(accounting.formatNumber(t + accounting.unformat($("#chargeAmount").val()), 2));
    }



    function cancelEdit(me){

    var dID = $(me).attr("data-itemId");
            var tr = $(me).parent().parent();
            $(tr).replaceWith('<tr id="trItem' + $(me).attr("data-itemID") + '"> <td>' + $("#itemList").attr("data-lineNo") + '</td>' +
            '<td>' + $("#itemList").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#itemdesc").attr("data-previewvalue") + '</td>' +
             '<td class="tac">' + $("#idUnitOfMeasure").attr("data-previewvalue") + '</td>' +
            '<td class="quantity">' + $("#itemqte").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemunitprice").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemAmountET").attr("data-previewvalue") + '</td>' +
            '<td class="tac">' + $("#itemTax").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemTaxAmount").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemAmountIT").attr("data-previewvalue") + '</td>' +
            '<td class="tac">' +
            '<button data-itemID="' + $(me).attr("data-itemID") + '"  data-locationID="' + $(me).attr("data-locationID") + '" data-taxcode="' + $(me).attr("data-taxcode") + '" data-taxrate="' + $(me).attr("data-taxrate") + '"  onClick="editRow(this)" data-taxid="' + $(me).attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
            ' <button onclick="deleteSaleItemRow(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 getTotal (){

    $("#totalamount").val("");
            $("#impotpayable").val("");
            $("#totalpayable").val("");
            var n = $("#listDetails > tbody > tr").length - 1;
            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(6)').text()) * 1;
            impot = impot + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(8)').text()) * 1;
            total = total + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(9)').text()) * 1;
    }

    // calcul for charge

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

    $("#totalamount").val(accounting.formatNumber(totalAmount + totalAmountCharge, 2));
            $("#impotpayable").val(accounting.formatNumber(impot + impotCharge, 2));
            $("#totalpayable").val(accounting.formatNumber(total + totalCharge, 2));
    }

    function updateRow(me){
    //if (document.getElementById("trItem" + $("#itemList").val()) !== null){
    //msg (1, "alert", "This item has already been inserted ...");
   // } else{
    $.ajax({
    type: "POST",
            data: {
                invoiceId : $("#saleInvoiceId").val(),
                rowID : $(me).attr("data-myid"),
                    itemID : $("#itemList").val(),
                    itemdescription : $("#itemdesc").val(),
                    umid : $("#idUnitOfMeasure").val(),
                    quantity : $("#itemqte").val(),
                    unitPrice: accounting.unformat($("#itemunitprice").val()),
                    taxAmount : accounting.unformat($("#itemTaxAmount").val()),
                    amountIncludedTax :accounting.unformat( $("#itemAmountIT").val()),
                    amountExcludedTax:accounting.unformat( $("#itemAmountET").val()),
                    taxID: $("#itemTax").attr("data-taxid"),
                    taxRate: $("#itemTax").val()

            },
            url: "<?php echo base_url() ?>Artransaction/updateRowDetail",
            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 id="trItem' + $("#itemList").val() + '"> <td>' + $("#itemList").attr("data-lineNo") + '</td>' +
                    '<td>' + $("#itemList option:selected").text() + '</td>' +
                    '<td>' + $("#itemdesc").val() + '</td>' +
                    '<td class="tac">' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                     '<td class="tac">' + $("#itemqte").val() + '</td>' +
                    '<td class="amount">' + accounting.formatNumber($("#itemunitprice").val(),2) + '</td>' +
                    '<td class="amount">' + $("#itemAmountET").val() + '</td>' +
                    '<td class="tac">' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                    '<td class="amount">' + $("#itemTaxAmount").val() + '</td>' +
                    '<td class="amount">' + $("#itemAmountIT").val() + '</td>' +
                    '<td class="tac">' +
                    '<button data-itemID="' + $("#itemList").val() + '"  data-taxcode="' + $("#displayTaxCode").text() + '" data-taxrate="' + $("#itemTax").val() + '"  onClick="editRow(this)" data-taxid="' + $("#itemTax").attr("data-taxid") + '" data-myid="' + $(me).attr("data-myid") + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                    ' <button onclick="deleteSaleItemRow(this)" data-locationID="' + $(me).attr("data-locationID") + '" data-myid="' + dID + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>' +
                    '</td>' +
                    '</tr>'
                    );
                    getTotal ();
            } });
            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 deleteSaleItemRow(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: {
                    rowID :$(me).attr("data-myid"),
                    invoiceId : $("#saleInvoiceId").val()
                    },
                    url: "<?php echo base_url() ?>Artransaction/deleteSaleItemRow",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully deleted");
                            delRowInvoice(me);
                    } });
    });
            getTotal();
    }
    
    
        function deleteNormalSaleItemRow(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: {
                    rowID :$(me).attr("data-myid"),
                    invoiceId : $("#saleInvoiceId").val(),
                    itemID: $(me).attr("data-itemID"),
                    deliveryID : $(me).attr("data-deliveryDetailID"),
                    },
                    url: "<?php echo base_url() ?>Artransaction/deleteNormalSaleItemRow",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully deleted");
                            delRowInvoice(me);
                    } });
    });
            getTotal();
    }


    function editRowCharge(me){

        var tax = '';
        if(gstStatus){

            tax = '<td class="span2">\
                        <div class="input-prepend">\
                            <input disabled="disabled" 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 disabled="disabled" 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">OS</span>\
                        </div>\
                  </td>';
        }

    var tr = $(me).parent().parent();
            if (!$("#chargeAccount").length)
    {
    $(tr).replaceWith('<tr><td>' + $(me).parent().parent().find("td").eq(0).html() + '</td>' +
            '<td class="span2" ><select data-lineNo="' + $(me).parent().parent().find("td").eq(0).html() + '" 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);
        ?>
            '<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="span6" id="chargeAmount" onchange="calculChargeAmount()" name="chargeAmount" value="' + $(me).parent().parent().find("td").eq(3).html() + '" class="input-mini validate[required, custom[number]]" type="text" placeholder="Amount"></td>'+
            //'<input class="span6" data-taxid="" id="inclusiveTax" onchange="modAmount(this)" name="incTax" class="tac" type="checkbox">Inc. Tax</td>' +
            tax+
            '<td class="span1"> <input disabled="disabled" 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 tr = $(me).parent().parent();
            var taxPercent = $("#listTax").val();
            var taxID = $("#listTax").attr('data-taxid');
            console.log(taxID);
            $("#chargeAccount").val($(me).attr("data-accid"));
            $("#listTax").val($(me).attr("data-taxid"));
            $(tr).replaceWith('<tr><td>' + $("#chargeAccount").attr("data-lineNo") + '</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 saveCharge(me) {
    var tr = $(me).parent().parent();
    $(me).attr("disabled","disabled");
            $.ajax({
            type: "POST",
                    data: {
                        invoiceId : $("#saleInvoiceId").val(),
                        rowID : $(me).attr("data-myid"),
                        accountNoID : $("#chargeAccount").val(),
                        chargeDescription : $("#chargedesc").val(),
                        amountExcludedTax :  accounting.unformat($("#chargeAmount").val()),
                        taxID : $("#listTax").attr('data-taxid'),
                        taxAmount : accounting.unformat($("#chargetaxAmount").val()),
                        taxRate: $("#listTax").val(),
                        amountIncludedTax : accounting.unformat($("#chargeAmountIT").val())

                    },
                    url: "<?php echo base_url() ?>Artransaction/updateCharge",
                    success: function(data) {
                            if(gstStatus){
                              var taxText = '<td>' + $("#listTax option:selected").text() + '</td>';
                            }else{
                              var taxText = '<td>' + $("#nonGSt").val() + '</td>';
                            }
                    msg (2, "alert alert-success", "Details successfully updated");
                            var taxPercent = $("#listTax").val();
                            var taxID = $("#listTax").attr('data-taxid');
                            $(tr).replaceWith('<tr><td>' + $("#chargeAccount").attr("data-lineNo") + '</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>' + $("#listTax option:selected").attr("data-taxcode") + ' | ' + $("#listTax option:selected").attr("data-tax") + '</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: {
                    rowID :$(me).attr("data-myid"),
                    invoiceId : $("#saleInvoiceId").val()
                    },
                    url: "<?php echo base_url() ?>Artransaction/deleteSaleCharge",
                    success: function(data) {
                    msg (1, "alert alert-success", "Details successfully deleted");
                            delRowInvoice(me);
                            getTotal();
                    } });
    });
            getTotal ();
    }



    function taxPopup () {
    $('#popupModal').modal('show');
            $("#_popupTitle").html("Purchase Invoice");
            $("#_popupContent").html('' +
            '<label>Select a tax</label>' +
            '<select style="width:100%;" onclick="calculChargeAmount()" name="listTaxPopup" id="listTaxPopup"  class= "validate[required]">' +
<?php
if ($taxmaster) {
    foreach ($taxmaster as $row2) {
        $temp = str_replace(array("\n", "\r","'"), " ", $row2->name);
        ?>
            '<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();
              $("#itemTax" ).focus();
    });
            $("#calcul").trigger("click");
    }

    function addNewItemRow(){
    if (!$("#itemList").length) {
    $('' +
            '<tr><td>' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
            '<td class="span2"> <select class="span12" onclick="displaysItemDefaultValue()" name="itemList" id="itemList" class="span12"><option></option>' +
            '</select></td>' +
            '<td class="span2"><input id="itemdesc"  class="span12" type="text"></td>' +
              '<td class="span1"><select onchange="getLatestItemPrice()" id="idUnitOfMeasure" class="span12"><option></option></select></td>'+
              '<td class="span1"><input id="itemqte" onkeyup="calculamount()"  name="itemqte" class="span12 validate[required,custom[integer]]" type="text" placeholder="Qty"></td>' +
            '<td class="span1"><input id="itemunitprice" onkeyup="calculamount()" name="itemunitprice" class="span12 amount validate[required,custom[number]]" type="text" placeholder="Unit Priece"></td>' +
            '<td class="span1"><input id="itemAmountET" name="itemAmountET" disabled class="input-mini amount validate[required]" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1"><div class="input-prepend"><input data-taxid="" id="itemTax" onkeyup="calculamount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)"><span onclick="taxPopup ()" style="margin-top:0;" id="displayTaxCode"  class="btn add-on">....</span></div></td>' +
            '<td class="span1"><input id="itemTaxAmount" name="itemTaxAmount" disabled class="span12 amount" type="text" placeholder="Tax Amount"></td>' +
            '<td class="span1"><input id="itemAmountIT" name="itemAmountIT" disabled 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"><i class="i-checkmark-3"></i></button>' +
            ' <button id="btnCancel" class="btn-icon btn-mini  btn-danger-form" onclick="delRowInvoice(this)" type="button"><i class="i-cross"></i></button>' +
            '</td>' +
            '</tr>').insertBefore("#trInfos");
            refreshItemList ();
            $('#itemList').select2();
            
            $('#idUnitOfMeasure').select2();
            
    
    } 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 : $("#saleInvoiceId").val(),
                    itemID : $("#itemList").val(),
                     itemdescription : $("#itemdesc").val(),
                    lineNo : $("#trInfos").attr("data-currentRow") * 1 + 1,
                    quantity : $("#itemqte").val(),
                    umid : $("#idUnitOfMeasure").val(),
                    unitPrice: accounting.unformat($("#itemunitprice").val()),
                    taxAmount : accounting.unformat($("#itemTaxAmount").val()),
                    currentTotalInvoice : accounting.unformat($("#totalpayable").val()),
                    currentTaxAmount : accounting.unformat($("#totalamount").val()),
                    amountIncludedTax : accounting.unformat($("#itemAmountIT").val()),
                    amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
                    taxID: $("#itemTax").attr("data-taxid"),
                    taxRate: $("#itemTax").val()

            },
            url: "<?php echo base_url() ?>Artransaction/saveNewSaleDetailOnly",
            success: function(data) {
            msg (1, "alert alert-success", "Details successfully saved");
                    var resul = eval ("(" + data + ")");
                    $('' +
                            '<tr id="saleItemInList' + $("#itemList").val() + '">' +
                            '<td>' + ($("#trInfos").attr("data-currentRow") * 1 + 1) + '</td>' +
                            '<td>' + $("#itemList option:selected").text() + '</td>' +
                            '<td>' + $("#itemdesc").val() + '</td>' +
                            '<td class="tac">' + $("#idUnitOfMeasure option:selected").text() + '</td>' +
                            '<td class="quantity">' + $("#itemqte").val() + '</td>' +
                            '<td class="amount">' + $("#itemunitprice").val() + '</td>' +
                            '<td class="amount">' + $("#itemAmountET").val() + '</td>' +
                            '<td class="tac">' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                            '<td class="amount">' + $("#itemTaxAmount").val() + '</td>' +
                            '<td class="amount">' + $("#itemAmountIT").val() + '</td>' +
                            '<td class="tac">' +
                            '<button data-itemID="' + $("#itemList").val() + '"  data-taxcode="' + $("#displayTaxCode").text() + '" data-taxrate="' + $("#itemTax").val() + '"  onClick="editRow(this)" data-taxid="' + $("#itemTax").attr("data-taxid") + '" data-myid="' + resul.detailID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                            ' <button onclick="deleteSaleItemRow(this)"  data-myid="' + resul.detailID + '" class="btn-icon btn-mini btn-danger-form"><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");
                    getTotal();
            }
    }); //end ajax
    }


 function addnewchargerow(){
    var tax = '';
    if(gstStatus){
        tax = '<td class="span2">\
                        <div class="input-prepend">\
                            <input disabled="disabled" data-taxid="" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)" value="">\
                            <span 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 disabled="disabled"  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">OS</span>\
                        </div>\
                  </td>';
    }

    if (!$("#chargeAccount").length) {
    $('' +
            '<tr><td>' + ($("#trInfosCharge").attr("data-currentRow") * 1 + 1) + '</td>' +
            '<td class="span2"> <select name="chargeAccount" id="chargeAccount" class="span12" validate[required]"><option></option>' +
<?php
if ($chargeAccount) {
    foreach ($chargeAccount as $row) {
        $v =  str_replace(array("\n", "\r","'"), " ", $row->acctName);
        $v = trim(preg_replace('/\s+/', ' ', $v));
        ?>
            '<option value="<?php echo $row->ID; ?>"><?php echo substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7) . " | "; echo $v; ?></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 amount validate[required, custom[number]]" type="text" placeholder="Amount"></td>' +
            tax+
            '<td class="span1"><input id="chargetaxAmount"  name="chargetaxAmount" class="span12 amount" type="text" placeholder="Amount"></td>' +
            '<td class="span1"><input disabled  id="chargeAmountIT" name="chargeAmountIT" class="span12 amount" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1">' +
            '<button onclick = "savenewchargerow(this)" class="btn-icon btn-mini btn-success-form" type="button"><i class="i-checkmark-3"></i></button>' +
            ' <button onclick="delRowInvoice(this)" id="btnCancelCharge" class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-cross"></i></button>' +
            '</td>' +
            '</tr>'
            ).insertBefore("#trInfosCharge");
            $('#chargeAccount').select2();
            if($('#listTax option').length){
              $('#listTax').select2();
            }
    } else{
    msg (2, "alert", "Please, do save the current details before adding new one");
    }
    }
    
    function savenewchargerow(me){
        var dataSet = {
                        invoiceId : $("#saleInvoiceId").val(),
                        lineNo : $("#trInfosCharge").attr("data-currentRow")*1 +1,
                        accountNoID : $("#chargeAccount").val(), 
                        chargeDescription : $("#chargedesc").val(),
                        taxAmount : accounting.unformat($("#chargetaxAmount").val()),
                        currentTotalInvoice : accounting.unformat($("#totalpayable").val()),
                        amountIncludedTax : accounting.unformat($("#chargeAmountIT").val()),
                        amountExcludedTax: accounting.unformat($("#chargeAmount").val()),
                        taxID: $("#listTax").attr("data-taxid"),
                        taxRate: $("#listTax").val()

                          };
            $(me).attr("disabled","disabled");              
        $.ajax({
                  type: "POST",
                  data: dataSet,
                   url: "<?php echo base_url() ?>Artransaction/saveNewSaleDetailOnlyCharges",
                   success: function(data) {
                   if(gstStatus){
                      var taxText = '<td>' + $("#listTax option:selected").text() + '</td>';
                    }else{
                      var taxText = '<td>' + $("#nonGSt").val() + '</td>';
                    }

                   msg (2,"alert alert-success","Details successfully saved");
                        var resul = eval ("(" + data + ")");
                        var taxPercent = $("#listTax").val();
                        var taxID = $("#listTax").attr('data-taxid'); 
                        $(''+
                           '<tr> <td>' + ($("#trInfosCharge").attr("data-currentRow")*1 +1) + '</td>' +
                          '<td>' + $("#chargeAccount option:selected").text() + '</td>'+
                          '<td>' + $("#chargedesc").val() + '</td>'+
                          '<td class="amount">' + $("#chargeAmount").val() + '</td>'+
                          '<td>' + $("#displayCode").text() + " | " + taxPercent + '</td>'+
                          '<td class="amount">' + $("#chargetaxAmount").val() + '</td>'+
                          '<td class="amount">' + $("#chargeAmountIT").val() + '</td>'+
                          '<td><button onClick="editRowCharge(this)"  data-percent="'+taxPercent+'" data-code="'+$('#displayCode').text()+'"  data-myid="' + resul.detailID + '" data-accid="' + $("#chargeAccount").val() + '" data-taxid="' + taxID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                            '<br /><button onclick="deleteCompanyCharge(this)" data-myid="' + resul.detailID  + '" 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();
                 }
           }); //end ajax
    }

          function getItemListOfUM(){
        $("#idUnitOfMeasure").empty();
        if ($("#itemList option:selected").attr("data-umid") > 0 && $("#itemList option:selected").attr("data-umCode")!=null){
        //  $("#idUnitOfMeasure").select2('destroy'); 
            $("#idUnitOfMeasure").append("<option data-unitm='1' data-factor='1'  value="+ $("#itemList option:selected").attr("data-umid") +">"+ $("#itemList option:selected").attr("data-umCode") +"</option>");
           $("#idUnitOfMeasure").select2("val",$("#itemList option:selected").attr("data-umid"));

        }
             $.ajax({
            type: "POST",
            data : "unitFrom=" + $("#itemList option:selected").attr("data-umid") + "&itemID=" + $("#itemList").val() ,
            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);
            }
          }); 
    }

    function updateMaster(){
     if( $("#SaleDetailForm").validationEngine('validate') && finanEngine('financhk')){
        if(confirm('Please, confirm update ...')){
    $.ajax({
    type: "POST",
            data: {
                    invoiceId : $("#saleInvoiceId").val(),
                    custumerpono : $("#custumerpono").val(),
                    dateInvoice : $("#createDate").val(),
                    project : $("#project").val(),
                    termsID : $("#term").val(),
                    memo : $("#memo").val(),
                    customer :$("#customer").val(),
                    shipToID : $("#shiptoAddress").val(),
                    formNo :$("#formNo").val(),
                    agendID: $("#saler").val()

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

    function getTermDescription(me){
         $("#termDescription").html("");
    $("#termDescription").html($("#term option:selected").attr("data-desc"));
}

function loadCustomerDefaultValue(me){
        $('#currency').attr("value",'');
        $('#exchange_rate').attr("value",'');
        $("#termDescription").text('');
        $("#shiptoDesc").html('');
          $('#shiptoAddress').select2("val", "");
        $.ajax({
                type: "POST",
                data: "customer="+ $("#customer").val(),
                url: "<?php echo base_url() ?>artransaction/loadCustomerDefaultValue",
                dataType:'json',
                success: function(data) {
                        console.log(data);
                        $('#currency').val(data.records[0].currencyWord);
                        $('#currency').attr("data-currencyID",data.records[0].currencyID);
                        $('#exchange_rate').val(accounting.formatNumber(data.records[0].exchangeRate,5));
                        if(data.shipto != ""){
                            $("#shiptoAddress").html('<option value="null"></option>' + data.shipto);
                           
                        }else{
                            $("#shiptoAddress").html('<option></option>');
                        }

                        $("#term").select2('val',data.records[0].termsID).trigger('change');
                }
         });
        
}

function displaysAdress(){
                $("#shiptoDesc").html("");
                $("#shiptoDesc").select2('val','');
                console.log($("#shiptoAddress option:selected").attr("data-line2"));
                if($("#shiptoAddress option:selected").attr("data-line2")=="undefined"){
                    return false;
                }
                $("#shiptoDesc").html($("#shiptoAddress option:selected").attr("data-line1") +
                                                           "&#10;" + $("#shiptoAddress option:selected").attr("data-line2") +
                                                           "&#10;" + $("#shiptoAddress option:selected").attr("data-line3"));
                
}

</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('editDirectSaleInvoice') ?></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">

      	<div class="block">
            <div class="head">
     <h2><strong><?php echo $this->lang->line('editDirectSaleInvoice') ?></strong></h2>
</div><!-- head -->
<form id="SaleDetailForm" action="#">  
      	<div class="content">
            <?php
            $memo = "";
            $employeeName = "";
            $shippingmethod = "";
            $locationID = "";
            $type ="";
            $salepersionID = 0;
            if ($invoice) {

                foreach ($invoice as $rowIn) {
                    //var_dump($rowIn);
                    $memo = $rowIn->memo;
                    $type = $rowIn->invoiceCodeID;
                    $employeeName = $rowIn->employeeName;
                    $shippingmethod = $rowIn->shippingmethod;
                    $locationID = $rowIn->locationID;
                    $salepersionID = $rowIn->agentID;
                    ?> 
                    <input type="hidden" id="saleInvoiceId" value="<?php echo $rowIn->InvID; ?>" />
                    <div class="row-fluid scRow">                            
                        <div class="span4 scCol">
                            <div class="block ns" id="grid_block_1">
                                       <div class="controls-row">
                     
                                        <div class="span4"><?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="span11" 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="span4"><?php echo $this->lang->line('customer'); ?></div>
                                        <div class="span8">
                                            <select class="span12 validate[required]" id="customer" onchange="loadCustomerDefaultValue()">
                                                    <option></option>
                                                    <?php
                                                        if ($customer) {
                                                            foreach ($customer as $row) {
                                                        ?>
                                                            <option  <?php if($row->ID == $rowIn->customerID ) echo "selected='selected'" ?> value="<?php echo $row->ID; ?>"> <?php echo $row->customerName; echo ($row->gstRegNo != '' && $row->gstRegNo != '0')?' (GST)':''; ?></option>
                                                        <?php }
                                                    } ?>
                                                </select>
                                        </div>
                                    </div> <!-- row -->
                                    
                                    <div class="controls-row">
                                        <div class="span4"><?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->salesInvoiceDate)); ?>" />
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('custumerpono') ?></div>
                                        <div class="span8">
                                            <input id="custumerpono" name="custumerpono" type="text" class="span12"  value="<?php echo $rowIn->customerPoNo; ?>" />
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span4"><?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="span4 scCol">
                            <div class="block" id="grid_block_2">

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

                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('location') ?></div>
                                        <div class="span8">
                                            <input type="text" data-idLocation="<?php echo $rowIn->locationID; ?>" id="location" class="span12" disabled="disabled" value="<?php echo $rowIn->location; ?>" />
                                        </div>
                                    </div> <!-- row -->

                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('terms') ?></div>
                                        <div class="span8">
                                            <select id="term" onchange="getTermDescription(this)" class="span12 validate[required]">
                                               
                                                    <?php
                                                        if ($terms != '') {
                                                            foreach ($terms as $row) {
                                                        ?>
                                                            <option <?php if($rowIn->termsID == $row->ID) echo "selected"; ?> data-desc="<?php echo $row->termDescription; ?>" value="<?php echo $row->ID; ?>"><?php echo $row->termName; ?></option>
                                                        <?php }
                                                    } ?>
                                            </select>
                                        </div>
                                    </div> <!-- row -->

                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('termsdesc') ?></div>
                                        <div class="span8">
                                            <textarea class="span12" disabled="disabled" id="termDescription"><?php echo $rowIn->termDescription ?></textarea>
                                        </div>
                                    </div> <!-- row -->
                            </div><!-- grid block 1-->
                        </div><!-- scCol -->
                        <div class="span4 scCol">
                            <div class="block ns" id="grid_block_3">
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('shipto') ?></div>
                                        <div class="span8">
                                            <select id="shiptoAddress" onchange ="displaysAdress()" class="span12">
                                                 <option  data-line1="<?php echo $rowIn->line1; ?>" data-line2="<?php echo $rowIn->line2; ?>" data-line3="<?php echo $rowIn->line3; ?>" value="<?php echo  $rowIn->shipToID;  ?>"><?php echo $rowIn->addressCode; ?></option>
                                            </select>
                                           
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('shiptoDesc') ?></div>
                                        <div class="span8">
                                            <textarea id="shiptoDesc" class="span12" disabled="disabled"><?php echo $rowIn->addressName; ?>
        <?php echo $rowIn->line1; ?>
        <?php echo $rowIn->line2; ?>
        <?php echo $rowIn->line3; ?>
                                            </textarea>
                                        </div><!-- span -->
                                    </div><!-- row control -->
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('currency') ?></div>
                                        <div class="span8">
                                            <input type="text" class="span12" disabled="disabled" value="<?php echo $rowIn->currencyWord; ?>" />
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('exchangeRate') ?></div>
                                        <div class="span8">
                                            <input type="text" class="span12 tar" disabled="disabled" value="<?php echo $rowIn->exchangeRate; ?>" />
                                        </div>
                                    </div> <!-- 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 -->     
            </form>
                    </div><!-- row-fluid scRow-->

			    <?php
			    }
			}
			?>

            <div class="row-fluid scRow">                            
                <div class="span12 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="head">
                            <h2><?php echo $this->lang->line('items') ?></h2>
                            <ul class="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 id="btnAddNew212" <?php if($type==2) echo 'href="#trInfos"'; ?> onclick="<?php if($type==2) echo "addNewItemRow()"; ?>" title="Add New"><span class="i-plus-2"></span></a></li>
                            </ul>
                        </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('items') ?></th>
                                        <th><?php echo $this->lang->line('description') ?></th>
                                        <th class="tac"><?php echo $this->lang->line('um') ?></th>
                                        <th class="quantity"><?php echo $this->lang->line('quantity') ?></th>
                                        <th class="amount"><?php echo $this->lang->line('unitPrice') ?></th>
                                        <th class="amount"><?php echo $this->lang->line('amountExcludeTax') ?></th>
                                        <th><?php echo $this->lang->line('tax') ?></th>
                                        <th class="amount"><?php echo $this->lang->line('taxAmount') ?></th>
                                        <th class="amount"><?php echo $this->lang->line('amountIncludeTax') ?></th>
                                        <th><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $t_taxAmount = 0;
                                    $t_amountIncludedTax = 0;
                                    $lastrow = 0;
                                    if ($items && $invoice) {
                                        foreach ($items as $row) {
                                            if ($lastrow < $row->lineNo)
                                                $lastrow = $row->lineNo;
                                            $t_taxAmount+= $row->taxAmount;
                                            $t_amountIncludedTax += $row->amountIncludedTax;
                                            ?>
                                            <tr id="trItem<?php echo $row->itemID; ?>">
                                                <td><?php echo $row->lineNo; ?></td>
                                                <td><?php echo $row->name . " [" . $row->itemCode . "]" ?></td>
                                                <td><?php echo $row->itemdescription; ?></td>
                                                 <td class="tac"><?php echo $row->unitOfMeasure; ?></td>
                                                 <td class="tac"><?php echo $row->quantity; ?></td>
                                                <td class="amount"><?php echo number_format($row->unitPrice, 2); ?></td>
                                               
                                                <td class="amount"><?php echo number_format($row->amountExcludedTax, 2); ?></td>
                                                <td class="tac"><?php echo $row->code . " | " . $row->taxRate; ?></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="editRow(this)"  <?php if($type==1) echo "disabled"; ?>
                                                            data-taxcode="<?php echo $row->code; ?>" data-itemID="<?php echo $row->itemID; ?>" data-locationID="<?php echo $locationID; ?>" data-taxrate="<?php echo $row->taxRate; ?>"
                                                            data-taxid="<?php echo $row->taxID; ?>" data-myid="<?php echo $row->ID; ?>" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>
                                                      <button data-itemID="<?php echo $row->itemID; ?>" onClick=" <?php if($type==1) echo "deleteNormalSaleItemRow(this)"; else echo "deleteSaleItemRow(this)"; ?>" data-deliveryDetailID ="<?php echo $row->doID; ?>" data-myid="<?php echo $row->ID; ?>" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>
                                                </td>
                                            </tr>
                                        <?php
                                    } ?>
                                          <tr id="trInfos" data-currentRow="<?php echo $lastrow; ?>">
                                    <td colspan="11">
                                        <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 id="trInfos" data-currentRow="<?php echo $lastrow; ?>">
                                    <td colspan="11">
                                        <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">
                            <h2><?php echo $this->lang->line('othercharges') ?></h2>
                            <ul class="buttons">
                                <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="addnewchargerow()" title="Add New"><span class="i-plus-2"></span></a></li>
                            </ul>
                        </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="amount"><?php echo $this->lang->line('amount') ?></th>
                                        <th><?php echo $this->lang->line('tax') ?></th>
                                        <th class="amount"><?php echo $this->lang->line('taxAmount') ?></th>
                                        <th class="amount"><?php echo $this->lang->line('amountIncludeTax') ?></th>
                                        <th><?php echo $this->lang->line('action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $t_amountExcludedTaxC = 0;
                                    $t_taxAmountC = 0;
                                    $lastrow = 0;
                                    if ($charges && $invoice) {
                                        foreach ($charges as $row) {
                                            if ($lastrow < $row->lineNo)
                                                $lastrow = $row->lineNo;
                                            $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->chargeDescription; ?></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>
                                                    <button onClick="editRowCharge(this)" data-taxid="<?php echo $row->taxId ?>" data-percent="<?php echo $row->taxPercentage; ?>" data-code ="<?php echo $row->code; ?>" 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><br />
                                                    <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 id="trInfosCharge" data-currentRow="<?php echo $lastrow; ?>">
                                    <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 id="trInfosCharge" data-currentRow="<?php echo $lastrow; ?>">
                                    <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="span6 scCol">
                    <div class="block" id="grid_block_4">
                        <div class="content np">
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('shippingMethod') ?></div>
                                <div class="span8">
                                    <input type="text" class="span12" disabled="disabled" value="<?php echo $shippingmethod; ?>" />
                                </div><!-- span -->

                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span4"><?php echo $this->lang->line('saleperson') ?></div>
                                <div class="span8">
                                    <select class="span12" id="saler"><option></option>
                                                    <?php
                                                    if ($saler != '') {
                                                        foreach ($saler as $row) {
                                                            ?>
                                                            <option <?php if($row->ID == $salepersionID) echo "selected" ?> value="<?php echo $row->ID; ?>"> <?php echo $row->employeeName; ?></option>
    <?php }
}
?>
                                                </select></div>
                            </div><!-- row control -->


                        </div>    
                    </div><!-- grid block 1-->
                </div><!-- scCol -->   

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

                                <div class="span5"><?php echo $this->lang->line('totalTaxAmount') ?></div>
                                <div class="span7">
                                    <input id="impotpayable" value="<?php echo (number_format($t_taxAmountC + $t_taxAmount, 2)); ?>" class="span12 amount" type="text" placeholder="0" disabled="disabled" >
                                </div>
                            </div><!-- row control -->
                            <div class="controls-row">
                                <div class="span5"><?php echo $this->lang->line('totalReceivable') ?></div>
                                <div class="span7">
                                    <input id="totalpayable" disabled="disabled" value="<?php echo (number_format($t_amountExcludedTaxC + $t_amountIncludedTax, 2)); ?>"  class="span12 amount" type="text" placeholder="0">
                                </div>
                            </div><!-- row control -->

                        </div>    
                    </div><!-- grid block 1-->
                </div><!-- row-fluid scRow-->

                </form>
            </div><!-- grid 1 -->

        </div><!-- grid 1 -->
    </div><!-- wrap -->
</div><!-- content -->


