<style type="text/css">
    .amount{
        text-align: right;
    }
    
    .btn-group button {
        height:30px;}
    
    button {
        margin-left:2px;
    }
   
    #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 {
        font-size: 10px;
    }
    #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
	if(isset($taxmaster) && !empty($taxmaster)){ 
    	foreach($taxmaster as $k=>$v){
        	$val = null;
        	$val = array_search('NR',(array) $taxmaster[$k]);  
        	if($val != null){
            	$nonGstTaxID = $taxmaster[$k]->ID;
            	break;
        	}
    	}
	}
?>
<script type="application/javascript">
			
$(document).ready(function(){
	$('select').select2();

  function format(state) {
      var text = state.text.match(/\(GST\)/g);
      var modTxt = state.text.replace("(GST)","");
      if(text != null)  return '<span style="color:#85c420;">'+modTxt+"</span>";
      else              return modTxt;
  }
  $("#supplier").select2({
      formatResult: format,
      formatSelection: format,
      escapeMarkup: function(m) { return m; }
  });
  

	$.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
        });
});


var gstStatus = true;
function loadSupplierDefaultValue(me){
  $('#currency').attr("value",'');
  $('#exchange_rate').attr("value",'');
  var date = $.datepicker.formatDate('yymmdd', new Date());
  $.ajax({
      type: "POST",
      data: "supplier="+ $("#supplier option:selected").val()+'&effdate='+date,
      url: "<?php echo base_url() ?>aptransaction/loadSupplierDefaultValue",
      dataType: "JSON",
      success: function(data) {
              /*var resul = eval ("(" + data + ")"); */
              console.log(data);
              $('#currency').attr("value",data[0].currencyWord);
              $('#currency').attr("data-curID",data[0].currencyID);
              //$('#exchange_rate').attr("value",data[0].exchangeRate);
              $('#exchange_rate').val(accounting.formatNumber(data[0].exchangeRate,5));
			  $('#term').select2('val',data[0].termsID).trigger('change');
              gstStatus = isGstRegistered($('#supplier').select2('val'),'supplier');
      }
  });
}

function refreshSupplier(){
            //<span style="color:#85c420;">'+modTxt+"</span>
  $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>supplier/refreshSupplier",
    success: function(data) {
    
       var resul = eval ("(" + data + ")"); 
               var n=resul.records.length;
               var i=0;
               var opt='' +
          '<option></option>';
                for (i=0;i<n;i++)
                  if(resul.records[i].gstRegNo != ''){
                    opt=opt + '<option value="' + resul.records[i].id + '">' + resul.records[i].supplierName + ' (GST)</option>';
                  }else{
                    opt=opt + '<option value="' + resul.records[i].id + '">' + resul.records[i].supplierName + '</option>';
                  }
      $('#supplier').empty();
              $('#supplier').append(opt);
    }
     });
   
}




/**function getItemCode(me){
$.ajax({
    type: "POST",
    data: "itemCode="+$(me).val(),
    url: "<?php echo base_url() ?>purchasetransaction/getItemCodes",
    success: function(data) {
       $("#itemcode").attr("data-source", data);
    }
});
}  */

function refreshTerms(){
   $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>purchasetransaction/refreshTerms",
    success: function(data) {

       var resul = eval ("(" + data + ")"); 
var n=resul.records.length;
var i=0; 
var opt='' +
    '<option></option>';
for (i=0;i<n;i++)
opt=opt + '<option value="' + resul.records[i].id + '">' + resul.records[i].termName + '</option>';
            $('#term').empty();
$('#term').append(opt);
    }
});

}

function refreshProject(){
 $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>purchasetransaction/refreshProject",
    success: function(data) {

       var resul = eval ("(" + data + ")"); 
var n=resul.records.length;
var i=0;
var opt='' +
    '<option></option>';
for (i=0;i<n;i++)
opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].projectName + '</option>';
            $('#project').empty();
$('#project').append(opt);
    }
});
} 


function getTermDescription(me){
$.ajax({
    type: "POST",
    data: "term="+ me.value,
    url: "<?php echo base_url() ?>purchasetransaction/getTermDescription",
    success: function(data) {
        	$('#termDescription').val(data);
    }
});
}


function saveParchaseRow(me){

 if( $("#parchaseDetailForm").validationEngine('validate') && finanEngine('financhk')){
 if ( $("#purchaseInvoiceId").val()=="null"){
    getTotal();
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: {
            shippingMethodID : $("#shippingmethod").val(),
            employeeID : $("#purchaser").val(),
            memo : $("#memo").val(),
              totalPayable : accounting.unformat($("#totalpayable").val()), 
              totalTaxAmount :  accounting.unformat($("#totalamount").val()),
              supplierID : $("#supplier").val(),
              locationID :  $("#location").val(),
              formNo : $("#formNo").val(),
              invoiceDate: $("#createdDate").val(),
              supplierInvoiceNo : $("#supinvoicenumber").val(),
              projectID: $("#project").val(),
              termsID: $("#term").val(),
              currencyID: $("#currency").attr('data-curID'),
              exchangeRate : $("#exchange_rate").val(),
              shipToID : $("#shiptoAddress").val(),
              lineNo : $("#listDetails").attr("data-currentRow")*1 +1,
              itemID:  $("#itemComboList").val(),
              itemdescription: $("#itemdes").val(),
              quantity : $("#itemqte").val(),
              unitPrice: accounting.unformat($("#itemunitprice").val()),
              amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
              taxAmount: accounting.unformat($("#itemTaxAmount").val()),
              amountIncludeTax: accounting.unformat($("#itemAmountIT").val()),
              taxID: $("#itemTax").attr("data-taxid"),
              taxRate: $("#itemTax").val()

            },
     url: "<?php echo base_url() ?>purchasetransaction/savePurchaseRow",
     success: function(data) {
     var resul = eval ("(" + data + ")"); 
      $("#purchaseInvoiceId").val(resul.invoiceID);
      $(''+
       '<tr>  <td>' +  ($("#listDetails").attr("data-currentRow")*1 +1) + '</td>' +
              '<td>' +  $("#itemComboList option:selected").text() + '</td>'+
              '<td>' + $("#itemdes").val() + '</td>'+
              '<td class="amount">' + accounting.formatNumber($("#itemunitprice").val(),2) + '</td>'+
              '<td>' + $("#itemqte").val() + '</td>'+
              '<td class="amount">' + accounting.formatNumber($("#itemAmountET").val(),2) + '</td>'+
              '<td>' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>'+
              '<td class="amount">' + accounting.formatNumber($("#itemTaxAmount").val(),2) + '</td>'+
              '<td>' + $("#itemAmountIT").val() + '</td>'+
              '<td>'+
              '<button onclick="deleteCompanyDetail(this)" data-detailid='+ resul.detailID +' class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-trashcan"></i></button>'+
              '</td>'+
          '</tr>'
            ).insertBefore( "#trInfos" );
            var op =$("#listDetails").attr("data-currentRow")*1;
            $("#listDetails").attr("data-currentRow", op +1);
            $("#btnCancel").trigger("click");
            $("#calcul").trigger( "click" );
            getTotal();
            $.ajax({
              type: "POST",
              data: {
                        invoiceId : $("#purchaseInvoiceId").val(),
                        totalPayable : accounting.unformat($("#totalpayable").val()), 
                        totalTaxAmount : accounting.unformat( $("#totalamount").val())
                      },
              url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
              success: function(data) {
                       //update the invoice after delete
                      }
              });
   msg (1,"alert alert-success","Details successfully saved");
    } //end function
});//end ajax
}else{
    $.ajax({
    type: "POST",
    data: {
              invoiceId : $("#purchaseInvoiceId").val(),

              itemID:  $("#itemComboList").val(),
              itemdescription: $("#itemdes").val(),
              quantity : $("#itemqte").val(),
              lineNo : $("#listDetails").attr("data-currentRow")*1 +1,
              unitPrice: accounting.unformat($("#itemunitprice").val()),
              amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
              taxAmount: accounting.unformat($("#itemTaxAmount").val()),
              amountIncludeTax: accounting.unformat($("#itemAmountIT").val()),
              taxID: $("#itemTax").attr("data-taxid"),
              taxRate: $("#itemTax").val()

            },
    url: "<?php echo base_url() ?>purchasetransaction/saveParchaseDetail",
    success: function(data) {
     msg (1,"alert alert-success","Details successfully saved");
      var resul = eval ("(" + data + ")"); 
$(''+
     '<tr>  <td>' +  ($("#listDetails").attr("data-currentRow")*1 +1) + '</td>' +
            '<td>' +  $("#itemComboList option:selected").text() + '</td>'+
            '<td>' + $("#itemdes").val() + '</td>'+
            '<td class="amount">' + accounting.formatNumber($("#itemunitprice").val(),2) + '</td>'+
            '<td >' + $("#itemqte").val() + '</td>'+
            '<td class="amount">' + accounting.formatNumber($("#itemAmountET").val(),2) + '</td>'+
            '<td>' + $("#displayTaxCode").text() + " | " +  $("#itemTax").val() + '</td>'+
            '<td class="amount">' + accounting.formatNumber($("#itemTaxAmount").val(),2) + '</td>'+
            '<td>' + $("#itemAmountIT").val() + '</td>'+
            '<td>'+
            '<button onclick="deleteCompanyDetail(this)" data-detailid='+ resul.detailID +' class="btn-icon btn-mini btn-danger-form" type="button"><i class="i-trashcan"></i></button>'+
            '</td>'+
    '</tr>'
).insertBefore( "#trInfos" );
var op =$("#listDetails").attr("data-currentRow")*1;
$("#listDetails").attr("data-currentRow", op +1);
$("#btnCancel").trigger("click");
    $( "#calcul" ).trigger( "click" );
    getTotal();
    $.ajax({
      type: "POST",
      data: {
                    invoiceId : $("#purchaseInvoiceId").val(),
                    totalPayable : accounting.unformat($("#totalpayable").val()), 
                    totalTaxAmount :  accounting.unformat($("#totalamount").val())
              },
      url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
      success: function(data) {
               //update the invoice after delete
              }
      });
}
}); //end ajax
} //end if data valide
}else {
    msg (1,"alert alert-error", "Data incorrect or invalid ...");
}
$( "#calcul" ).trigger( "click" );
}

