<!---- 
    Author 	: Fachri
    Tanggal : 20/11/2015
    Revisi 	:
-->
<?php
			//---------Untuk privellege jika dia ada tombol save----------
			if($group_user->SavePrivillage == 1){
				$cek_autority_save 		= "";
			}
			else{
				$cek_autority_save 		= "disabled";
			}
			
			if($group_user->DeletePrivillage == 1){
				$cek_autority_delete 		= "";
			}
			else{
				$cek_autority_delete 		= "disabled";
			}
			
			if($group_user->JournalPrivillage == 1){
				$cek_autority_journal 		= "";
			}
			else{
				$cek_autority_journal 		= "disabled";
			}
			
			//-------------end----------------------------
?>	

<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" width="30%">
                        <input type="checkbox" class="easyui-checkbox" name="chk_suspended" id="chk_suspended" style="margin-top:0px;margin-right:1px;" onClick="suspend(1)" <?=(!in_array($detail->TransStatus,array(4,6))) ? 'disabled' : ''?> <?php echo $cek_autority_delete;?>/>
                    	<span style="display:inline-block;margin-top:2px;<?=(($detail->AppLevel2Status!=0)?'color:gray;':'')?>"><?=(($detail->TransStatus!=3)?"Suspend":"Suspend")?> </span>
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-journal" plain="true"  id="btn_journal" 
							onclick="parent.tab_add('Preview <?=$menu_label?>', '<?php echo $menu_link; ?>', 'icon-print', 'to_preview_journal/<?php echo $detail->JVchNumber ?>')" <?php echo $cek_autority_journal;?>>Journal
						</a>
                         
                        <a href="#" 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==4){
                            if($this->session->userdata('jobtitle_status')==0){
                                echo 'Need Your Approval';
                            }
                            else{
                                echo 'Need Dir Approval';
                            }
                        }
                        ?>
                        </span></td>
                    <td height="25" align="right" valign="middle">
                        <span class="form-title" style="margin-left:7px;">
                            <?=$menu_label?>
                        </span>
                    </td>
                </tr>
            </table>		     	
        </div>			
    </div>
    <!-- End of top view -->
    
    <div id="form-body" data-options="region:'center',border:false">
    	<div id="form-wrapper" class="easyui-panel" fit="true" style="padding:5px;">
         <?php if(in_array($detail->TransStatus,array(2,3,9))){ ?>
        	<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.'; }else{ echo 'Unknown'; } ?></b></div>
         <?php } ?>
            
		
        <form id="fm_journal_voucher" name="fm_journal_voucher" method="post">
        <input type="hidden" id="detail" name="detail" />
        <input type="hidden" name="detail_id" id="detail_id">
        <input type="hidden" name="JVchType" id="JVchType" value="<?php echo $detail->JVchType;?>">
        
       		<table width="100%" height="141" cellpadding="0" cellspacing="0">
                <tr>
                    <td width="50%" valign="top">
                    	<table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
                            <tr height="20px">
                                <td width="140"><b>Journal Voucher No.</b></td>
                                <td width="12"><b>:</b></td>
                                <td width="499">
                                    <input name="txt_jv_no" id="txt_jv_no" type="text" class="easyui-validatebox" style="width:252px;height:18px" value="<?php echo $detail->JVchNumber; ?>" required="required" readonly />
                                </td>
                                <!--
                                <td width="100" height="20" align="center" valign="middle"><span style="color: #fff">Item Category</span></td>
                                -->
                            </tr>
                            
                            <tr height="25">
                                <td><b>Voucher Date</b></td>
                                <td><b>:</b></td>
                                <td>
                                    <input name="txt_voucher_date" id="txt_voucher_date" type="text" class="easyui-datebox validBackward" style="width:253px;" required editable="false" value=" <?=date('d-m-Y',strtotime($detail->JVchDate))?>" panelWidth="253" readonly="readonly"/>
                                </td>
                            </tr>
                            <tr height="20">
                                <td valign="top" style="padding-top:4px;"><b>Description</b></td>
                                <td valign="top" style="padding-top:4px;"><b>:</b></td>
                                <td>
                                    <textarea class="textbox" style="width:250px;resize:none;white-space:normal;" name="txa_description" id="txa_description" rows="4"><?php echo $detail->JVchDesc;?></textarea>
                                </td>
                            </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">&nbsp;</td>
                </tr>
             </table> 
             
             <!--Item Grid -->
            <div class="easyui-tabs" data-options="tabHeight:18">
                <div title="Journal Voucher">
                    <table toolbar="#tb_dg_item" id="dtg_jv" class="easyui-edatagrid" idField="id"
                        rownumbers="true" fitColumns="true" 
                        singleSelect="true" style="height:356px;"
                        url="<?php echo base_url(); ?>list/journal_voucher/get_jv_detail/<?php echo $detail->JVchNumber; ?>" 
                        >
                        <thead>
                        <tr>
                            <th field="AccountName" 	halign="center"	align="left" valign="middle"	data-options="width:900,align:'left'" 	editor="{type:'AccountName',options:{required:true}}">Account Name</th>
                            <th field="Debit" 			halign="center" align="left" valign="middle"	data-options="width:700,align:'left'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp">Debit</th>
                            <th field="Credit" 			halign="center" align="left" valign="middle"	data-options="width:700,align:'left'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp">Credit</th>
                            <th field="Rate" 			halign="center" align="left" valign="middle"	data-options="width:700,align:'left'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp">Exchange Rate</th>
                        	<th field="Customer"		halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="Customer">Customer Name</th>
                            <th field="Vendor"			halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="Vendor">Vendor Name</th>
                            <th field="Memo"			halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="Memo">Memo</th>
                            
                            <th field="SubTypeName"		halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="SubTypeName" hidden>Sub Type Name</th>
                            <th field="CurrencyCode"	halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="CurrencyCode" hidden>Currency Code</th>
                            <th field="CustomerCode"	halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="CustomerCode" hidden>Customer Code</th>
                            <th field="VendorCode"		halign='center'	align="left" valign="middle"	data-options="width:700,align:'left'"  	editor="VendorCode" hidden>Vendor Code</th>
                            
                            <th field="Debit_Currency" 	halign="center" align="left" valign="middle"	data-options="width:700,align:'left'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp" hidden>Debit Currency</th>
                            <th field="Credit_Currency" halign="center" align="left" valign="middle"	data-options="width:700,align:'left'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp" hidden>Credit Currency</th>
                        	<th field="AccountNumber" 	halign="center"	align="left" valign="middle"	data-options="width:900,align:'left'" 	editor="{type:'AccountNumber',options:{required:true}}" hidden>Account Number</th>
                            <th field="AccountType" 	halign="center"	align="left" valign="middle"	data-options="width:900,align:'left'" 	editor="{type:'AccountType',options:{required:true}}" hidden>Account Type</th>
                            <th field="JVchDetailID" 	halign="center"	align="left" valign="middle"	data-options="width:900,align:'left'" 	editor="{type:'text'}" hidden>JV Detail ID</th>
                        </tr>
                        </thead>
                    </table>	
                    <div id="tb_dg_item">
                        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row();" <?= in_array($detail->TransStatus,array(0,1,2,3)) ? 'disabled' : '' ?>>Delete</a>
                    </div>					
                </div>
                
            </div>
            <input type="text" min="0" name="sub_total_kredit" id="sub_total_kredit" class="easyui-numberbox" value="0" style="text-align:right;" readonly 
                                    data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" hidden
                                />
            <input type="text" min="0" name="sub_total_debet" id="sub_total_debet" class="easyui-numberbox" value="0" style="text-align:right;" readonly 
                                    data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" hidden
                                />
            <!-- End 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="approval_jv()" <?= ($this->session->userdata("jobtitle_status") != 0 || (date('Y-m-d') < date('Y-m-d', strtotime($detail->JVchDate))) || !in_array($detail->TransStatus,array(4,6))) ? 'disabled' : ''?>> App. Dir</a>		
                     <?php
					 if(($group_user->ReversePrivillage == 1)){
					 ?>
                    	<a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-reload" onclick="app_reverse()" <?=(($this->session->userdata("jobtitle_status") == 0) && (in_array($detail->TransStatus,array(1,2,8))))?'':'disabled'?>>Reverse</a>  
                     <?php
					 }
					 ?>						
                    <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':''?> <?php echo $cek_autority_save;?>>Save</a> 	
                    <a href="javascript:void(0)" 	class="easyui-linkbutton form-button" 				iconCls="icon-print" 	onclick="parent.tab_edit('Print Journal Voucher', '<?php echo $menu_link; ?>', 'icon-print', 'to_print_detail','<?php echo $detail->JVchNumber;?>')" <?=(in_array($detail->TransStatus,array(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,4,6)))?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
                </td>
             </tr>
        </table>				
    </div>
