<style type="text/css">
    .sambox{
        display:none;
    }
    .amount{
        text-align: right;
    }

    .quantity {
        text-align: center;
    }

    .btn-group button {
        height:30px; }

    #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(!empty($taxmaster)){
    foreach ($taxmaster as $k => $v) {
        $val = null;
        $val = array_search('OS', (array) $taxmaster[$k]);
        if ($val != null) {
            $nonGstTaxID = $taxmaster[$k]->ID;
            break;
        }
    }
}else{
    $nonGstTaxID = 0;
}
?>
<script type="application/javascript">

    var gstStatus = true;
    $(document).ready(function(){
    gstStatus = isGstRegistered(<?php echo element('compID', $this->session->userdata('logged_in')); ?>,'company');
    console.log(gstStatus);
    $('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:#368e5c;">'+modTxt+"</span>";
    else              return modTxt;
    }
    $("#customer").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
    });
    });


    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 refreshShip(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>artransaction/refreshShip/",
    data: "custID="+$('#customer').select2('val'),
    success: function(data) {
    if(data != ''){
    $('#shiptoAddress').html(data);	
    //$('#shiptoAddress').html('<option value="null">Select</option>'+data);	

    }
    }
    });

    }


    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 value="null">Select</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"));
    }



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

    $("#totalamount").val("0");

    $("#impotpayable").val("0");

    $("#totalpayable").val("0");
    }
    // if ($("#itemTax").attr("data-taxid")=="") {
    //       taxPopup ();
    //}
    var qtyMax = accounting.unformat($("#itemList option:selected").attr("data-qty"));
    if(accounting.unformat($("#itemqte").val())*1>qtyMax || accounting.unformat($("#itemqte").val()) < 1){
    $("#itemqte").attr("style","color:red;");
    $("#itemqte").val("");
    msg (1,"alert", "The quantity available of this item is :" + qtyMax
    + "<br> The current quantity should more than 0 and less than " + qtyMax);
    }else{
    $("#itemqte").attr("style","color:green;");
    $("#itemqte").val(accounting.unformat($("#itemqte").val())*1);
    msg (1,"alert alert-info", "...");
    if (isNaN($("#itemqte").val()))
    $("#itemqte").val("");
    }
    var j_itemAmountET =accounting.unformat($("#itemunitprice").val())*accounting.unformat($("#itemqte").val());
    $("#itemAmountET").val(accounting.formatNumber(j_itemAmountET,2));
    var j_itemTaxAmount=j_itemAmountET*accounting.unformat($("#itemTax").val())/100;
    $("#itemTaxAmount").val(accounting.formatNumber(j_itemTaxAmount,2));
    $("#itemAmountIT").val(accounting.formatNumber(j_itemTaxAmount+j_itemAmountET,2));


    }

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

    if (!$("#chargeAccount").length) {
    $(''+
    '<tr><td>' + ($("#listCharge tbody tr").length) +'</td>' +
    '<td class="span4"> <select name="chargeAccount" id="chargeAccount" class="span12 validate[required]"><option></option>' +
    <?php
    if ($chargeAccount) {
        foreach ($chargeAccount as $row) {
            $temp = str_replace(array("\n", "\r", "'"), " ", $row->acctName, $count);
            ?>
            '<option value="<?php echo $row->ID; ?>"><?php echo substr($row->acctCode, 0, 4) . '-' . substr($row->acctCode, 4, 3) . '-' . substr($row->acctCode, 7) . " | ";
        echo $temp;
            ?></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 amount validate[required, custom[number]]" type="text" placeholder="Amount"></td>'+
    tax+
    '<td class="span1"><input disabled="disabled" id="chargetaxAmount"  name="chargetaxAmount" class="span12 amount" type="text" placeholder="Amount"></td>'+
    '<td class="span1"><input disabled  id="chargeAmountIT" name="chargeAmountIT" class="span12 amount" type="text" placeholder="Amount (Exclude Tax)"></td>'+
    '<td class="span1">'+
    '<button onclick = "saveCharge(this)" class="btn-icon btn-mini btn-success-form" type="button"><i class="i-checkmark-3"></i></button>'+
    '<button onclick="delRowInvoice(this)" id="btnCancelCharge" class="btn-icon btn-mini btn-danger-form remove" type="button"><i class="i-cross"></i></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" );

    $('#chargeAccount').select2();
	
		$.each($(".select2-container"), function (i, n) {
            $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
            $(n).prepend($(n).next());
            $(n).delay(500).queue(function () {
                $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                $(this).dequeue();
            });
        });

    }else{
    msg (2,"alert","Please, do save the current details before adding new one");
    }
    }

    function refreshLocation(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>artransaction/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 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() { 
        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())*1,2));
    }


    function displaysAdress(){
    var address = $("#shiptoAddress option:selected").attr("data-line1")+'\n'+$("#shiptoAddress option:selected").attr("data-line2")+'\n'+ $("#shiptoAddress option:selected").attr("data-line3");
    console.log(address);
    $("#shiptoDesc").html("");
    $("#shiptoDesc").html(address);
    }

    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"  class= "validate[required]" 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(".taxid").val($("#listTaxPopup").select2('val'));
        me.find(".itemTax").attr("value",$("#listTaxPopup option:selected").attr("data-tax"));
        me.find(".displayTaxCode").html($("#listTaxPopup option:selected").attr("data-taxcode"));
        me.find("td:nth-child(11)").html(accounting.formatNumber((accounting.unformat(me.find("td:nth-child(9)").html())/100)*me.find(".itemTax").val(),2));
        me.find("td:nth-child(12)").html(accounting.formatNumber(accounting.unformat(me.find("td:nth-child(9)").html())+accounting.unformat(me.find("td:nth-child(11)").html()),2));
        //calculamountET();
        $("#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();
    });


    }

    function refreshCustomer(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>CustomerSetup/refreshCustomer",
    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].customerName + ' (GST)</option>';
    else
    opt=opt + '<option value="' + resul.records[i].id +'">' + resul.records[i].customerName + '</option>';

    $('#customer').empty();
    $('#customer').append(opt);
    }
    });	
    }

    function refreshAgent(){
    $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>SaleAgentSetup/refreshAgent",
    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].agentName + '</option>';
    $('#agent').empty();
    $('#agent').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,
    {"bSortable": false},
    {"bSortable": false}
    ] 
    });
    oTable.fnSort( [ [1,'asc'] ] );

    //Check all items from the order
    $("table .checkall1").live("click", "checkall1",function(){           
    $(oTable.fnGetNodes()).find(':checkbox').prop('checked', this.checked);
    getTotal();
    });
    $('.checkbox').live("click",function(){
    getTotal();
    });


    //Gather customer invoice detail by customer ID & invoice no
    $('#customer,#createdDate').live('change',function(){		
    var str = $(this).val();
    $('#currency').val("");
    $('#termDescription').text("");
    jQuery.ajax({
    url: "<?php echo base_url() ?>arTransaction/getOrderItemsCust",
    async: false,
    type: "POST",
    data: "customerID="+$('#customer').val()+'&date='+$('#createdDate').val(),
    dataType: "html",
    success: function(data) {
    var obj = jQuery.parseJSON(data);        
    if(obj != false){
    //console.log(obj.info[0].ID+'<->'+obj.info[0].companyID);
    //$('#createdDate').val(obj.info[0].salesOrderDate);					
    //$('#saler').select2("val",obj.info[0].salesPerson);
    //$('#shiptoAddress').select2("val",obj.info[0].deliveryToID);					
    if(obj.info[0] != 'undefined'){
    $('#currency').val(obj.info[0].fldcurr_code);
    $('#currency').attr("data-currencyID",obj.info[0].currencyID);
    $('#exchange_rate').val(accounting.formatNumber(obj.info[0].exchangeRate,5));
    $('#term').select2('val',parseInt(obj.info[0].termsID)).trigger('change');

    }

    if(obj.shipto != 'undefined'){
    $('#shiptoAddress').html(obj.shipto);	
    //$('#shiptoAddress').html("<option value='null'>Select</option>"+obj.shipto);	
    $('#shiptoAddress').select2("val",null);
    $('#shiptoDesc').text("");
    }else{
    $('#shiptoAddress').html("");
    //$('#shiptoAddress').html("<option value='null'>Select</option>");	
    $('#shiptoAddress').select2("val",null);
    $('#shiptoDesc').text("");
    }


    if(typeof(obj.detail) != 'undefined'){
    //Items listing
    var serial = 1;
    oTable.fnClearTable();
    jQuery.each(obj.detail,function(i,v){
    var total = parseFloat(v.amount).toFixed(2);
    if(!gstStatus){
    v.taxPercentage = 0;
    v.code = 'OS';
    v.outputTaxID = "<?php echo $nonGstTaxID; ?>";
    var taxDet = v.taxPercentage+' | '+v.code+'<input class="taxid" type="hidden" value="'+v.outputTaxID+'" />';
    }else{
    var taxDet = '<td class="span1">\
    <div  class="input-prepend">\
    <input disabled="disabled" data-taxid="'+v.outputTaxID+'" onkeyup="calculamountET()" name="itemTax" class="span6 itemTax validate[required, custom[number]]" type="text" placeholder="Tax(%)" value="'+v.taxPercentage+'">\
    <span onclick="taxPopup ()" style="margin-top:0;"  class="btn add-on displayTaxCode">'+v.code+'</span>\
    <input class="taxid" type="hidden" value="'+v.outputTaxID+'" />\
    </div>\
    </td>';

    }

    var desc = v.description;
    var tax = parseFloat((v.amount*v.taxPercentage)/100).toFixed(2);
    var totalpayble = parseFloat(total) + parseFloat(tax);
    var rowIndex = oTable.fnAddData( [
                                v.deliveryID,
                                serial++,
                                v.formNo,
                                v.name,
                                '<input type="text" class="desc span12" value="'+v.description+'" />',
                                accounting.formatNumber(v.unitPrice*v.factor,2),
                                v.quantitySent/v.factor,
                                v.umCode,
                                accounting.formatNumber(total,2),
                                taxDet,
                                accounting.formatNumber(tax,2),
                                accounting.formatNumber(totalpayble,2),
                                //+'<button class="btn btn-mini btn-primary editTax" type="button"><i class="icon-edit icon-white"></i></button>'
                                '<input type="checkbox" class="checkbox">',
                                v.itemID
                        ] );
    var row = oTable.fnGetNodes(rowIndex);
    $(row).find('td:nth-child(6),td:nth-child(7),td:nth-child(9),td:nth-child(11),td:nth-child(12)').addClass('tar');
    $(row).find('td:nth-child(8)').addClass('tac');
    $(row).find('td:nth-child(1),td:nth-child(14)').css('display','none');
    $(row).find('td:nth-child(8)').append('<input type="hidden" value="'+v.umID+'" />');
    });
    }else{
    oTable.fnClearTable();
    }
    }else{
    oTable.fnClearTable();
    }	
    }
    });
    });
    //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="" name="itemTax" class="span6 itemTax 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{
    alertBox1(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-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'){
    alertBox1(1,"Successfully updated tax information");
    }else{
    alertBox1(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();
    }

    function getOrderDet(){
    var str = '[';
    var i = 1;
    $('#listDetails tbody tr').each(function(){
    if(($(this).find('input:checked').is(':checked'))){
    if(str == '['){
    str += '{"lineNo":'+i+
    ',"doID":'+$('td:nth-child(1)',this).html()+
    ',"quantity":'+$('td:nth-child(7)',this).html()+
    ',"unitPrice":'+accounting.unformat($('td:nth-child(6)',this).html())+
    ',"umID":'+$('td:nth-child(8) input',this).val()+
    ',"amountExcludedTax":'+accounting.unformat($('td:nth-child(9)',this).html())+
    ',"taxID":'+$('td:nth-child(10) .taxid',this).val()+
    ',"taxRate":'+$('td:nth-child(10) .itemTax',this).val()+
    ',"taxAmount":'+accounting.unformat($('td:nth-child(11)',this).html())+
    ',"amountIncludedTax":'+accounting.unformat($('td:nth-child(12)',this).html())+
    ',"itemID":'+$('td:nth-child(14)',this).html()+
    ',"itemdescription":"'+$('td:nth-child(5) input',this).val()+'"'+
    '}';
    }else{
    str += ',{"lineNo":'+i+
    ',"doID":'+$('td:nth-child(1)',this).html()+
    ',"quantity":'+$('td:nth-child(7)',this).html()+
    ',"unitPrice":'+accounting.unformat($('td:nth-child(6)',this).html())+
    ',"umID":'+$('td:nth-child(8) input',this).val()+
    ',"amountExcludedTax":'+accounting.unformat($('td:nth-child(9)',this).html())+
    ',"taxID":'+$('td:nth-child(10) .taxid',this).val()+
    ',"taxRate":'+$('td:nth-child(10) .itemTax',this).val()+
    ',"taxAmount":'+accounting.unformat($('td:nth-child(11)',this).html())+
    ',"amountIncludedTax":'+accounting.unformat($('td:nth-child(12)',this).html())+
    ',"itemID":'+$('td:nth-child(14)',this).html()+
    ',"itemdescription":"'+$('td:nth-child(5) input',this).val()+'"'+
    '}';'}';
    }
    i++;
    }
    });
    str += ']'
    return str;
    }
    //Save sales order as invoie
    function saveInvoice(me){
    	if($("#SaleDetailForm").validationEngine('validate') && finanEngine('financhk')){
    		console.log('um here');
    		if ( $("#saleInvoiceId").val()=="null"){
    			$itemDetail = getOrderDet();
    			getTotal();
                        $(me).attr("disabled","disabled");
    			$.ajax({
                            
    				type: "POST",
    				data: {
    					showinInvoice : $("input[name='showinInvoice']:checked").val(),
    					invoiceCodeID:1,
    					salesOrderID : $("#orderNo").val(),
    					shippingMethodID : $("#shippingmethod").val(),
    					employeeID : $("#saler").val(),
    					memo : $("#memo").val(),
    					invoiceCodeID : 1,
    					totalPayable : $("#totalpayable").val(), 
    					totalTaxAmount :  $("#totalTaxAmount").val(),
    					customerID : $("#customer").val(),
    					locationID :  0,//$("#location").val(),
    					agentID : $("#agent").val(),
    					formNo : $("#formNo").val(),
    					invoiceDate: $("#createdDate").val(),
    					customerPoNo : $("#customerPoNo").val(),
    					projectID: $("#project").val(),
    					termsID: $("#term").val(),
    					currencyID: $("#currency").attr("data-currencyID"),
    					exchangeRate : $("#exchange_rate").val(),
    					shipToID : $("#shiptoAddress").val(),

    					//Sales order detail
    					salesDetail:getOrderDet(),

    					accountNoID : $("#chargeAccount").val(),
    					lineNo : $("#listCharge").attr("data-currentRow")*1 +1,
    					chargeDescription : $("#chargedesc").val(),
    					taxAmount : accounting.unformat($("#totalTaxAmount").val()),
    					amountIncludedTax : accounting.unformat($("#totalpayable").val()),
    					amountExcludedTax: accounting.unformat($("#totalamount").val()),
    					taxID: $("#listTax").val(),
    					taxRate: $("#listTax option:selected").attr("data-tax")

    				},
    				url: "<?php echo base_url() ?>artransaction/saveSaleInvoice",
    				success: function(data) {
                                        $(me).removeAttr("disabled");
    					var resul = eval ("(" + data + ")"); 
    					$("#saleInvoiceId").val(resul.invoiceID);
    					getTotal();
    					alertBox1(1,"Success ! The Invoice successfully saved");
						
                        /*var urls = "<?php echo base_url();?>artransaction/salesinvoice";  //No need to refresh because need to add charges after save command.
									window.location = urls;*/
    				} //end function
    			});//end ajax
    			}else{
    				$itemDetail = getOrderDet();
    				getTotal();
                                $(me).attr("disabled","disabled");
    				$.ajax({
    				type: "POST",
    				data: {
    					showinInvoice : $("input[name='showinInvoice']:checked").val(),
    					invoiceID:$("#saleInvoiceId").val(),
    					invoiceCodeID:1,
    					salesOrderID : $("#orderNo").val(),
    					shippingMethodID : $("#shippingmethod").val(),
    					employeeID : $("#saler").val(),
    					memo : $("#memo").val(),
    					invoiceCodeID : 1,
    					totalPayable : $("#totalpayable").val(), 
    					totalTaxAmount :  $("#totalTaxAmount").val(),
    					customerID : $("#customer").val(),
    					locationID : 0,// $("#location").val(),
						agentID : $("#agent").val(),
						formNo : $("#formNo").val(),
						invoiceDate: $("#createdDate").val(),
						customerPoNo : $("#customerPoNo").val(),
						projectID: $("#project").val(),
						termsID: $("#term").val(),
						currencyID: $("#currency").attr("data-currencyID"),
						exchangeRate : $("#exchange_rate").val(),
						shipToID : $("#shiptoAddress").val(),

						//Sales order detail
						salesDetail:getOrderDet(),
					
						taxAmount : accounting.unformat($("#totalTaxAmount").val()),
						amountIncludedTax : accounting.unformat($("#totalpayable").val()),
						amountExcludedTax: accounting.unformat($("#totalamount").val()),					
    				},
    			url: "<?php echo base_url() ?>artransaction/updateSaleInvoice",
    			success: function(data) {
					var resul = eval ("(" + data + ")");
					if(resul.status == 'success'){
    					getTotal();
   		 				alertBox1(1,"Update ! The Invoice updated successfully");
    				}
    			} //end function
    		});//end ajax
    	}

    }
    }

    //Save sales order while adding charges.
    function saveCharge(me){
    if( $("#SaleDetailForm").validationEngine('validate') && finanEngine('financhk')){
    if ( $("#saleInvoiceId").val()=="null"){
    $itemDetail = getOrderDet();
    getTotal();
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: {
    showinInvoice : $("input[name='showinInvoice']:checked").val(),
    invoiceCodeID:1,
    salesOrderID : $("#orderNo").val(),
    shippingMethodID : $("#shippingmethod").val(),
    employeeID : $("#saler").val(),
    memo : $("#memo").val(),
    invoiceCodeID : 1,
    totalPayable : accounting.unformat($("#totalpayable").val()), 
    totalTaxAmount :  accounting.unformat($("#totalTaxAmount").val()),
    customerID : $("#customer").val(),
    locationID :  0,//$("#location").val(),
    agentID : $("#agent").val(),
    formNo : $("#formNo").val(),
    invoiceDate: $("#createdDate").val(),
    customerPoNo : $("#customerPoNo").val(),
    projectID: $("#project").val(),
    termsID: $("#term").val(),
    currencyID: $("#currency").attr("data-currencyID"),
    exchangeRate : $("#exchange_rate").val(),
    shipToID : $("#shiptoAddress").val(),

    //Sales order detail
    salesDetail:getOrderDet(),

    accountNoID : $("#chargeAccount").val(),
    lineNo : $("#listCharge").attr("data-currentRow")*1 +1,
    chargeDescription : $("#chargedesc").val(),
    taxAmount : accounting.unformat($("#chargetaxAmount").val()),
    amountIncludedTax : accounting.unformat($("#chargeAmountIT").val()),
    amountExcludedTax: accounting.unformat($("#chargeAmount").val()),
    taxID: $("#listTax").attr('data-taxid'),
    taxRate: $("#listTax").val()

    },
    url: "<?php echo base_url() ?>artransaction/saveSaleInvoiceCharges",
    success: function(data) {
    var resul = eval ("(" + data + ")"); 
    $("#saleInvoiceId").val(resul.invoiceID);
    $(''+
    '<tr> <td>' + ($("#listCharge").attr("data-currentRow")*1 +1) + '</td>' +
    '<td>' + $("#chargeAccount option:selected").text() + '</td>'+
    '<td>' + $("#chargedesc").val() + '</td>'+
    '<td class="amount">' + $("#chargeAmount").val() + '</td>'+
    '<td>' + $("#displayCode").text() + " | " + $("#listTax").val() + '</td>'+
    '<td class="amount">' + $("#chargetaxAmount").val() + '</td>'+
    '<td class="amount">' + $("#chargeAmountIT").val() + '</td>'+
    '<td>'+
    '</td>'+
    '</tr>'
    ).insertBefore( "#trInfosCharge" );
    $("#btnCancelCharge").trigger("click");
    $("#listCharge").attr("data-currentRow",$("#listCharge").attr("data-currentRow")*1 +1)
    getTotal();
    saveInvoice(me);
    msg (2,"alert alert-success","Details successfully saved");
    } //end function
    });//end ajax
    }else{
    $(me).attr("disabled","disabled");
    $.ajax({
    type: "POST",
    data: {
    invoiceId : $("#saleInvoiceId").val(),
    lineNo : $("#listCharge").attr("data-currentRow")*1 +1,
    accountNoID : $("#chargeAccount").val(), 
    chargeDescription : $("#chargedesc").val(),
    currentTotalInvoice : accounting.unformat($("#totalpayable").val()),
    taxAmount : accounting.unformat($("#chargetaxAmount").val()),
    amountIncludedTax : accounting.unformat($("#chargeAmountIT").val()),
    amountExcludedTax: accounting.unformat($("#chargeAmount").val()),
    taxID: $("#listTax").attr('data-taxid'),
    taxRate: $("#listTax").val()

    },
    url: "<?php echo base_url() ?>Artransaction/saveNewSaleDetailOnlyCharges",
    success: function(data) {
    msg (2,"alert alert-success","Details successfully saved");
    var resul = eval ("(" + data + ")"); 
    $(''+
    '<tr> <td>' + ($("#listCharge").attr("data-currentRow")*1 +1) + '</td>' +
    '<td>' + $("#chargeAccount option:selected").text() + '</td>'+
    '<td>' + $("#chargedesc").val() + '</td>'+
    '<td class="amount">' + $("#chargeAmount").val() + '</td>'+
    '<td>' + $("#displayCode").text() + " | " + $("#listTax").val() + '</td>'+
    '<td class="amount">' + $("#chargetaxAmount").val() + '</td>'+
    '<td class="amount">' + $("#chargeAmountIT").val() + '</td>'+
    '<td>'+
    '</td>'+
    '</tr>'
    ).insertBefore( "#trInfosCharge" );
    $("#listCharge").attr("data-currentRow",$("#listCharge").attr("data-currentRow")*1 +1);
    $("#btnCancelCharge").trigger("click");
    getTotal();
    saveInvoice(me);
    }
    }); //end ajax
    }
    }else {
    msg (2,"alert alert-error","Fill up the required fields");
    }
    }

    //Alert message box
    function alertBox1(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
    });
    }

    //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')){
    console.log('um here');
    totalAmount= totalAmount + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(8)').text())*1; 
    impot= impot + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(10)').text()) *1; 
    total= total + accounting.unformat($('#listDetails > tbody > tr:eq(' + i + ') > td:eq(11)').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));

    $("#totalamount").val(accounting.formatNumber(totalAmount + totalAmountCharge,2));

    $("#totalTaxAmount").val(accounting.formatNumber(impot +  impotCharge,2));

    $("#totalpayable").val(accounting.formatNumber(total + totalCharge,2));

    }

    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() ?>artransaction/deleteChargeOnly",
    success: function(data) {
    msg (2,"alert alert-success","Data deleted succesfuly ...");
    var totalCrgRow = $("#listCharge tbody tr").length-1;
    $("#listCharge").attr("data-currentRow",totalCrgRow+1);
    var td=me.parentNode;
    var tr=td.parentNode;
    var tBody=tr.parentNode;
    tBody.removeChild(tr);
    getTotal();
    $.ajax({
    type: "POST",
    data: {
    invoiceId : $("#saleInvoiceId").val(),
    totalPayable : $("#totalpayable").val(), 
    totalTaxAmount :  $("#totalamount").val()
    },
    url: "<?php echo base_url() ?>artransaction/updateInvoice",
    success: function(data) {
    //update the invoice after delete
    }
    });
    }
    });
    });

    getTotal()
    }

    function refreshsalerlist(){
    $.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>';
    $('#saler').empty();
    $('#saler').append(opt);
    }
    });
    }