function deleteCompanyDetail(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-small btn-success-form" id="detButton">Ok</button>' +
'<button class="btn-form btn-small 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: "detailsId="+ $(me).attr("data-detailid"),
    url: "<?php echo base_url() ?>purchasetransaction/deleteCompanyDetails",
    success: function(data) {
            msg (1,"alert alert-success","Data deleted succesfuly ...");
            var td=me.parentNode;
            var tr=td.parentNode;
            var tBody=tr.parentNode;
            tBody.removeChild(tr);
            getTotal();
            $.ajax({
              type: "POST",
              data: {
                        invoiceId : $("#purchaseInvoiceId").val(),
                            totalPayable : $("#totalpayable").val(), 
                        totalTaxAmount :  $("#totalamount").val()
                      },
              url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
              success: function(data) {
                       //update the invoice after delete
                      }
              });
            }
    });
});

$( "#calcul" ).trigger( "click" );
}

/**function getItemDetails(me){
$("#itemname").val("");
$("#itemdes").val("");
$.ajax({
    type: "POST",
    data: "code="+ me.value,
    url: "<?php echo base_url() ?>purchasetransaction/getItemDetails",
    success: function(data) {
            if(data!="item Not found"){
                     var resul = eval ("(" + data + ")");
                    $("#itemname").val(resul.name);
                    $("#itemdes").val(resul.description);
                    $("#itemTax").val(resul.tax);
                    $("#itemTax").attr("data-taxid",resul.taxID);
                    $("#displayTaxCode").text(resul.taxcode); 
            }else{
                    $("#itemdes").attr("placeholder",data);
                    $("#itemname").attr("placeholder",data);
                    $("#itemTax").val("");
                    $("#itemTaxAmount").val("");
                    $("#itemAmountIT").val("");
                    $("#itemTax").attr("data-taxid",""); 
                    $("#displayTaxCode").html("");
                    }
    }
});
}
 */