</div>



<div id="dialog-vendor" class="easyui-dialog" style="width:835px;height:523px;top:27px;background-color:#F8F8F8;padding:0px" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-vendor-button">
    <table width="100%" align="left" border="0">
        <input type="hidden" style="width:690px;height:20px" name="txt_currencycode_vendor" id="txt_currencycode_vendor" class="easyui-validatebox" />
        <tr>
            <td><b>Vendor Code</b></td>
            <td width="10"><b>:</b></td>
            
            <td>
                <input type="text" style="width:705px;height:20px" name="txt_VendorCode" id="txt_VendorCode" class="easyui-validatebox" placeholder="Vendor Code" onkeyup="search_vendor_text();" />
            </td>
        </tr>
        
        <tr>
            <td><b>Vendor Name</b></td>
            <td><b>:</b></td>
        
            <td>
                <input type="text" style="width:705px;height:20px" name="txt_VendorName" id="txt_VendorName" class="easyui-validatebox" placeholder="Vendor Name" onkeyup="search_vendor_text();" />
            </td>
        </tr>
        
        <tr>
            <td colspan="3">
                <table id="dtg_vendor" class="easyui-datagrid" singleSelect="true"  rownumbers="true" style="width:810px;height:387px;"
                    
                    pageSize="150" 
                    data-options = "border:true,view:scrollview,autoRowheight:false"
                >
                    <thead>
                        <tr bgcolor="">
                           	<th field="VendorCode" width="150" sortable="true">Vendor Code</th>
                            <th field="VendorName" width="204" sortable="true">Vendor Name</th>
                            <th field="VendorAddress" width="380" sortable="true">Vendor Address</th>
                        </tr>
                    </thead>
                </table>
            </td>
        </tr>
    </table>
