<?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">
			
$(document).ready(function() {
        $('select').select2();
         $.each($(".select2-container"), function (i, n) {
                    $(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
                    $(n).prepend($(n).next());
                    $(n).delay(500).queue(function () {
                        $(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
                        $(this).dequeue();
                    });
                });	
        jQuery('.datepicker2').datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true
        });

        $("table.editable").on("click", ".edit", function() {
            var eRow = $(this).parents('tr');
            var eState = $(this).attr('data-state');

            if (eState == null) {
                $(this).html('Save');
                eState = 1;
            }
            if (eState == 1)
                $(this).attr('data-state', '2');
            else {
                $(this).removeAttr('data-state');
                $(this).html('Edit');
            }
        });



    });



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


function saveData(me){
	//var formNo =  $('#formNo').val();
	var historicalID =  me;
	var customerID =  $('#customer').val();
	var createdDate =  $('#createdDate').val();
	var customerPoNo =  $('#customerPoNo').val();
	var amount =  accounting.unformat($('#chargeAmount').val());
	var taxID =  $('#listTaxPopup').val();
	var taxAmount =  accounting.unformat($('#chargetaxAmount').val());
	var amountIncludedTax =  accounting.unformat($('#chargeAmountIT').val());
		
		var postData = {
			//'formNo' : formNo,
			'historicalID' : historicalID,
			'customerID' : customerID,
			'createdDate' : createdDate,
			'customerPoNo' : customerPoNo,
			'amount' : amount,
			'taxID' : taxID,
			'totalTaxAmount' : taxAmount,
			'totalReceivable' : amountIncludedTax,
			'totalAmount' : amountIncludedTax,
		};
	
	$.ajax({
		type: "POST",
		dataType: "json",
		url: "<?php echo base_url()?>historicalInvoice/saveHistoricalCusInvoice",
		data: postData ,
		success: function(content){
			if(content.status == "success") {
				alert('Data successfully saved');
				window.location.href = "<?php echo base_url()?>historicalinvoice/historicalCustomerInvoice";
			}
		}
	});
	
}

function changeNumberFormat(){
	var changeAmount = accounting.formatNumber($('#amount').val(),2);
	$('#amount').val(changeAmount);
	
}


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 calculChargeAmount() { 
        if($('#inclusiveTax').attr("checked") == "checked"){          
          var t = (accounting.unformat($("#chargeAmount").attr('data-actual')) * accounting.unformat($("#listTax").val())) /(100+accounting.unformat($("#listTax").val()));  
        }else{
            var t = accounting.unformat($("#chargeAmount").val()) * accounting.unformat($("#listTax").val()) /100;
        }
        $("#chargetaxAmount").val(accounting.formatNumber(t,2));
        $("#chargeAmountIT").val(accounting.formatNumber(t+ accounting.unformat( $("#chargeAmount").val())*1,2));
    }
	
	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 refreshCustomer(){
		$.ajax({
			type: "POST",
			url: "http://192.168.1.177/iaccounts/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);
			}
		});	
    }
