<!---- 
    Author 	: Wahyu
    Tanggal : 12-08-2014	
    Revisi 	:
-->
<?php
//---------Untuk privellege jika dia ada tombol save----------
	if($group_user->SavePrivillage == 1){
		$cek_autority_save  = "";
	}
	else{
		$cek_autority_save 	= "disabled";
	}
//-------------end----------------------------
?>
<style type="text/css">
	.combo-text{background-color:white;}
</style>
<div class="easyui-layout" data-options="fit:true,border:false">
	<!-- top view-->
	<div id="form-header" data-options="region:'north',border:false" >
		 <div id="form-header-wrapper">
				<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
					<tr>
						<td align="left" valign="middle">
							<a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="location.reload()">New</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="location.reload()">Refresh</a>
							<!-- <a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="" disabled>Journal</a> -->
						</td>							
						<td height="25" align="right" valign="middle">								
							<span class="form-title">
								<?= $menu_label; ?>
							</span>
						</td>
					</tr>
				</table>		     	
		 </div>			
	</div>
	<!-- end top view -->	
	<!-- center view -->
	<div id="form-body" data-options="region:'center',border:false">
		<div id="form-wrapper" class="easyui-panel"  style="width:1180%;height:548px;padding:5px;" fit='true'>
			<form id="fm_loan_payment" name="fm_loan_payment" method="post" action="">
            <!-- Form Header -->
                <table width="100%" height="141" cellpadding="0" cellspacing="0">
	                <tr>
	                    <td width="50%" valign="top">   
			                <table cellpadding="0" cellspacing="3" width="100%" height="100%" border="0">
								<tr>
								    <input name="txt_piutang_no" id="txt_piutang_no" type="hidden" style="width:100px" />
								    <input name="txt_total_piutang" id="txt_total_piutang" type="hidden" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" style="width:100px" />
			                        <input type="hidden" id="hide_new_index" name="hide_new_index" value="" />
			                        <input type="hidden" id="txt_new_status" name="txt_new_status" />
			                        <input type="hidden" id="detail" name="detail" />
			                        
									<td width="150"><b><label>Payment For</label></b></td>
								  	<td width="10"><b>:</b></td>
									<td valign="top" align="left"  width="768">
										 <input name="txt_payment_for" id="txt_payment_for" type="text" style="width:200px" class="disabled" readonly/>	
										 <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-sales" onclick="modal_open('Payment List','dialog-payment-list')" style="width:110px;" plain="true">List Payment</a>
									</td>
									
								</tr>
								<tr>
									<td width="150"><b><label>Transfer From</label></b></td>
								  	<td width="10"><b>:</b></td>
									<td valign="top" align="left"  width="768">
										<select name="cmb_bank" class="combo-grid" editable="true" id="cmb_bank" required="required" style="width:405px;height:20px" data-options="
											panelWidth: 405,
											idField: 'AccountNumber',
											textField: 'AccountName',
											url: '<?= base_url().$menu_link; ?>/get_bank_account',            
											columns: [[
												{field:'AccountNumber',title:'Account Code',width:150},
												{field:'AccountName',title:'Account Name',width:250},
												{field:'CurrencyCode',title:'Currency Code',width:50}
											]],
											fitColumns: false,
											onSelect:function(rowIndex,rowData){
												eventCMBSelect(rowData.AccountNumber,rowData.CurrencyCode);
											}
											">
										</select>
																
									</td>
									
								</tr>
								
								<tr>
		                            <td width="150"><b><?php echo label_grid('check_no');?></b></td>
		                            <td width="10"><b>:</b></td>
		                            <td>
		                                 <input type="text" name="cheque_number" id="cheque_number" style="width:369px">
		                            </td>
		                        </tr>
			                        
								<tr>
									<td width="150" valign="top"><b><label>Description</label></b></td>
								  	<td width="10" valign="top"><b>:</b></td>
									<td><textarea class="textbox" style="resize:none;" name="txa_description" id="txa_description" cols="55" rows="3"></textarea></td>
									
								</tr>
								<tr>
								  <td width="150"><b><label>Rate</label></b></td>
								  <td width="10"><b>:</b></td>
								 <td>
                            		<input name="txt_rate" id="txt_rate" type="numberbox" value="" class="easyui-numberbox" style="width:200px;" 
                            			data-options=" 
                            				min:0.01,
                            				precision:2,
                            				decimalSeparator:',',
                            				groupSeparator:'.',
                            				onChange:function(newValue,oldValue){
                            					changeRate(newValue,oldValue);
                            				}
                            			" formatter="formatRp" /> <strong>Currency :</strong> <span id="from_currency"></span> <span>TO</span> <span id="to_currency"></span>
                            	</td>
								  
							    </tr>
								<tr>
								  <td width="150"><b><label>Amount (<span id="amount_currency"></span>)</label></b></td>
								  <td width="10"><b>:</b></td>
								  <td>
									<input name="txt_amount_total" id="txt_amount_total" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:405px;" required="required" />
									<input type="hidden" name="txt_amount" id="txt_amount" value="">
									<input type="hidden" name="txt_new_no" id="txt_new_no" value="">
									<input type="hidden" name="lf_account" id="lf_account" value="">
									<input type="hidden" name="total_expense" id="total_expense" value="">
									<input type="hidden" name="currency_funding" id="currency_funding" value="">
									<input type="hidden" name="currency_payment" id="currency_payment" value="">
									<input type="hidden" name="rate_funding" id="rate_funding" value="">
									<input type="hidden" name="exp_account" id="exp_account" value="">
									<input type="hidden" name="exp_amount" id="exp_amount" value="">
								  </td>
								  
							    </tr>
							    				
							</table>
						</td>
						<td width="50%" valign="top">
	                        <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
	                        <tr height="20">
	                            <td valign="top">&nbsp;</td>
	                            <td width="122">&nbsp;</td>
	                            <td width="200" style="background:#333399;text-align:center;color:#FFF;"><b>Available Balance (<span class='bank_balance_currency'></span>)</b></td>
	                            <td width="200" style="background:#333399;text-align:center;color:#FFF;">Payment Date</td>
	                        </tr>
	                        <tr height="20">
	                        	<td>&nbsp;</td>
	                        	 <td width="122">&nbsp;</td>
	                            <td><input name="txt_bank_balance" id="txt_bank_balance" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="text-align:right;width:200px;height:22px" readonly /></td>
	                            <input type="hidden" name="txt_payment_no" id="txt_payment_no" class="easyui-validatebox disabled" style="width:200px;" readonly  required="required" />
	                            <td><input type="text" name="txt_payment_date" id="txt_payment_date" class="easyui-datebox validBackward" style="width:200px;height:22px" required editable="false" value="<?= $date_now;?>"/></td>
	  
	                        </tr>
	                        <tr height="20">
	                            <td valign="top">&nbsp;</td>
	                            <td width="122">&nbsp;</td>
	                            <td width="200" style="background:#333399;text-align:center;color:#FFF;">Loan Amount</td>
	                            <td width="200" style="background:#333399;text-align:center;color:#FFF;">OutStanding Amount</td>
	                        </tr>
	                        <tr height="20">
	                        	<td>&nbsp;</td>
	                        	<td width="122">&nbsp;</td>
	                            <td><input name="txt_loan_amount" id="txt_loan_amount" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="text-align:right;width:200px;height:22px" readonly /></td>
	                            <td><input name="txt_outstanding_amount" id="txt_outstanding_amount" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="text-align:right;width:200px;height:22px" readonly/></td>
	                            <input name="txt_outstanding_amount_hidden" id="txt_outstanding_amount_hidden" type="hidden" style="text-align:right;width:200px;height:22px" readonly/>
	                        </tr>
	                        
	                        </table>
                    	</td>
					</tr>
				</table>
				<table id="dtg_payment_history" class="easyui-edatagrid"
					title="Payment History" idField="id"
					rownumbers="true" fitColumns="true" singleSelect="true" style="height:290px;" toolbar="#tb_dtg_pay_piutang" 
						data-options="
						onClickRow:function(){
				             var selected_data=$('#dtg_payment_history').datagrid('getSelected');
				             var no_paymen = $('#txt_payment_no').val();
				             if(selected_data.LPNumber != no_paymen){
				                 $.messager.alert('Unseccessfull','Data tidak sama dengan Nomor Loan Payment','error',function(){	
					                $('#dtg_payment_history').datagrid('reload');
					                $('#txt_amount').val('');
					                $('#txt_amount_total').numberbox('setValue',0);
					                $('#txt_new_status').val(0);
				                });
				             }
				        },onBeginEdit:function(rowIndex){
                        
	                        /*====================on beg in edit saat grid di klik maka tombol save disable===================*/
	                        save_button_begendedit('<?=$group_user->SavePrivillage;?>');
	                        /*=================================end============================================================*/
	                        status_editor 			= 1;
	                        var payment_currency 	= $('#currency_payment').val();
							var loan_currency 		= $('#currency_funding').val();
							var rate 				= parseFloat($('#txt_rate').numberbox('getValue'));

	                        var dg_rows 			= $('#dtg_payment_history').datagrid('getEditors', rowIndex);

							//if(payment_currency == loan_currency){
							//	var account_name	= $(dg_rows[4].target);
							//}else{
							//	var account_name	= $(dg_rows[5].target);
							//}

	                        //account_name.combobox().next().children(':text').blur(function(){
							//	var txt_value 	= $(this).val();
							//	alert(txt_value);
							//	clearComboBoxInGrid(txt_value,account_name);
							//});
	
							if(payment_currency != loan_currency){
								var payPerPeriod1		= $(dg_rows[2].target);
								var payPerPeriod2		= $(dg_rows[3].target);
								
								var expamount1 			= $(dg_rows[6].target);
								var expamount2			= $(dg_rows[7].target);

							
								payPerPeriod2.numberbox({
						            onChange:function(){
						            	
						            	if(loan_currency =='IDR'){
						            		PayAmount 	= parseFloat(payPerPeriod2.numberbox('getValue')) * rate;
						            		payPerPeriod1.numberbox('setValue',PayAmount);
						            	}else{
						            		PayAmount 	= parseFloat(payPerPeriod2.numberbox('getValue')) / rate;
						            		payPerPeriod1.numberbox('setValue',PayAmount);
						            	}
							            
						            }
						        });

						        expamount2.numberbox({
						            onChange:function(){
						            	
						            	if(loan_currency =='IDR'){
						            		ExpAmount 	= parseFloat(expamount2.numberbox('getValue')) * rate;
						            		expamount1.numberbox('setValue',ExpAmount);
						            	}else{
						            		ExpAmount 	= parseFloat(expamount2.numberbox('getValue')) / rate;
						            		expamount1.numberbox('setValue',ExpAmount);
						            	}
							            
						            }
						        });
						    }
							
						},
	                    onEndEdit:function(indexRow,row,changes){

	                        /*====================on beg in edit saat grid di klik maka tombol save disable===================*/
	                        save_button_endedit('<?=$group_user->SavePrivillage;?>');
	                        /*=================================end============================================================*/
	                    }
					">
					<thead>
						<tr>
							<th rowspan="2" formatter="formatRp" data-options="field:'LoanPayment',width:120,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0.01,precision:2,decimalSeparator:',',required:true, disabled:true}}">Loan Amount</th>
							<th rowspan="2" data-options="field:'PaymentPeriod',width:15,halign:'center',align:'center', editor:{type:'numberbox',options:{min:0.01,precision:2,decimalSeparator:',',required:true,disabled:true}}" hidden="true">Period</th>
							
							<th colspan="2" rowspan="1" data-options="width:300,fixed:true">Payment Per Period</th>

							<th rowspan="2" formatter="formatRp" data-options="field:'PaymentBalance',width:120,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',required:true, disabled:true}}">OutStanding Balance</th>
                            
                            <th rowspan="2" align="center" valign="middle" data-options="
                                field:'ExpenseAccount',
                                width:200,									
                                align:'left',
                                editor:{
                                type:'combobox',
                                options:{
                                    valueField:'AccountName',
                                    textField:'AccountName',
                                    url: '<?= base_url().$menu_link; ?>/get_expense_account',
                                    editable:true
                                } 
                            }">Interest Account</th>	
                            <th colspan="2" rowspan="1" data-options="width:300,fixed:true">Interest Payment</th>
                            <th rowspan="2" data-options="field:'LPNumber',width:75,halign:'center',align:'right'" hidden="true">LP Number</th>
						</tr>
						<tr>
							<th colspan="2" formatter="formatRp" data-options="field:'PaymentPerPeriod1',width:150,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0.01,precision:2,decimalSeparator:',',required:true,disabled:false}}">IDR </th>
							<th formatter="formatRp" data-options="field:'PaymentPerPeriod2',width:150,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0.01,precision:2,decimalSeparator:',',required:true,disabled:true}}" hidden="true">Payment Per Period </th>
							
							<th colspan="2" formatter="formatRp" data-options="field:'ExpenseAmount1',width:150,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',disabled:false}}" >IDR</th>
                            <th formatter="formatRp" data-options="field:'ExpenseAmount2',width:150,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',disabled:true}}" hidden="true">Interest Payment</th>
						</tr>
					</thead>
				</table>
			</form>
		</div>
        <div id="tb_dtg_pay_piutang">
            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addNewRow(false)">New</a>
        </div>
	</div>
    <div id="form-footer" data-options="region:'south',border:false">
			<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
				 <tr>
				   <td align="left">
						
				   </td>
					<td align="right">                              
						 <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-help" onclick="" plain="true">Help</a>
                         <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="save_data();" <?php echo $cek_autority_save;?>>Save</a> 								
                         <!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="" disabled>Preview & Print</a>    -->
                         <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="parent.tab_close('tt')">Cancel</a>
					</td>
				 </tr>
			</table>				
		</div>