</div>
<!-- Dialog Button -->
<div id="dialog-vendor-button">
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_vendor();">OK</a>
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-vendor')">Cancel</a>
</div>

<div id="dialog-customer" class="easyui-dialog" style="width:835px;height:523px;top:27px;background-color:#F8F8F8;padding:0px" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-customer-button">
    <table width="100%" align="left" border="0">
        <input type="hidden" style="width:690px;height:20px" name="txt_currencycode_customer" id="txt_currencycode_customer" class="easyui-validatebox" />
        <tr>
            <td width="111"><b>Customer Code</b></td>
            <td width="5"><b>:</b></td>
            
            <td width="705">
                <input type="text" style="width:690px;height:20px" name="txt_CustomerCode" id="txt_CustomerCode" class="easyui-validatebox" placeholder="Customer Code" onkeyup="search_customer_text();" />
            </td>
        </tr>
        
        <tr>
            <td><b>Customer Name</b></td>
            <td><b>:</b></td>
        
            <td>
                <input type="text" style="width:690px;height:20px" name="txt_CustomerName" id="txt_CustomerName" class="easyui-validatebox" placeholder="Customer Name" onkeyup="search_customer_text();" />
            </td>
        </tr>
        
        <tr>
            <td colspan="3">
                <table id="dtg_customer" class="easyui-datagrid" singleSelect="true"  rownumbers="true" style="width:812px;height:387px;"
                    
                    pageSize="150" 
                    data-options = "border:true,view:scrollview,autoRowheight:false"
                >
                    <thead>
                        <tr bgcolor="">
                           	<th field="CustomerCode" width="150" sortable="true">Customer Code</th>
                            <th field="CustomerName" width="204" sortable="true">Customer Name</th>
                            <th field="CustomerAddress" width="380" sortable="true">Customer Address</th>
                        </tr>
                    </thead>
                </table>
            </td>
        </tr>
    </table>
