<!---- 
    Author 	: Wahyu
    Tanggal : 12-08-2014	
    Revisi 	: Daswan
-->
<?php
//---------Untuk privellege jika dia ada tombol save,suspen,jurnal----------
	if($group_user->SavePrivillage == 1){
		$cek_autority_save  = "";
	}
	else{
		$cek_autority_save 	= "disabled";
	}
	
	if($group_user->JournalPrivillage == 1){
		$cek_autority_journal  = "";
	}
	else{
		$cek_autority_journal 	= "disabled";
	}
	
	if($group_user->DeletePrivillage == 1){
		$cek_autority_delete  = "";
	}
	else{
		$cek_autority_delete 	= "disabled";
	}
	if($group_user->ReversePrivillage == 1){
        $cek_autority_reverse  = "";
    }
    else{
        $cek_autority_reverse    = "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">
                            <input type="checkbox" class="easyui-checkbox" name="chk_suspended" id="chk_suspended" style="margin-top:0px;margin-right:1px;" onclick="suspend_transaction(1,'<?= $menu_link;?>',$('#txt_payment_no').val(),'<?=$menu_label;?>')" <?=(!in_array($detail->TransStatus,array(5,6))) ? 'disabled' : ''?> <?=($detail->TransStatus) == 3 ? 'checked':''?> <?= $cek_autority_delete;?>/>
                            <span style="display:inline-block;margin-top:2px;<?=(($detail->TransStatus==3)?'color:gray;':'color:black')?>">Suspend</span>
							<a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="parent.tab_edit('Journal Loan Payment', '<?= $menu_link; ?>', 'icon-bank', 'to_journal',$('#txt_payment_no').val())" <?= $cek_autority_journal;?>>Journal</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="location.reload()">Refresh</a>
							
						</td>
						<td align="center" width="40%"><span id="approval_information">
		                <?php
		                if($detail->TransStatus == 5){
		                    echo get_status_approval_header($detail->TransStatus);
		                }
		                ?>
		                </span></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">
    <?php if($detail->TransStatus==2){ ?>
        <div class="blanket"></div>
        <div class="paid-box"><b>Paid</b></div>
    <?php }else if($detail->TransStatus==3){ ?>
    	 <div class="blanket"></div>
         <div class="suspend-box"><b>Suspended</b></div>
	<?php
	}
	?>
		<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">
				<!-- 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_payment_for_1" id="txt_payment_for_1" value="<?=  $detail->LFNumber; ?>" type="hidden" style="width:100px" />
								    <input name="txt_piutang_no" id="txt_piutang_no" value="<?= $detail->LFNumber; ?>" type="hidden" style="width:100px" />
								    <input name="txt_total_piutang" id="txt_total_piutang" value="<?= $total_piutang; ?>" type="hidden" style="width:100px" />
									
			                        <input type="hidden" id="hide_new_index" name="hide_new_index" />
			                        
			                        <input type="hidden" id="detail" name="detail" />
			                        <input type="hidden" id="total_balance" name="total_balance" />
			                        
			                        <input type="hidden" name="pay_period" id="pay_period" value="<?= $detail->PaymentPerPeriod;?>"/>
			                		<input type="hidden" name="pay_balance" id="pay_balance" value="<?= $detail->PaymentBalance;?>"/>
			                        <input type="hidden" name="trans_status" id="trans_status" value="<?= $detail->TransStatus;?>"/>
			                
			                        <td width="150"><b><label>Payment For</label></b></td>
								  	<td width="10"><b>:</b></td>
								  	<td>
										 <input name="txt_payment_for" id="txt_payment_for" value="<?=  $detail->LFNumber; ?>" class="disabled" type="text" style="width:200px" readonly/>	
									</td>
									<td valign="top" align="left">&nbsp;</td>
								</tr>
								<tr>
									<td width="150"><b><label>Transfer From</label></b></td>
								  	<td width="10"><b>:</b></td>
								  	<td>
			                           <select name="cmb_bank" class="combo-grid" editable="true" id="cmb_bank" required="required" style="width:405px;height:20px" data-options="
											value:'<?= $detail->BankAccount; ?>',
											panelWidth: 405,
											idField: 'AccountNumber',
											textField: 'AccountName',
											url: '<?= base_url().$menu_link; ?>/get_bank_account/<?=$detail->CurrencyFunding;?>',            
											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>
									<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" value="<?=$detail->ChequeNumber;?>" style="width:300px" <?=in_array($detail->TransStatus,array(1,2,3,9))?'disabled':'';?>>
		                            </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" <?php if($detail->TransStatus == 3 || $detail->TransStatus == 2 || $detail->TransStatus == 1) {echo "disabled";} ?>><?=  $detail->LPDesc; ?></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" class="easyui-numberbox" style="width:200px;" value="<?= $detail->CurrencyRate;?>"
                            			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">
                            			<?php 
                            				if($detail->CurrencyFunding == "IDR" and $detail->CurrencyPayment=='IDR'){
                            					echo $detail->CurrencyFunding;
                            				}elseif($detail->CurrencyFunding=='IDR' and $detail->CurrencyPayment!='IDR'){
                            					echo $detail->CurrencyPayment;
                            				}elseif($detail->CurrencyFunding!='IDR' and $detail->CurrencyPayment=='IDR'){
                            					echo $detail->CurrencyFunding;
                            				}else{
                            					echo $detail->CurrencyPayment;
                            				}
                            				
                            			?>
                            			</span> <span>TO</span> <span id="to_currency">IDR</span>
                            	</td>
								  
								  
							    </tr>
								<tr>
								  <td width="150"><b><label>Amount (<span id="amount_currency"><?=$detail->CurrencyCode;?></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" value='<?= ($detail->LPAmount + $detail->ExpAmount); ?>' style="width:405px;height:20px" readonly="true"
			                        data-options="
			                            min:0,
			                            precision:2,
			                            decimalSeparator:',',
			                            groupSeparator:'.'
			                        "
			                        />
			                        <?php
			                        	// if($detail->CurrencyFunding == 'IDR' and $detail->CurrencyPayment =='IDR'){
			                        	// 	$txt_amount 	= $detail->PaymentPerPeriod;
			                        	// }elseif($detail->CurrencyFunding == 'IDR' and $detail->CurrencyPayment != 'IDR'){
			                        	// 	$txt_amount 	= $detail->PaymentPerPeriod;
			                        	// }elseif($detail->CurrencyFunding !='IDR' and $detail->CurrencyPayment == 'IDR'){
			                        	// 	$txt_amount 	= $detail->PaymentPerPeriod;
			                        	// }elseif($detail->CurrencyFunding !='IDR' and $detail->CurrencyPayment!='IDR'){
			                        	// 	$txt_amount 	= $detail->PaymentPerPeriod;
			                        	// }
			                        ?>
			                        <input type="hidden" name="txt_amount" id="txt_amount" value="<?= ($detail->PaymentPerPeriod);?>">
									<input type="hidden" name="txt_new_no" id="txt_new_no" value="">
									<input type="hidden" name="lf_account" id="lf_account" value=" <?= $detail->LFAccount;?>">
									<input type="hidden" name="total_expense" id="total_expense" value="<?=$detail->ExpAmount;?>">
									<input type="hidden" name="currency_funding" id="currency_funding" value="<?=$detail->CurrencyFunding;?>">
									<input type="hidden" name="currency_payment" id="currency_payment" value="<?=$detail->CurrencyPayment;?>">
									<input type="hidden" name="rate_funding" id="rate_funding" value="<?=$detail->rate_funding;?>">
									<input type="hidden" name="exp_account" id="exp_account" value="<?= $detail->ExpenseAccount;?>">
									<input type="hidden" name="exp_amount" id="exp_amount" value="<?= $detail->ExpenseAmount;?>">
									
			                      </td>
								  
							    </tr>
							   				
							</table>
						</td>
						<td width="50%" valign="top">
	                        <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
	                        <tr height="20">
	                            <td rowspan="7" valign="top">&nbsp;</td>
	                            <td width="122">&nbsp;</td>
	                            <td width="190" style="background:#333399;text-align:center;color:#FFF;">Payment No.</td>
	                            <td width="122" style="background:#333399;text-align:center;color:#FFF;">Payment Date</td>
	                        </tr>
	                        <tr height="20">
	                        	<td>&nbsp;</td>
	                            <td><input type="text" name="txt_payment_no" id="txt_payment_no" value="<?= $detail->LPNumber; ?>" class="easyui-validatebox" style="width:190px;height:18px;text-align:center;" required readonly  /></td>
	                            <td><input type="text" name="txt_payment_date" id="txt_payment_date" class="easyui-datebox validBackward" style="width:122px;height:22px" required editable="false" value="<?= convert_to_dmy($detail->LPDate);?>" readonly></td>
	                        </tr>
	                        </table>
	                        <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:1px;">
	                        <tr height="20">
	                            <td rowspan="7" valign="top">&nbsp;</td>
	                            <td width="122">&nbsp;</td>
	                            <td width="190" style="background:#333399;text-align:center;color:#FFF;">Loan Amount</td>
	                            <td width="122" style="background:#333399;text-align:center;color:#FFF;">Outstanding Amount</td>
	                        </tr>
	                        <tr height="20">
	                        	<td>&nbsp;</td>
	                            <td><input type="text" name="txt_loan_amount" id="txt_loan_amount" value="<?= $detail->LoanPayment; ?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="width:190px;height:22px;text-align:right;" readonly  /></td>
	                            <td><input type="text" name="txt_outstanding_amount" id="txt_outstanding_amount" value="" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="width:122px;height:22px;text-align:right" readonly></td>
	                        	<input name="txt_outstanding_amount_hidden" id="txt_outstanding_amount_hidden" value="<?=$detail->Outstanding_amount;?>" type="hidden" style="text-align:right;width:200px;height:22px" readonly/>
	                        </tr>
	                        </table>
	                        <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:1px;">
	                        <tr height="20">
	                            <td rowspan="7" valign="top">&nbsp;</td>
	                            <td width="122">&nbsp;</td>
	                            <td width="190" style="background:#333399;text-align:center;color:#FFF;"><b>Availabel Balance (<span class='bank_balance_currency'></span>)</b></td>
	                        </tr>
	                        <tr height="20">
	                        	<td>&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;height:18px;width:316px" readonly /></td>
	                        </tr>
	                        </table>
	                    </td>
					</tr>
				</table>

                <table id="dtg_payment_history" class="easyui-<?=(in_array($detail->TransStatus,array(0,1,2,5)))?'edatagrid':'datagrid'?>"
				title="Payment History" idField="id" 
				url="<?= base_url().$menu_link; ?>/get_payment_periode/<?= $detail->LPNumber; ?>/<?= $detail->PaymentPeriod; ?>/<?=$detail->CurrencyPayment;?>"
				rownumbers="true" fitColumns="true" singleSelect="true" style="height:290px;"
				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 payment afiliasi','error',function(){	
			                	$('#dtg_payment_history').datagrid('reload');
			                	$('#txt_new_status').val(0);
			                });
			             }
			        },
			        onBeforeLoad:function(){
						$('#dtg_payment_history').datagrid('loadData', {'total':0,'rows':[]});
					},
			        onBeginEdit:function(rowIndex){

			        	save_button_begendedit('<?=$group_user->SavePrivillage;?>');

			        	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 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:100,halign:'center',align:'center', editor:{type:'numberbox',options:{min:0.01,precision:2,decimalSeparator:',',required: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',
                                    required:false,
                                    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>
                             <th rowspan="2" data-options="field:'LPDetailID',width:75,halign:'center',align:'right'" hidden="true">LPDetailID</th>
						</tr>
						<tr>
							<?php if($detail->CurrencyFunding == $detail->CurrencyPayment):?>
								<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}}"><?=$detail->CurrencyFunding;?> </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}}" ><?=$detail->CurrencyFunding;?></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>
							<?php else:?>
								<th colspan="1" 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:true}}"><?=$detail->CurrencyFunding;?> </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:false}}"><?=$detail->CurrencyPayment;?> </th>
								
								<th colspan="1" formatter="formatRp" data-options="field:'ExpenseAmount1',width:150,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',disabled:true}}" ><?=$detail->CurrencyFunding;?></th>
	                            <th formatter="formatRp" data-options="field:'ExpenseAmount2',width:150,halign:'center',align:'right', editor:{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',disabled:false}}"><?=$detail->CurrencyPayment;?></th>
							<?php endif;?>
						</tr>
					</thead>
				</table>
                
			</form>
		</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 app-button" iconCls="icon-ok" onclick="app_dir()" <?= (($this->session->userdata("jobtitle_status") != 0 || !in_array($detail->TransStatus, array(5,6))) || (date('Y-m-d') < date('Y-m-d', strtotime($detail->LPDate))))?'disabled':'' ?>>App. Dir</a>
			 		 <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-reload" onclick="app_reverse()" <?=(in_array($detail->TransStatus,array(1,2,9)))?'':'disabled'?> <?= $cek_autority_reverse;?>>Reverse</a>
			 		 <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="update_loan_payment()" <?=(in_array($detail->TransStatus,array(0,1,2,3)))?'disabled':''?> <?= $cek_autority_save;?>>Save</a> 								
			 	 	 <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="parent.tab_edit('Print Loan Payment', '<?=$menu_link?>', 'icon-print', 'to_print_detail','<?= $detail->LPNumber;?>');" <?=(in_array($detail->TransStatus,array(4,5,6,1,2,3,9)))?'':'disabled'?>>Preview & Print</a>  
			 		 <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="<?=($this->session->userdata('jobtitle_status')==0)?'suspend(2)':'parent.tab_close(\'tt\')'?>" <?=(!in_array($detail->TransStatus,array(0,5,6)))?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
                </td>
             </tr>
        </table>				
    </div>
