<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 },
						{"bSortable": false },
					<?php foreach($tbHdr as $v): ?>
						null,
					<?php endforeach; ?>
						{"bSortable": false }
					] 
	});
	oTable.fnSort( [ [1,'asc'] ] );

	//
	$('#startDate,#endDate,#bankID').change(function(){
		var startDate = $('#startDate').val();
		var endDate = $('#endDate').val();
		var bankCode = $('#bankID').val();
		var url = "<?php echo base_url(); ?>bankreconciliation/concileList/"+startDate+'/'+endDate+'/'+bankCode;
		window.location = url;
	});	  

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

		var rcvDeposit = parseFloat(accounting.unformat($(this).parents('tr').find('.debit').text()));
		var payCredit = parseFloat(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();
	});

	//Remove Reconcile entry
	$("table.editable").on("click",".remove",function(){
        rRow = $(this).parents("tr");
        ID = $('td:first', $(this).parents('tr')).text(); 
        $("#row_delete").dialog("open");
    });

    function remove_row(row){
    	var concilID = $(row).find('.ID').text();
        row.remove();
 		$.ajax({
  			type: "POST",
  			url: "<?php echo base_url()?>bankreconciliation/remove/"+concilID,
			data:"ID="+ID,
  			success: function(data){
  				console.log(data);
  				if(data == 'success'){
					alertbox('Bank Reconcile is deleted...');
					
					setTimeout(function(){ 
						location.reload();
					}, 3000);
  				}else{
  					alertbox("Remove latest entry/'s first");
  				}
			},
		});       // Here your ajax action after delete confirmed
    }

    $("#row_delete").dialog({
        autoOpen: false,
        resizable: false,        
        modal: true,
        buttons: {
            "Delete": function() {
                remove_row(rRow);
                $(this).dialog("close");
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        }
    }); 
}); 

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

		$('#statClosBal').val(accounting.formatNumber(statClosBal,2));
		console.log(statClosBal+"<->"+deposit+"<->"+unPresnChk+'<->'+glBal);
		var unReconcileBal = statClosBal + deposit - unPresnChk - glBal;
		$('#UnReconciledDifference').val(accounting.formatNumber(unReconcileBal,2));
}
function reconcile(){
	var totalDebit = 0;
	var totalCredit = 0;
	var conID = '';
	$('.reconsil input:checked').each(function(){
		if(conID == ''){
			conID += $(this).val();
		}else{
			conID += ','+$(this).val();
		}
	});
	if(conID != ''){
		$.ajax({
			url: "<?php echo base_url(); ?>bankreconciliation/setconcile",
			async: false,
			type: "POST",
			data: 'conID='+conID
					+'&bankLinkAcctCode='+$('.bankID').select2('val')
					+'&reconcileDate='+$('#selDateFrom').val()
					+'&reconcileBalance='+$('#statClosBal').val(),
			dataType: "html",
			success: function(data) {
				if(data == 'Success'){
					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(); ?>'><?php echo $this->lang->line('dashboard') ?></a> <span class="divider">-</span></li>
            <li><a href="<?php echo base_url(); ?>/locationtransfer"><?php echo $this->lang->line('module') ?></a> <span class="divider">-</span></li>
            <li class="active"><?php echo $this->lang->line('bankRecList') ?></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="wrap">        
        <div class="content">
            <div class="wrap">                 
                <div class="row-fluid">
                    <div class="span12">        
                    <div class="block">
                        <div class="block">
        	        <div class="head">
     <h2><strong><?php echo $this->lang->line('bankRecList') ?></strong></h2>
</div><!-- head -->
                    <div class="content np">    
                        <!--Location transfer top form-->  

			            <div class="row-fluid scRow">
			                <div class="span6 scCol">
	                            <div class="controls-row" style="padding:10px 10px 8px;">
			                    	<div class="span4"><?php echo $this->lang->line('bank') ?>*</div>
		                            <div class="span8">
		                                <?php
		                                	$preselcat = '';
											//$options[''] = 'Please select';
											$options = '<option value="all">'.$this->lang->line('pleaseSelect').'</option>';
											if ($bank){
												//print_r($bank);
												//$options = '<option value="all">'.$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).")";
		                                            if($bankCode == $row->caID):
		                                            	$options .='<option selected value="'.$row->caID.'">'.$row->bankName." (".substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7).")".'</option>';
		                                        	else:
		                                            	$options .='<option value="'.$row->caID.'">'.$row->bankName." (".substr($row->acctCode,0,4).'-'.substr($row->acctCode,4,3).'-'.substr($row->acctCode,7).")".'</option>';		                                        		
		                                           	endif;
		                                        }
		                                    }
		                                    $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>
			            </div>
			            <div class="row-fluid scRow">
			                <div class="span6 scCol">
	                            <div class="controls-row" style="padding:10px 10px 8px;">
			                    	<div class="span4"><?php echo form_label($this->lang->line('concileStartDate')); ?></div>
			                        <div class="input-prepend">
				                        <span class="add-on"><i class="i-calendar"></i></span>
										<?php
											$data = array(
											'name' => 'selDateFrom',
											'id' => 'startDate',
											'type' => 'text',
											'class' => 'input-small datepicker2 financhk',);
											$js='';
											echo form_input($data, date('d-m-Y', strtotime($startDate)), $js);
											
										?>       
			                        </div>
			                    </div>                         			                        
			                </div>
			                <div class="span6 scCol"> 
			                    <div class="controls-row" style="padding:10px 10px 8px;">
			                    	<div class="span4"><?php echo form_label($this->lang->line('concileEndDate')); ?></div>
			                        <div class="input-prepend">
				                        <span class="add-on"><i class="i-calendar"></i></span>
										<?php
											$data = array(
											'name' => 'selDateFrom',
											'id' => 'endDate',
											'type' => 'text',
											'class' => 'input-small datepicker2 financhk',);
											$js='';
											echo form_input($data, date('d-m-Y', strtotime($endDate)), $js);
											
										?>       
			                        </div>
			                    </div>                         			                        			                        	    			          
			                </div>
			            </div>
			            <!--Location transfer top form-->
			        </div>
                    </div>    
                        <div class="block">                            
                            <div class="head">
                                <h2><?php echo $this->lang->line('bankRecList') ?></h2>
                            	<!--<ul class="buttons">
                                     <li><a href="<?php echo base_url()?>locationtransfer/printReport/<?php echo $dateFrom.'/'.$dateTo; ?>" title="updatePosting" onclick=""><?php echo $this->lang->line('print') ?></a></li>
                                     <li><a href="<?php echo base_url(); ?>locationtransfer/add" title="Add New"><span class="i-plus-2"></span></a></li>  
                                </ul>-->
                            </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 span2">#</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 span2"><?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): 
											$cls = 'tac';
											if(in_array($row,$alignRight)){
												$cls = 'tar';
												$item->$row = number_format($item->$row,2);
											}

										?>
                                            <td class="<?php echo $cls; ?> span2">
												<?php
													echo $item->$row; 
												?>                                            	        
                                            </td>
                                        <?php 
                                        	endforeach; ?>    
                                        	<td class="tac">
                                        		<!-- <a class="btn-icon" target="_blank" href="<?php echo base_url()?>bankreconciliation/undo/<?php echo $item->ID ?>" name="Undo Re-conciliation" title="Undo Re-Conciliation"><span class="i-pen"></span></a> -->
                                        		<?php if($bil <2 ): ?><a class="btn-icon btn-mini btn-danger-form remove" href="javascript:" name="Remove Re-conciliation" title="Remove Re-Conciliation"><span class="i-trashcan"></span></a> <?php endif; ?>
												<a class="btn-icon btn-mini btn-success-form " target="_blank" href="<?php echo base_url()?>bankreconciliation/printRpt/<?php echo $item->ID ?>" name="Print Reconcilation" title="Print Reconcilation"><span class="i-printer"></span></a>
											</td>
                                        </tr>
                                        <?php 
                                        endforeach;
                                    endif;
                                    ?>
                                    </tbody>         
                                </table>
                            </div><!-- content -->                              

                            <div class="footer">
	                            <div class="side fr">
	                                <div class="btn-group">
	                                    &nbsp;
	                                </div>
	                            </div>
	                        </div>
                        </div><!-- block -->
                    </div><!-- span12 -->
                </div><!-- row-fluid -->	
            </div><!-- wrap -->
        </div><!-- content -->
	</div>
</div>
<div class="dialog" id="row_delete" style="display: none;" title="Are you sure to Undo?">
    <p>Reconcile will be Undo</p>
</div> 
</div>
</div>
</div>