</div>


<!-- Dialog Payment List -->
<div id="dialog-payment-list" class="easyui-dialog" style="width:815px; left:150px; top:50px; background-color:#F8F8F8; height:500px; padding: 0 0px 0 0px" closed="true" data-options="modal:true" buttons="#dialog-buttons">
	<table id="dtg_payment_list" style="width:780px;height:480px" 
        url="<?= base_url().$menu_link; ?>/get_piutang"
        singleSelect="true"
        idField="" >
		<thead>
			<tr>
				<th field="BranchName" width="120" align="center">Branch</th>
				<th field="AccountName" width="250" align="left">Loan Account</th>
				<th field="LFNumber" width="150" align="center">No Hutang</th>
				<th field="LFAmount" width="135" align="right" halign="center" hidden="true">Amount</th>
				<th field="LFAmountview" width="135" align="right" halign="center" formatter="formatRp">Amount</th>
                <th field="outstanding" width="130" align="right" halign="center" hidden="true" >Sisa Hutang</th>	
                <th field="outstandingview" width="130" align="right" halign="center" formatter="formatRp">Sisa Hutang</th>	
                <th field="LFIsLock" align="right" width="90"  halign="center" >Status</th>
                <th field="LFDesc" align="right" width="90"  halign="center" hidden="true">Memo</th>
                <th field="BranchCode" hidden="true" width="120" align="center">Branch Code</th>	
                <th field="LFAccount" hidden="true" width="120" align="center">LFAccount</th>
                <th field="CurrencyRate" hidden="true" width="120" align="center">CurrencyRate</th>			
			</tr>
		</thead>
	</table>
	<div id="dialog-buttons">
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_loan_funding(false)">OK</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-payment-list')">Cancel</a>
	</div>
