<script type="application/javascript">
   $(document).ready(function(){
                $('select').select2();
        /*****GST Register supplier's color change start******/    
        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; }
        });
        /*****GST Register supplier's color change end******/
                $.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
                });

                /*$('#calcul').live('click',function(){
                    console.log('i am here');
					$('#editSaleInvoice').submit();
                });*/
                getTotal();
        });
 
			
function refreshTerms(){
    $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>artransaction/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() ?>artransaction/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){
    $("#termDescription").html($("#term option:selected").attr("data-desc"));
}

//Gather supplier currency & exchange rate
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) {
              console.log(data);
              /*var resul = eval ("(" + data + ")"); */
              $('#currency').attr("value",data[0].currencyWord);
              //$('#exchange_rate').attr("value",data[0].exchangeRate);
			  $('#exchange_rate').attr("value",accounting.formatNumber(data[0].exchangeRate,5));
      }
  });
}

//Change shipping location while select any
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"));
}


//Calculate total amount
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++) {
                        totalAmount= totalAmount + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(5)').text())*1; 
                        impot= impot + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(7)').text()) *1; 
                        total= total + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(8)').text())*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));
  
        $("#impotpayable").val(accounting.formatNumber(impot +  impotCharge,2));
  
        $("#totalpayable").val(accounting.formatNumber(total + totalCharge,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-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();
        }
        }
});
} else {
$('#itemList').empty();
        $('#itemList').append(lisItem);
        $("#location").attr("data-ispopulated", "true");
        $("#itemList").val(selectedItem);
        $('#itemList').select2();
}
}
function displaysItemDefaultValue(){
        $("#itemdes").val($("#itemCombo option:selected").attr("data-desc"));
        $("#itemunitprice").val(accounting.formatNumber($("#itemCombo option:selected").attr("data-price"),2));
        $("#itemTax").val($("#itemCombo option:selected").attr("data-taxPercentage"));
        $("#itemTax").attr("data-taxid",$("#itemCombo option:selected").attr("data-taxid"));
        $("#displayTaxCode").text($("#itemCombo option:selected").attr("data-taxcode"));
    }

