<script type="text/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();
        });
    });
	//Datepicker
   jQuery('.datepicker2').datepicker({
			dateFormat : 'dd-mm-yy',
			changeMonth : true,
			changeYear : true
			});
   
   //Data table configurations
   var oTable = $("#test").dataTable({
	   	"iDisplayLength": 10,
		"aLengthMenu": [5,10,25,50,100],
		"sPaginationType": "full_numbers",
		"aoColumns": [	{"bSortable": false },
						null,
					<?php foreach($tbHdr as $v): ?>
						null,
					<?php endforeach; ?>
						{"bSortable": false }
					] 
	});
	oTable.fnSort( [ [1,'asc'] ] );

	//
	var unReconcileBal = 0;
	$('.bankID,#selDateFrom').change(function(){
		var flag = true;
		if($(this).attr("id") == 'selDateFrom'){
			flag = false;
		}
		if(true || finanEngine('financhk')){
			var date = $('#selDateFrom').val();
			var bankInfo = $('.bankID').select2('val').split(">");
			$.ajax({
				url: "<?php echo base_url(); ?>bankreconciliation/gatherinfo",
				async: false,
				type: "POST",
				data: 'bankAcctID='+bankInfo[0]+'&bankID='+bankInfo[1]+'&date='+date,
				dataType: "html",
				success: function(data) {
					var obj = jQuery.parseJSON(data);
					console.log(obj);
					if(obj != ''){
						oTable.fnClearTable();
						$('.lasReconDate').val('');
						$('.lasReconBal').val('');
						$('.statClosBal').val('');
						$('.unreconcil').val('');
						var serial = 1;
						var unReConDiff = 0;
						var deposit = 0;
						var credit = 0;
						if(obj.statements){
							jQuery.each(obj.statements,function(i,v){
								var input = "";
								id = v.ID.replace(/\s/g, "");
								if(v.bank_reconcile != 1){
									//No need tableName as long as there is only one table journal detail.
									var input = "<input type='checkbox' value='"+id+"' class='tac' />";
									//var input = "<input type='checkbox' value='"+v.ID+"' class='tac' /><input class='tblName' type='hidden' value='"+v.tableName+"' />";
									unReConDiff = parseFloat(unReConDiff)+parseFloat(v.amount_dr)+parseFloat(v.amount_cr);
								}	
								deposit = accounting.unformat(deposit) + accounting.unformat(v.debitAmount);
								credit = accounting.unformat(credit) + accounting.unformat(v.creditAmount);
								
								var rowIndex = oTable.fnAddData( [
													id,
													serial,
													v.transDate,
													v.formNo,
													v.description,
													v.referenceNo,
													accounting.formatNumber(v.debitAmount,2),
													accounting.formatNumber(v.creditAmount,2),
													input
													] );


								
							    var row = oTable.fnGetNodes(rowIndex);
							    $(row).find('td:nth-child(1)').css('display','none').addClass('ID');
							    $(row).find('td').addClass('tac');
							    $(row).find('td:nth-child(7)').addClass('debit tar').removeClass('tac');
							    $(row).find('td:nth-child(8)').addClass('credit tar').removeClass('tac');
							    $(row).find('td:last-child').addClass('reconsil');
								serial++;
							});
						}
						unReconcileBal = unReConDiff.toFixed(2);
						$('#deposit').val(accounting.formatNumber(deposit,2));
						$('#credit').val(accounting.formatNumber(credit,2));
						$('#glBalance,#statClosBal').val(accounting.formatNumber(obj.glBalance,2));
						jQuery.each(obj.reconcile,function(i,v){
							var a = new Date(Date.parse(v.reconcileDate));
							var date = a.getDate();
							var month = a.getMonth()+1;
							var year = a.getFullYear();
							$('.lasReconDate').val(date+'-'+month+'-'+year);
							if(flag){
								var a = new Date(Date.parse(v.nxtReconcileDate));
								var date = a.getDate();
								var month = a.getMonth()+1;
								var year = a.getFullYear();
								$('#selDateFrom').val(date+'-'+month+'-'+year);
							}
							$('.lasReconBal').val(accounting.formatNumber(v.reconcileBalance,2));
							//$('.statClosBal').val(parseFloat(v.bankStatementBalance).toFixed(2));
						});
						
					}else{
						oTable.fnClearTable();
						$('.lasReconDate').val('');
						$('.lasReconBal').val('');
						$('.statClosBal').val('');
						$('.unreconcil').val('');
						$('#deposit').val('');
						$('#credit').val('');
						$('#glBalance,#statClosBal').val('');
					}
				}
			});
		}
	});	  

	
	//reconsiliation
	$('.reconsil input').live('change',function(){
		var deposit = parseFloat(accounting.unformat($("#deposit").val()));
		var credit = parseFloat(accounting.unformat($("#credit").val()));

		var rcvDeposit = accounting.unformat($(this).parents('tr').find('.debit').text());
		var payCredit = accounting.unformat($(this).parents('tr').find('.credit').text());

		if($(this).attr('checked') == 'checked'){
			$("#deposit").val(accounting.formatNumber(deposit-rcvDeposit,2));
			$("#credit").val(accounting.formatNumber(credit-payCredit,2));
		}else{
			$("#deposit").val(accounting.formatNumber(deposit+rcvDeposit,2));
			$("#credit").val(accounting.formatNumber(credit+payCredit,2));
		}
		calculReconcil();
	});

	//change un-Reconcile according to bank statement.
	$('#statClosBal').live('blur',function(){
		calculReconcil();
	});
}); 