function calculamountET(){
    if  ($("#totalamount").val()=="NaN"){
        $("#totalamount").val("0");
        $("#impotpayable").val("0");
        $("#totalpayable").val("0");
    }
    //if ($("#itemTax").attr("data-taxid")=="") {
    //    taxPopup ();
    //}
    var j_itemAmountET =accounting.unformat($("#itemunitprice").val())*accounting.unformat($("#itemqte").val());
    $("#itemAmountET").val(accounting.formatNumber(j_itemAmountET,2));
    var j_itemTaxAmount=j_itemAmountET*$("#itemTax").val()/100;
    $("#itemTaxAmount").val(accounting.formatNumber(j_itemTaxAmount,2));
    $("#itemAmountIT").val(accounting.formatNumber(j_itemTaxAmount+j_itemAmountET,2));


}
    function displaysItemDefaultValue(){
        $("#itemdes").val($("#itemComboList option:selected").attr("data-desc"));
        $("#itemunitprice").val(accounting.formatNumber($("#itemComboList option:selected").attr("data-price"),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"));
    }
    
    function addRowInvoice(){
       if (!$("#itemComboList").length) {
            $(''+
                 '<tr><td class="span1">' + ($("#listDetails").attr("data-currentRow")*1 + 1) + '</td>'+
                    '<td class="span2" >' +
                        '<select id="itemComboList" class="span12" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        ?>
                                    '<option data-desc= "<?php echo addslashes($row->description); ?>" data-price= "<?php echo $row->supplierPrice; ?>" \n\
                                        data-taxid="<?php echo $row->inputTaxID; ?>" data-taxcode="<?php echo $row->inputTaxCode; ?>" \n\
                                        data-taxPercentage="<?php echo $row->inputTaxPercentage; ?>" value="<?php echo $row->ID; ?>"><?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 validate[required]" type="text" placeholder="Description"></td>'+
                        '<td class="span1"><input id="itemunitprice" onkeyup="calculamountET()" name="itemunitprice" class="span12 amount validate[required,custom[number]]" type="text" placeholder="Unit Priece"></td>'+
                        '<td class="span1"><input id="itemqte" onkeyup="calculamountET()"  name="itemqte" class="span12 validate[required,custom[integer]]" type="text" placeholder="Qty"></td>'+
                        '<td class="span1"><input id="itemAmountET" name="itemAmountET" disabled class="span12 amount validate[required]" type="text" placeholder="0.00"></td>'+
                        '<td class="span1"><div  class="input-prepend"><input data-taxid="" id="itemTax" disabled="disabled onkeyup="calculamountET()" 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="0.00"></td>'+
                        '<td class="span1"><input id="itemAmountIT" name="itemAmountIT" disabled class="span12 amount" type="text" placeholder="0.00"></td>'+
                        '<td class="span1">'+
                           '<button class="btn-icon btn-mini btn-success-form" onclick="saveParchaseRow(this)" title="Save" 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();

    }else{
    msg (1,"alert","Please, do save the current details before adding new one");
    }
    }
 
  				
					
function msg(n,type, message){
	
        $("#msg_div"+n +" p").html(message);
        $("#msg_div"+n).attr("class","alert " + type);
}

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

/**function checkformNumber(me){
        var answer ="no";
        $.ajax({
          type: "POST",
          data: "code="+ me.value,
          url: "<?php echo base_url() ?>purchasetransaction/checkformNumber",
          success: function(data) {
                  answer = data;
                  if(data=="yes"){
                          $("#formNo").attr("placeholder","Error: Number exist ...");
                          $("#formNo").val("");
                          msg (1,"alert", "This form number is already used ");
                  }
          }
   });
   return answer;
}
*/

//Save purchase order as invoice
function saveInvoice(me){
	if( $("#parchaseDetailForm").validationEngine('validate') && finanEngine('financhk')){
        if ( $("#purchaseInvoiceId").val()=="null"){
        getTotal();
            $(me).attr("disabled","disabled");
           	 $.ajax({
                  type: "POST",
                  data: {
                      			purchaseInvoiceCodeID:1,
                      			purchaseOrdID:$("#orderNo").val(),
                      			purchaserID:$("#purchaser").val(),
                      			supplierID : $("#supplier").val(),
                            formNo : $("#formNo").val(),
                            shipToID : $("#shiptoAddress").val(),
                            invoiceDate: $("#createdDate").val(),
                            supplierInvoiceNo : $("#supinvoicenumber").val(),
                            projectID: $("#project").val(),
                            termsID: $("#term").val(),
                            currencyID: $("#currency").attr('data-curID'),
                            exchangeRate : $("#exchange_rate").val(),
                            locationID :  $("#location").val(),
                            shippingMethodID : $("#shippingmethod").val(),
                            employeeID : $("#purchaser").val(),
                            memo : $("#memo").val(),

                          	//Sales order detail
                            suppInvDetail:getOrderDet(),

                            totalAmount: accounting.unformat($("#totalamount").val()),
                            totalPayable : accounting.unformat($("#totalpayable").val()), 
                            totalTaxAmount : accounting.unformat( $("#impotpayable").val())
                      },
                  url: "<?php echo base_url() ?>purchaseinvoice/saveInvoice",
                  success: function(data) {
                       $(me).removeAttr("disabled");
                        var resul = eval ("(" + data + ")"); 
						if(resul.status == 'success'){
							//alertBox(1,"The invoice successfully saved");
							$("#purchaseInvoiceId").val(resul.invoiceID);
							
							var urls = "<?php echo base_url();?>aptransaction/purchaseinvoice";
							window.location = urls;
						
						}
                  } // function	
            });//end ajax
          }else{              
              getTotal();
              $(me).attr("disabled","disabled");
              $.ajax({
                type: "POST",
                data: {
                              invoiceId : $("#purchaseInvoiceId").val(),
							  totalAmount: accounting.unformat($("#totalamount").val()),
                              totalPayable : accounting.unformat( $("#totalpayable").val()), 
                              totalTaxAmount : accounting.unformat( $("#impotpayable").val())
                        },
                url: "<?php echo base_url() ?>purchaseinvoice/updateInvoice",
                success: function(data) {
                    $(me).removeAttr("disabled");
                         //mesage
              	  			alertBox(1,"The invoice successfully updated");
                        }
                });
          }
  }
	
}

//Saving charges
function saveCharge(me){
         if( $("#parchaseDetailForm").validationEngine('validate') && finanEngine('financhk')){
        if ( $("#purchaseInvoiceId").val()=="null"){
            $(me).attr("disabled","disabled");
                  $.ajax({
                  type: "POST",
                  data: {
                      			purchaseInvoiceCodeID:1,
                      			purchaseOrdID:$("#orderNo").val(),
                      			purchaserID:$("#purchaser").val(),
                      			supplierID : $("#supplier").val(),
                                formNo : $("#formNo").val(),
                                shipToID : $("#shiptoAddress").val(),
                                invoiceDate: $("#createdDate").val(),
                                supplierInvoiceNo : $("#supinvoicenumber").val(),
                                projectID: $("#project").val(),
                                termsID: $("#term").val(),
                                currencyID: $("#currency").attr('data-curID'),
                                exchangeRate : $("#exchange_rate").val(),
                                locationID :  $("#location").val(),
                                shippingMethodID : $("#shippingmethod").val(),
                                employeeID : $("#purchaser").val(),
                                memo : $("#memo").val(),
                                totalTaxAmount: accounting.unformat($('#impotpayable').val()),
                                totalPayable: accounting.unformat($('#totalpayable').val()),
                                total: accounting.unformat($('#totalamount').val()),

                              	//Sales order detail
                                suppInvDetail:getOrderDet(),
                                	
                                //Supplier invoice charges detail.
                                accountNoID : $("#chargeAccount").val(), 
                                lineNo : $("#listCharge").attr("data-currentRow")*1 + 1,
                                chargeDescription: $("#chargedesc").val(),
                                taxID: $("#listTax").attr("data-taxid"),
                                taxRate: $("#listTax").val(),
                                amountExcludedTax : accounting.unformat( $("#chargeAmount").val()),
                                taxAmount: accounting.unformat($("#chargetaxAmount").val()),
                                amountIncludedTax: accounting.unformat($("#chargeAmountIT").val())
				
                          },
                  url: "<?php echo base_url() ?>purchaseinvoice/saveCharge",
                  success: function(data) {
                        var resul = eval ("(" + data + ")"); 
                        $("#purchaseInvoiceId").val(resul.invoiceID);
                        $('<tr><td class="span1">' + ($("#listCharge").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() + " | " + $("#listTax").val() + '</td>'+
                          '<td class="amount">' + accounting.formatNumber($("#chargetaxAmount").val(),2) + '</td>'+
                          '<td class="amount">' + accounting.formatNumber($("#chargeAmountIT").val(),2) + '</td>'+
                          '<td></td>'+
		                  '</tr>'
                        ).insertBefore( "#trInfosCharge" );
                        var op =$("#listCharge").attr("data-currentRow")*1;
                        $("#listCharge").attr("data-currentRow",op+1);
                        $("#btnCancelCharge").trigger("click");
                        $("#calcul" ).trigger( "click" );
                    	msg (2,"alert alert-success","Charge successfully saved");
                        getTotal();
                        $.ajax({
                          type: "POST",
                          data: {
                                        invoiceId : $("#purchaseInvoiceId").val(),
                                        totalAmount : accounting.unformat( $("#totalamount").val()), 
                                        totalTaxAmount : accounting.unformat( $("#impotpayable").val()),
                                        totalPayable : accounting.unformat($("#totalpayable").val())
                                  },
                          url: "<?php echo base_url() ?>purchaseinvoice/updateInvoice",
                          success: function(data) {
                                   //update the invoice after delete
                                  }
                          });
                  } // function
            });//end ajax
          }else{
                 $(me).attr("disabled","disabled");
                  $.ajax({
                  type: "POST",
                  data: {
                                invoiceId : $("#purchaseInvoiceId").val(),
                                accountNoID : $("#chargeAccount").val(), 
                                itemdescription: $("#chargedesc").val(),
                                amountExcludedTax : accounting.unformat($("#chargeAmount").val()),
                                 taxID: $("#listTax").attr("data-taxid"),
                                taxRate: $("#listTax").val(),
                                lineNo : $("#listCharge").attr("data-currentRow")*1 + 1,
                                taxAmount: accounting.unformat($("#chargetaxAmount").val()),
                                amountIncludedTax: accounting.unformat($("#chargeAmountIT").val())
				
                          },
                  url: "<?php echo base_url() ?>purchasetransaction/saveChargeDetailOnly",
                  success: function(data) {
                        var resul = eval ("(" + data + ")"); 
                        $(''+
                         '<tr><td class="span1">' + ($("#listCharge").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() + " | " + $("#listTax").val() + '</td>'+
                          '<td class="amount">' + accounting.formatNumber($("#chargetaxAmount").val(),2) + '</td>'+
                          '<td class="amount">' + accounting.formatNumber($("#chargeAmountIT").val(),2) + '</td>'+
                          '<td>'+
                          '</td>'+
                  '</tr>'
                        ).insertBefore( "#trInfosCharge" );
                 var op =$("#listCharge").attr("data-currentRow")*1;
                        $("#listCharge").attr("data-currentRow",op+1);
                        $("#btnCancelCharge").trigger("click");
                        $("#calcul").trigger( "click" );
                    msg (2,"alert alert-success","Charge successfully saved");
                        getTotal();
                        $.ajax({
                          type: "POST",
                          data: {
                                        invoiceId : accounting.unformat($("#purchaseInvoiceId").val()),
                                        totalPayable :accounting.unformat( $("#totalpayable").val()), 
                                        totalTaxAmount : accounting.unformat( $("#totalamount").val()),
                                  },
                          url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
                          success: function(data) {
                                   //update the invoice after delete
                                  }
                          });
                  }
           });//end ajax
          }
  }else {
   msg (2,"alert alert-error", "Data incorrect or invalid ...");
  }
  
  $("#calcul").trigger( "click" );
}

//get purchase order detail
function getOrderDet(){
       
	var str = '[';
	var i = 1;
	$('#listDetails tbody tr').each(function(){
		if(($(this).find('input:checked').is(':checked'))){
                         var txId = $('td:nth-child(11) input',this).attr('data-taxid');
                         var txRate = $('td:nth-child(11) input',this).val()
        if(txId==""){
            txId = -1;
            txRate = 0;
        }
        
        
        
			if(str == '['){
				str += '{"lineNo":'+i+
					',"itemname":"'+$('td:nth-child(5)',this).html()+'"'+
					',"itemdescription":"'+$('td:nth-child(6)',this).html()+'"'+	
					',"itemID":'+$('td:nth-child(1)',this).html()+
					',"receiveID":'+$('td:nth-child(2)',this).html()+
          ',"quantity":'+$('td:nth-child(8)',this).html()+
					',"umID":'+$('td:nth-child(7) input',this).val()+
					',"unitPrice":'+accounting.unformat($('td:nth-child(9)',this).html())+
					',"amountExcludedTax":'+accounting.unformat($('td:nth-child(10) input',this).val())+
          ',"taxID":'+txId+
					',"taxRate":'+txRate+
					',"taxAmount":'+accounting.unformat($('td:nth-child(12) input',this).val())+
					',"amountIncludedTax":'+accounting.unformat($('td:nth-child(13) input',this).val())+'}';
			}else{
				str += ',{"lineNo":'+i+
					',"itemname":"'+$('td:nth-child(5)',this).html()+'"'+
          ',"itemdescription":"'+$('td:nth-child(6)',this).html()+'"'+  
          ',"itemID":'+$('td:nth-child(1)',this).html()+
          ',"receiveID":'+$('td:nth-child(2)',this).html()+
          ',"quantity":'+$('td:nth-child(8)',this).html()+
          ',"umID":'+$('td:nth-child(7) input',this).val()+
          ',"unitPrice":'+accounting.unformat($('td:nth-child(9)',this).html())+
          ',"amountExcludedTax":'+accounting.unformat($('td:nth-child(10) input',this).val())+
          ',"taxID":'+txId+
          ',"taxRate":'+txRate+
          ',"taxAmount":'+accounting.unformat($('td:nth-child(12) input',this).val())+
          ',"amountIncludedTax":'+accounting.unformat($('td:nth-child(13) input',this).val())+'}';
			}
			i++;
		}
	});
	str += ']'
	return str;
}

function addRowInvoiceCharge(){
        var tax = '';
        if(gstStatus){
            tax = '<td class="span2">\
                        <div class="input-prepend">\
                            <input data-taxid="" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" disabled="disabled" class="span6 validate[required, custom[number]]" type="text" placeholder="Tax(%)">\
                            <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 data-taxid="<?php echo $nonGstTaxID; ?>" value="0" id="listTax" onkeyup="calculChargeAmount()" name="itemTax" disabled="disabled" 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">' + ($("#listCharge").attr("data-currentRow")*1 + 1) + '</td>'+
                   '<td class="span4">\n\
        <select name="chargeAccount" id="chargeAccount" class="span12 validate[required]"><option></option>' +
<?php 
if ($chargeAccount) {
    foreach ($chargeAccount as $row) {
        $accName = 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 $accName;
        ?></option>'+
    <?php
    }
}
?>
        '</select></td>'+
        '<td class="span3"><input  id="chargedesc" name="chargedesc"  type="text" class="span12 validate[required]" placeholder="Description"></td>'+
        '<td class="span1"><input id="chargeAmount" onkeyup="calculChargeAmount()" onfocus="modAmount(this)" name="chargeAmount" class="span12 validate[required, custom[number]]" type="text" placeholder="Amount"></td>'+
        tax+
                                                                                                        '<td class="span1"><input disabled 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 = "saveCharge(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>'+
                        '<td class="span1" style="text-align:center;"><input data-taxid="" id="inclusiveTax" onchange="modAmount(this)" name="incTax" class="tac" type="checkbox"></td>'+
                    '</tr>'
                                          ).insertBefore( "#trInfosCharge" );
					                               if($('#listTax option').length){
                                          $('#listTax').select2();
                                        }
                                        $('#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 refreshLocation(){
 $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>purchasetransaction/refreshLocation",
        success: function(data) {
	
           var resul = eval ("(" + data + ")"); 
           var n=resul.records.length;
           var i=0;
           var opt='' +
                '<option></option>';
                for (i=0;i<n;i++)
                        opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].location + '</option>';
                $('#location').empty();
                $('#location').append(opt);
        }
   });	
}

function refreshShipto(){
 $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>aptransaction/refreshShipto",
        dataType:'json',
        success: function(data) {
          var resul = data; 
          var n=resul.length;
          var i=0;
          var opt='' +
              '<option></option>';
              for (i=0;i<n;i++){
                opt=opt + '<option value="' + resul[i].ID +'">' + resul[i].line1+' | '+resul[i].city + '</option>';
              }
          $('#shiptoAddress').empty();
          $('#shiptoAddress').append(opt);
        }
   });  
}

    function modAmount(me){
        console.log($(me).attr('type'));
        var $taxPer = accounting.unformat($("#listTax").val());
        var $chargeAmount = accounting.unformat($("#chargeAmount").val());
        if($(me).attr('type') != 'text'){
            if($('#inclusiveTax').attr("checked") == "checked"){
                $("#chargeAmount").attr('data-actual',accounting.unformat($("#chargeAmount").val()));
                var $taxAmount = ($chargeAmount*$taxPer)/(100+$taxPer);
                var $actualCharge = $chargeAmount - $taxAmount;
                $("#chargeAmount").val(accounting.formatNumber($actualCharge,2));
                calculChargeAmount();
            }else{
                $("#chargeAmount").val(accounting.formatNumber($("#chargeAmount").attr('data-actual'),2));
                calculChargeAmount();
            }
        }else{
            $("#chargeAmount").val(accounting.formatNumber($("#chargeAmount").attr('data-actual'),2));
            $('#inclusiveTax').attr("checked",false);
            calculChargeAmount();
        }
    }

    function calculChargeAmount() { 
        if($('#inclusiveTax').attr("checked") == "checked"){          
          var t = (accounting.unformat($("#chargeAmount").attr('data-actual')) * accounting.unformat($("#listTax").val())) /(100+accounting.unformat($("#listTax").val()));  
        }else{
          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 displaysAdress(){
                $("#shiptoDesc").html("");
                $("#shiptoDesc").html($("#shiptoAddress option:selected").attr("data-line1") +
                                                           "&#10;" + $("#shiptoAddress option:selected").attr("data-line2") +
                                                           "&#10;" + $("#shiptoAddress option:selected").attr("data-line3"));
}

var lineIndex = 0;
$(".displayTaxCode").live('click',function(){
    lineIndex = $(".displayTaxCode").index(this)+1;
    console.log($(".displayTaxCode").index(this)+1);
});

function taxPopup () {
        $('#popupModal').modal('show');
        $("#_popupTitle").html("Purchase Invoice");
        $("#_popupContent").html('' +
          '<label>Select a tax</label>' +
          '<select  onclick="calculChargeAmount()" name="listTaxPopup" id="listTaxPopup" style="width:100%;" >' +
                <?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() {
                var me = $("#listDetails tbody tr:nth-child("+lineIndex+")");
                $('#popupModal').modal('hide');
                 me.find(".itemTax,#listTax").attr("data-taxid",$("#listTaxPopup").val());
                 me.find(".itemTax,#listTax").val ($("#listTaxPopup option:selected").attr("data-tax"));
                 me.find(".displayTaxCode,#displayCode").html($("#listTaxPopup option:selected").attr("data-taxcode"));

                //reset the values
                var j_itemTax = $("#listTaxPopup option:selected").attr("data-tax");
                var j_totalAmount = accounting.unformat(me.find(".itemAmountET").val());
                var j_itemTaxAmount = j_totalAmount*j_itemTax/100;
                var j_itemIncTax = j_itemTaxAmount + j_totalAmount;

                me.find(".itemTaxAmount").val(accounting.formatNumber(j_itemTaxAmount,2));
                me.find(".itemAmountIT").val(accounting.formatNumber(j_itemIncTax,2));


                 $("#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();
                 //calculamountET(me);
        });
	
	
}

function refreshpurchaserlist(){
         $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>employeeSetup/refreshEmployee",
        success: function(data) {
	
           var resul = eval ("(" + data + ")"); 
           var n=resul.records.length;
           var i=0;
           var opt='' +
                '<option></option>';
                for (i=0;i<n;i++)
                        opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].employeeName + '</option>';
                $('#purchaser').empty();
                $('#purchaser').append(opt);
        }
   });	
}

function refreshshippingmethod(){
 $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>setting/refreshShippingMethod",
        success: function(data) {
	
           var resul = eval ("(" + data + ")"); 
           var n=resul.records.length;
           var i=0;
           var opt='' +
                '<option></option>';
                for (i=0;i<n;i++)
                        opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].name + '</option>';
                $('#shippingmethod').empty();
                $('#shippingmethod').append(opt);
        }
   });		
}