</div>
<!-- Dialog Payment List -->
<div id="dialog-payment-list" class="easyui-dialog" style="width:595px; left:150px; top:50px; background-color:#F8F8F8; height:300px; padding: 0 0px 0 0px" closed="true" data-options="modal:true" buttons="#dialog-buttons">
	<table id="dtg_payment_list" class="easyui-datagrid"  style="width:580px;" 
        url="<?= base_url(); ?><?= $menu_link; ?>/get_piutang"
        singleSelect="true"
        idField="" >
		<thead>
			<th field="BranchName" width="120" align="center">Branch</th>
			<th field="AccountName" width="250" align="center">Loan Account</th>
			<th field="LFNumber" hidden="true" width="50" align="center">No Piutang</th>
			<th field="LFAmount" formatter="formatRp" width="135" align="right" halign="center">Amount</th>
            <th field="outstanding" width="130" formatter="formatRp" align="right" halign="center">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>
		</thead>
	</table>
	<div id="dialog-buttons">
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_loan_funding()">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_date').datebox('setValue', '<?= date("d-m-Y", strtotime($detail->LPDate));?>');
       
    $('#fm_loan_payment').click(function(){
    	if(status_editor == 1){
			calculate_payment();
		}
    });

    var currency_code 		= '<?= $detail->CurrencyCode;?>';
    var currency_funding 	= '<?=$detail->CurrencyFunding;?>';
    var AccountNumber		= '<?= $detail->BankAccount; ?>';
    get_bank_balance(AccountNumber,currency_code); 

	if(currency_code == 'IDR' && currency_funding=='IDR'){
		$('#txt_rate').prop('readonly',true);
	}else{
		$('#txt_rate').prop('readonly',false);
	}

	/*============================= hitung outstanding amount ===================================*/
	var val_outstanding 	= '<?=$detail->Outstanding_amount;?>';
	var outstanding_amount 	=  Math.floor(parseFloat(val_outstanding) * 100) / 100 ;
	$('#txt_outstanding_amount').numberbox('setValue',val_outstanding);
	/*============================= end hitung outstanding amount ===============================*/

	$('#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 item 				= $('#dtg_payment_history').datagrid('getRows');
    var indexRow 			= item.length - 1;

	if(indexRow >= 0){

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

			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{
		alert(indexRow);
	}
}

function eventCMBSelect(accountnumber,currency){

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

	$('.app-button').linkbutton('disable');

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

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

		status_editor 	= 0;

		$('#txt_amount_total').numberbox('setValue',0);
		$('#txt_amount').val(0);

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

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

	    }else{

	    	$('#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('IDR');
        	}else{
        		$('#from_currency').html(loan_currency);
        	}

        }

        $('#txt_new_status').val(0);
        
        var piutang_no = $('#txt_payment_no').val();
        var no_trans 	= piutang_no.replace(/\//g,"__");

        $('#dtg_payment_history').datagrid({
            url:'<?php echo base_url(); ?><?php echo $menu_link; ?>/get_history_payment/'+no_trans+'/'+currency+'/'+1,
            onLoadSuccess:function(data){
            	var Data 		= data.rows;
            	var TotalData 	= Data.length;
            	if(TotalData > 0){
            		if(loan_currency == currency){
            			$('#dtg_payment_history').datagrid('updateRow',{
							index: (TotalData-1),
							row: {
								PaymentBalance: 0,
								PaymentPerPeriod1: 0,
								ExpenseAmount1: 0,
							}
						});
            		}else{
            			$('#dtg_payment_history').datagrid('updateRow',{
							index: (TotalData-1),
							row: {
								PaymentBalance: 0,
								PaymentPerPeriod1: 0,
								PaymentPerPeriod2: 0,
								ExpenseAmount1: 0,
								ExpenseAmount2: 0,
							}
						});
            		}
            		get_master_rate(currency);
            	}
            }
        });
    }
}

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

    var TotalItem 			= $('#dtg_payment_history').datagrid('getRows');
    var newIndex 			= TotalItem.length - 1;
	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{

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

		var dg_rows2 		= $('#dtg_payment_history').datagrid('getEditors', newIndex);
		
		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', newIndex);

		status_editor 	= 0;
	// }
}