</div>

<script type="text/javascript">

var SavePrivillage 	= '<?=$group_user->SavePrivillage;?>';
var status_editor 	= 0;

$(document).ready(function(){

    $('#txt_payment_no').val('<?php echo $loan_payment; ?>');

    $('#fm_loan_payment').click(function(){
		var txt_new_no 		= $('#txt_new_no').val();
		
		if(txt_new_no == 1){
			if(status_editor == 1){
				calculate_payment();
				var rownumbers = $('.datagrid-cell-rownumber').length;
				for(var x = 0; x < rownumbers; x++){
					$('.datagrid-cell-rownumber').eq(x).html(x+1);
				}
			}
		}
    });

    var no_piutang = '<?= $no_piutang;?>';

    $('#dtg_payment_list').datagrid({
    	rowStyler: function(index,row){
				if (row.LFIsLock=='Locked'){					
					return 'background-color:#FF6666;color:#fff;';
				}					
			},
			onLoadSuccess:function(data){
				if(no_piutang !=''){
				    var ind_piutang = findWithAttr(data.rows,'LFNumber',no_piutang);
				    $('#dtg_payment_list').datagrid('selectRow',ind_piutang);
				    if(data.rows[ind_piutang]['LFIsLock']!='Locked'){
				    	choose_loan_funding(true);
				    }
				}
			}
    });

    $('#txt_payment_for').on('mouseover',function(){
    	$(this).css({'color':'blue','font-weight':'bold','cursor':'pointer'});
    }).on('mouseout',function(){
    	$(this).css({'color':'#545454','font-weight':'normal'});
    }).on('click',function(){
    	var TransNumber = $(this).val();
    	parent.tab_edit('Edit Loan Funding','list/loan_funding', 'icon-edit', 'edit',TransNumber);
    });

});