$(document).ready(function(){
	//Data table configurations
   	var oTable = $("#listDetails").dataTable({
	   	"iDisplayLength": 10,
		"aLengthMenu": [5,10,25,50,100],
		"sPaginationType": "full_numbers",
		"aoColumns": [	{"bSortable": false},
		              	{"bSortable": false},
						null,
						null,
						null,
						null,
						null,
						null,
						null,
						null,
						null,
            null,
						null,
						{"bSortable": false}
					] 
	});
	oTable.fnSort( [ [2,'asc'] ] );
	//Check all items from the order
	$("table .checkall1").live("click", "checkall1",function(){           
		$(oTable.fnGetNodes()).find(':checkbox').prop('checked', this.checked);
	});
	
	//Gather customer invoice no by custormer ID
	/*$('#supplier').live('change',function(){

		jQuery.ajax({
			url: "<?php echo base_url() ?>purchaseinvoice/getOrderItemBySupp",
			async: false,
			type: "POST",
			data: "supplierID="+$(this).val(),
			dataType: "html",
			success: function(data) {        
 				if(data != ''){
 					$('#supinvoicenumber').attr('data-source',data);
 				}
				
				if(data != ''){
					$('#orderNo').html("<option value=''>--Select Order</option>"+data);
				}	
		    }
		});
	});*/
	//Gather supplier invoice detail by supplier ID & invoice no
	$('#supplier,#createdDate').live('change',function(){		
		var id = $("#supplier").val();
		jQuery.ajax({
			url: "<?php echo base_url() ?>purchaseinvoice/getOrderItemBySupp",
			async: false,
			type: "POST",
			data: "supplierID="+id+"&date="+$('#createdDate').val(),
			dataType: "html",
			success: function(data) {        
				if(data != ''){
					var obj = jQuery.parseJSON(data);
					//console.log(obj.info[0].ID+'<->'+obj.info[0].companyID);
// 					$('#createdDate').val(obj.info[0].purchaseOrderDate);					
// 					$('#purchaser').select2("val",obj.info[0].purchaserID);
// 					$('#memo').val(obj.info[0].memo);
// 					$('#term').select2("val",obj.info[0].termAndConditionID);
// 					$('#termDescription').val(obj.info[0].termDescription);
					
	
	
					//Items listing
          gstStatus = isGstRegistered(id,'supplier');
					var serial = 1;
					oTable.fnClearTable();
          console.log(gstStatus);
					jQuery.each(obj,function(i,v){
              var taxPercent;
              if(gstStatus){
                  if( v.code != null){
                      taxPercent = '<td class="span1"><div  class="input-prepend"><input data-taxid="'+ v.inputTaxID+'" readonly id="" onkeyup="calculamountET()" name="itemTax" disabled="disabled" class="itemTax span6" type="text" placeholder="Tax(%)" value = "'+v.taxPercentage+'"><span onclick="taxPopup ()" style="margin-top:0;"  class="displayTaxCode btn add-on">'+ v.code+'</span></div></td>';
                  }else{
                      taxPercent = '<td class="span1"><div  class="input-prepend"><input data-taxid="" id="" onkeyup="calculamountET()" name="itemTax" disabled="disabled" class="itemTax span6" type="text" placeholder="Tax(%)" value = ""><span onclick="taxPopup ()" style="margin-top:0;"  class="displayTaxCode btn add-on">....</span></div></td>';
                  }
                  var tax = parseFloat((v.amount*v.taxPercentage)/100).toFixed(2);
              }else{
                  taxPercent = '<td class="span1"><div  class="input-prepend"><input readonly data-taxid="<?php echo $nonGstTaxID; ?>" id="" name="itemTax" disabled="disabled" class="itemTax span6" type="text" placeholder="Tax(%)" value = "0"><span style="margin-top:0;"  class="displayTaxCode btn add-on">NR</span></div></td>';    
                  var tax = 0;
              }
              var umID = 0;
              if(parseInt(v.standUM) == 0){  umID = v.defaultUM;} else{  umID = v.standUM;}
							var total = parseFloat(v.amount).toFixed(2);
							var totalpayble = parseFloat(total) + parseFloat(tax);
              if(v.factor > 0){
                var qtyRcv = v.quantityReceived/v.factor;
                var unitPrice = v.unitPrice*v.factor;
              }else{
                var qtyRcv = v.quantityReceived;
                var unitPrice = v.unitPrice;
              }
              console.log(umID);
							var rowIndex = oTable.fnAddData( [
					      					v.itemID,
					      					v.rcvID,
													serial++,
													v.formNo,
													v.name,
													v.description,
                          v.umCode,
                          qtyRcv,
													accounting.formatNumber(unitPrice,2),
                          '<td class="span1"><input id="" name="itemAmountET" disabled class="itemAmountET span12 amount " type="text" placeholder="0.00" value="'+accounting.formatNumber(v.unitPrice*v.quantityReceived,2)+'"></td>',
                          taxPercent,
                          '<td class="span1"><input id="" name="itemTaxAmount" disabled class="itemTaxAmount span12 amount" type="text" placeholder="0.00" value="'+accounting.formatNumber(tax,2)+'"></td>',
                          '<td class="span1"><input id="" name="itemAmountIT" disabled class="itemAmountIT span12 amount" type="text" placeholder="0.00" value="'+accounting.formatNumber(accounting.unformat(v.unitPrice)*accounting.unformat(v.quantityReceived)+accounting.unformat(tax),2)+'"></td>',
													'<input type="checkbox" class="checkbox" id="checkbox">'
												] );
						var row = oTable.fnGetNodes(rowIndex);
				    	$(row).find('td:nth-child(7),td:nth-child(8),td:nth-child(9),td:nth-child(10),td:nth-child(11),td:nth-child(12)').addClass('tar');
				    	$(row).find('td:nth-child(1),td:nth-child(2)').css('display','none');
              $(row).find('td:nth-child(11)').append('<input type="hidden" value="'+v.outputTaxID+'" />');
				    	$(row).find('td:nth-child(7)').append('<input type="hidden" value="'+umID+'" />');
					});
				}	
		    }
		});
	});
	//Edit tax information
	$('.editTax').live('click',function(){
		if($(".taxEditCont").length == 0) {
			var tax = $('#listDetails #itemTax').val();
			var trIndx = $('#listDetails tbody tr').index($('.taxEditCont').parents('tr'))+1;
			var tdIndx = $('#listDetails tr:nth-child('+trIndx+') td').index($('.taxEditCont'))+1;
			$('#listDetails tr:nth-child('+trIndx+')').find('td:nth-child('+tdIndx+')').html(tax);

			$(this).parents('tr').find('td:nth-child(8)')
						.addClass('taxEditCont')
						.html('<div class="input-prepend"><input data-taxid="" id="itemTax" disabled="disabled" 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>');
			$(this).parents('tr').find('td:nth-child(11)').html('<button class="btn-icon btn-mini btn-success-form saveItm" type="button"><i class="i-checkmark-3"></i></button>');
		}else{
            alertBox(2,"Save one item first...");
		}
		
		
	});

	//modify tax information
	$('.saveItm').live('click',function(){
		var tax = $('#listDetails #itemTax').val();
		var taxID = $('#listDetails #itemTax').attr('data-taxid');
		var trIndx = $('#listDetails tbody tr').index($('.taxEditCont').parents('tr'))+1;
		var tdIndx = $('#listDetails tbody tr:nth-child('+trIndx+')').find('td').index($('.taxEditCont'))+1;
		$('#listDetails tr:nth-child('+trIndx+')').find('td:nth-child('+tdIndx+')').html(tax).append('<input type="hidden" value="'+taxID+'" />').removeClass('taxEditCont');
		$(this).parents('tr').find('td:nth-child(11)').html('<button class="btn-icon btn-mini btn-warning-form editTax" type="button"><i class="i-pop-in"></i></button>');
		calNsaveTax(trIndx);
	});
});