function update_loan_payment(){

	$('#dtg_payment_history').edatagrid('saveRow');
	var cek = $('#dtg_payment_history').datagrid('getRows');
    var loan_payment 		= 0;
    var payment_perperiod 	= 0;
    var amount 				= parseFloat($("#txt_amount").val());
    
    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);
    }
   	
    // if(payment_perperiod > loan_payment){
    //     $.messager.alert('Unseccessfull','Pembayaran melebihi sisa nilai pinjaman','error',function(){
    //         $('#dtg_payment_history').datagrid('reload');
    //         return false;
    //     });
    // }
    //else 
    if(payment_perperiod != amount){
        $.messager.alert('Unseccessfull','Payment Per Period Tidak Sama Dengan Amount.','error',function(){
            $('#dtg_payment_history').datagrid('reload');
            return false;
        });
    }
    else{

        var login_as        = "<?= $this->session->userdata('username');?>";
	    var created_by      = "<?= $detail->CreatedBy;?>";
	    var depart_by       = "<?= $detail->DepartmentCode;?>";
		var depart_ses      = "<?= $this->session->userdata('department');?>";
		var jobtitle_status = "<?= $this->session->userdata('jobtitle_status');?>";

	    var no_transaksi    = $('#txt_payment_no').val();
	    var status          = '<?= $detail->TransStatus;?>';
	

	    $('#dtg_payment_history').edatagrid('saveRow');
        var i=$('#dtg_payment_history').datagrid('getRows');
        var detail = JSON.stringify(i);
        $("#detail").val(detail);

	    checking_update(no_transaksi,status,function(check){
        
	        if(check.status == true){

	        	$('#dtg_payment_history').edatagrid('saveRow');
		        var i=$('#dtg_payment_history').datagrid('getRows');
		        var detail = JSON.stringify(i);
		        $("#detail").val(detail);
	            edit_data('<?=$menu_link?>','#fm_loan_payment',created_by,login_as,depart_by,depart_ses,jobtitle_status);

	        }else{
	            $.messager.alert('Unseccessfull',check.message,'error',function(){
	                location.reload();
	            });
	        }

	    });
    }
}