function calculReconcil(){
		var statClosBal = accounting.unformat($('#statClosBal').val());
		var deposit = accounting.unformat($("#deposit").val());
		var unPresnChk = accounting.unformat($("#credit").val());
		var glBal = accounting.unformat($("#glBalance").val());

		$('#statClosBal').val(accounting.formatNumber(statClosBal,2));
		var left = statClosBal + deposit;
		var right = unPresnChk+glBal;
		var unReconcileBal = left.toFixed(2) - right.toFixed(2);
		
		$('#UnReconciledDifference').val(accounting.formatNumber(unReconcileBal,2));
		
		//console.log(statClosBal+"<->"+deposit+"<->"+unPresnChk+"<->"+glBal+"<->"+unReconcileBal);
		if(unReconcileBal == 0)
			$("#reconcile").removeAttr('disabled');
		else
			$("#reconcile").attr('disabled','disabled');
}
function reconcile(){
	var totalDebit = 0;
	var totalCredit = 0;
	var conID = '';
	var trackID = '';
	var rows = $("#test").dataTable().fnGetNodes();
	for(var i=0;i<rows.length;i++){
        // Get HTML of 3rd column (for example)
        if($(rows[i]).find("td:nth-child(9) input:nth-child(1):checked").val()){	
        	if(conID == ''){
				conID += $(rows[i]).find("td:nth-child(9) input:nth-child(1)").val();//+"->"+$(rows[i]).find("td:nth-child(9) input:nth-child(2)").val();
			}else{
				conID += ','+$(rows[i]).find("td:nth-child(9) input:nth-child(1)").val();//+"->"+$(rows[i]).find("td:nth-child(9) input:nth-child(2)").val();
			}
		}else{
			if(trackID == ''){
				trackID += $(rows[i]).find("td:nth-child(9) input:nth-child(1)").val();//+"->"+$(rows[i]).find("td:nth-child(9) input:nth-child(2)").val();
			}else{
				trackID += ','+$(rows[i]).find("td:nth-child(9) input:nth-child(1)").val();//+"->"+$(rows[i]).find("td:nth-child(9) input:nth-child(2)").val();
			}
		}
    }

	/*$('.reconsil').each(function(){
		if($(this).find('input:checked').val()){
			if(conID == ''){
				conID += $(this).find('input:checked').val()+"->"+$(this).find('.tblName').val();
			}else{
				conID += ','+$(this).find('input:checked').val()+"->"+$(this).find('.tblName').val();
			}
		}else{
			if(trackID == ''){
				trackID += $(this).find('input:nth-child(1)').val()+"->"+$(this).find('.tblName').val();
			}else{
				trackID += ','+$(this).find('input:nth-child(1)').val()+"->"+$(this).find('.tblName').val();
			}
		}		
	});*/
	if(conID != ''){
		$.ajax({
			url: "<?php echo base_url(); ?>bankreconciliation/setconcile",
			async: false,
			type: "POST",
			data: 'conID='+conID
					+'&trackID='+trackID
					+'&bankLinkAcctCode='+$('.bankID').select2('val')
					+'&reconcileDate='+$('#selDateFrom').val()
					+'&reconcileBalance='+accounting.unformat($('#statClosBal').val())
					+'&concileDebit='+accounting.unformat($('#deposit').val())
					+'&concileCredit='+accounting.unformat($('#credit').val())
					+'&glBalance='+accounting.unformat($('#glBalance').val()),
			dataType: "html",
			success: function(data) {
				if(data == 'Success'){
					$("#reconcile").attr("disabled","disabled");
					location.reload();
				}
			}
		});
	}
}