function changeRate(newValue,oldValue){

	var payment_currency 	= $('#currency_payment').val();
	var loan_currency 		= $('#currency_funding').val();
	var indexRow 			= $('#hide_new_index').val();
	// alert(loan_currency+' vs '+payment_currency);
	if(indexRow !=''){

		if(loan_currency !=payment_currency){
			$('#dtg_payment_history').datagrid('selectRow',indexRow);
			var selectedrow     = $('#dtg_payment_history').datagrid('getSelected');

			var item        	= $('#dtg_payment_history').datagrid('getRows');
			var TotalItem 		= item.length;
		    var Pay_Balance   	= 0;
		    
		    if(TotalItem > 1){
		    	var no 				= 1;
			    $.each(item, function(index, value) {
			        if(value.PaymentBalance != undefined){
			        	if((no+1)==TotalItem){
			            	Pay_Balance = parseFloat(value.PaymentBalance);
			        	}
			        	no++;
			        }               
			    });
			}else{
				  var no 				= 0;
				 $.each(item, function(index, value) {
			        if(value.LoanPayment != undefined){
			        	if((no+1)==TotalItem){
			            	Pay_Balance = parseFloat(value.LoanPayment);
			        	}
			        	no++;
			        }               
			    });
			}
			if(loan_currency =='IDR'){
				$('#dtg_payment_history').datagrid('updateRow',{
					index: indexRow,
					row: {
						PaymentPerPeriod1		: (parseFloat(selectedrow.PaymentPerPeriod2) * parseFloat(newValue)),
						PaymentBalance 			: (Pay_Balance - (parseFloat(selectedrow.PaymentPerPeriod2) * parseFloat(newValue))),
						ExpenseAmount1			: (parseFloat(selectedrow.ExpenseAmount2) * parseFloat(newValue)),
					}
				});
				//var total_payment 	= (parseFloat(selectedrow.PaymentPerPeriod2) * parseFloat(newValue)) + (parseFloat(selectedrow.ExpenseAmount2) * parseFloat(newValue));
				var exp_amount 		= (parseFloat(selectedrow.ExpenseAmount2) * parseFloat(newValue));
				var txt_amount 		= (parseFloat(selectedrow.PaymentPerPeriod2) * parseFloat(newValue));
				var payment_balance = (Pay_Balance - (parseFloat(selectedrow.PaymentPerPeriod2) * parseFloat(newValue)));

			}else{
				$('#dtg_payment_history').datagrid('updateRow',{
					index: indexRow,
					row: {
						PaymentPerPeriod1		: (parseFloat(selectedrow.PaymentPerPeriod2) / parseFloat(newValue)),
						PaymentBalance 			: (Pay_Balance - (parseFloat(selectedrow.PaymentPerPeriod2) / parseFloat(newValue))),
						ExpenseAmount1			: (parseFloat(selectedrow.ExpenseAmount2) / parseFloat(newValue)),
					}
				});
				//var total_payment 	= (parseFloat(selectedrow.PaymentPerPeriod2) / parseFloat(newValue)) + (parseFloat(selectedrow.ExpenseAmount2) / parseFloat(newValue));
				var exp_amount 		= (parseFloat(selectedrow.ExpenseAmount2) / parseFloat(newValue));
				var txt_amount 		= (parseFloat(selectedrow.PaymentPerPeriod2) / parseFloat(newValue));
				var payment_balance = (Pay_Balance - (parseFloat(selectedrow.PaymentPerPeriod2) / parseFloat(newValue)));
				
			}

			// $('#txt_amount_total').numberbox('setValue',total_payment);
			$('#exp_amount').val(exp_amount);
			$('#txt_amount').val(txt_amount);
			$('#payment_balance').numberbox('setValue',payment_balance);
		}
	}else{
		
	}
}