//Calculate total after tax added
function calNsaveTax(row){
	var totalAmnt = parseFloat($('#listDetails tbody tr:nth-child('+row+')').find('td:nth-child(7)').html());
	var taxPer = parseFloat($('#listDetails tbody tr:nth-child('+row+')').find('td:nth-child(8)').html());
	
	var taxAmnt = (totalAmnt * taxPer)/100;
	var ttlAmntIncTax = totalAmnt + taxAmnt;
	var str = '';
	$('#listDetails tbody tr').each(function(){
		var rowID = parseFloat($(this).find('td:nth-child(1)').html());
		var outputTaxID = parseFloat($(this).find('td:nth-child(8) input').val());	
		if(str == '')	str += rowID+'-'+outputTaxID;
		else			str += ','+rowID+'-'+outputTaxID;
	});

	//Save new output tax for items
	$.ajax({
		type: "POST",
		data: {taxInfo : str},
		url: "<?php echo base_url() ?>artransaction/savetax",
		success: function(data) {
			if(data == 'Success'){
				alertBox(1,"Successfully updated tax information");
			}else{
				alertBox(2,"Error occured during the update");
			}
		}
	});
	
	$('#listDetails tbody tr:nth-child('+row+')').find('td:nth-child(9)').html(taxAmnt);
	$('#listDetails tbody tr:nth-child('+row+')').find('td:nth-child(10)').html(ttlAmntIncTax);

	getTotal();
}