</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('cust') ?></li>
                </ul>
            </div>
            <div class="search">
                <form action="<?php echo base_url() ?>admin/search" method="post">
                    <input name="search_text" type="text" placeholder="search..."/>                                
                    <button type="submit"><span class="i-magnifier"></span></button>
                </form>
            </div> 
        </div><!-- head --> 
        <div class="content" id="grid_content_1">
            <form id="parchaseDetailForm" action="#">    
            <input type="hidden" value="null" id="purchaseInvoiceId" />
				<div class="block">
					<div class="head">
						<h2><?php echo $this->lang->line('titlelist') ?></h2>
						<!--<ul class="buttons">
							<li><a href="#" class="block_toggle"><span class="i-arrow-down-3"></span></a></li>
						</ul>-->
					</div><!-- head -->
					<div class="content">
						<div class="row-fluid scRow">                            
							<div class="span6 scCol">
								<div class="block ns" id="grid_block_1">
									
                                    <!--<div class="controls-row">
										<div class="span4"><?php //echo $this->lang->line('formNo') ?></div>
										<div class="span2">
											<input class="span12 validate[required]" id="formNo" name="formNo" value='<?php echo "$formNo"; ?>' 
												style="color:red;" type="text" placeholder="Form number ...">
										</div>
										<div class="span6">
											<input  class="span11"   type="text" id="invID" placeholder="Serial" disabled="disabled">
										</div>
									</div> <!-- row -->
                                    
									<div class="controls-row">
                                        <div class="span4"><?php echo $this->lang->line('customerName') ?></div>
                                        <div class="span8">
                                            <select class="span10 validate[required]" id="customer">
                                            <?php
												if($historicalCusInvoice == ''){
                                                	echo"<option>Please Select</option>";
												}
												else{
												?>
												<option value="<?php echo $historicalCusInvoice->customerID; ?>"> <?php echo $historicalCusInvoice->customerName; echo ($historicalCusInvoice->gstRegNo != '' && $historicalCusInvoice->gstRegNo != '0')?' (GST)':''; ?></option>
												<?php
                                                }
											?>
                                            <?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 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() ?>CustomerSetup/CustomerNew" id="newcustumer">
														<i class="i-plus-3"></i><?php echo $this->lang->line('addNewCustomer') ?></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 -->
                                    
									<div class="controls-row">
										<div class="span4"><?php echo $this->lang->line('date') ?></div>
										<div class="span8">
											<div class="input-prepend span10"><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',);
												if($historicalCusInvoice->salesInvoiceDate == ''){
													echo form_input($data, date("d-m-Y"));
												}
												else{
													echo form_input($data, date("d-m-Y", strtotime($historicalCusInvoice->salesInvoiceDate)));
												}
											?>
											</div>
										</div>
									</div> <!-- row -->
									
									                                
									<div class="controls-row">
										<div class="span4"><?php echo $this->lang->line('customerPoNo') ?></div>
										<div class="span8">
                                        <?php
											if($historicalCusInvoice->customerPoNo == ''){
												echo"<input id='customerPoNo' class='span10 validate[required]' type='text' placeholder='Customer Po. No.'>";
											}
											else{
												echo"<input id='customerPoNo' class='span10 validate[required]' type='text' placeholder='Customer Po. No.' value='".$historicalCusInvoice->customerPoNo."'>";
											}
										?>
										</div><!-- span -->
									</div> <!-- row -->
                                    
                                    <div class="controls-row">
										<div class="span4"><?php echo $this->lang->line('amount') ?></div>
										<div class="span8">
											<!--<input id="amount" class="span10 validate[required]" type="text" onblur="changeNumberFormat()">-->
                                            <?php
												if($historicalCusInvoice->amount == ''){
													echo"<input id='chargeAmount' onkeyup='calculChargeAmount()' onfocus='modAmount(this)' name='chargeAmount' class='span10 amount validate[required, custom[number]]' placeholder='Amount' type='text'>";
												}
												else{
													echo"<input id='chargeAmount' onkeyup='calculChargeAmount()' onfocus='modAmount(this)' name='chargeAmount' class='span10 amount validate[required, custom[number]]' placeholder='Amount' type='text' value='".number_format($historicalCusInvoice->amount,2)."'>";
												}
											?>
                                            
										</div><!-- span -->
									</div> <!-- row -->
                                    
								</div><!-- grid block 1-->
                            </div><!-- scCol -->
                            
                            
                            <div class="span6 scCol">
								<div class="block ns" id="grid_block_1">
									
                                    <!--<div class="controls-row">
										<div class="span4"><?php //echo $this->lang->line('formNo') ?></div>
										<div class="span2">
											<input class="span12 validate[required]" id="formNo" name="formNo" value='<?php echo "$formNo"; ?>' 
												style="color:red;" type="text" placeholder="Form number ...">
										</div>
										<div class="span6">
											<input  class="span11"   type="text" id="invID" placeholder="Serial" disabled="disabled">
										</div>
									</div> <!-- row -->
                                    
									<div class="controls-row">
										<div class="span4"><?php echo $this->lang->line('taxRate') ?></div>
										<div class="span8">
                                        	<?php
												if($historicalCusInvoice->taxPercentage == '' && $historicalCusInvoice->code == ''){
													echo"<input readonly='readonly' data-taxid='' id='listTax' onkeyup='calculChargeAmount()' name='itemTax' class='span6 validate[required, custom[number]]' placeholder='Tax(%)' type='text'>
													<span onclick='taxPopup()' style='margin-top:0;' id='displayCode' class='btn add-on'>....</span>";
												}
												else{
													echo"
													<input readonly='readonly' data-taxid='' id='listTax' onkeyup='calculChargeAmount()' name='itemTax' class='span6 validate[required, custom[number]]' placeholder='Tax(%)' type='text' value='".$historicalCusInvoice->taxPercentage."'>
													<span onclick='taxPopup()' style='margin-top:0;' id='displayCode' class='btn add-on'>".$historicalCusInvoice->code."</span>";
												}
											?>
											
                                        </div>
									</div> <!-- row -->
                                    
									<div class="controls-row">
										<div class="span4"><?php echo $this->lang->line('taxAmount') ?></div>
										<div class="span8">
                                        	<?php
												if($historicalCusInvoice->totalTaxAmount == ''){
													echo"<input readonly='readonly' id='chargetaxAmount' name='chargetaxAmount' class='span10 amount' placeholder='Amount' type='text'>";
												}
												else{
													echo"<input readonly='readonly' id='chargetaxAmount' name='chargetaxAmount' class='span10 amount' placeholder='Amount' type='text' value='".number_format($historicalCusInvoice->totalTaxAmount,2)."'>";
												}
											?>
											
										</div>
									</div> <!-- row -->
                                    
                                    <div class="controls-row">
										<div class="span4"><?php echo $this->lang->line('amountIncludedTax') ?></div>
										<div class="span8">
                                        	<?php
												if($historicalCusInvoice->totalTaxAmount == ''){
													echo"<input readonly='readonly' id='chargeAmountIT' name='chargeAmountIT' class='span10 amount' placeholder='Amount (Exclude Tax)' type='text'>";
												}
												else{
													echo"<input readonly='readonly' id='chargeAmountIT' name='chargeAmountIT' class='span10 amount' placeholder='Amount (Exclude Tax)' type='text' value='".number_format($historicalCusInvoice->totalAmount,2)."'>";
												}
											?>
											
										</div><!-- span -->
									</div> <!-- row -->
                                    
								</div><!-- grid block 1-->
                            </div><!-- scCol -->
                            
                            
						</div><!-- row-fluid scRow-->
					</div><!-- content np -->
                
					<div class="content np">    
                    	<div class="footer">
                        	<div class="side fr">
                        		<div class="btn-group">
                                	<button id="" onclick="saveData(<?php echo $historicalID ?>)" class="btn-icon btn-success-form" type="button"><?php echo $this->lang->line('submit') ?></button>
                                </div>
                            </div>
                        </div>                                    
                    </div>
				
                
			</div><!-- block -->
			
			
				
			 
            </form>
        </div><!-- grid 1 -->
    </div><!-- wrap -->
</div><!-- content -->