function eventCMBSelect(accountnumber,currency){

	var loan_currency 	= $('#currency_funding').val();

	if(loan_currency == ''){
		$.messager.alert('Warning','Pleas, select Loan Funding.','error');
		$('#cmb_bank').combogrid('setValue','');
	}else{

		$('#hide_new_index').val('');

		status_editor 	= 0;

		if(loan_currency == 'IDR' && currency =='IDR'){

	    	get_master_rate(currency);
	   		$('#txt_rate').prop('readonly',true);
	   		$('#currency_payment').val(currency);
	   		$('#amount_currency').html(currency);

	    }else{

	    	get_master_rate(currency);
	    	$('#txt_rate').prop('readonly',false);
	    	$('#amount_currency').html(currency);
			$('#currency_payment').val(currency);
	    	
	    }

		get_bank_balance(accountnumber,currency);

		var dg 		= $('#dtg_payment_history');

		if(currency == loan_currency){

	   		var Payment2 		= dg.datagrid('getColumnOption','PaymentPerPeriod2');
        	Payment2.hidden		= true;
        	Payment2.title 		= '';
        	Payment2.width 		= 180;
        	Payment2.editor.options.disabled 	= true;

        	var Payment1 		= dg.datagrid('getColumnOption','PaymentPerPeriod1');
    		Payment1.hidden		= false;
    		Payment1.colspan 	= '2';
    		Payment1.title 		= loan_currency;
    		Payment1.editor.options.disabled  	= false;



        	var expense2 		= dg.datagrid('getColumnOption','ExpenseAmount2');
        	expense2.hidden		= true;
        	expense2.title 		= '';
        	expense2.width 		= 200;
        	expense2.editor.options.disabled 	= true;

        	var expense1 		= dg.datagrid('getColumnOption','ExpenseAmount1');
    		expense1.hidden		= false;
    		expense1.colspan 	= '2';
    		expense1.title 		= loan_currency;
    		expense1.editor.options.disabled 	= false;

        	$('#from_currency').html(currency);

        }else{

        	var Payment2 		= dg.datagrid('getColumnOption','PaymentPerPeriod2');
        	Payment2.hidden		= false;
        	Payment2.title 		= currency;
        	Payment2.width 		= 200;
        	Payment2.editor.options.disabled 	= false;

        	var expense2 		= dg.datagrid('getColumnOption','ExpenseAmount2');
        	expense2.hidden		= false;
        	expense2.title 		= currency;
        	expense2.width 		= 200;
        	expense2.editor.options.disabled	= false;

        	var Payment1 		= dg.datagrid('getColumnOption','PaymentPerPeriod1');
    		Payment1.hidden		= false;
    		Payment1.colspan 	= '1';
    		Payment1.title 		= loan_currency;
    		Payment1.editor.options.disabled 	= true;

        	var expense1 		= dg.datagrid('getColumnOption','ExpenseAmount1');
    		expense1.hidden		= false;
    		expense1.colspan 	= '1';
    		expense1.title 		= loan_currency;
    		expense1.editor.options.disabled 	= true;

    		if(loan_currency == 'IDR'){
        		$('#from_currency').html(currency);
        	}else{
        		$('#from_currency').html(loan_currency);
        	}

        }

        $('#txt_new_status').val(0);

        $('#dtg_payment_history').datagrid('loadData', {'total':0,'rows':[]});
        $('#dtg_payment_history').datagrid({
            url:'',
        });
    }
}


