<script type="text/javascript">	

	function OpeningBalanceYearChange() {
		var y = $('input[name="yearCurr"], input#year0').val();
		var p = $('input[name="yearPrev"], input#year1').val();
		
		$.post('<?php echo base_url(); ?>apply/openingBalanceAjax',{ y:y, p:p },function(result) {			
			var obj = (result) ? JSON.parse(result) : null;
			if ( $.isEmptyObject( obj ) ) return;
			
			$('tr').show();
			$('input.item').val('');
			fnGetTotal();
			
			var years = (obj.hasOwnProperty('years') && obj['years'].length) ? obj['years'] : null;
			var balance = (obj.hasOwnProperty('balance') && !$.isEmptyObject( obj['balance'] )) ? obj['balance'] : null;
			var profit = (obj.hasOwnProperty('profit') && !$.isEmptyObject( obj['profit'] )) ? obj['profit'] : null;
			
			if ( !$.isEmptyObject( balance ) ) {
				$.each(balance, function(k,year) {					
					var $row = $('#item_'+k);					
					if ($row.length) {
						$.each(year, function(y,v) {
							if ( !$.isEmptyObject( v ) ) {
								$row.find('input[id*="bal_b_'+y+'"]').val(v['openingBalanceId']);
								$row.find('input[id*="debit_b_'+y+'"]').val(	accounting.formatNumber(v['openingBalanceDr'],2)	);
								$row.find('input[id*="credit_b_'+y+'"]').val(	accounting.formatNumber(v['openingBalanceCr'],2)	);
							}							
						});
					}
				});
			}
			
			if ( !$.isEmptyObject( profit ) ) {
				$.each(profit, function(k,year) {					
					var $row = $('#item_'+k);					
					if ($row.length) {
						$.each(year, function(y,v) {
							if ( !$.isEmptyObject( v ) ) {
								$row.find('input[id*="bal_p_'+y+'"]').val(v['openingBalanceId']);
								$row.find('input[id*="debit_p_'+y+'"]').val(	accounting.formatNumber(v['openingBalanceDr'],2)	);
								$row.find('input[id*="credit_p_'+y+'"]').val(	accounting.formatNumber(v['openingBalanceCr'],2)	);
							}							
						});
					}
				});
			}
			
			fnGetTotal();
			InitCheckUnbalance();
		});
		
	}

	/**
	* @title : fnHideZeroField
	* @desc	 : Hide Fields with no value
	* @author : Salikeen
	* @last-update : Zul Zolkaffly (22/08/2016)
	*/
	function fnHideZeroField(me, option){
		var $tbody = $('#'+option+' > tbody > tr');
		if(!$tbody.length) return;
		
		if ( $(me).is(':checked') ) {
			$tbody.each(function(){
				var c = 0;
				
				$(this).find('input.item').each(function(k,v) {
					var val = accounting.unformat($(this).val());
					if (!val) c++;
				});
				if(c >= 4) $(this).hide();
				c = 0;
			});
		} else {
			$tbody.show();
		}
	}	
	
	/**
	* @title : OnValueChange
	* @desc	 : Trigger Get Total and Post Record when input item changes value
	* @author : Zul Zolkaffly
	* @last-update : Zul Zolkaffly (22/08/2016)
	*/
	function onValueChange(me) {
		fnGetTotal(me);
		fnPostRecord(me);
	}	
	
	/**
	* @title : fnFormatValue
	* @desc	 : Reformat Number when value has been changed
	* @author : Zul Zolkaffly
	* @last-update : Zul Zolkaffly (22/08/2016)
	*/
	function fnFormatValue(me) {
		var v = accounting.unformat( $(me).val().replace(',','').replace(/[^\d.,]/g,"") );
						if(v) {
							$(me).val( accounting.formatNumber(v,2) );
						} else {
							$(me).val('');
						}
						
		var i = me.id.split('_');
		var c = i[0];
		var t = i[1];
		var y = i[2];
		var r = i[3];
		
		var $other = $('#'+((c == 'debit') ? 'credit' : 'debit')+'_'+t+'_'+y+'_'+r);
				vOther = accounting.unformat($other.val());
		
		$('#debit_'+t+'_'+y+'_'+r).removeClass('highlight');
		$('#credit_'+t+'_'+y+'_'+r).removeClass('highlight');
		$('#sts_'+t+'_'+y+'_'+r).html('');
		if(v > 0 && vOther > 0) {
			$('#debit_'+t+'_'+y+'_'+r).addClass('highlight');
			$('#credit_'+t+'_'+y+'_'+r).addClass('highlight');
			$('#sts_'+t+'_'+y+'_'+r).html("<i class=\"ion ion-android-hand text-red\"></i><i class=\"fa fa-exclamation-circle text-red\"></i>");
		}
	}
	
	/**
	* @title : fnGetTotal
	* @desc	 : Calculate Sub-Totals and Grand-Totals
	* @author : Zul Zolkaffly
	* @last-update : Zul Zolkaffly (22/08/2016)
	*/
	function fnGetTotal(me){
		var total = {
			sub : {
				credit 	: {
						b: { 0 : 0, 1 : 0 },
						p: { 0 : 0, 1 : 0 }
				},
				debit 	: {
						b: { 0 : 0, 1 : 0 },
						p: { 0 : 0, 1 : 0 }
				}
			},
			grand : {
				credit	: { 0 : 0, 1 : 0 },
				debit		: { 0 : 0, 1 : 0 }
			}
		};
		
		$('input.item').each(function() {
			fnFormatValue(this);
			
			var i = this.id.split('_');
			var c = i[0];
			var t = i[1];
			var y = i[2];
			
			total['sub'][c][t][y] += accounting.unformat( $(this).val() );
			total['grand'][c][y] += accounting.unformat( $(this).val() );
		});
		
		$.each(total,function(k,v) {
			if(k == 'sub') {
				$.each(v,function(c,n) {
					$.each(n,function(t,m) {
						$.each(m,function(y,val) {
							$('input#'+k+'_'+c+'_'+t+'_'+y).val( accounting.formatNumber(val,2) );
						});
					});
				});
			} else {
				$.each(v,function(c,n) {
					$.each(n,function(y,val) {
						$('input#'+k+'_'+c+'_'+y).val( accounting.formatNumber(val,2) );
					});
				});
			}
		});
		
		$('input[id*="grand_"]').each(function() {
			var v = accounting.unformat( $(this).val().replace(',','').replace(/[^\d.,]/g,"") );
							if(v) $(this).val( accounting.formatNumber(v,2) );
							
			var i = this.id.split('_');
			var c = i[1];
			var y = i[2];
			
			var $other = $('#grand_'+((c == 'debit') ? 'credit' : 'debit')+'_'+y);
					vOther = accounting.unformat($other.val());
			
			$('#grand_debit_'+y).removeClass('highlight');
			$('#grand_credit_'+y).removeClass('highlight');
			$('#grand_sts_'+y).html('');
			if(v != vOther) {
				$('#grand_debit_'+y).addClass('highlight');
				$('#grand_credit_'+y).addClass('highlight');
				$('#grand_sts_'+y).html("<i class=\"ion ion-android-hand text-red\"></i><i class=\"fa fa-exclamation-circle text-red\"></i>");
			}
		});
		
		InitCheckUnbalance();
	}
	
	/**
	* @title : fnPostRecord
	* @desc	 : Post changes to be saved
	* @author : Zul Zolkaffly
	* @last-update : Zul Zolkaffly (22/08/2016)
	*/
	function fnPostRecord(me) {
		var arr = me.id.split('_');
		var c = arr[0], t = arr[1], y = arr[2], r = arr[3];
		
		var typeMe = c, typeOther = (c == 'debit') ? 'credit' : 'debit';
		
		var $me = $(me);
		var	$other = $('#'+typeOther+'_'+t+'_'+y+'_'+r);
		
		var $acc = $('#acc_'+t+'_'+r);
		var $bal = $('#bal_'+t+'_'+y+'_'+r);		
		
		var year = Number( $('input#year'+y).val() );
		var vMe = accounting.unformat( $(me).val() );
		var vOther = accounting.unformat( $other.val() );
		var openingBalanceId = Number($bal.val());
		var accountID = Number($acc.val());	
		
		var data = {
			'openingBalanceId' : openingBalanceId,
			'accountID' : accountID,
			'year' : year,
			'debit' : ((typeMe=='debit') ? vMe : vOther),
			'credit' : ((typeMe=='credit') ? vMe : vOther)
		};
		
		$.ajax({
			type: 'POST',
			cache: false,
			data: data,
			url: '<?php echo base_url() ?>apply/updateBalance',
			success: function(data) {
				if($.trim(data.toUpperCase()) == "SUCCESS") {			
					new PNotify({ title: 'Disimpan', type: 'success', icon: 'fa fa-check' });
							
					fnFormatValue(me);					
					OpeningBalanceYearChange();
					FinPosYearChange();
					PNLYearChange();
					FinRatioYearChange();
					FinPerfYearChange();
				} else {
					new PNotify({ title: 'Gagal Disimpan', type: 'error', icon: 'fa fa-times' });
				}
			}
		});
	}