</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()."bankSetup/bankList" ?>'><?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">
			<!--Company information start-->
			<?php //$this->load->view('layouts/rptheader'); ?>
			<!--Company information end-->
			<div class="row-fluid">
				<div class="span12">        
					<div class="block">
						<div class="head">
							<h2><strong><?php echo $this->lang->line('searchParam') ?></strong></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 np">  						 
							<div class="controls-row">
								<div class="span3"><?php echo $this->lang->line('bank') ?>*</div>
	                            <div class="span5">
	                            <?php
	                            $preselcat = '';
								$options = '<option>'.$this->lang->line('pleaseSelect').'</option>';
								if (!empty($bank)){
								//print_r($bank);
								//$options = '<option>'.$this->lang->line('pleaseSelect').'</option>';
		                        foreach($bank as $row){
									//$options[$row->caID] = $row->bankName." (".substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7).")";
		                            $options .='<option value="'.$row->caID.">".$row->ID.'">'.$row->bankName." (".substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7).")".'</option>';
		                            }
		                        }
	                            $js=' class="validate[required] span10 bankID"';
									//echo form_dropdown('bankID', $options, $preselcat, $js);
	                                echo '<select id="bankID" class="validate[required] span10 bankID">'.$options.'</select>';
	                            ?>
								</div>                          
							</div> 
	                        <div class="controls-row">
								<div class="span3"><?php echo $this->lang->line('lastReconciliationDate') ?></div>
	                            <div class="span3">
	                            <?php
	                            $data = array(
									'value'=>'',//$formNo,
	                                'name'=>'lasReconDate',
	                                'id'=>'lasReconDate',
	                                'disabled'=>'disabled',
	                                'class'=>'span12 validate[required] lasReconDate',); 
										echo form_input($data, '');//set_value($formNo));
	                            ?>
	                            </div> 
								<div class="span3"><?php echo $this->lang->line('lastReconciliationBalance') ?></div>
	                            <div class="span2">
	                            <?php
	                            $data = array(
									'value'=>'',//$formNo,
	                                'name'=>'lasReconBal',
	                                'id'=>'lasReconBal',
	                                'disabled'=>'disabled',
	                                'class'=>'input-medium validate[required] lasReconBal',); 
										echo form_input($data, '');//set_value($formNo));
	                            ?>
	                            </div>      
							</div>							
	                        <div class="controls-row">
								<div class="span3"><?php echo form_label($this->lang->line('statDate')); ?></div>
			                    <div class="span3 input-prepend">
									<span class="add-on"><i class="i-calendar"></i></span>
									<?php
									$data = array(
										'name' => 'selDateFrom',
										'id' => 'selDateFrom',
										'type' => 'text',
										'class' => 'span10 datepicker2 validate[required] financhk',);
									$js='';
										echo form_input($data, date('d-m-Y', time($statDate)), $js);
									?>       
								</div>
								<div class="span3"><?php echo $this->lang->line('statClosBal') ?></div>
								<div class="span2">
			                    <?php
			                    $data = array(
									'value'=>'',//$formNo,
			                        'name'=>'statClosBal',
			                        'id'=>'statClosBal',
			                        'class'=>'input-medium statClosBal',); 
										echo form_input($data, '');//set_value($formNo));
								?>
			                    </div>  
							</div>
							<div class="controls-row">
								<div class="span3"><?php echo $this->lang->line('deposit') ?></div>
								<div class="span3">
			                    <?php
			                    $data = array(
									'value'=>'',//$formNo,
			                        'name'=>'deposit',
			                        'id'=>'deposit',
			                        'disabled' => 'disabled',
			                        'class'=>'span12 input-medium validate[required]',); 
										echo form_input($data, '');//set_value($formNo));
								?>
								</div>
								<div class="span3"><?php echo $this->lang->line('unpresentedCheque') ?></div>
								<div class="span2">
			                    <?php
								$data = array(
									'value'=>'',//$formNo,
			                        'name'=>'credit',
			                        'id'=>'credit',
			                        'disabled' => 'disabled',
			                        'class'=>'input-medium',); 
										echo form_input($data, '');//set_value($formNo));
			                    ?>
			                    </div> 
							</div>
							<div class="controls-row">
								<div class="span3"><?php echo $this->lang->line('glBalance') ?></div>
			                    <div class="span3">
			                    <?php
			                    $data = array(
									'value'=>'',//$formNo,
									'name'=>'glBalance',
			                        'id'=>'glBalance',
			                        'disabled' => 'disabled',
			                        'class'=>'span12 input-medium validate[required]',); 
										echo form_input($data, '');//set_value($formNo));
			                    ?>
			                    </div>
								<div class="span3"><?php echo $this->lang->line('UnReconciledDifference') ?></div>
								<div class="span2">
								<?php
			                    $data = array(
									'value'=>'',//$formNo,
			                        'name'=>'UnReconciledDifference',
			                        'id'=>'UnReconciledDifference',
			                        'disabled' => 'disabled',
			                        'class'=>'input-medium unreconcil',); 
										echo form_input($data, '');//set_value($formNo));
								?>
								</div>   			                   								              
							</div><!-- End Row 1-->
						</div><!-- content np-->
					</div><!-- block -->
				</div><!-- span12 -->
			</div><!-- row-fluid -->
			
			<div class="row-fluid">
				<div class="span12">
					<div class="block">                                                
						<div class="head">
							<h2><?php echo $this->lang->line('transBankReconcile') ?></h2>
							<ul class="buttons">
								<li><a href="#" class="block_toggle"><span class="i-arrow-down-3"></span></a></li>
							</ul>
							<div class="side fr">                                    
								<!-- <a href="<?php echo base_url()?>locationtransfer/printReport/" class="btn-form btn-small btn-success-form" title="updatePosting" onclick="" ><?php echo $this->lang->line('print') ?></a>							
                               <li><a href="<?php echo base_url(); ?>locationtransfer/add" title="Add New"><span class="i-plus-2"></span></a></li> -->  
							</div><!-- side -->
						</div><!-- head -->
						<div class="content np table-sorting">
							<table cellpadding="0" cellspacing="0" width="100%" id="test" class="editable itemTbl">
								<thead>
                                    <tr>
                                    	<th style="display:none;">&nbsp;</th>
                                    	<th class="tac">#</th>
										<?php foreach($tbHdr as $row): 
											if(!in_array($row,$alignRight)):
										?>
                                        <th class="tac"><?php echo $this->lang->line($row); ?></th>
										<?php else:?>
                                        <th class="tar"><?php echo $this->lang->line($row); ?></th>
										<?php 
                                    		endif;
                                    	endforeach; ?>                       	
				                		<th width="55" class="tac"><?php echo $this->lang->line('action');?></th>
                                    </tr>
								</thead>
                                <tbody>
                                    <?php $bil = 0; 
                                    if(isset($datatbls) && !empty($datatbls)):
                                        foreach($datatbls as $item):
                                        $bil++?>
                                        <tr class="itemList">
                                        	<td class="ID" style="display:none"><?php echo $item->ID; ?></td>
                                            <td class="tac"><?php echo $bil; ?></td>
										<?php foreach($tbHdr as $row): ?>
                                            <td class="tac span2">
												<?php
													echo $item->$row; 
												?>                                            	        
                                            </td>
                                        <?php endforeach; ?>    
                                        	<td class="tac"><?php
												$js = 'class="btn-form btn-mini btn-info-form detail" title="'.$this->lang->line("Show Detail").'"';
												echo form_button('edit','<span class="i-pen">',$js); ?>
											</td>
                                        </tr>
                                        <?php 
                                        endforeach;
                                    endif;
                                    ?>
                                    </tbody>         
                                </table>
							</div><!-- content -->                              
							<div class="footer">
								<div class="side fr">
									<div class="btn-group">
									<?php 
										$data = array(
											'name'=>'postcrdtn', 
	                                        'disabled'=>'disabled',
	                                        'title'=>"UnReconciled Difference must be zero (0.00)",
	                                        'class'=>'btn-form btn-success-form confirm');
	                                    $js = "id='reconcile' onclick='reconcile()'";
											echo form_submit($data,$this->lang->line('save'),$js);
	                                ?>
									</div>
								</div>
							</div>
						</div><!-- block -->
					</div><!-- span12 -->
				</div><!-- row-fluid -->
					
	
		</div><!-- content -->
	</div><!-- wrap -->
</div><!-- content -->