function addNewRow(val){

	$('#txt_new_no').val(1);
	status_editor 	= 1;

	/*=========================== total loan funding ===============================*/
	var loan_value 		= parseFloat($('#txt_loan_amount').numberbox('getValue'));
	var cmb_bank 		= $('#cmb_bank').combogrid('getValue');

	if(cmb_bank !=""){
	    /*===================== alert jika loan funding belum di pilih ( atau jika loan value masih kosong) ==============*/
	    if(loan_value == "" || isNaN(loan_value)){
			$.messager.alert('Info','Piutang belum dipilih','error',function(){
				return false;
			});
		}
	    else if($('#txt_new_status').val() == 1){
	    	/*================= dalam satu transaksi payment hanya boleh 1 x ==========================*/
	    	/*================= variabel txt_new_status jika bernilai 1 berarti user telah menekan tombol addNew ==================*/

	    	$.messager.alert('Info','Tidak Boleh Memilih Lebih Dari Satu','error',function(){
				return false;
			});
	    }else{

	    	/*============ ubah value txt_new_status = 1, sebagai acuan user tidak boleh tekan tombol new lebih dari 1 dalam 1 transaksi ===============*/
	    	$('#txt_new_status').val(1);
	    	/*========================================================== end ==================================================================*/

	    	var txt_payment_for		= $('#txt_payment_for').val();
			var period 				= 1;
			var payment_perperiod1 	= 0;
			var payment_perperiod2 	= 0;
			var payment_balance 	= 0;
			var LPNumber 			= $('#txt_payment_no').val();
			var outstanding 		= $('#txt_outstanding_amount').numberbox('getValue');
	        
			var dg_rows = $('#dtg_payment_history').datagrid('getRows');

			for(var i=0; i<dg_rows.length; i++){

				/*============== calculate payment hhistory ===========================*/
				if(isNaN(dg_rows[i].PaymentPeriod)){ dg_rows[i].PaymentPeriod = 1; }
				if(isNaN(dg_rows[i].PaymentBalance)){ dg_rows[i].PaymentBalance = 0; }
				if(isNaN(dg_rows[i].PaymentPerPeriod1)){ dg_rows[i].PaymentPerPeriod1 = 0; }
				
				period = ++period;
				payment_perperiod1  += parseInt(dg_rows[i].PaymentPerPeriod1);
				payment_balance 	+= parseFloat(dg_rows[i].PaymentBalance);

				/*============ variabel new index nantinya di masukkan ke dalam variabel hide_new_index sebagai acuan row editing datagrid =================*/
				var newIndex = i+1;
				$('#hide_new_index').val(newIndex);
	        }

	        if(payment_balance != ""){

	        	/*================== jika total payment_perperiod == loan value (loan funding amount) kemudian alert bahwa pemyaran sudah balance ===================*/
				if(loan_value == payment_perperiod1){
					$.messager.alert('Info','Pembayaran piutang sudah balance');
					return false;
				}else{

					/*============ jika tidak maka buat row baru di datagrid payment ==============================*/
					if(val==false){
						$('#dtg_payment_history').datagrid('appendRow',{
							LoanPayment 	: loan_value,
		                    LPNumber		: LPNumber,
							PaymentPeriod 	: period
						});
					}else{
						$('#dtg_payment_history').datagrid('appendRow',{
							LoanPayment 		: loan_value,
		                    LPNumber			: LPNumber,
							PaymentPeriod 		: period,
							PaymentPerPeriod1 	: outstanding,
							PaymentBalance 		: 0
						});
					}
				}
			}
			else{

				/*================= jika payment balance = "", buat row baru ========================*/
				if(val==false){
					$('#dtg_payment_history').datagrid('appendRow',{
						LoanPayment 	: loan_value,
	                    LPNumber		: LPNumber,
						PaymentPeriod 	: period
					});
				}else{
					$('#dtg_payment_history').datagrid('appendRow',{
						LoanPayment 		: loan_value,
	                    LPNumber			: LPNumber,
						PaymentPeriod 		: period,
						PaymentPerPeriod1 	: outstanding,
						PaymentBalance 		: 0
					});
				}

				var dg_rows = $('#dtg_payment_history').datagrid('getRows');

				for(var i=0; i<dg_rows.length; i++){
					var newIndex = i;
				}

				/*============ variabel new index nantinya di masukkan ke dalam variabel hide_new_index sebagai acuan row editing datagrid =================*/
				$('#hide_new_index').val(newIndex);
			}

			var currency_payment 	= $('#currency_payment').val();
			var loan_currency 		= $('#currency_funding').val();

			/*========= jika loan currency = payment currency kemudian field PaymentPerPeriod1 focus editing, jika tidak field PaymentPerPeriod2 focus editing ========*/

			if(loan_currency == currency_payment){
				var ed = $('#dtg_payment_history').datagrid('beginEdit', newIndex);
				var ed2 = $('#dtg_payment_history').edatagrid('getEditor',{index:newIndex,field:'PaymentPerPeriod1'});
				$(ed2.target).focus();
			}else{
				var ed = $('#dtg_payment_history').datagrid('beginEdit', newIndex);
				var ed2 = $('#dtg_payment_history').edatagrid('getEditor',{index:newIndex,field:'PaymentPerPeriod2'});
				$(ed2.target).focus();
			}

			//call function for calculate payment if val==true
			if(val==true){
				calculate_payment();
			}
	    }
	}else{
		$.messager.alert('Info','Silahkan pilih Bank Payment terlebih dahulu');
		return false;
	}
}    	

