<!---- 
    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;?>',$('#SJrnNumber').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 Sales Journal', '<?= $menu_link; ?>', 'icon-bank', 'to_journal',$('#SJrnNumber').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">
    	<div id="form-wrapper" class="easyui-panel"  style="width:1180px;height:526px;padding:5px;" fit='true'>
        	<?php if(in_array($detail->TransStatus,array(2,3,9,8))){ ?>
        	<div class="blanket"></div>
            <div class="status-box"><b><?php if($detail->TransStatus==2){ echo 'Finished'; }elseif($detail->TransStatus==3){ echo 'Suspended'; }elseif($detail->TransStatus==9){ echo 'Canceled by Dir.'; }elseif($detail->TransStatus==8){ echo 'Suspended Item'; }else{ echo 'Unknown'; } ?></b></div>
            <?php } ?>
			<form id="fm_sales_journal" name="fm_sales_journal" method="post">
                <table cellpadding="0" cellspacing="3" width="100%" height="100%" border="0">
					<tr>
                    	<td width="143"><b>Customer</b></td>
                        <td width="10"><b>:</b></td>
                        <td colspan="5">
                            <select class="easyui-combogrid" id="cmb_customer" readonly
                                name="cmb_customer" required="required" 
                                style="width:230px;height:20px;" 
                                data-options="
                                	value:'<?=$detail->CustomerCode?>',
                                    panelWidth: 329,
                                    idField: 'CustomerCode',
                                    textField: 'CustomerName',
                                    url: '<?php echo base_url(); ?>custom/get_data/customer_with_rate',
                                    method: 'get',
                                    columns: [[
                                    {field:'CustomerCode',title:'Customer Code',width:110},
                                    {field:'CustomerName',title:'Customer Name',width:190}
                                    ]],
                                    fitColumns: true
                                "
                            >
                            </select>
                             <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-sales" onclick="modal_open('Payment List','dialog-payment-list')" style="width:110px;" plain="true" disabled>List Invoice</a> 
                        </td>
                        <td align="left" valign="middle">&nbsp;</td>
						<td rowspan="6" align="left" valign="top">
							<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
								<tr>
									<td align="right" valign="top">
										<table cellpadding="0" cellspacing="1" width="100%" border="0">
											<tr>
												<td height="20">&nbsp;</td>
												<td width="190" align="center" valign="middle" bgcolor="#333399"><span style="color: #fff">SJournal No.</span></td>
												<td width="122" align="center" valign="middle" bgcolor="#333399"><span style="color:#fff;">SJournal Date</span></td>
											</tr>
											<tr>
												<td>&nbsp;</td>
												<td height="20" align="left" valign="top">
												<input type="text" name="SJrnNumber" id="SJrnNumber" value="<?=$detail->SJrnNumber;?>" class="easyui-validatebox" style="width:190px;background-color:#E3E2E2;text-align:center;" required readonly />
												</td>
												<td align="right" valign="top"><input name="txt_payment_date" value="<?= date("d-m-Y", strtotime($detail->SJrnDate)) ?>" id="txt_payment_date" type="text" class="easyui-datebox validBackward" style="width:122px;height:20px" required editable="false"/></td>
											</tr>
										</table>
									</td>
								</tr>
							</table>
						</td>
					</tr>	
                    <tr>
						<td valign="middle" height="22" width="180" align="left"><b>Payment for</b></td>
                        <td><b>:</b></td>
						<td valign="top" align="left" width="800">
							<input name="txt_payment_for" id="txt_payment_for" type="text" style="width:230px;background-color:#E3E2E2;" value="<?=$detail->SInvNumber;?>" 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 Funding</a> -->
						</td>
                    </tr>				
					<tr>
						<td valign="top" height="51" align="left" style="padding-top:4px;"><b>Memo</b></td>
                        <td valign="top" style="padding-top:4px;"><b>:</b></td>
						<td valign="top" align="left">
							<textarea class="textbox" name="txa_memo" id="txa_memo" rows="4" style="width:362px;resize:none;white-space:normal;"><?=$detail->SJrnDesc;?></textarea>
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr style="display:none">
						<td height="22" valign="top" align="left"><b>Rate</b></td>
                        <td width="10"><b>:</b></td>
						<td valign="top" height="22" align="left">
							<input name="txt_rate" id="txt_rate" type="text" value="<?=$detail->CurrencyRate;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" autoComplete="off" style="width:200px;" required="required" />
							<strong>Currency :</strong> <span id="from_currency"><?=$detail->CurrencyCode;?></span> <span>TO</span> <span id="to_currency">IDR</span>
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr>
						<td height="22" valign="top" align="left"><b>Invoice Owing</b></td>
                        <td width="10"><b>:</b></td>
						<td valign="top" height="22" align="left">
							<input name="owing_amount" id="owing_amount" type="text" value="<?=$detail->SJrnAmount;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:185px;" required="required" />
							~ <input name="txt_equal_invoice"  	 id="txt_equal_invoice" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:162px;" value="<?=$convert_amount;?>" required="required" />
                            
				            
							<input name="txt_amount" id="txt_amount" type="hidden" value="<?=$detail->SJrnAmount;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:362px;" />
							<input type="hidden" id="detail" name="detail" value=""/>
							<input type="hidden" id="fiscal_rate" name="fiscal_rate" value="<?=$detail->InvoiceFiscalRate;?>"/>
							<input type="hidden" id="inv_rate" name="inv_rate" value="<?=$detail->InvoiceCurrRate;?>"/>
							<input type="hidden" id="currency_code" name="currency_code" value="<?=$detail->CurrencyCode;?>"/>
							<input type="hidden" id="type_fiscal" name="type_fiscal" value="<?=$detail->InvoiceType;?>"/>
							<input type="hidden" id="customer_code" name="customer_code" value="<?=$detail->CustomerCode;?>"/>
							<input type="hidden" id="detail_id" name="detail_id" value=""/>
							
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr height="20" style="display:none">
                        <td width="150" align="left"><b>Bank Balance (<span class='bank_balance_currency'></span>)</b></td>
                        <td width="10"><b>:</b></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:362px" readonly />
                        </td>
                    </tr>					
				</table>
                
                <!-- Item Grid -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div title="Item">
                        <table toolbar="#tb_dtg_loan_payment" id="dtg_payment_history" 
                        class="easyui-edatagrid" title="Payment History" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" style="height:250px;"
                        url="<?=base_url().$menu_link;?>/get_history_payment/<?= str_replace('/','__',$detail->SJrnNumber);?>/<?=$detail->CurrencyCode;?>/<?=$detail->InvoiceType;?>"
                        data-options = "
                        	onBeginEdit:function(rowIndex){
								save_button_begendedit('<?=$group_user->SavePrivillage;?>');

								editors = $('#dtg_payment_history').datagrid('getEditors',rowIndex);
								var account_name	= $(editors[0].target);
                                var CurrCode        = $(editors[1].target);
                                var RecAmount       = $(editors[2].target);
                                var JrnRate         = $(editors[3].target);
                                var PrimeAmount     = $(editors[4].target);
                                var Memo            = $(editors[5].target);

                                /*================= Currency COde Customer ===============================*/
                                var CurrCustCode    = $('#currency_code').val();
                                /*========================================================================*/

                                /*================= Currency Code Account ===============================*/
                                var CurrAccountCode = CurrCode.val();
                                /*========================================================================*/

                                var type_fiscal     = index_tab;

                                if(type_fiscal == 1 || CurrCustCode == 'IDR'){
                                    if(CurrAccountCode == 'IDR'){
                                        $(JrnRate).prop('readonly',true);
                                    }
                                }
								
                                $(CurrCode).prop('readonly',true);
                                $(PrimeAmount).prop('readonly',true);
                                $(account_name).prop('readonly',true);
                                $(account_name).click(function(){
                                    open_list_gl(rowIndex);
                                }).mouseover(function(){
                                    $(this).css('cursor','pointer'); 
                                });

                                $(RecAmount).change(function(){
                                    if(CurrCustCode != 'IDR'){
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val()); 
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val());
                                            } 
                                        }
                                    }else{
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val());
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val());
                                            } 
                                        }
                                    }

                                   $(PrimeAmount).numberbox('setValue', PrimeAmount_Con);
                                   
                                });  

                                $(JrnRate).change(function(){
                                    if(CurrCustCode != 'IDR'){
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            } 
                                        }
                                    }else{
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            } 
                                        }
                                    }

                                    $(PrimeAmount).numberbox('setValue', PrimeAmount_Con);
                                });  
					          
							},
							onEndEdit:function(){
								save_button_endedit('<?=$group_user->SavePrivillage;?>');
							}
                        "
                        >
                            <thead>
                                <tr>
                                	<?php if($detail->TransStatus == 5):?>
	                                	<th data-options="field:'SJrnDetailID',halign:'center',align:'left',width:200" hidden="true">ID</th>
	                                	<th data-options="field:'AccountHutang',halign:'center',align:'left',width:200" hidden="true">Account Hutang</th>
	                                	<th align="center" valign="middle" data-options="field:'GLAccount',width:200,align:'left'" editor="{type:'AccountName',options:{required:true}}">GL Account</th>
	                                    <th align="center" valign="middle" data-options="field:'CurrencyCode',width:80,align:'left'"  editor="{type:'text',options:{required:true}}">Currency</th>
	                                    <th data-options="field:'PaymentAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Receipt Amount</th>
	                                    <th data-options="field:'SJrnRate',width:150,halign:'center',align:'right',editor:{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Rate</th>
	                                    <th data-options="field:'PrimeAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',disabled:'true',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Equal(~)</th>
	                                    <th data-options="field:'Memo',halign:'center',align:'left',width:250,editor:{type:'text'}">Memo</th>
                                	<?php else:?>
	                                	<th data-options="field:'SJrnDetailID',halign:'center',align:'left',width:200" hidden="true">ID</th>
	                                	<th data-options="field:'AccountHutang',halign:'center',align:'left',width:200" hidden="true">Account Hutang</th>
	                                	<th align="center" valign="middle" data-options="field:'GLAccount',width:200,align:'left'" editor="{type:'AccountName',options:{required:true}}">GL Account</th>
	                                    <th align="center" valign="middle" data-options="field:'CurrencyCode',width:80,align:'left'"  editor="{type:'text',options:{required:true}}">Currency</th>
	                                    <th data-options="field:'PaymentAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',disabled:true,options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Receipt Amount</th>
	                                    <th data-options="field:'SJrnRate',width:150,halign:'center',align:'right',editor:{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Rate</th>
	                                    <th data-options="field:'PrimeAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',disabled:'true',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Equal(~)</th>
	                                    <th data-options="field:'Memo',halign:'center',align:'left',width:250,editor:{type:'text',disabled:true}">Memo</th>
                                	<?php endif;?>
                                </tr>
                            </thead>
                        </table>
                        
                        <div id="tb_dtg_loan_payment">
                            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row()">Delete</a>							
                        </div>
                    </div>
                </div>
                <!-- End of item grid -->
            </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->SJrnDate))))?'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="save_me()" <?=(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 Journal', '<?=$menu_link?>', 'icon-print', 'to_print_detail','<?= $detail->SJrnNumber;?>');" <?=(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>