</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="SaleDetailForm" action="#">    
                <input type="hidden" value="null" id="saleInvoiceId" />                
                <div class="block">
                    <div class="head">
                        <h2><?php echo $this->lang->line('title') ?></h2>
                    </div><!-- head -->
                    <div class="content np">
                        <div class="row-fluid scRow">                            
                            <div class="span4 scCol">
                                <div class="block ns" id="grid_block_1">
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('customer') ?></div>
                                        <div class="span9">
                                            <select class="span10 validate[required]" id="customer">
                                                <option></option>
                                                <?php
                                                if ($customer) {
                                                    foreach ($customer as $row) {
                                                        ?>
                                                        <option value="<?php echo $row->ID; ?>"> <?php echo $row->customerName;
                                                        echo ($row->gstRegNo != '' && $row->gstRegNo != '0') ? ' (GST)' : ''; ?></option>
													<?php }
													}
												?>
                                            </select>
                                            <div class="btn-group span2">
                                                <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() ?>CustomerSetup/CustomerNew" id="newcustumer">
                                                            <i class="i-plus-3"></i> 
															<?php echo $this->lang->line('newcustumer') ?>
														</a>
                                                    </li>
                                                    <li>
                                                        <a href="#" onclick="refreshCustomer()">
                                                            <i class="i-ccw"></i>
															<?php echo $this->lang->line('refreshlist') ?>
														</a>
                                                    </li>
                                                </ul>
                                            </div>					
                                        </div>
                                    </div> <!-- row -->
                                    <?php /* ?>
                                      <div class="controls-row">
                                      <div class="span3"><?php //echo $this->lang->line('orderNo') ?></div>
                                      <div class="span9">
                                      <select class="span11 validate[required]" id="orderNo">
                                      <option></option>
                                      </select>
                                      </div>
                                      </div> <!-- row -->
                                     */ ?>
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('formNo') ?></div>
                                        <div class="span9">
                                            <input class="span8 validate[required]" id="formNo" name="formNo" value='<?php echo "$formNo"; ?>' style="color:red;"   type="text" placeholder="Form number ..."><input  class="span4" id="invID"   type="text" placeholder="Serial" disabled="disabled">
                                        </div>
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span3"><?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="span3"><?php echo $this->lang->line('custumerpono') ?></div>
                                        <div class="span9">
                                            <input id="customerPoNo" placeholder="<?php echo $this->lang->line('custumerpono') ?>" data-provide="typeahead" class="span12" type="text">
                                        </div><!-- span -->
                                    </div> <!-- row -->
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('agent') ?></div>
                                        <div class="span9">
                                            <select class="span10" id="agent">
                                                <option></option>
                                                <?php
                                                if ($agent) {
                                                    foreach ($agent as $row) {
                                                        ?>
                                                        <option value="<?php echo $row->ID; ?>"><?php echo $row->agentName ?></option>
    <?php }
}
?>
                                            </select>
                                            <div class="btn-group span2">
                                                <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() ?>SaleAgentSetup/newAgent" >
                                                            <i class="i-plus-3"></i><?php echo $this->lang->line('addsaleagent') ?></a></li>
                                                    <li><a href="#" onclick="refreshAgent()"><i class="i-ccw"></i><?php echo $this->lang->line('refreshlist') ?></a></li>
                                                </ul>
                                            </div>
                                        </div> <!-- btnn group -->

                                        <label class="radio inline"><?php echo $this->lang->line('showinInvoice') ?></label>
                                        <label class="radio inline"><input type="radio" value="1" name="showinInvoice"> Yes</label>   
                                        <label class="radio inline"><input type="radio" value="0" name="showinInvoice" checked="checked"> No</label>
                                    </div><!-- row control -->                                    
                                </div><!-- grid block 1-->
                            </div><!-- scCol -->
                            <div class="span4 scCol">
                                <div class="block" id="grid_block_2">
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('saleperson') ?></div>
                                        <div class="span9">
                                            <div class="span12">   
                                                <select class="span10" id="saler">
                                                    <option></option>