function choose_loan_funding(val){
	var selected_data=$('#dtg_payment_list').datagrid('getSelected');
	if(selected_data.LFIsLock=='Locked'){
		$.messager.alert('Info','Tidak bisa memilih Transaksi yang di-Lock');
	}
	else{

		// var outstanding_string 			= selected_data.outstanding.toString();
		// var outstanding_arr 			= outstanding_string.split('.');
		// var outstanding_right 			= outstanding_arr[1];
		// var outstanding_left 			= outstanding_arr[0];
		// var outstanding_right_length 	= selected_data.outstanding.length;
		// var outStanding_amount 			= parseFloat(outstanding_string.substr);

		//var outstanding_amount 	=  Math.floor(parseFloat(selected_data.outstanding) * 100) / 100 ;
		var outstanding_amount 	=  selected_data.outstanding;

		status_editor 	= 0;
        $('#txt_new_status').val(0);
        $('#hide_new_index').val('');

        $('#currency_funding').val(selected_data.CurrencyCode);
        $('#rate_funding').val(selected_data.CurrencyRate);
        $('#lf_account').val(selected_data.LFAccount);
        $('#txt_loan_amount').numberbox('setValue',selected_data.LFAmount);
        $('#txt_outstanding_amount').numberbox('setValue',outstanding_amount);
        $('#txt_outstanding_amount_hidden').val(selected_data.outstanding);
        $('#txa_description').html(selected_data.LFDesc);
        
        $('#txt_payment_for').val(selected_data.LFNumber);

        $('#dtg_payment_history').datagrid('loadData', {'total':0,'rows':[]});
		$('#to_currency').html('IDR');
		$('#from_currency').html('');
		$('#amount_currency').html('');
		$('#currency_payment').val('');
		$('#txt_rate').numberbox('setValue','');
		$('#txt_amount_total').numberbox('setValue','');

		$('#cmb_bank').combogrid('setValue','');
		$('#cmb_bank').combogrid('grid').datagrid({
			url: '<?= base_url().$menu_link; ?>/get_bank_account/'+selected_data.CurrencyCode,
			onLoadSuccess:function(data){
				if(val==true){
					var DataBank = data.rows;
					$.each(DataBank,function(index,value){
						if(value.AccountNumber == selected_data.ReceiptAccount){
							var ValueBank = value.AccountNumber;
							$('#cmb_bank').combogrid('setValue',ValueBank);
							addNewRow(true);
							return;
						}
					});
				}
			}
		});

		/*======================== Hidden fields ========================================*/
		var dg 				= $('#dtg_payment_history');

		var Payment2 		= dg.datagrid('getColumnOption','PaymentPerPeriod2');
    	Payment2.hidden		= true;
    	Payment2.title 		= '';
    	Payment2.width 		= 180;
    	Payment2.editor.options.disabled 	= true;

    	var expense2 		= dg.datagrid('getColumnOption','ExpenseAmount2');
    	expense2.hidden		= true;
    	expense2.title 		= '';
    	expense2.width 		= 200;
    	expense2.editor.options.disabled 	= true;

    	/*================= end hidden fileds ===============================================*/

    	/*======================== show fields ==============================================*/

    	var Payment1 		= dg.datagrid('getColumnOption','PaymentPerPeriod1');
		Payment1.hidden		= false;
		Payment1.title 		= 'IDR';
		Payment1.colspan 	= '2';
		Payment1.width 		= 180;
		Payment1.editor.options.disabled  	= false;

    	var expense1 		= dg.datagrid('getColumnOption','ExpenseAmount1');
		expense1.hidden		= false;
		expense1.title 		= 'IDR';
		expense1.colspan 	= '2';
		expense1.width 		= 200;
		expense1.editor.options.disabled 	= false;

		/*======================= end show fields ==============================================*/

		$('#dtg_payment_history').datagrid({
            url:'',
        });

        modal_close('dialog-payment-list');
    }
}