//total invoice calculation
function getTotal(){
         $("#totalamount").val("0.00");
         $("#impotpayable").val("0.00");
         $("#totalpayable").val("0.00");

         var n =$("#listDetails > tbody > tr").length-1;
         var totalAmount =0;
         var impot = 0;
         var total = 0;
         for (i=0; i<=n; i++) {
        	 if($('#listDetails > tbody > tr:eq(' + i + ')').find('input:checkbox').is(':checked')){
                        totalAmount= totalAmount + accounting.unformat($('#listDetails tbody tr:nth-child(' + (i+1) + ') .itemAmountET').val())*1;
                        impot= impot + accounting.unformat($('#listDetails tbody tr:nth-child(' + (i+1) + ') .itemTaxAmount').val()) *1;
                        total= total + accounting.unformat($('#listDetails tbody tr:nth-child(' + (i+1) + ') .itemAmountIT').val())*1;
        	 }
         }

        // calcul for charge
	
         var n =$("#listCharge > tbody > tr").length-1;
         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));
  		$("#totalamount").val(accounting.formatNumber(totalAmount+totalAmountCharge,2));
		
        $("#impotpayable").val(accounting.formatNumber(impot +  impotCharge,2));
  
        $("#totalpayable").val(accounting.formatNumber(total + totalCharge,2));

  }


  
//Alert message box
function alertBox(mode,msg){
	$('.sambox .alert').removeClass('alert-error').removeClass('alert-success');
	if(mode == 1)
		$('.sambox .alert').addClass('alert-success').html("<strong>Success! </strong>"+msg);
	else if(mode == 2)
		$('.sambox .alert').addClass('alert-error').html("<strong>Error! </strong>"+msg);
	else
		$('.sambox .alert').html("<strong>Worning! </strong>"+msg);
	$('.sambox').show();

	$('.sambox').effect( "pulsate", {times:3}, 5000,function(){
		setTimeout(function(){
			$('.sambox').fadeOut();
		},10000);	
	});
	$('html,body').animate({
	   scrollTop: $('.sambox').offset().top
	});
}

function deleteCharge(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-ChargeId") },
	                  url: "<?php echo base_url() ?>purchasetransaction/deleteChargeOnly",
	                  success: function(data) {
	                        //  msg (2,"alert alert-success","Data deleted succesfuly ...");
	                          var td=me.parentNode;
	                          var tr=td.parentNode;
	                          var tBody=tr.parentNode;
	                          tBody.removeChild(tr);
	                          getTotal();
	                          $.ajax({
	                                type: "POST",
	                                data: {
	                                          invoiceId : $("#purchaseInvoiceId").val(),
	                                          totalPayable : $("#totalpayable").val(), 
	                                          totalTaxAmount :  $("#totalamount").val()
	                                        },
	                                url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
	                                success: function(data) {
	                                         //update the invoice after delete
	                                        }
	                                });
	                          }
	                  });
	          });
		  
	          $("#calcul").trigger( "click" );
	}

