<!---- 
    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;?>',$('#PJrnNumber').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 Purchase Journal', '<?= $menu_link; ?>', 'icon-bank', 'to_journal',$('#PJrnNumber').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:1180px;height:526px;padding:5px;" fit='true'>
			<form id="fm_purchase_journal" name="fm_purchase_journal" method="post">
                <table cellpadding="0" cellspacing="3" width="100%" height="100%" border="0">
                	 <tr height="20">
                    	<td width="150"><b>Branch</b></td>
                        <td width="10"><b>:</b></td>
                        <td>
                        	<select name="cmb_branch" id="cmb_branch" 
                            	class="combo-grid" editable="true"
                            	style="width:250px;height:24px;"
                                required
                                data-options="
                                	value:'<?= $detail->PayBranchCode;?>',
                                    panelWidth: 302,
                                    idField: 'BranchCode',
                                    textField: 'BranchName',
                                    disabled:true,
                                    url: '<?= base_url().$menu_link; ?>/get_branch',               
                                    columns: [[                
                                        {field:'BranchCode',title:'BranchCode',width:100},  
                                        {field:'BranchName',title:'BranchName',width:190}
                                    ]],
                                    fitColumns: true,
                                    onSelect:function(indRow,dataRow){

                                    	/*==================== clear grid ============================*/
                                       $('#dtg_list_invoice').datagrid('loadData', {'total':0,'rows':[]});
                                       //alert(dataRow.BranchCode);
                                       $('#tb_invoice_list').datagrid({
                                       		url:'<?= base_url().$menu_link;?>/get_invoice/'+dataRow.BranchCode
                                       });

                                    }
                                "
                            >
                            </select>
                        </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">PJournal No.</span></td>
												<td width="122" align="center" valign="middle" bgcolor="#333399"><span style="color:#fff;">PJournal Date</span></td>
											</tr>
											<tr>
												<td>&nbsp;</td>
												<td height="20" align="left" valign="top">
												<input type="text" name="PJrnNumber" id="PJrnNumber" value="<?=$detail->PJrnNumber;?>" class="easyui-validatebox" style="width:190px;background-color:#E3E2E2;text-align:center;height:20px" required readonly />
												</td>
												<td align="right" valign="top" height="20"><input name="txt_payment_date" value="<?= date("d-m-Y", strtotime($detail->PJrnDate)) ?>" 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 height="20">
                        <td width="120"><b>Vendor</b></td>
                        <td width="10"><b>:</b></td>
                        
                        <td>
                            <select class="combo-grid" name="cbg_vendor" id="cbg_vendor" style="width:250px;height:22px;" required readonly
                                data-options="
                                    panelWidth:400,
                                    value:'<?=$detail->VendorCode?>',
                                    idField: 'VendorCode',
                                    textField: 'VendorName',
                                    url: '<?=base_url()?>custom/get_data/vendor_new_by_branch',
                                    method: 'get',
                                    columns: [[
                                        {field:'VendorCode',title:'Vendor No',width:100,halign:'center'},
                                        {field:'VendorName',title:'Vendor Name',width:161}
                                    ]],
                                    fitColumns: true
                                ">
                            </select>
                             <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-Purchase" onclick="modal_open('Payment List','dialog-payment-list')" style="width:110px;" plain="true" disabled>List Funding</a> 
                        </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:246px;background-color:#E3E2E2;height:20px" value="<?=$detail->PInvNumber;?>" readonly />
							<!-- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-Purchase" 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->PJrnDesc;?></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->PJrnAmount;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:362px;" 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->PJrnAmount;?>" 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="vendor_code" name="vendor_code" value="<?=$detail->VendorCode;?>"/>
							<input type="hidden" id="detail_id" name="detail_id" value=""/>
							<input type="hidden" id="type_fiscal" name="type_fiscal" value="<?=$detail->InvoiceType;?>"/>
						</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_list_invoice" 
                        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->PJrnNumber);?>/<?=$detail->CurrencyCode;?>/<?=$detail->InvoiceType;?>"
                        data-options = "
                        	onBeginEdit:function(rowIndex){
								save_button_begendedit('<?=$group_user->SavePrivillage;?>');

								editors = $('#dtg_list_invoice').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:'PJrnDetailID',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:'PJrnRate',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:'PJrnDetailID',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:'PJrnRate',width:150,halign:'center',align:'right',editor:{type:'numberbox',disabled:true,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:',',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->PJrnDate))))?'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 Purchase Journal', '<?=$menu_link?>', 'icon-print', 'to_print_detail','<?= $detail->PJrnNumber;?>');" <?=(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>

<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-gl">
    <form id="form_payment_account" method="post" novalidate>
        <table width="100%" align="left" border="0">
            <tr>
                <td width="197" align="left" valign="middle"><b>Account Number</b></td>
                <td width="14"><b>:</b></td>

                <td width="625" colspan="2">
                    <input type="text" style="width:608px;height:20px" name="txt_account_number" id="txt_account_number" class="easyui-validatebox" placeholder="< Account Number >" onkeyup="search_payment_account_popup();" />
                </td>
            </tr>

            <tr>
                <td width="197" align="left" valign="middle"><b>Account Name</b></td>
                <td><b>:</b></td>

                <td colspan="2">
                    <input type="text" style="width:608px;height:20px" name="txt_account_name" id="txt_account_name" class="easyui-validatebox" placeholder="< Account Name >" onkeyup="search_payment_account_popup();" />
                </td>
            </tr>

            <tr>
                <td colspan="3">
                    <table id="tt_choose_payment" class="easyui-datagrid" 
                        
                        singleSelect="true" fitColumns="true" pagesize="150"
                        style="width:828px;height:380px" data-options = "border:false,view:scrollview,autoRowheight:false"
                    >
                        <thead>
                            <tr>
                                <th field="AccountNumber" width="150" sortable="true">Account Number</th>
                                <th field="AccountName" width="460" sortable="true">Name</th>
                            </tr>
                        </thead>
                    </table>
                </td>
            </tr>
        </table>
    </form>