<!--  Tagor Dialog Payment AccountName -->
<div id="dialog-gl-account" class="easyui-dialog" style="width:850px;height:523px;top:27px;background-color:#F8F8F8;padding:0px" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-buttons-account-payment">
    <table width="100%" align="left" border="0">
        
        <tr>
            <td><b>Account Number</b></td>
            <td width="10"><b>:</b></td>
            
            <td>
                <input type="text" style="width:705px;height:20px" name="txt_AccountNumber" id="txt_AccountNumber" class="easyui-validatebox" placeholder="Account Number" onkeyup="get_account_gl();" />
            </td>
        </tr>
        
        <tr>
            <td><b>Account Name</b></td>
            <td><b>:</b></td>
        
            <td>
                <input type="text" style="width:705px;height:20px" name="txt_AccountName" id="txt_AccountName" class="easyui-validatebox" placeholder="Account Name" onkeyup="get_account_gl();" />
            </td>
        </tr>
        
        <tr>
            <td colspan="3">
                <table id="tt_choose_payment" class="easyui-datagrid" singleSelect="true"  rownumbers="true" style="width:828px;height:387px;"
                    pageSize="150" 
                    data-options = "border:true,view:scrollview,autoRowheight:false" 
                >
                    <thead>
                        <tr bgcolor="">
                           	<th field="AccountNumber" width="150" sortable="true" formatter="format_acc">Account Number</th>
                            <th field="AccountName" width="304" sortable="true" formatter="format_acc">Account Name</th>
                            <th field="SubtypeName" width="300" sortable="true" >Type Name</th>
                            <th field="CurrencyCode" width="460" sortable="true" hidden="true">Currency Code</th>
                            <th field="AccountLevel" width="460" sortable="true" hidden="true">Account Level</th>
                        </tr>
                    </thead>
                </table>
            </td>
        </tr>
    </table>