function editRow(me){
    var tr = $(me).parent().parent();
    //  alert( $(me).parent().parent().find("td").eq(0).html()); 
    $(tr).replaceWith('<tr>' +
            '<td class="span1"><input id="lineNo" disabled class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(0).html() + '" value="' + $(me).parent().parent().find("td").eq(0).html() + '"></td>' +
            '<td class="span1"><select data-previewvalue="' + $(me).parent().parent().find("td").eq(1).html() + '" name="itemCombo" id="itemCombo" class="span12" onchange="displaysItemDefaultValue()"><option></option>' +
			<?php
			if ($items) {
			    foreach ($items as $row) {
			        ?>
                                    '<option data-desc= "<?php echo $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" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(2).html() + '" value="' + $(me).parent().parent().find("td").eq(2).html() + '"></td>' +
            '<td class="span1"><input  id="itemunitprice" onkeyup="calculamount()" onchange="calculamount()" name="itemunitprice" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(3).html() + '" value="' + $(me).parent().parent().find("td").eq(3).html() + '"></td>' +
            '<td class="span1"><input id="itemqte"  onkeyup="calculamount()" onchange="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="itemAmountET" disabled name="itemAmountET" 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"><div  class="span12 input-prepend"><input style="max-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="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>' +
            '<td class="span1"><input disabled id="itemTaxAmount" name="itemTaxAmount" class="span12" type="text" data-previewvalue="' + $(me).parent().parent().find("td").eq(7).html() + '" value="' + $(me).parent().parent().find("td").eq(7).html() + '"></td>' +
            '<td class="span1"><input disabled id="itemAmountIT" name="itemAmountIT" 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">' +
            '<button onclick="updateRow(this)" data-itemID="' + $(me).attr("data-itemID") +'"  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"><span class="i-checkmark-3"></span></button>' +
            '<button  id="btnCancel" 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"><span class="i-cross"></span></button></td>' +
            '</tr>'
            );
            $("#itemCombo").val($(me).attr("data-itemID"));
            $('#itemCombo').select2();
    }

    function calculamount(){

    	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 * 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 option:selected").attr("data-tax")) / 100;
    	            $("#chargetaxAmount").val(accounting.formatNumber(t,2));
    	            $("#chargeAmountIT").val(accounting.formatNumber(t + $("#chargeAmount").val() * 1,2));
    	    }

    	    function EndEdit(me){
    	        var tr = $(me).parent().parent();
    	    var dID = $("#itemCombo").val();
    	            $(tr).replaceWith('<tr>' +
    	                    '<td>' + $("#lineNo").val() + '</td>' +
    	                    '<td>' + $("#itemCombo option:selected").text() + '</td>' +
    	                    '<td>' + $("#itemdes").val() + '</td>' +
    	                    '<td class="amount">' + $("#itemunitprice").val() + '</td>' +
    	                    '<td>' + $("#itemqte").val() + '</td>' +
    	                    '<td class="amount">' + $("#itemAmountET").val() + '</td>' +
    	                    '<td>' + $("#displayTaxCode").text() + ' | ' + $("#itemTax").val() + '</td>' +
    	                    '<td class="amount">' + $("#itemTaxAmount").val() + '</td>' +
    	                    '<td class="amount">' + $("#itemAmountIT").val() + '</td>' +
    	                    '<td>' +
    	                    '<button data-itemID="' + $(me).attr("data-itemID") +'" 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="deleteCompanyDetails(this)" data-myid="' + dID + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>' +
    	                    '</td>' +
    	                    '</tr>'
    	                    );
    	            getTotal ();
    }



    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>' + $("#itemDesc").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#itemList").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemunitprice").attr("data-previewvalue") + '</td>' +
            '<td class="quantity">' + $("#itemqte").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemAmountET").attr("data-previewvalue") + '</td>' +
            '<td>' + $("#itemTax").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemTaxAmount").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#itemAmountIT").attr("data-previewvalue") + '</td>' +
            '<td>' +
            '<button type="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 type="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(5)').text()) * 1;
            impot = impot + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(7)').text()) * 1;
            total = total + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(8)').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){
        // alert($(me).attr("data-myid"));
        $.ajax({
        type: "POST",
                data: {
                        invoiceId : $("#purchaseInvoiceId").val(),
                        invDetailsId :$(me).attr("data-myid"),
                        itemID:  $("#itemCombo").val(),
                        itemdescription: $("#itemdes").val(),
                        quantity : $("#itemqte").val(),
                        unitPrice: accounting.unformat($("#itemunitprice").val()),
                        amountExcludedTax: accounting.unformat($("#itemAmountET").val()),
                        taxID :  $("#itemTax").attr("data-taxid"),
                        taxRate: $("#itemTax").val(),
                        taxAmount: accounting.unformat($("#itemTaxAmount").val()),
                        amountIncludedTax:accounting.unformat($("#itemAmountIT").val()),
                        invoiceId : $("#purchaseInvoiceId").val()

                },
                url: "<?php echo base_url() ?>purchasetransaction/updateRowDetail",
                success: function(data) {
                msg (1, "alert alert-success", "Details successfully updated");
                        EndEdit(me);
                } });
                getTotal();
              /*  $.ajax({
                type: "POST",
                        data: {
                        invoiceId : $("#purchasetransactionId").val(),
                                totalPayable : $("#totalpayable").val(),
                                totalTaxAmount :  $("#totalamount").val()
                        },
                        url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
                        success: function(data) {
                        //update the invoice after delete
                        }
                });
                */
        }

    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: {
		                     invDetailsId :$(me).attr("data-myid"),
		                     invoiceId : $("#purchaseInvoiceId").val()
		                },
		                url: "<?php echo base_url() ?>purchasetransaction/deleteCompanyDetails",
		                success: function(data) {
		                msg (1, "alert alert-success", "Details successfully deleted");
		                        delRowInvoice(me);
		                } });
		        getTotal();
		       /* $.ajax({
		        type: "POST",
		                data: {
		                invoiceId : $("#purchasetransactionId").val(),
		                        totalPayable : $("#totalpayable").val(),
		                        totalTaxAmount :  $("#totalamount").val()
		                },
		                url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
		                success: function(data) {
		                //update the invoice after delete
		                }
		         }); */
		});
		}



    function editRowCharge(me){
    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) {
        ?>
            '<option   value="<?php echo $row->ID; ?>"><?php
        echo substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7) . " | ";
        echo str_replace(array("\n", "\r","'"), " ", $row->acctName, $count);
        ?></option>' +
    <?php
    }
}
?>
    '</select></td>' +
            '<td class="span4"><input value="' + $(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 value="' + $(me).parent().parent().find("td").eq(3).html() + '" class="span12" 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>' +
            '<td class="span2"><select  value="' + $(me).parent().parent().find("td").eq(4).html() + '" onclick="calculChargeAmount()" name="listTax" id="listTax"  class= "span12 validate[required]"><option></option>' +
<?php
if ($taxmaster) {
    foreach ($taxmaster as $row2) {
        ?>
            '<option data-taxcode="<?php echo $row2->code; ?>" data-tax="<?php echo $row2->taxPercentage; ?>" value="<?php echo $row2->ID; ?>" data-tax="' + <?php echo $row2->taxPercentage; ?> + '">' +
                    '<?php echo $row2->code . " | " . $row2->taxPercentage; ?></option>' +
    <?php
    }
}
?>
    '</select></td>' +
            '<td class="span1"> <input data-previewvalue="' + $(me).parent().parent().find("td").eq(5).html() + '" id="chargetaxAmount" value="' + $(me).parent().parent().find("td").eq(5).html() + '"  name="chargetaxAmount" class="span12" type="text" placeholder="Amount"></td>' +
            '<td class="span1"><input data-previewvalue="' + $(me).parent().parent().find("td").eq(6).html() + '" onkeydown="return false;" id="chargeAmountIT" value="' + $(me).parent().parent().find("td").eq(6).html() + '"name="chargeAmountIT" class="span12" type="text" placeholder="Amount (Exclude Tax)"></td>' +
            '<td class="span1">' +
            '<button type="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 type="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-trashcan"></i></button>' +
            '</td>' +
            '</tr>'
            );
            $("#chargeAccount").val($(me).attr("data-accid"));
            $("#listTax").val($(me).attr("data-taxid"));
            $("#chargeAccount").select2();
            $("#listTax").select2();
    } else{
    msg (2, "alert", "Please, do save the current details before adding new one");
    }
    }

    function delCancelEditCharge (me){
    var tr = $(me).parent().parent();
            $("#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 >' + $("#listTax").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#chargetaxAmount").attr("data-previewvalue") + '</td>' +
            '<td class="amount">' + $("#chargeAmountIT").attr("data-previewvalue") + '</td>' +
            '<td>' +
            '<button type="button" onClick="editRowCharge(this)" data-myid="' + $(me).attr("data-myid") + '" data-accid="' + $(me).attr("data-accid") + '" data-taxid="' + $(me).attr("data-taxid") + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
            ' <button type="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();
    	    $.ajax({
    	    type: "POST",
    	            data: {
                            invoiceId : $("#purchaseInvoiceId").val(),
    	                    chargeId : $(me).attr("data-myid"),
    	                    accountNoID : $("#chargeAccount").val(),
    	                    itemdescription : $("#chargedesc").val(),
    	                    amountExcludedTax :  accounting.unformat($("#chargeAmount").val()),
    	                    taxID : $("#listTax").val(),
    	                    taxAmount : accounting.unformat($("#chargetaxAmount").val()),
    	                    amountIncludedTax : accounting.unformat($("#chargeAmountIT").val())

    	            },
    	            url: "<?php echo base_url() ?>purchasetransaction/updateCharge",
    	            success: function(data) {
    	            msg (2, "alert alert-success", "Details successfully updated");
    	                    $(tr).replaceWith('<tr><td>' + $("#lineNo").attr("data-previewvalue") + '</td>' +
    	                            '<td>' + $("#chargeAccount option:selected").text() + '</td>' +
    	                            '<td>' + $("#chargedesc").val() + '</td>' +
    	                            '<td class="amount">' + accounting.formatNumber($("#chargeAmount").val(),2) + '</td>' +
    	                            '<td>' + $("#listTax option:selected").text() + '</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-myid="' + $(me).attr("data-myid") + '" data-accid="' + $("#chargeAccount").val() + '" data-taxid="' + $("#listTax").val() + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
    	                            '<br /> <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();
    	                    $.ajax({
    	                    type: "POST",
    	                            data: {
    	                            invoiceId : $("#purchasetransactionId").val(),
    	                                    totalPayable : $("#totalpayable").val(),
    	                                    totalTaxAmount :  $("#totalamount").val()
    	                            },
    	                            url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
    	                            success: function(data) {
    	                            //update the invoice after delete
    	                            }
    	                    });
    	            } });
    	    }

    function  deleteCompanyCharge(me){
    	 $('#popupModal').modal('show');
         $("#_popupTitle").html("Confirm delete");
         $("#_popupContent").html("Your about to delete definively this row. <br/> Click on ok to confirm");
         $('#_popupFooter').empty();
         $('#_popupFooter').append('<button class="btn-form btn-success-form" id="detButton">Ok</button>' +
         '<button class="btn-form btn-danger-form" id="canb">Cancel</button>');
         $("#_popupTitle").html("Confirm delete");
         $("#canb").click(function() {
		 $('#popupModal').modal('hide');
		 });
		         $("#detButton").click(function() {
		 $('#popupModal').modal('hide');
		         $.ajax({
		         type: "POST",
		                 data: {
		                     chargeID :$(me).attr("data-myid"),
		                     invoiceId : $("#purchaseInvoiceId").val()
		                 },
		                 url: "<?php echo base_url() ?>purchasetransaction/deleteCharge",
		                 success: function(data) {
		                 msg (1, "alert alert-success", "Details successfully deleted");
		                         delRowInvoice(me);
		                         getTotal();
		                      /*   $.ajax({
		                         type: "POST",
		                                 data: {
		                                 invoiceId : $("#purchasetransactionId").val(),
		                                         totalPayable : $("#totalpayable").val(),
		                                         totalTaxAmount :  $("#totalamount").val()
		                                 },
		                                 url: "<?php echo base_url() ?>purchasetransaction/updateInvoice",
		                                 success: function(data) {
		                                 //update the invoice after delete
		                                 }
		                         }); */
		                 } });
		 });
		         getTotal ();
	}



    function 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) {
        ?>
            '<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 str_replace(array("\n", "\r","'"), " ", $row2->name, $count);
        ?></option>' +
    <?php
    }
}
?>
    '</select>');
            $("#listTaxPopup").select2();
            $('#_popupFooter').empty();
            $('#_popupFooter').append('<button type="button" class="btn-form btn-success-form" id="confButton">Ok</button>' +
            '<button type="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").attr("data-taxid", $("#listTaxPopup").val());
            	$("#itemTax").val ($("#listTaxPopup option:selected").attr("data-tax"));
            	$("#displayTaxCode").html($("#listTaxPopup option:selected").attr("data-taxcode"));
            	calculamount();
        	});            
    }

    function addNewItemRow(){
    	if (!$("#itemComboList").length) {
            $(''+
                 '<tr><td class="span1">' + ($("#trInfos").attr("data-currentRow")*1 + 1) + '</td>'+
                    '<td class="span1"><select name="itemCombo" id="itemCombo" class="span12" onchange="displaysItemDefaultValue()"><option></option>' +
<?php
if ($items) {
    foreach ($items as $row) {
        ?>
                                    '<option data-desc= "<?php echo $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="calculamount()" name="itemunitprice" class="span12 amount validate[required,custom[number]]" type="text" placeholder="Unit Priece"></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="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" 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="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="savenewitem()" 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" );
    $('#itemCombo').select2();

    }else{
    msg (1,"alert","Please, do save the current details before adding new one");
    }
    }
        
        
        function savenewitem(){
              $.ajax({
                    type: "POST",
                    data: {
                              invoiceId : $("#purchaseInvoiceId").val(),

                              itemID:  $("#itemCombo").val(),
                              itemdescription: $("#itemdes").val(),
                              quantity : $("#itemqte").val(),
                              lineNo : $("#trInfos").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>' +  ($("#trInfos").attr("data-currentRow")*1 +1) + '</td>' +
                            '<td>' +  $("#itemCombo 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 class="amount">' + $("#itemAmountIT").val() + '</td>'+
                            '<td>'+
                            '<button data-itemID="' + $("#itemCombo").val() +'" data-taxcode="' + $("#itemTax").val() + '"  onClick="editRow(this)" data-taxid="' + $("#itemTax").attr("data-taxid") + '" data-myid="' + data.detailID + '" class="btn-icon btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                            ' <button onclick="deleteCompanyDetails()" data-myid="' + data.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();
                    $.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
        }



    function savenewitemrow(){
    $.ajax({
    type: "POST",
            data: {
                    invoiceId : $("#purchaseInvoiceId").val(),
                    itemID : $("#itemList").val(),
                    lineNo : $("#trInfos").attr("data-currentRow") * 1 + 1,
                    quantity : $("#itemqte").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="amount">' + $("#itemunitprice").val() + '</td>' +
                            '<td class="quantity">' + $("#itemqte").val() + '</td>' +
                            '<td class="amount">' + $("#itemAmountET").val() + '</td>' +
                            '<td>' + $("#displayTaxCode").text() + " | " + $("#itemTax").val() + '</td>' +
                            '<td class="amount">' + $("#itemTaxAmount").val() + '</td>' +
                            '<td class="amount">' + $("#itemAmountIT").val() + '</td>' +
                            '<td>' +
                            '<button type="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 type="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(){
	    if (!$("#chargeAccount").length) {
            $(''+
            '<tr><td class="span1">' + ($("#trInfosCharge").attr("data-currentRow")*1 + 1) + '</td>'+
                  '<td class="span2">\n\
       <select name="chargeAccount" id="chargeAccount" class="span12" validate[required]"><option></option>' +
<?php 
if ($chargeAccount) {
   foreach ($chargeAccount as $row) {
       ?>
                                            '<option value="<?php echo $row->ID; ?>"><?php
       echo substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7). " | ";
       echo str_replace(array("\n", "\r","'"), " ", $row->acctName, $count);
       ?></option>'+
   <?php
   }
}
?>
       '</select></td>'+
       '<td class="span4"><input  id="chargedesc" name="chargedesc"  type="text" class="span12 validate[required]" placeholder="Description"></td>'+
       '<td class="span1"><input id="chargeAmount" onkeyup="calculChargeAmount()" name="chargeAmount" class="span12 validate[required, custom[number]]" type="text" placeholder="Amount"></td>'+
       '<td class="span2"><select onclick="calculChargeAmount()" name="listTax" id="listTax"  class= "span12 validate[required]"><option></option>' +
<?php
if ($taxmaster) {
   foreach ($taxmaster as $row2) {
       ?>
       '<option value="<?php echo $row2->ID; ?>" data-tax="' + <?php echo $row2->taxPercentage; ?> + '">' + 
'<?php
       echo $row2->code . " [" . $row2->taxPercentage . "] ";
       ?></option>'+
   <?php
   }
}
?>
                                                        '</select></td>'+
                                                                                                       '<td class="span1"><input id="chargetaxAmount"  name="chargetaxAmount" class="span12" type="text" placeholder="Amount"></td>'+
                                                                                                       '<td class="span1"><input disabled id="chargeAmountIT" name="chargeAmountIT" class="span12" type="text" placeholder="Amount (Exclude Tax)"></td>'+
                                               '<td class="span1">'+
                                                       '<button title="Add New Row" onclick = "saveNewChargeRow()" class="btn-icon btn-mini btn-success-form" type="button"><span class="i-checkmark-3"></span></button>'+
                                                       '<button onclick="delRowInvoice(this)" id="btnCancelCharge" title="Cancel" class="btn-icon btn-mini btn-danger-form" type="button"><span class="i-cross"></span></button>'+
                                               '</td>'+
                   '</tr>'
                                         ).insertBefore( "#trInfosCharge" );
					$('#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 saveNewChargeRow(){
    	$.ajax({
            type: "POST",
            data: {
                          invoiceId : $("#purchaseInvoiceId").val(),
                          accountNoID : $("#chargeAccount").val(), 
                          itemdescription: $("#chargedesc").val(),
                          amountExcludedTax : accounting.unformat($("#chargeAmount").val()),
                          taxID: $("#listTax").val(),
                          lineNo : $("#trInfosCharge").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">' + ($("#trInfosCharge").attr("data-currentRow")*1 + 1) + '</td>'+
                    '<td>' + $("#chargeAccount option:selected").text() + '</td>'+
                    '<td>' + $("#chargedesc").val() + '</td>'+
                    '<td class="amount">' + accounting.formatNumber($("#chargeAmount").val(),2) + '</td>'+
                    '<td>' + $("#listTax option:selected").text() + '</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-myid="' + resul.chargeId + '" data-accid="' + $("#chargeAccount").val() + '" data-taxid="' + $("#listTax").val() + '" class="btn-ion btn-mini btn-warning-form"><i class="i-pen"></i></button>' +
                       '<br /><button onClick="deleteCompanyCharge(this)" data-myid="' + resul.chargeId + '" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i</button>' +
                    '</td>'+
            '</tr>'
                  ).insertBefore( "#trInfosCharge" );
                  $("#trInfosCharge").attr("data-currentRow",$("#trInfosCharge").attr("data-currentRow")*1+1);
                  $("#btnCancelCharge").trigger("click");
              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
}
	function checkBtn(me){
		console.log('hello');//+$('button',me).attr('id'));
		//$('#editSaleInvoice').submit();
		return true;
	} 

</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('editSalesInvoice') ?></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">
            <form id="editPurchaseInvoice" action="#" onsubmit="" method="post" enctype="application/x-www-form-urlencoded">
            
            <div class="content" id="grid_content_1" >
    
    
                <?php
                    $memo = !empty($invoice[0]->memo)?$invoice[0]->memo:'';
                    $employeeName = !empty($invoice[0]->employeeName)?$invoice[0]->employeeName:'';
                    $shippingmethod = !empty($invoice[0]->shippingmethod)?$invoice[0]->shippingmethod:'';
                    $locationID = !empty($invoice[0]->locationID)?$invoice[0]->locationID:'';
                    $rowIn = $invoice[0];
                
                ?> 
                <input type="hidden" name="ID" id="purchaseInvoiceId" value="<?php echo $rowIn->InvID; ?>" />
                <div class="row-fluid scRow"> 
				    <div class="span4 scCol">
				        <div class="block" id="grid_block_1">
                                               <div class="head">
     <h2><strong><?php echo $this->lang->line('editSalesInvoice') ?></strong></h2>
</div><!-- head -->
				            <div class="content">
				                <div class="controls-row">
		                            <div class="span4"><?php echo $this->lang->line('supplier') ?></div>
		                            <div class="span8">
		                                <div class="span12">
		                                    <select class="span10 validate[required]" name="supplierID" id="supplier" onchange="loadSupplierDefaultValue(this)">
		                                        <option></option>
		                                        <?php
		                                        if ($supplier != '') {
		                                            foreach ($supplier as $row) {
		                                                ?>
		                                                <option value="<?php echo $row->ID; ?>" <?php echo ($rowIn->supplierID == $row->ID)?'selected="selected"':''; ?>> <?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> <!-- row -->
				                <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 $rowIn->formNo; ?>' style="color:red;"   type="text" placeholder="Form number ...">
					                </div>
					                <div class="span3">
					                	<input  class="span12"   type="text" placeholder="Serial" value="<?php echo $rowIn->InvID; ?>" disabled="disabled">
					                </div>
				                </div> <!-- row -->
				                <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' => 'invoiceDate',
				                        'id' => 'createdDate',
				                        'type' => 'text',
				                        'onkeydown' => 'return false',
				                        'class' => 'span10 datepicker validate[required] financhk',);
				                    echo form_input($data, $rowIn->invoiceDate);
				                    ?>
				                </div>
				                </div>
				                </div> <!-- row -->
				                <div class="controls-row">
				                <div class="span4"><?php echo $this->lang->line('supplierInvoiceNo') ?></div>
				                <div class="span8">
				                <input id="supinvoicenumber" name="supplierInvoiceNo" value="<?php echo $rowIn->supplierInvoiceNo; ?>" 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('project') ?></div>
				                <div class="span8">
				                <div class=" span12">
				                    <select id="project" name="projectID" class="span10 validate[required]">
				                        <option></option>
				                        <?php
				                        if ($project != '') {
				                            foreach ($project as $row) {
				                                ?>
				                                <option value="<?php echo $row->ID; ?>" <?php echo ($rowIn->projectID == $row->ID)?'selected="selected"':''; ?>><?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><!-- scCol -->
				    	</div>
					</div>
				    <div class="span4 scCol">
				        <div class="block" id="grid_block_1">
				            <div class="content">
				                <div class="controls-row">
				
				                    <div class="span4"><?php echo $this->lang->line('location') ?></div>
				                    <div class="span8">
				                        <div class=" span12">
				                            <select class="span10 validate[required]" name="locationID" id="location">
				                                <option></option>
												<?php
												if ($location != '') {
													foreach ($location as $row) {
												?>
				                                        <option value="<?php echo $row->fldid; ?>" <?php echo ($rowIn->locationID == $row->fldid)?'selected="selected"':''; ?>><?php echo $row->code . " | " . $row->address . " | " . $row->city; ?></option>
												<?php
													}
												}
												?>
				                            </select>
				                            <div class="btn-group span1">
				                                <button class="btn-icon btn-small dropdown-toggle" data-toggle="dropdown">
				                                    <span class="caret"></span>
				                                </button>
				                                <ul class="dropdown-menu">
				                                    <!-- dropdown menu links -->
				                                    <li><a target="_blank" href="<?php echo base_url() ?>ItemSetup/location"  id="btnLocation">
				                                            <i class="i-plus-3"></i><?php echo $this->lang->line('addLocation') ?></a></li>
				                                    <li><a href="#" onclick="refreshLocation()"><i class="i-ccw"></i><?php echo $this->lang->line('refreshlist') ?></a></li>
				                                </ul>
				                            </div>
				                        </div> <!-- btnn group -->
				                    </div>
				                </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" name="termsID" onchange="getTermDescription(this)" class="span10 validate[required]">
				                                <option></option>
												<?php
												if ($terms != '') {
													foreach ($terms as $row) {
												?>
				                                        <option data-desc="<?php echo $row->termDescription; ?>" value="<?php echo $row->ID; ?>" <?php echo ($rowIn->termsID == $row->ID)?'selected="selected"':''; ?>><?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="controls-row">
				                    <div class="span4"><?php echo $this->lang->line('termsdesc') ?></div>
				                    <div class="span8">
				                        <textarea style="height: 123px; " disabled="disabled" id="termDescription" class="span12">
				                        	<?php echo $rowIn->termDescription; ?>
				                        </textarea>
				                    </div><!-- span -->
				                </div><!-- row control -->
							</div><!-- scCol -->
				    	</div>
					</div>
				    <div class="span4 scCol">
				        <div class="block" id="grid_block_1">
				            <div class="content">
				                <div class="controls-row">
				                    <div class="span4"><?php echo $this->lang->line('shipto') ?></div>
				                    <div class="span8">
				                        <select id="shiptoAddress" name="shipToID" onchange ="displaysAdress()" class="span12 validate[required]">
				                            <option data-line1="" data-line2="" data-line3="" data-postcode=""></option>
										    <?php
										    if ($shipto != '') {
										    foreach ($shipto as $row) {
										    ?>
				                                    <option <?php echo ($rowIn->shipToID == $row->ID)?'selected="selected"':''; ?>  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('shiptoDesc') ?></div>
				                    <div class="span8">
				                        <textarea style="height: 75px;" disabled="disabled"ssss id="shiptoDesc" class="span12">
				        					<?php echo $rowIn->line1."\r\n".$rowIn->line2."\r\n".$rowIn->line3."\r\n".$rowIn->postCode; ?>
				                        </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" value="<?php echo $rowIn->currencyWord; ?>" name="currency" type="text" placeholder="Currency" disabled="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" value="<?php echo number_format($rowIn->exchangeRate, 5); ?>" name="exchangeRate" type="text" placeholder="Example: 3.20000" >           
				                    </div><!-- span -->
				                </div><!-- control row -->
				            </div>
				        </div>
				    </div>
				</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('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 href="javascript:" onclick="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="amount"><?php echo $this->lang->line('unitPrice') ?></th>
                                            <th class="quantity"><?php echo $this->lang->line('quantity') ?></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 ($itemList && $invoice) {
                                            foreach ($itemList 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->description; ?></td>
                                                    <td class="amount"><?php echo number_format($row->unitPrice, 2); ?></td>
                                                    <td><?php echo $row->quantity; ?></td>
                                                    <td class="amount"><?php echo number_format($row->amountExcludedTax, 2); ?></td>
                                                    <td><?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>
                                                        <button type="button" onClick="editRow(this)" 
                                                                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 type="button" onClick="deleteSaleItemRow(this)" data-myid="<?php echo $row->ID; ?>" class="btn-icon btn-mini btn-danger-form"><i class="i-trashcan"></i></button>
                                                    </td>
                                                </tr>
                                            <?php
                                        }
                                    } else {
                                        ?>
                                        <div class="alert alert-error">
                                            <?php echo $this->lang->line('message1') ?>
                                            </div>
                                        <?php } ?>
                                    <tr id="trInfos" data-currentRow="<?php echo $lastrow; ?>">
                                        <td colspan="10">
                                            <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>
                                    </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="#trInfosCharge" 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 type="button" onClick="editRowCharge(this)" data-taxid="<?php echo $row->taxId ?>" data-accid= "<?php echo $row->accountNoID ?>" data-myid="<?php echo $row->myid; ?>" class="btn-icon btn-mini btn-warning-form">
															<i class="i-pen"></i></button>                                                     
                                                        <br />
                                                        <button type="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
                                        }
                                    } else {
                                        ?>
                                        <div class="alert alert-error">
                                            No charges found ...
                                        </div>
                                    <?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>
                                    </tbody>
                                </table>     
                            </div><!-- content -->
                        </div><!-- grid block 1-->
                    </div><!-- scCol -->
                </div><!-- row-fluid scRow-->
                <div class="row-fluid scRow"> 
                    <div class="span7 scCol">
                        <div class="block" id="grid_block_4">
                            <div class="content np">
                                <div class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('shippingmethod') ?></div>
                                    <div class="span8">
                                        <div class="span12">
                                            <select id="shippingmethod" name="shippingMethodID"  class="span11 validate[required]">
                                                <option></option>
												<?php
												if ($shipmethod != '') {
												    foreach ($shipmethod as $row) {
												        ?>
                                                        <option value="<?php echo $row->ID; ?>" <?php echo ($rowIn->shippingMethodID==$row->ID)?'selected="selected"':''; ?> ><?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('purchaser') ?></div>
                                    <div class="span8">
                                        <div class=" span12">


                                            <select name="purchaserID" class="span11 validate[required]" id="purchaser">
                                                <option></option>
												<?php
												if ($purchaser != '') {
												    foreach ($purchaser as $row) {
        										?>
                                                        <option value="<?php echo $row->ID; ?>" <?php echo ($rowIn->purchaserID==$row->ID)?'selected="selected"':''; ?>> <?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 class="controls-row">
                                    <div class="span4"><?php echo $this->lang->line('memo') ?></div>
                                    <div class="span8">
                                        <textarea style="height: 75px;" id="memo" class="span12" name="memo"><?php echo $rowIn->memo; ?></textarea>
                                    </div><!-- span -->
                                </div><!-- row control -->

                            </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" name="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" name="totalTaxAmount" 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" name="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-mini btn-warning-form"> 
                                                <i class="i-checkmark-3"></i><?php echo $this->lang->line('updateInfo') ?></button>

                                        </div><!-- btn group -->      
                                    </div><!-- side fr -->      
                                </div><!-- footer -->   
                            </div>    
                        </div><!-- grid block 1-->
                    </div><!-- scCol -->
                </div><!-- row-fluid scRow-->
    
            </div><!-- grid 1 -->
            </form>
        </div>
    </div><!-- wrap -->
</div><!-- content -->