</script>

<style>
input[type="text"].highlight { border: 1px solid red; }
</style>
<?php
// MODIFIED: Zul Zolkaffly (17/08/2016)
// Adjust layout so that this method view can be called within "apply" controller, method "index"
// Record now are separated to two years: current and previous. Thus the data array should be expanded to matrix of 3 layers instead.

if (!$years) {
	$years[0] = date("Y");
	$years[1] = date("Y") - 1;
}

foreach($years as $y=>$year) {
	$debitTotal[$year] = 0;
	$creditTotal[$year] = 0;
	$debitGrandTotal[$year] = 0;
	$creditGrandTotal[$year] = 0;
	echo "<input type=\"hidden\" id=\"year".$y."\" value=\"".$year."\" />\n";
}
?>
<div class="content no-padding">
	<!-- FINANCIAL POSITION -->
	<div class="box box-warning">
		<div class="box-header with-border">
			<h3 class="box-title">Kedudukan Kewangan</h3>
			<div class="box-tools pull-right">
				<a href="<?php echo base_url(); ?>glsetting/print_openingBalance" class="btn btn-success btn-sm"><i class="fa fa-print"></i></a>
				<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		
		<div class="box-body">
			<table id="balance" class="table table-bordered table-striped datatables">
				<thead>
					<tr>
						<th>
							<input type="checkbox" onchange="fnHideZeroField(this, 'balance')" />&nbsp;Tutup Baris Kosong
						</th>
						<th colspan="3">
							Tahun : <span class="year_curr"><?php echo ($years && $years[0]) ? $years[0] : NULL; ?></span>
						</th>
						<th colspan="3">
							Tahun Sebelum : <span class="year_prev"><?php echo ($years && $years[1]) ? $years[1] : NULL; ?></span>
						</th>
					</tr>
					<tr>
						<th class="col-sm-6"><?php echo $this->lang->line('accountName') ?></th>
						<?php
						foreach($years as $year) {
							$debitTotal[$year] = 0;
							$creditTotal[$year] = 0;
							?>
							<th class="col-sm-1"><?php echo $this->lang->line('debit') ?></th>
							<th class="col-sm-1"><?php echo $this->lang->line('credit') ?></th>
							<th class="col-sm-1"></th>
							<?php
						}
						?>
					</tr>
				</thead>
				<tbody>
				<?php
					if ($balance) {
						foreach($balance as $key=>$row) {
							?>
							<tr id="item_<?php echo $row['ID']; ?>">
								<td class="span4">
									<span class="acctName"><?php echo $row['acctName']; ?></span>
									<input class="data-account" id="acc_b_<?php echo $key; ?>" type="hidden" value="<?php echo $row['ID'] ?>" />
								</td>
								<?php
								foreach($years as $y=>$year) {
									$db = ($row['data'][$year] && $row['data'][$year]['openingBalanceDr'] > 0) ? $row['data'][$year]['openingBalanceDr']:'';
									$cr = ($row['data'][$year] && $row['data'][$year]['openingBalanceCr'] > 0) ? $row['data'][$year]['openingBalanceCr']:'';
									$debitTotal[$year] += ($db) ? $db : 0;
									$creditTotal[$year] += ($cr) ? $cr : 0;
									?>
									<input class="data-balance" data-year="<?php echo $year; ?>" id="bal_b_<?php echo $y; ?>_<?php echo $key; ?>"
												type="hidden" value="<?php echo ($row['data'][$year]) ? $row['data'][$year]['openingBalanceID'] : NULL; ?>" />
									<td class="span2">
										<input 	class="item span12 data-debit <?php echo ($db > 0 && $cr > 0) ? "highlight" : NULL; ?>"
														id="debit_b_<?php echo $y; ?>_<?php echo $key; ?>"
														type="text"
														onChange="onValueChange(this)"
														value="<?php echo ($db) ? number_format($db,2) : NULL; ?>" />
									</td>
									<td class="span2">
										<input 	class="item span12 data-credit <?php echo ($db > 0 && $cr > 0) ? "highlight" : NULL; ?>" 
														id="credit_b_<?php echo $y; ?>_<?php echo $key; ?>"
														type="text"
														onChange="onValueChange(this)"
														value="<?php echo ($cr) ? number_format($cr,2) : NULL; ?>" />
									</td>
									<td>
										<span id="sts_b_<?php echo $y; ?>_<?php echo $key; ?>">
										<?php echo ($db > 0 && $cr > 0) ? "<i class=\"ion ion-android-hand text-red\"></i><i class=\"fa fa-exclamation-circle text-red\"></i>" : NULL; ?>
										</span>
									</td>
									<?php									
								}
								?>								
							</tr>
							<?php
						}
					}
				?>
				</tbody>
				<tfoot>
					<tr>
						<th class="text-right">Sub Jumlah</th>
						<?php
						foreach($years as $y=>$year) {
							?>
							<th><input class="debit-total" id="sub_debit_b_<?php echo $y; ?>" type="text" value="<?php echo number_format($debitTotal[$year],2); ?>" readonly /></th>
							<th><input class="credit-total" id="sub_credit_b_<?php echo $y; ?>" type="text" value="<?php echo number_format($creditTotal[$year],2); ?>" readonly /></th>
							<th><span id="sub_sts_b_<?php echo $y; ?>"></span></th>
							<?php
							$debitGrandTotal[$year] += $debitTotal[$year];
							$creditGrandTotal[$year] += $creditTotal[$year];
						}
						?>
					</tr>
				</tfoot>
			</table>
		</div>
	</div>
	
	<!-- COMPREHENSIVE INCOME -->
	<div class="box box-warning">
		<div class="box-header with-border">
			<h3 class="box-title">Perolehan / Hasil</h3>
			<div class="box-tools pull-right">
				<a href="<?php echo base_url(); ?>glsetting/print_openingBalance/" class="btn btn-success btn-sm"><i class="fa fa-print"></i></a>
				<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		
		<div class="box-body">
			<table id="profit" class="table table-bordered table-striped datatables">
				<thead>
					<tr>
						<th>
							<input type="checkbox" onchange="fnHideZeroField(this, 'profit')" />&nbsp;Tutup Baris Kosong
						</th>
						<th colspan="3">
							Tahun : <span class="year_curr"><?php echo ($years && $years[0]) ? $years[0] : NULL; ?></div>
						</th>
						<th colspan="3">
							Tahun Sebelum : <span class="year_prev"><?php echo ($years && $years[1]) ? $years[1] : NULL; ?></div>
						</th>
					</tr>
					<tr>
						<th class="col-sm-6"><?php echo $this->lang->line('accountName') ?></th>
						<?php
						foreach($years as $year) {
							$debitTotal[$year] = 0;
							$creditTotal[$year] = 0;
							?>
							<th class="col-sm-1"><?php echo $this->lang->line('debit') ?></th>
							<th class="col-sm-1"><?php echo $this->lang->line('credit') ?></th>
							<th class="col-sm-1"></th>
							<?php
						}
						?>
					</tr>
				</thead>
				<tbody>
				<?php
					if ($profit) {
						foreach($profit as $key=>$row) {
							?>
							<tr id="item_<?php echo $row['ID']; ?>">
								<td class="span4">
									<span class="acctName"><?php echo $row['acctName']; ?></span>
									<input class="data-account" id="acc_p_<?php echo $key; ?>" type="hidden" value="<?php echo $row['ID'] ?>" />
								</td>
								<?php
								foreach($years as $y=>$year) {
									$db = ($row['data'][$year] && $row['data'][$year]['openingBalanceDr'] > 0) ? $row['data'][$year]['openingBalanceDr']:'';
									$cr = ($row['data'][$year] && $row['data'][$year]['openingBalanceCr'] > 0) ? $row['data'][$year]['openingBalanceCr']:'';
									$debitTotal[$year] += ($db) ? $db : 0;
									$creditTotal[$year] += ($cr) ? $cr : 0;
									?>
									<input class="data-balance" data-year="<?php echo $year; ?>" id="bal_p_<?php echo $y; ?>_<?php echo $key; ?>"
												type="hidden" value="<?php echo ($row['data'][$year]) ? $row['data'][$year]['openingBalanceID'] : NULL; ?>" />
									<td class="span2">
										<input 	class="item span12 data-debit <?php echo ($db > 0 && $cr > 0) ? "highlight" : NULL; ?>"
														id="debit_p_<?php echo $y; ?>_<?php echo $key; ?>"
														type="text"
														onChange="onValueChange(this)"
														value="<?php echo ($db) ? number_format($db,2) : NULL; ?>" />
									</td>
									<td class="span2">
										<input 	class="item span12 data-credit <?php echo ($db > 0 && $cr > 0) ? "highlight" : NULL; ?>" 
														id="credit_p_<?php echo $y; ?>_<?php echo $key; ?>"
														type="text"
														onChange="onValueChange(this)"
														value="<?php echo ($cr) ? number_format($cr,2) : NULL; ?>" />
									</td>
									<td>
										<span id="sts_p_<?php echo $y; ?>_<?php echo $key; ?>">
										<?php echo ($db > 0 && $cr > 0) ? "<i class=\"fa fa-hand-stop bg-red\"></i>" : NULL; ?>
										</span>
									</td>
									<?php									
								}
								?>								
							</tr>
							<?php
						}
					}
				?>
				</tbody>
				<tfoot>
					<tr>
						<th class="text-right">Sub Jumlah</th>
						<?php
						foreach($years as $y=>$year) {
							?>
							<th><input type="text" id="sub_debit_p_<?php echo $y; ?>" class="debit-total" value="<?php echo number_format($debitTotal[$year],2); ?>" readonly /></th>
							<th><input type="text" id="sub_credit_p_<?php echo $y; ?>" class="credit-total" value="<?php echo number_format($creditTotal[$year],2); ?>" readonly /></th>
							<th><span id="sub_sts_p_<?php echo $y; ?>"></span></th>
							<?php
							$debitGrandTotal[$year] += $debitTotal[$year];
							$creditGrandTotal[$year] += $creditTotal[$year];
						}
						?>
					</tr>
				</tfoot>
			</table>
		</div>
	</div>
		
	<!-- TOTAL -->
	<div class="box box-warning">
		<div class="box-body">
			<table id="total" class="table table-bordered table-striped datatables">
				<thead>
					<tr>
						<th class="col-sm-6">Jumlah Keseluruhan</th>
						<?php
						foreach($years as $year) {
							?>
							<th class="col-sm-1"><?php echo $this->lang->line('debit') ?></th>
							<th class="col-sm-1"><?php echo $this->lang->line('credit') ?></th>
							<th class="col-sm-1"></th>
							<?php
						}
						?>
					</tr>
				</thead>
				<tbody>
					<tr>
					<td class="col-sm-6" class="text-right">Jumlah</td>
					<?php
					foreach($years as $y=>$year) {
						?>
						<td class="col-sm-1">
							<input 	class="debit-grand-total <?php echo ($debitGrandTotal[$year] != $creditGrandTotal[$year]) ? "highlight" : NULL; ?>"
											id="grand_debit_<?php echo $y; ?>"
											type="text"
											value="<?php echo number_format($debitGrandTotal[$year],2); ?>" readonly />
						</td>
						<td class="col-sm-1">
							<input 	class="credit-grand-total <?php echo ($debitGrandTotal[$year] != $creditGrandTotal[$year]) ? "highlight" : NULL; ?>"
											id="grand_credit_<?php echo $y; ?>"
											type="text"
											value="<?php echo number_format($creditGrandTotal[$year],2); ?>" readonly />
						</td>
						<td>
							<span id="grand_sts_<?php echo $y; ?>">
								<?php echo ($debitGrandTotal[$year] != $creditGrandTotal[$year]) ? "<i class=\"ion ion-android-hand text-red\"></i><i class=\"fa fa-exclamation-circle text-red\"></i>" : NULL; ?>
							</span>
						</td>
						<?php
					}
					?>
					</tr>

				</tbody>
			</table>
		</div>
	</div>	
</div>










	
	
	