<?php
if ($saler != '') {
    foreach ($saler as $row) {
        ?>
                                                            <option value="<?php echo $row->ID; ?>"> <?php echo $row->employeeName; ?></option>
    <?php }
}
?>
                                                </select>
                                                <div class="span2 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('newsaleperson') ?></a>
                                                        </li>
                                                        <li><a href="#" onclick="refreshsalerlist()" 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="span3"><?php echo $this->lang->line('project') ?></div>
                                        <div class="span9">
                                            <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 span2">
                                                <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><!-- span -->       
                                    </div> <!-- row control -->

                                    <?php /*
                                      <div class="controls-row"> <!--remove location from normal sales invoice - akmal >

                                      <div class="span3"><?php echo $this->lang->line('location') ?></div>
                                      <div class="span9">
                                      <select class="span11 validate[required]" id="location">
                                      <option></option>
                                      <?php
                                      if ($location != '') {
                                      foreach ($location as $row) {
                                      ?>
                                      <option value="<?php echo $row->fldid; ?>"><?php echo $row->code . " | " . $row->desc; ?></option>
                                      <?php }
                                      } ?>
                                      </select>
                                      <div class="btn-group span1">
                                      <button class="btn span12 btn-primary 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--><!-- row control -->
                                     */ ?>
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('terms') ?></div>
                                        <div class="span9">
                                            <select id="term" 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 $row->termName; ?></option>
    <?php }
}
?>
                                            </select>
                                            <div class="btn-group span2">
                                                <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><!-- span -->
                                    </div><!-- row control -->
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('termsdesc') ?></div>
                                        <div class="span9">
                                            <textarea disabled="disabled" id="termDescription" class="span12"  rows="4"></textarea>
                                        </div><!-- span -->
                                    </div><!-- row control -->


                                </div><!-- grid block 1-->
                            </div><!-- scCol -->
                            <div class="span4 scCol">
                                <div class="block" id="grid_block_3">
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('shippingMethod') ?></div>
                                        <div class="span9">
                                            <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="span2 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="span3"><?php echo $this->lang->line('shipto') ?></div>
                                        <div class="span9">
                                            <select id="shiptoAddress" onchange ="displaysAdress()" class="span10">
                                                <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 class="btn-group span2">
                                                <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() ?>customerSetup/customerList"  id="btnNewTer">
                                                            <i class="i-plus-2"></i><?php echo $this->lang->line('addNewShip') ?></a>
                                                    </li>
                                                    <li><a href="#" onclick="refreshShip()">
                                                            <i class="i-ccw"></i><?php echo $this->lang->line('refreshlist') ?></a>
                                                    </li>
                                                </ul>
                                            </div><!-- btn group -->
                                        </div><!-- span -->
                                    </div><!-- row control -->
                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('shiptoDesc') ?></div>
                                        <div class="span9">
                                            <textarea  disabled="disabled"ssss id="shiptoDesc" class="span12" rows="1"></textarea>
                                        </div><!-- span -->
                                    </div><!-- row control -->

                                    <div class="controls-row">
                                        <div class="span3"><?php echo $this->lang->line('currency') ?></div>
                                        <div class="span9">
                                            <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="span3"><?php echo $this->lang->line('exchangeRate') ?></div>
                                        <div class="span9">
                                            <input class="span12 tar" id="exchange_rate" name="exchange_rate" type="text" placeholder="Example: 3.20000" >           
                                        </div><!-- span -->
                                    </div><!-- control row -->
                                </div><!-- grid block 1-->
                            </div>
                        </div>
                    </div><!-- scCol -->
                </div><!-- row-fluid scRow-->

                <div class="row-fluid scRow">                            
                    <div class="span12 scCol">
                        <textarea style="margin-top:10px;" placeholder="<?php echo $this->lang->line('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>#</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="amount tar"><?php echo $this->lang->line('unitPrice') ?></th>
                                            <th class="quantity tar"><?php echo $this->lang->line('quantity') ?></th>
                                            <th class="quantity tar"><?php echo $this->lang->line('unitmeasure') ?></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>
                                            <th style="display:none">&nbsp;</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('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>                                        
                            </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">
                                               
                                            </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="span8 scCol">
                        <div class="block" id="grid_block_4">
                            <div class="content np">
                                <div class="controls-row">
                                    <div class="span12">
                                        <div style="height: 130px;" 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>
                                    </div><!-- span -->
                                </div><!-- row control -->    
                            </div>    
                        </div><!-- grid block 1-->
                    </div><!-- scCol -->      
                    <div class="span4 scCol">
                        <div class="block" id="grid_block_4">
                            <div class="content np">
                                <div class="controls-row">    
                                    <div class="span5"><?php echo $this->lang->line('totalAmount') ?></div>
                                    <div class="span7">
                                        <input id="totalamount" class="span12 amount" type="text" placeholder="0" disabled="disabled" >
                                    </div>
                                </div><!-- row control -->
                                <div class="controls-row">    
                                    <div class="span5"><?php echo $this->lang->line('totalTaxAmount') ?></div>
                                    <div class="span7">
                                        <input id="totalTaxAmount" class="span12 amount" type="text" placeholder="0" disabled="disabled" >
                                    </div>
                                </div><!-- row control -->
                                <div class="controls-row">
                                    <div class="span5"><?php echo $this->lang->line('totalReceivable') ?></div>
                                    <div class="span7">
                                        <input id="totalpayable" disabled="disabled"  class="span12 amount" type="text" placeholder="0">
                                    </div>
                                </div><!-- row control -->    
                            </div>    
                            <div class="footer">
                                <div class="side fr">
                                    <div class="btn-group">
                                        <!-- <button id="calcul" onclick="getTotal()" class="btn btn-warning" type="button"> 
                                            <i class="i-checkmark-3"></i><?php echo $this->lang->line('calTotal') ?></button> -->
                                        <button id="calcul" onclick="saveInvoice(this)" class="btn-form btn-success-form" style="margin-left:5px;" type="button"> 
                                            <i class="i-checkmark-3"></i><?php echo $this->lang->line('saveInvoice') ?></button>
                                    </div><!-- btn group -->      
                                </div><!-- side fr -->      
                            </div><!-- footer -->
                        </div><!-- grid block 1-->
                    </div><!-- row-fluid scRow-->
                </div>
            </form>
        </div><!-- grid 1 -->
    </div><!-- wrap -->
</div><!-- content -->
</div>
</div>