function calculate_payment(){
	var payment_currency 	= $('#currency_payment').val();
	var loan_currency 		= $('#currency_funding').val();

    var newIndex 			= $('#hide_new_index').val();
	var dg_rows 			= $('#dtg_payment_history').datagrid('getEditors', newIndex);

	if(payment_currency == loan_currency){

		var loanPayment		= $(dg_rows[0].target);
		var payPerPeriod1	= $(dg_rows[2].target);
		var payBalance		= $(dg_rows[3].target);
		var expaccount		= $(dg_rows[4].target);
		var expamount1 		= $(dg_rows[6].target);

		var valExpense 		= expamount1.numberbox('getValue');
		var valExpAccount 	= expaccount.combobox('getValue');

		if(valExpAccount == ''){
			expamount1.numberbox('setValue',0);
		}else{
			if(valExpense == ''){
				expamount1.numberbox('setValue',0);
			}
		}

		var account  		= expaccount.combobox('getValue');
		var total_payment 	= parseFloat(payPerPeriod1.numberbox('getValue')) + parseFloat(expamount1.numberbox('getValue'));
		$('#total_expense').val(expamount1.numberbox('getValue'));

	}else{

		var loanPayment		= $(dg_rows[0].target);
		var payPerPeriod1	= $(dg_rows[2].target);
		var payPerPeriod2	= $(dg_rows[3].target);
		var payBalance		= $(dg_rows[4].target);
		var expaccount		= $(dg_rows[5].target);
		var expamount1 		= $(dg_rows[6].target);
		var expamount2		= $(dg_rows[7].target);

		var valExpAccount 		= expaccount.combobox('getValue');
		var valExpense1 		= expamount1.numberbox('getValue');
		var valExpense2 		= expamount2.numberbox('getValue');

		if(valExpAccount == ''){
			expamount1.numberbox('setValue',0);
			expamount2.numberbox('setValue',0);
		}else{
			if(valExpense1 == ''){
				expamount1.numberbox('setValue',0);
			}
			if(valExpense2 == ''){
				expamount2.numberbox('setValue',0);
			}
		}

		var account  		= expaccount.combobox('getValue');
		var total_payment 	= parseFloat(payPerPeriod2.numberbox('getValue')) + parseFloat(expamount2.numberbox('getValue'));
		$('#total_expense').val(expamount2.numberbox('getValue'));
	}

	$('#exp_account').val(account);
	$('#exp_amount').val(expamount1.numberbox('getValue'));
	$('#txt_amount').val(parseFloat(payPerPeriod1.numberbox('getValue')));
	$('#txt_amount_total').numberbox('setValue',total_payment);
	
	var cek = $('#dtg_payment_history').datagrid('getRows');

	$('#dtg_payment_history').datagrid('endEdit', newIndex);

	var OutStanding_amount 		= parseFloat($('#txt_outstanding_amount_hidden').val());
	var payment_perperiod 		= 0;

	for(var i=0; i<cek.length; i++){
		payment_perperiod = parseFloat(cek[i].PaymentPerPeriod1);
	}
	
	// if(OutStanding_amount < payment_perperiod){
	// 	$.messager.alert('Unseccessfull','Pembayaran melebihi sisa nilai pinjaman','error',function(){
	// 		$('#txt_amount_total').numberbox('setValue', 0);
	// 		$('#txt_amount').val('');
 //            $('#dtg_payment_history').datagrid('reload');
 //            $('#txt_new_status').val(0);
	// 		return false;
	// 	});
	// }
	// else{

		var newIndex2 		= $('#hide_new_index').val();

		$('#dtg_payment_history').datagrid('beginEdit', newIndex2);

		var dg_rows2 		= $('#dtg_payment_history').datagrid('getEditors', newIndex2);
		
		if(payment_currency == loan_currency){
			var payBalance		= $(dg_rows2[3].target);

		}else{

			var payBalance		= $(dg_rows2[4].target);
		}
		
		var countBalance	= OutStanding_amount - payment_perperiod;
		payBalance.numberbox('setValue', countBalance);
		
		$('#dtg_payment_history').datagrid('endEdit', newIndex2);

		status_editor 	= 0;
	// }
}

function cek_amount(value){
	var total = toAngka(value);
	$('#txt_amount_total').numberbox('setValue',total);
}

function save_data(){

	$('#dtg_payment_history').edatagrid('saveRow');

	var cek 				= $('#dtg_payment_history').datagrid('getRows');

	var total 				= parseFloat($("#txt_amount").val());	
	var OutStanding_amount 	= parseFloat($('#txt_outstanding_amount').numberbox('getValue'));

    var loan_payment 		= 0;
    var payment_perperiod 	= 0;
    var payment_period 		= 0;
	
    for(var i=0; i<cek.length; i++){
        if(isNaN(cek[i].LoanPayment)){ cek[i].LoanPayment = 0; }
        loan_payment 	= parseFloat(cek[i].LoanPayment);
        if(isNaN(cek[i].PaymentPerPeriod1)){ cek[i].PaymentPerPeriod1 = 0; }
        if(i==(cek.length-1)) 
        	payment_perperiod += parseFloat(cek[i].PaymentPerPeriod1);
        	payment_period 	  += 1;
    }
    
  
	if(total < 0.01){
		$.messager.alert('Unseccessfull','Transaksi Belum Lengkap','error');
		return false;
	// }
 //    else if(total > OutStanding_amount){		
 //        $.messager.alert('Unseccessfull','Pembayaran melebihi sisa nilai pinjaman','error',function(){
 //        	$('#txt_amount_total').numberbox('setValue','');
 //        	$('#txt_amount').val(0);
 //        	$('#dtg_payment_history').datagrid('reload');
 //            $('#txt_new_status').val(0);
 //        return false;
 //        });
	}	
    else if(payment_perperiod != total){
        $.messager.alert('Unseccessfull','Payment Per Period Tidak Sama Dengan Amount.','error',function(){
            $('#dtg_payment_history').datagrid('reload');
            $('#txt_new_status').val(0);
            return false;
        });
    }
	else {
		
        $('#dtg_payment_history').edatagrid('saveRow');
        var i=$('#dtg_payment_history').datagrid('getRows');
        var detail = JSON.stringify(i);
        $("#detail").val(detail);

        //save_transaction('<?php echo $menu_link; ?>', '#fm_loan_payment','1');

        var piutang_no   	= $('#txt_payment_for').val();

		checking_payment_save(piutang_no,payment_period,'LPay',function(check){
			
			if(check.status == false){
				save_transaction('<?php echo $menu_link; ?>', '#fm_loan_payment','1');
			}else{
				$.messager.alert('Unseccessfull',check.message,'error',function(){
					location.reload();
				});
			}
		});
		
	}

}
</script>