</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() . "AccountPayables/home" ?>'> <?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
                    <li class="active"><?php echo $this->lang->line('title') ?></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">
            <form id="parchaseDetailForm" action="#">    
                <input type="hidden" value="null" id="purchaseInvoiceId" />
      		<div class="block">
        		<div class="head">
            		<h2><?php echo $this->lang->line('title2') ?></h2>
        		</div><!-- head -->
      			<div class="content">
                	<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('supplier') ?></div>
                                    <div class="span8">
                                        <div class="span12">
                                            <input type="hidden" id="purchaseInvoiceId" value="null"/>
                                            	<select class="span10 validate[required]" id="supplier" onchange="loadSupplierDefaultValue(this)">
                                            	<option></option>
                        							<?php
                        							if ($supplier != '') {
                        								foreach ($supplier as $row) {
                        							?>
                                           	 	<option value="<?php echo $row->ID; ?>"> <?php echo $row->supplierName; echo ($row->gstRegNo != '' && $row->gstRegNo != '0')?' (GST)':''; ?></option>
                        						<?php
                        						}
                        						}
                        						?>
                                            	</select>
                                            <div class="btn-group span1">
                                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                     <span class="i-arrow-down-2"></span>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <!-- dropdown menu links -->
                                                    <li><a target="_blank" href="<?php echo base_url() ?>supplier/SupplierNew"  id="btnNewSupplier">
                                                            <i class="i-plus-3"></i> <?php echo $this->lang->line('addNewSupplier') ?></a></li>
                                                    <li><a href="#" onclick="refreshSupplier()" id="btnNewSupplier">
                                                            <i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                                </ul>
                                            </div>
                                         </div>
                                     </div>
                                </div> <!-- content nb -->                                
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('formNo') ?></div>
                                    <div class="span5">
                                    	<input class="span12 validate[required]" id="formNo" name="formNo" value='<?php echo "$formNo"; ?>' style="color:red;"   type="text" placeholder="Form number ...">
                                    </div>
                                    <div class="span3">
                                        <input  class="span12"   type="text" id="invID" placeholder="Serial" disabled="disabled">
                                    </div>
                                </div> <!-- nb -->
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('date') ?></div>
                                    <div class="span8">
                                        <div class="input-prepend span12">
                                            <span class="add-on span2"><i class="i-calendar"></i></span>
                                            <?php
                                            $data = array(
                                                'name' => 'createdDate',
                                                'id' => 'createdDate',
                                                'type' => 'text',
                                                'onkeydown' => 'return false',
                                                'class' => 'span10 datepicker2 validate[required] financhk',);
                                            echo form_input($data, date("d-m-Y"));
                                            ?>
                                        </div>
                                    </div>
                                </div> <!-- row -->
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('supplierInvoiceNo') ?></div>
                                    <div class="span8">
                                        <input id="supinvoicenumber" data-provide="typeahead" class="span12 validate[required]" type="text" placeholder="Supplier Invoice Number">
                                    </div><!-- span -->
                                </div> <!-- row -->     
                                 <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('purchaser') ?></div>
                                    <div class="span8">
                                        <div class=" span12">


                                            <select class="span10" id="purchaser">
                                                <option></option>
<?php
if ($purchaser != '') {
    foreach ($purchaser as $row) {
        ?>
                                                        <option value="<?php echo $row->ID; ?>"> <?php echo $row->employeeName; ?></option>
    <?php
    }
}
?>
                                            </select>
                                            <div class="span1 btn-group">
                                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                     <span class="i-arrow-down-2"></span>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <!-- dropdown menu links -->
                                                    <li><a target="_blank" href="<?php echo base_url() ?>employeeSetup/EmployeeNew"  id="EmployeeNew">
                                                            <i class="i-plus-3"></i> <?php echo $this->lang->line('newpurchaser') ?></a></li>
                                                    <li><a href="#" onclick="refreshpurchaserlist()" id="btnNewSupplier">
                                                            <i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div><!-- row control -->
                        	</div><!-- grid block 1-->
                    	</div><!-- scCol -->
                    <div class="span4 scCol">
                        <div class="block ns" id="grid_block_2">
                            
                             <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('project') ?></div>
                                    <div class="span8">
                                        <div class=" span12">
                                            <select id="project" class="span10">
                                                <option></option>
												<?php
                                                if ($project != '') {
                                                    foreach ($project as $row) {
                                                ?>
                                                 <option value="<?php echo $row->ID; ?>"><?php echo $row->project_name; ?></option>
                                                <?php
                                               	}
                                                }
                                                ?>
                                            </select>
                                            <div class="btn-group span1">
                                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                    <span class="i-arrow-down-2"></span>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <!-- dropdown menu links -->
                                                    <li><a target="_blank" href="<?php echo base_url() ?>project/ProjectSetup"  id="btnNewPro">
                                                            <i class="i-plus-3"></i><?php echo $this->lang->line('addNewProject') ?></a></li>
                                                    <li><a href="#" onclick="refreshProject()"><i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a>
                                                    </li>
                                                </ul>
                                            </div> <!-- btn group -->
                                        </div> <!-- append -->
                                    </div><!-- span -->

                                </div> <!-- row control -->
                        	<div class="controls-row">
                            	<div class="span4"><?php echo $this->lang->line('terms') ?></div>
                                    <div class="span8">
                                        <div class=" span12">
                                            <select id="term" onchange="getTermDescription(this)" class="span10 validate[required]">
                                                <option></option>
													<?php
														if ($terms != '') {
   														foreach ($terms as $row) {
        											?>
                                                        <option value="<?php echo $row->ID; ?>"><?php echo $row->termName; ?></option>
   													<?php
    													}
													}
													?>
                                            </select>
                                            <div class="btn-group span1">
                                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                     <span class="i-arrow-down-2"></span>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <!-- dropdown menu links -->
                                                    <li><a target="_blank" href="<?php echo base_url() ?>term/termSetup"  id="btnNewTer">
                                                            <i class="i-plus-3"></i><?php echo $this->lang->line('addNewTerms') ?></a></li>
                                                    <li><a href="#" onclick="refreshTerms()"><i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a>
                                                    </li>
                                                </ul>
                                            </div><!-- btn group -->
                                        </div><!-- append -->
                                    </div><!-- span -->
                             </div><!-- row control -->
                             <div class="content nb">
                                 <div class="span4"><?php echo $this->lang->line('termsdesc') ?></div>
                                 <div class="span8">
                                     <textarea rows="4" readonly id="termDescription" class="span12"></textarea>
                                  </div><!-- span -->
                             </div><!-- row control -->
                        </div><!-- grid block 1-->
                    </div><!-- scCol -->
                    
                    <div class="span4 scCol">
                        <div class="block ns" id="grid_block_3">
                                <?php /*
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('shipto') ?></div>
                                    <div class="span8">
                                        <select id="shiptoAddress" onchange ="displaysAdress()" class="span12 validate[required]">
                                            <option data-line1="" data-line2="" data-line3="" data-postcode=""></option>
<?php
if ($shipto != '') {
    foreach ($shipto as $row) {
        ?>
                                                    <option  data-line1="<?php echo $row->line1 ?>" data-line2="<?php echo $row->line2 ?>" data-line3="<?php echo $row->line3 ?>" data-postcode="<?php echo $row->postCode ?>" value="<?php echo $row->ID; ?>">
        <?php echo $row->addressName . " | " . $row->city; ?></option>
    <?php
    }
}
?>
                                        </select>
                                    </div><!-- span -->
                                </div><!-- row control -->
								*/ ?>
                              
                                
                                
                                  <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('shippingmethod') ?></div>
                                    <div class="span8">
                                        <div class="span12">
                                            <select id="shippingmethod"  class="span10">
                                                <option></option>