</div>
<!-- Dialog Button -->
<div id="dialog-customer-button">
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_customer();">OK</a>
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-customer')">Cancel</a>
</div>

<script type="text/javascript">
/*========================deklar variabel array for remove===================*/
var array_item 			= [];
/*==============================end=========================================*/
var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';

$(document).ready(function(){
	editor_grid();
	
	var jv_number ='<?php echo $detail->JVchNumber; ?>';
	$('#dtg_jv').datagrid('load',{
		jv_number : jv_number
	});
			
	$('#fm_journal_voucher').click(function(){
		$('#dtg_jv').edatagrid('saveRow');
	});
});

function search_customer(CurrencyCode){
	$('#txt_currencycode_customer').val(CurrencyCode);
	$('#dtg_customer').datagrid({
		url:'<?php echo base_url(); ?>list/journal_voucher/customer/'+CurrencyCode
	});
}

function search_vendor(CurrencyCode){
	$('#txt_currencycode_vendor').val(CurrencyCode);
	$('#dtg_vendor').datagrid({
		url:'<?php echo base_url(); ?>list/journal_voucher/vendor/'+CurrencyCode
	});
}

function search_vendor_text(){
	searchParameter = {};
	
	searchParameter['txt_VendorCode'] 		= $('#txt_VendorCode').val();
	searchParameter['txt_VendorName'] 		= $('#txt_VendorName').val();
	searchParameter['txt_CurrencyCode'] 	= $('#txt_currencycode_vendor').val();
	
	$('#dtg_vendor').datagrid('load',{
		param: searchParameter
	});
}

function search_customer_text(){
	searchParameter = {};
	
	searchParameter['txt_CustomerCode'] 	= $('#txt_CustomerCode').val();
	searchParameter['txt_CustomerName'] 	= $('#txt_CustomerName').val();
	searchParameter['txt_CurrencyCode'] 	= $('#txt_currencycode_customer').val();
	
	$('#dtg_customer').datagrid('load',{
		param: searchParameter
	});
}

function close_modal(){
	modal_close('dialog-account');
	
	/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
	$('.save-button').linkbutton('enable');
	/*=================================end============================================================*/
}