</div>

<!-- Dialog Button -->
<div id="dialog-buttons-account-payment">
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_account_gl();">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-gl-account');">Cancel</a>
</div>



<script type="text/javascript">

	var SavePrivillage 	= '<?=$group_user->SavePrivillage;?>';
	var array_item 		= [];
	var indChoAccount   = 0;
	var index_tab 		= 0;

	$(document).ready(function(){

		index_tab = $('#type_fiscal').val();

		$('#fm_sales_journal').click(function(){
			calculate_amount();
			var rownumbers = $('.datagrid-cell-rownumber').length;
			for(var x = 0; x < rownumbers; x++){
				$('.datagrid-cell-rownumber').eq(x).html(x+1);
				
			}
	    });

	    $('#tab_invoice').tabs({
	    	onSelect:function(titel,index){
	    		index_tab = index;
	    	}
	    });

	    var CurrencyCode = '<?=$detail->CurrencyCode;?>';
	    if(CurrencyCode == 'IDR'){
	    	$('#txt_rate').numberbox({'disabled':true});
	    }
		
		search_account('<?php echo $detail->CurrencyCode;?>');
		
	    $('#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 Sales Invoice','list/sales_invoice', 'icon-edit', 'edit',TransNumber) ;
	    });

	});
	
	function search_account(CurrencyCode){
		$('#tt_choose_payment').datagrid({
			url: '<?= base_url().$menu_link; ?>/get_gl_account/'+CurrencyCode
		});
	}
	
	function format_acc(val,row){
		return '<span style="padding-left:'+row.AccountLevel+'em;">'+val+'</span>';	
	}

	//function addNewRow(){