<?php
if ($shippingmethod != '') {
    foreach ($shippingmethod as $row) {
        ?>
                                                        <option value="<?php echo $row->ID; ?>"><?php echo $row->name; ?></option>
    <?php
    }
}
?>
                                            </select>
                                            <div class="span1 btn-group">
                                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                     <span class="i-arrow-down-2"></span>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <!-- dropdown menu links -->
                                                    <li><a target="_blank" href="<?php echo base_url() ?>setting/masterCodeSetup">
                                                            <i class="i-plus-3"></i><?php echo $this->lang->line('newshippingmethod') ?></a></li>
                                                    <li><a href="#" onclick="refreshshippingmethod()"><i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a>
                                                    </li>
                                                </ul>
                                            </div><!-- btn group -->
                                        </div><!-- append -->
                                    </div><!-- span -->

                                </div><!-- row control -->
                                
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('shipto') ?></div>
                                    <div class="span8">
                                        <div class=" span12">
                                            <select class="span10" id="shiptoAddress">
                                                <option></option>
												<?php

                                                if ($compShipto != '') {
                                                    foreach ($compShipto as $row) {
                                                        ?>
                                                        <option value="<?php echo $row->ID; ?>"><?php echo $row->line1 . " | " . $row->city; ?></option>
                                                    <?php
                                                    }
                                                }
                                                ?>
                                            </select>
                                            <div class="btn-group span1">
                                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
                                                    <span class="i-arrow-down-2"></span>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <!-- dropdown menu links -->
                                                    <li><a target="_blank" href="<?php echo base_url() ?>setting/shiptoList"  id="btnLocation">
                                                            <i class="i-plus-3"></i><?php echo $this->lang->line('addShipto') ?></a></li>
                                                    <li><a href="#" onclick="refreshShipto()"><i class="i-ccw "></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                                </ul>
                                            </div>
                                        </div> <!-- btnn group -->
                                    </div>
                                </div>
                                <?php /*
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('shiptoDesc') ?></div>
                                    <div class="span8">
                                        <textarea style="height: 75px;" disabled="disabled"ssss id="shiptoDesc" class="span12">
                   		
                                        </textarea>
                                    </div><!-- span -->
                                </div><!-- row control -->
                                */ ?>
								<div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('currency') ?></div>
                                    <div class="span8">
                                        <input id="currency" name="currency" type="text" placeholder="Currency" disabled class="span12 validate[required,minSize[5],maxSize[10]]">            
                                    </div><!-- span -->
                                </div><!-- control row -->
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('exchangeRate') ?></div>
                                    <div class="span8">
                                        <input class="span12 validate[required] tar" id="exchange_rate" name="exchange_rate" type="text" placeholder="Example: 3.20000" >           
                                    </div><!-- span -->
                                </div><!-- control row -->
                        </div><!-- grid block 1-->
                    </div><!-- scCol -->
                </div><!-- row-fluid scRow-->
                </div><!-- row-fluid scRow-->
                </div><!-- row-fluid scRow-->
                
                <div class="row-fluid scRow">                            
                    <div class="span12 scCol">
                        <textarea style="margin-top:10px;" placeholder="Memo" id="memo" class="span12"></textarea>
                        
                        </div>
                </div>
                
                <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>                                        
                            </div><!-- head -->
                    <div class="content sambox" style="display: none;">                                                
				                <div class="row-fluid">
				                    <div class="span12">        
				                        <div class="alert">            
				                            <strong>Success! </strong>
				                        </div>       
				                    </div>
				                </div>
				            </div>                            
                        	<div class="content np table-sorting">
                                <table data-currentRow="0" id="listDetails" cellpadding="0" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                        	<th style="display:none">&nbsp;</th>
                                            <th style="display:none">&nbsp;</th>
                                            <th>#</th>
                                            <th><?php echo $this->lang->line('formNo') ?></th>
                                            <th><?php echo $this->lang->line('item') ?></th>
                                            <th><?php echo $this->lang->line('description') ?></th>
                                            <th class="quantity tar"><?php echo $this->lang->line('um') ?></th>
                                            <th class="quantity tar"><?php echo $this->lang->line('quantity') ?></th>
                                            <th class="amount tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                            <th class="amount tar" ><?php echo $this->lang->line('amountExcludeTax') ?></th>
                                            <th class="tar"><?php echo $this->lang->line('tax') ?></th>
                                            <th class="amount tar"><?php echo $this->lang->line('taxAmount') ?></th>
                                            <th class="amount tar"><?php echo $this->lang->line('amountIncludeTax') ?></th>
                                            <th class="amount tar"><input type="checkbox" id="checkall1" class="checkall1"></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        
                                    </tbody>
                                </table>
                                <div class="footer">
                                    <div class="side fr">
                                        &nbsp;      
                                    </div><!-- side fr -->      
                                </div><!-- footer -->      
                            </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('charge') ?></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>                                        
                            </div><!-- head -->
                            <div class="content np">
                                <table data-currentRow="0" 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>
                                            <th><?php echo $this->lang->line('inclusiveTax') ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr id="trInfosCharge">
                                            <td colspan="9">
                                                <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>
                                    </tbody>
                                </table>
                                <div class="footer">
                                    <div class="side fr">
                                        <div class="btn-group">
                                            <button style="margin-right:6px;" onclick="$('#SaleDetailForm').validationEngine('hide');" class="btn-form btn-warning-form" type="button" name="validat">Hide prompts</button>
                                            <button id="addRowCharge" onclick="addRowInvoiceCharge()" class="btn-icon btn-warning-form" type="button">
                                                <i class="i-plus-2"></i><?php echo $this->lang->line('addNewCharge') ?></button>

                                        </div><!-- btn group -->      
                                    </div><!-- side fr -->      
                                </div><!-- footer -->      
                            </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 class="content np">
                              

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

                                    <div class="span4"><?php echo $this->lang->line('totalAmount') ?></div>
                                    <div class="span8">
                                        <input id="totalamount" class="span12 amount" type="text" placeholder="0.00" disabled="disabled" >
                                    </div>
                                </div><!-- row control -->
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('importDutyPayable') ?></div>
                                    <div class="span8">
                                        <input id="impotpayable" class="span12 amount" type="text" disabled="disabled"  placeholder="0.00">
                                    </div>
                                </div><!-- row control -->
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('totalPayable') ?></div>
                                    <div class="span8">
                                        <input id="totalpayable" disabled="disabled"  class="span12 amount" type="text" placeholder="0.00">
                                    </div>
                                </div><!-- row control -->
                                <div class="footer">
                                    <div class="side fr">
                                        <div class="btn-group">
                                            <button id="calcul" onclick="getTotal()" class="btn-icon btn-warning-form" type="button"> 
                                                <i class="i-checkmark-3"></i><?php echo $this->lang->line('calTotal') ?></button>
											<button style="margin-left:5px;" id="calcul" onclick="saveInvoice()" class="btn-icon btn-success-form" type="button"> 
                                                <i class="i-checkmark-3"></i><?php echo $this->lang->line('saveInvoice') ?></button>
                                        </div><!-- btn group -->      
                                    </div><!-- side fr -->      
                                </div><!-- footer -->   
                            </div>    
                        </div><!-- grid block 1-->
                    </div><!-- scCol -->
                </div><!-- row-fluid scRow-->
            </form>
        </div><!-- grid 1 -->
    </div><!-- wrap -->
</div><!-- content -->