function editor_grid(){
	$('#dtg_jv').datagrid({
		onLoadSuccess:function(){
			calculate_sub();
		},
		onBeginEdit:function(rowIndex){
			editors = $('#dtg_jv').datagrid('getEditors',rowIndex);
			AccountName		= $(editors[0].target);
			Debit			= $(editors[1].target);
			Credit			= $(editors[2].target);
			Rate			= $(editors[3].target);
			Customer		= $(editors[4].target);
			Vendor			= $(editors[5].target);
			Memo			= $(editors[6].target);
			TypeName		= $(editors[7].target);
			CurrencyCode	= $(editors[8].target);
			Debit_Currency 	= $(editors[11].target);
			Credit_Currency = $(editors[12].target);
			 
			AccountTypeName = $(TypeName).val();
			Currency 		= $(CurrencyCode).val();
			Customer_Name 	= $(Customer).val();
			Vendor_Name 	= $(Vendor).val();
			CurrencyRate 	= $(Rate).numberbox('getValue');
			
			Customer.prop('disabled',true);
			Vendor.prop('disabled',true);
			Memo.prop('disabled',false);
			Debit.prop('disabled',false);
			Credit.prop('disabled',false);
			
			if($(Debit).numberbox('getValue') > 0){
				Credit.prop('readonly',true);
			}
			else if($(Credit).numberbox('getValue') > 0){
				Debit.prop('readonly',true);
			}
			
			if(AccountTypeName == ""){
				Debit.numberbox('setValue',0);
				Credit.numberbox('setValue',0);
				Debit_Currency.numberbox('setValue',0);
				Credit_Currency.numberbox('setValue',0);
			}
			else{
				/*
					Jika currency idr maka rate disable dan rate 1
					jika bukan idr rate enable
				*/
				if(Currency == "IDR"){
					Rate.prop('readonly',true);
				}
				else{
					Rate.prop('readonly',false);
				}
				/*===================End=========================================*/
			}
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			save_button_begendedit(SavePrivillage);
			/*=================================end============================================================*/
				
			//Debit_Currency.numberbox('setValue',0);
			//Credit_Currency.numberbox('setValue',0);
			
			/*
				Kondisi ini jika customer sudah dipilih tapi akan dipilih ulang
			*/
			search_customer(Currency);
			search_vendor(Currency);
			/*==============End=============================================*/
			
			/*
				Untuk sementara di disable karena tidak jadi dipakai
				Tgl : 12/07/2016
			*/
			
			/*if((AccountTypeName == "Retur Pembelian") || (AccountTypeName == "Hutang Leasing") || (AccountTypeName == "Biaya Dibayar Di Muka") || (AccountTypeName == "Pajak Dibayar Di Muka") || (AccountTypeName == "Biaya Pra Operational") || ( AccountTypeName == "Deposito") || ( AccountTypeName == "Hutang Pajak")){
				Customer.prop('disabled',true);
				Vendor.prop('disabled',false);
			}
			else if((AccountTypeName == "Bank Garansi Customer") || (AccountTypeName == "Retur Penjualan")){
				Customer.prop('disabled',false);
				Vendor.prop('disabled',true);
			}
			else{
				Customer.prop('disabled',true);
				Vendor.prop('disabled',true);
			}*/
			
			Debit.numberbox({
				onChange:function(){
					CurrencyRate 			= $(Rate).numberbox('getValue');
					
					//Debit_Currency_amount 	= $(Debit_Currency).numberbox('getValue');
					Debit_Amount 			= $(Debit).numberbox('getValue');
					
					Total_Debet 			= parseFloat(Debit_Amount) * parseFloat(CurrencyRate);
					
					$(Debit_Currency).numberbox('setValue',Total_Debet);
					if(Debit_Amount > 0){
						Credit.prop('readonly',true);
					}
					else{
						Credit.prop('readonly',false);
					}
				}
			});
			
			Credit.numberbox({
				onChange:function(){
					CurrencyRate 			= $(Rate).numberbox('getValue');
					
					//Debit_Currency_amount 	= $(Debit_Currency).numberbox('getValue');
					Credit_Amount 			= $(Credit).numberbox('getValue');
					
					Total_Credit			= parseFloat(Credit_Amount) * parseFloat(CurrencyRate);
					
					$(Credit_Currency).numberbox('setValue',Total_Credit);
					if(Credit_Amount > 0){
						Debit.prop('readonly',true);
					}
					else{
						Debit.prop('readonly',false);
					}
				}
			});
			
			Rate.numberbox({
				onChange:function(){
					CurrencyRate 			= $(Rate).numberbox('getValue');
					Debit_Amount 			= $(Debit).numberbox('getValue')
					Credit_Amount 			= $(Credit).numberbox('getValue')
					
					if(Debit_Amount != 0){
						Total_Debit			= parseFloat(Debit_Amount) * parseFloat(CurrencyRate);
					}
					else{
						Total_Debit			= 0;
					}
					
					if(Credit_Amount != 0){
						Total_Credit			= parseFloat(Credit_Amount) * parseFloat(CurrencyRate);
					}
					else{
						Total_Credit			= 0;
					}
					
					$(Credit_Currency).numberbox('setValue',Total_Credit);
					$(Debit_Currency).numberbox('setValue',Total_Debit);
				}
			});
		},
		onEndEdit:function(rowIndex, rowData, changes){
			var item 	= $('#dtg_jv').datagrid('getRows');
			
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			save_button_endedit(SavePrivillage);
			/*=================================end============================================================*/
			Credit_Total = 	0;
			Debit_Total	=	0;

			$.each(item, function( index, value ) {
				Credit_Total		+= parseFloat(value.Credit_Currency);
				Debit_Total		+= parseFloat(value.Debit_Currency);
			});
			
			$('#sub_total_kredit').numberbox('setValue', Credit_Total);
			$('#sub_total_debet').numberbox('setValue', Debit_Total);
		}
	});
}