</div>

<!-- Dialog Button -->
<div id="dialog-buttons-account-gl" style="border:none;">
    <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_purchase_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});
	    }
		
		var branch = $('#cmb_branch').combogrid('getValue');
		search_account('<?php echo $detail->CurrencyCode;?>',branch);
		
	    $('#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 Purchase Invoice','list/Purchase_invoice', 'icon-edit', 'edit',TransNumber) ;
	    });

	});
	
	function search_account(CurrencyCode, branch){
		$('#tt_choose_payment').datagrid({
			url: '<?= base_url().$menu_link; ?>/get_gl_account/'+CurrencyCode+'/'+branch
		});
	}
	
	function addNewRow(){

		var no_piutang 			= $('#txt_payment_for').val();
		// var hutang_name 		= $('#hutang_name').val();
		var row 				= $('#dtg_list_invoice').datagrid('getRows');
		$('#dtg_list_invoice').datagrid('endEdit', (row.length - 1));

		/*======================== tambahkan 1 row ke datagrid payment history ===============================*/
		if(no_piutang == ''){
			$.messager.alert('Warning','Silahkan pilih Funding terlebih dahulu','Warning');
		}else{
			 $('#dtg_list_invoice').datagrid('appendRow',{
				AccountHutang		: '',
				PaymentAmount 		: 0,
				GainAccount 		: ''
			});

			$('#dtg_list_invoice').datagrid('beginEdit', (row.length - 1));
		}

	}

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

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

	    var selectedrow         = $('#dtg_list_invoice').datagrid('getSelected');
	    var row_index           = $('#dtg_list_invoice').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.PJrnDetailID);
		                $('#dtg_list_invoice').datagrid('deleteRow', row_index);
		                calculate_amount();
		            }
		        }
		    );
		}else{
			$.messager.alert('Warning','Payment transaksi minimal 1.','error',function(){

			});
		}
	}

	function calculate_amount(){

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

		/*===================== save row & get all rows =======================*/
		$('#dtg_list_invoice').edatagrid('saveRow');	
		var row_payment 	= $('#dtg_list_invoice').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.PJrnRate);
	    });

        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 calculate_amount_pembulatan(){
        var row                 = $('#dtg_list_invoice').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.PJrnRate);
            }else{
                var Amount          = owing - total;
                var PaymentAmount   = value.PaymentAmount;
                var CurrAccountCode = value.CurrencyCode;
                var rate            = value.PJrnRate;
                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.PJrnRate);
            }
        });

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



	function save_me(){

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

		var row_payment 	= $('#dtg_list_invoice').datagrid('getRows');
		$('#dtg_list_invoice').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.PJrnRate);
	    });

	    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_list_invoice').datagrid('reload'); 
			});
	    }else{

	    	var amount_payment 		= parseFloat($('#txt_amount').numberbox('getValue'));
	    	var owing_amount 		= parseFloat($('#owing_amount').numberbox('getValue'));

	    	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    = $('#PJrnNumber').val();
				    var status          = '<?= $detail->TransStatus;?>';

				    $('#dtg_list_invoice').edatagrid('saveRow');
			        var i 			=$('#dtg_list_invoice').datagrid('getRows');
			        var detail 		= JSON.stringify(i);
			        var detail_id 	= JSON.stringify(array_item);
			        $("#detail").val(detail);
			        $("#detail_id").val(detail_id);
				    
				    checking_update(no_transaksi,status,function(check){
        
					    if(check.status == true){

				        	$('#dtg_list_invoice').edatagrid('saveRow');
					        var i 			= $('#dtg_list_invoice').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_purchase_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 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 app_dir(){

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

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

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

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

	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_list_invoice').datagrid('updateRow',{
                        index: indChoAccount,
                        row: {
                            PaymentAmount       : 0,
                            GLAccount           : selected_data.AccountName,
                            PJrnRate            : MstRate.value,
                            CurrencyCode        : 'IDR',
                        }
                    });
                    // var ed = $('#dtg_list_invoice').datagrid('getEditor', {index:indChoAccount,field:'PJrnRate'});
                    // $(ed.target).prop('readonly',true);
                }else{
                    $('#dtg_list_invoice').datagrid('updateRow',{
                        index: indChoAccount,
                        row: {
                            PaymentAmount       : 0,
                            GLAccount           : selected_data.AccountName,
                            PJrnRate            : MstRate.value,
                            CurrencyCode        : selected_data.CurrencyCode
                        }
                    });
                }
            }else{
                $('#dtg_list_invoice').datagrid('updateRow',{
                    index: indChoAccount,
                    row: {
                        PaymentAmount       : 0,
                        GLAccount           : selected_data.AccountName,
                        PJrnRate            : MstRate.value,
                       CurrencyCode        : selected_data.CurrencyCode
                    }
                });
            }
            $('#dtg_list_invoice').edatagrid('beginEdit', indChoAccount);
        });
        

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

	$.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 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()
	    });
	}

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

</script>