//
//		var no_piutang 			= $('#txt_payment_for').val();
//		// var hutang_name 		= $('#hutang_name').val();
//		var row 				= $('#dtg_payment_history').datagrid('getRows');
//		$('#dtg_payment_history').datagrid('endEdit', (row.length - 1));
//
//		/*======================== tambahkan 1 row ke datagrid payment history ===============================*/
//		if(no_piutang == ''){
//			$.messager.alert('Warning','Silahkan pilih Invoice terlebih dahulu','Warning');
//		}else{
//
//            var CurrencyCode = $('#currency_code').val();
//            var master_rate  = $('#txt_rate').numberbox('getValue');
//            
//			$('#dtg_payment_history').datagrid('appendRow',{
//				PaymentAmount 		: 0,
//				GainAccount 		: '',
//                SJrnRate            : master_rate,
//                CurrencyCode        : CurrencyCode,
//    		});
//
//			$('#dtg_payment_history').datagrid('beginEdit', (row.length - 1));
//		}
//
//	}

	function remove_row(){
		var row 			= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row.length - 1));

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

	    var selectedrow         = $('#dtg_payment_history').datagrid('getSelected');
	    var row_index           = $('#dtg_payment_history').datagrid('getRowIndex', selectedrow);

	    if(row.length >1){
	    
		    $.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.GLAccount + '"?',  
		        function(r){
		            if (r){
		            	array_item.push(selectedrow.SJrnDetailID);
		                $('#dtg_payment_history').datagrid('deleteRow', row_index);
		                calculate_amount();
		            }
		        }
		    );
		}else{
			$.messager.alert('Warning','Payment transaksi minimal 1.','error',function(){

			});
		}
	}

	function calculate_amount(){

		var row 			= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row.length - 1));

		/*===================== save row & get all rows =======================*/
		$('#dtg_payment_history').edatagrid('saveRow');	
		var row_payment 	= $('#dtg_payment_history').datagrid('getRows');
        var CurrCustCode    = $('#currency_code').val();

		var total_piutang  	= parseFloat($('#owing_amount').numberbox('getValue'));
		var total_payment 	= 0;

		/*============== looing item datagrid payment history ===================*/
		$.each(row_payment, function( index,value){
	        total_payment 	+= convert_payment(index_tab,CurrCustCode,value.CurrencyCode,value.PaymentAmount,value.SJrnRate);
	    });

        total_payment   = Number(total_payment.toFixed(2));
        total_piutang   = Number(total_piutang.toFixed(2));

	    if(total_payment > total_piutang){
	    	$.messager.alert('Warning','Pembayaran melebihi sisa nilai pinjaman','error',function(){
				$('#txt_amount').numberbox('setValue',0);
			});
	    }else{
	    	$('#txt_amount').numberbox('setValue',total_payment);
	    }
	}

	function convert_payment(type_fiscal,CurrCustCode,CurrAccountCode,Amount,rate){
        if(CurrCustCode != 'IDR'){
            if(type_fiscal != 1){
                if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount);
                }else{
                    return parseFloat(Amount) / parseFloat(rate);   
                }
            }else{
               if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount) * parseFloat(rate);
                }else{
                    return parseFloat(Amount);
                } 
            }
        }else{
            if(type_fiscal != 1){
                if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount) * parseFloat(rate);
                }else{
                    return parseFloat(Amount);   
                }
            }else{
               if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount) * parseFloat(rate);
                }else{
                    return parseFloat(Amount);
                } 
            }
        }
    }

	function save_me(){

		/*===================== save row & get all rows =======================*/
		$('#dtg_payment_history').edatagrid('saveRow');	

		var row_payment 	= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row_payment.length - 1));

		var total_payment  	= 0;
		var owing_amount 	= parseFloat($('#owing_amount').numberbox('getValue'));
        var CurrCustCode    = $('#currency_code').val();

		/*============== looing item datagrid payment history ===================*/
		$.each(row_payment, function( index,value) {
	        total_payment 	+= convert_payment(index_tab,CurrCustCode,value.CurrencyCode,value.PaymentAmount,value.SJrnRate);
	    });

        var sisa_owing      = owing_amount - total_payment;
        var limit_owing     = calculate_amount_pembulatan();

	    if(sisa_owing < 0){
	    	$.messager.alert('Unseccessfull','Pembayaran melebihi Invoice owing','error',function(){
				$('#txt_amount').numberbox('setValue',0);
				$('#dtg_payment_history').datagrid('reload'); 
			});
	    }else{

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

	    	if(total_payment > 0){
                //if(sisa_owing <= limit_owing){
                if((sisa_owing >= -0.01) && (sisa_owing <= 0.01 )){

	    			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    = $('#SJrnNumber').val();
				    var status          = '<?= $detail->TransStatus;?>';
				    
				    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);
					        var detail_id 	= JSON.stringify(array_item);
					        $("#detail").val(detail);
					        $("#detail_id").val(detail_id);

				            edit_data('<?=$menu_link?>','#fm_sales_journal',created_by,login_as,depart_by,depart_ses,jobtitle_status);

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

				    });	

				}else{
					$.messager.alert('Unseccessfull','Total Payment Amount harus sama dengan Invoice Owing.','error',function(){
					
					});
				}
			}else{
				$.messager.alert('Unseccessfull','Belum ada detail transaksi payment.','error',function(){

				});
			}
	    }
	}

	function calculate_amount_pembulatan(){
        var row                 = $('#dtg_payment_history').datagrid('getRows');
        var total_row           = row.length;
        var total               = 0;
        var CurrCustCode        = $('#currency_code').val();
        var owing               = parseFloat($('#owing_amount').numberbox('getValue'));

        /*============== looing item datagrid payment history ===================*/
        $.each(row, function( index,value){
            if((index+1)<total_row){
                total   += convert_payment(index_tab,CurrCustCode,value.CurrencyCode,value.PaymentAmount,value.SJrnRate);
            }else{
                var Amount          = owing - total;
                var PaymentAmount   = value.PaymentAmount;
                var CurrAccountCode = value.CurrencyCode;
                var rate            = value.SJrnRate;
                var sisa            = 0;
                var type_fiscal     = index_tab;

                if(CurrCustCode != 'IDR'){
                    if(type_fiscal != 1){
                        if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount);
                        }else{
                            sisa = parseFloat(Amount) * parseFloat(rate);   
                        }
                    }else{
                       if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount) / parseFloat(rate);
                        }else{
                            sisa = parseFloat(Amount);
                        } 
                    }
                }else{
                    if(type_fiscal != 1){
                        if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount) / parseFloat(rate);
                        }else{
                            sisa = parseFloat(Amount);   
                        }
                    }else{
                       if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount) / parseFloat(rate);
                        }else{
                            sisa = parseFloat(Amount);
                        } 
                    }
                }

                sisa            = parseFloat(sisa.toFixed(2));
                total           += convert_payment(index_tab,CurrCustCode,value.CurrencyCode,sisa,value.SJrnRate);
            }
        });

        var amount_pembulatan = Number(owing - total).toFixed(2);
        return amount_pembulatan;
    }

	function app_dir(){

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

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

	function app_reverse(){
		var no_transaksi    = $('#SJrnNumber').val();

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

	// function choose_account_gl() {
	//     var selected_data = $('#tt_choose_payment').datagrid('getSelected');

	//     $('.gl_account').val(selected_data.AccountName);
	//     modal_close('dialog-gl-account');
	// }

	// $.extend($.fn.datagrid.defaults.editors, {
	//     Payment_Account_Name: {
	//         init: function(container, options){
	//             var input = $('<input type="text" class="gl_account" onClick="open_list_gl()" style="height:18px;" readonly/>').appendTo(container);
	//             return input.validatebox(options);
	//         },
	//         destroy: function(target){
	//             $(target).remove();
	//         },
	//         getValue: function(target){
	//             return $(target).val();
	//         },
	//         setValue: function(target, value){
	//             $(target).val(value);
	//         },
	//         resize: function(target, width){
	//             $(target)._outerWidth(width);
	//         }
	//     }
	// });

	function choose_account_gl() {
	    var selected_data = $('#tt_choose_payment').datagrid('getSelected');

        //var CurrencyCode = $('#currency_code').val();
        get_master_rate_on_grid(selected_data.CurrencyCode,function(MstRate){
            if(index_tab == 1){
                if(selected_data.CurrencyCode == 'IDR'){
                    $('#dtg_payment_history').datagrid('updateRow',{
                        index: indChoAccount,
                        row: {
                            PaymentAmount       : 0,
                            GLAccount           : selected_data.AccountName,
                            SJrnRate            : MstRate.value,
                            CurrencyCode        : 'IDR',
                        }
                    });
                    // var ed = $('#dtg_payment_history').datagrid('getEditor', {index:indChoAccount,field:'SJrnRate'});
                    // $(ed.target).prop('readonly',true);
                }else{
                    $('#dtg_payment_history').datagrid('updateRow',{
                        index: indChoAccount,
                        row: {
                            PaymentAmount       : 0,
                            GLAccount           : selected_data.AccountName,
                            SJrnRate            : MstRate.value,
                            CurrencyCode        : selected_data.CurrencyCode
                        }
                    });
                }
            }else{
                $('#dtg_payment_history').datagrid('updateRow',{
                    index: indChoAccount,
                    row: {
                        PaymentAmount       : 0,
                        GLAccount           : selected_data.AccountName,
                        SJrnRate            : MstRate.value,
                       CurrencyCode        : selected_data.CurrencyCode
                    }
                });
            }
			
			$('#dtg_payment_history').edatagrid('beginEdit', indChoAccount);
        });
        

	    //$('.gl_account').val(selected_data.AccountName);
	    modal_close('dialog-gl-account');
	}

	// function open_list_gl() { 
	//    modal_open('Account List','dialog-gl-account');
	// }

	function open_list_gl(indexRow) { 
        indChoAccount = indexRow;
	    modal_open('Account List','dialog-gl-account');
	}

	function get_account_gl(){
		$('#tt_choose_payment').datagrid('load', {
	        AccountNo: $('#txt_AccountNumber').val(),
	        AccountName: $('#txt_AccountName').val(),
	        CurrencyCode:$('#currency_code').val()
	    });
	}
	
	$.extend($.fn.datagrid.defaults.editors, {
		AccountName: {
			init: function(container, options){
				var input = $('<input type="text" class="AccountName" style="height:18px;" readonly/>').appendTo(container);
				return input.validatebox(options);
			},
			destroy: function(target){
				$(target).remove();
			},
			getValue: function(target){
				 return $(target).val();
			},
			setValue: function(target, value){
				  $(target).val(value);
			},
			resize: function(target, width){
				   $(target)._outerWidth(width);
			}
		}
	});

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?>', $('#SJrnNumber').val(), '<?=$menu_label;?>', url, created_by, login_as, job_title);
}
</script>