function open_vendor(){ 
   modal_open('Vendor List','dialog-vendor');
}

function open_customer(){ 
   modal_open('Customer List','dialog-customer');
}

function choose_vendor() {
	var selected_vendor = $('#dtg_vendor').datagrid('getSelected');
	$('.Vendor').val(selected_vendor.VendorName);
	$('.VendorCode').val(selected_vendor.VendorCode);
	modal_close('dialog-vendor');
}

function choose_customer() {
	var selected_customer = $('#dtg_customer').datagrid('getSelected');
	$('.Customer').val(selected_customer.CustomerName);
	$('.CustomerCode').val(selected_customer.CustomerCode);
	modal_close('dialog-customer');
}

function remove_row(){
	var item = $('#dtg_jv').datagrid('getData').total;

	if(item <= 1){
		$.messager.alert('Warning','Anda tidak dapat menghapus list item, minimum list item adalah satu (1)','error');
	}
	else {
		var selectedrow     = $('#dtg_jv').datagrid('getSelected');
		var row_index       = $('#dtg_jv').datagrid('getRowIndex', selectedrow);

		$.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.AccountName + '"',  
			function(r){
				if (r){
					array_item.push(selectedrow.JVchDetailID);
					//array_item_detail.push(selectedrow.JCostDetailID, selectedrow.ItemCode, selectedrow.ItemQty);
					
                   	$("#detail_id").val(JSON.stringify(array_item));
					//$("#detail_item").val(JSON.stringify(array_item_detail));
					
                   	$('#dtg_jv').datagrid('deleteRow', row_index);	
					save_button_endedit(SavePrivillage);
					calculate_sub();
				}
			}
		);        
					
	}            
}

function calculate_sub(){
	var item       	= $('#dtg_jv').datagrid('getRows');
	
	Credit_Total 	= 	0;
	Debit_Total		=	0;
			
	$.each(item, function( index, value ) {
		Credit_Total		+= parseFloat(value.Credit_Currency);
		Debit_Total			+= parseFloat(value.Debit_Currency);
	});
	
	$('#sub_total_kredit').numberbox('setValue', Credit_Total);
	$('#sub_total_debet').numberbox('setValue', Debit_Total);
}