function app_dir(){

	var no_transaksi    = $('#txt_payment_no').val();
  

    //approved_dir('<?=$menu_link?>','#fm_loan_payment');

    checking_approval(no_transaksi,function(check){
        
        if(check.status == false){
             approved_dir('<?=$menu_link?>','#fm_loan_payment');
        }else{
            $.messager.alert('Unseccessfull',check.message,'error',function(){
                location.reload();
            });
        }
    });
		
}

function app_reverse(){
	var no_transaksi    = $('#txt_payment_no').val();
    var url             = '<?= base_url();?>custom/custom/checking_reverse';

    checking_reverse(no_transaksi,function(check){
        if(check.status == true){
            reversed_data('F','<?=$menu_link?>',no_transaksi, 'Payment Karyawan');
        }else{
           $.messager.alert('Unseccessfull',check.message,'error',function(){
                location.reload();
            });
        }
    });
}

function suspend(type){
    var created_by      = '<?php echo $detail->CreatedBy;?>';
    var login_as        = '<?php echo$this->session->userdata('username');?>';
    var job_title       = '<?php echo $this->session->userdata('jobtitle_status');?>';
    var url             = '<?= base_url();?>custom/custom/checking_suspend';
    
    suspend_check_trans('F', type, '<?=$menu_link?>', $('#txt_payment_no').val(), '<?=$menu_label;?>', url, created_by, login_as, job_title);
}

</script>