$.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);
		}
	},
	AccountNumber: {
		init: function(container, options){
			var input = $('<input type="text" class="AccountNumber" 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);
		}
	},
	Vendor: {
		init: function(container, options){
			var input = $('<input type="text" class="Vendor" onClick="open_vendor()" style="height:18px;" />').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);
		}
	},
	
	VendorCode: {
		init: function(container, options){
			var input = $('<input type="text" class="VendorCode" style="height:18px;" />').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);
		}
	},
	Customer: {
		init: function(container, options){
			var input = $('<input type="text" class="Customer" onClick="open_customer()" style="height:18px;" />').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);
		}
	},
	CustomerCode: {
		init: function(container, options){
			var input = $('<input type="text" class="CustomerCode" style="height:18px;" />').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);
		}
	},
	Memo: {
		init: function(container, options){
			var input = $('<input type="text" class="Memo" style="height:18px;" />').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);
		}
	},
	SubTypeName: {
		init: function(container, options){
			var input = $('<input type="text" class="SubTypeName" style="height:18px;" />').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);
		}
	},
	
	CurrencyCode: {
		init: function(container, options){
			var input = $('<input type="text" class="CurrencyCode" style="height:18px;" />').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);
		}
	},
	AccountType: {
		init: function(container, options){
			var input = $('<input type="text" class="AccountType" style="height:18px;" />').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?>', $('#txt_jv_no').val(), 'Journal Voucher', url, created_by, login_as, job_title);
}

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

	checking_reverse(no_transaksi,function(check){
		
		if(check.status == true){
			var i       = $('#dtg_jv').datagrid('getRows');
			var detail  = JSON.stringify(i);
	
			$("#detail").val(detail);
			reverse_data_by_detail('<?php echo $menu_link?>','#fm_journal_voucher');
		}else{
		   $.messager.alert('Unseccessfull',check.message,'error',function(){
				location.reload();
			});
		}
	});
}
	
function save_me(){
	var url             = '<?= base_url();?>custom/custom/checking_update';
	var no_transaksi    = $('#txt_jv_no').val();
	var trans_status 	= '<?php echo $detail->TransStatus; ?>';
	
	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 Total_kredit_data 	= $('#sub_total_kredit').numberbox('getValue');
	var Total_debit_data 	= $('#sub_total_debet').numberbox('getValue');
	flag 				 	= true;
	
	dtg_jv = $('#dtg_jv').datagrid('getRows');
	$.each(dtg_jv, function( index, value ) {
		if((value.Debit == 0) && (value.Credit == 0)){
			flag = false;
		}
		
	});
	if(flag != false){
		if((Total_kredit_data - Total_debit_data) != 0){
			$.messager.alert('Unseccessfull','Account Tidak Balance, silahkan lihat kembali transaksi ini','error');
			return false;
		}
		else{
			var rows 	= $('#dtg_jv').edatagrid('getRows');
			var jum 	= rows.length;
			var items 	= JSON.stringify(rows);
			$("#detail").val(items);
			edit_transaction_check('<?=$menu_link?>','#fm_journal_voucher', no_transaksi, url, trans_status,created_by, login_as, job_title);
		}
	}
	else{
		$.messager.alert('Unseccessfull','Transaksi gagal dibuat silahkan berikan nilai di debit atau kredit,cek kembali transaksi ini','info');
	}
}

function approval_jv() {
	var url_check           = '<?= base_url();?>custom/custom/checking_approval';
	var no_transaksi    	= $('#txt_jv_no').val();
	
	checking_approval(no_transaksi,function(check){
		if(check.status == false){
			app_dir();
		}else{
			$.messager.alert('Unseccessfull',check.message,'error',function(){
				location.reload();
			});
		}
	});
}

function app_dir(){
	var i       = $('#dtg_jv').datagrid('getRows');
	var detail  = JSON.stringify(i);

	$("#detail").val(detail);
	
	edit_approval('<?php echo $menu_link?>','#fm_journal_voucher');	
}

function edit_approval(url, form_id) {
	url = base_url + url;	
	
	$(form_id).form('submit',{
		url: url + '/approval',
		
		onSubmit: function(){
			return $(this).form('validate');
		},
		success: function(result){
			var result = eval('('+result+')');
			
			if (result.status==true){
				$.messager.alert('Success',result.message,'info',function(){						
					location.reload();								
				});				
			} 
			else {
				$.messager.alert('Failed',result.message,'error',function(){						
					location.reload();								
				});				
			}
		},		
	});
}
</script>