<!---- 
    Author 	: Fachri
-->
<?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";
	}
//-------------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%">
            <tr>
                <td align="left" width="30%">
                     <a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="parent.tab_add('Journal <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_preview_journal/<?=$detail->PPayNumber?>');"  <?php echo $cek_autority_journal;?>>Journal</a>						
                    <input type="checkbox" name="chk_suspended" id="chk_suspended" value="3" onClick="suspend(1);" style="margin-top:0px;margin-right:1px;" <?php if($detail->TransStatus == 3){ echo"checked"; } ?> <?=((!in_array($detail->TransStatus,array(0,6)) || ($detail->AppLevel1Status==1) || ($detail->AppLevel2Status==1) || ($detail->CreatedBy != $this->session->userdata('username')))?"disabled":"")?> <?php echo $cek_autority_delete;?>/>
                    <span style="display:inline-block;margin-top:2px;<?=(($detail->AppLevel1Status!=0)?'color:gray;':'')?>"><?=(($detail->TransStatus!=3)?"Suspend":"Un-Suspend")?> Transaction</span>
                	<a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" 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') == 1){
                                echo 'Need Your Approval';
                            }
                            else{
                                echo 'Need Manager Approval';
                            }
                        }
                        elseif($detail->TransStatus == 5){
                            if($this->session->userdata('jobtitle_status')==0){
                                echo 'Need Your Approval';
                            }
                            else{
                                echo 'Need Director Approval';
                            }
                        }
                        elseif($detail->TransStatus == 6){
                            if($this->session->userdata('jobtitle_status')==1){
                                echo 'Need Your Approval</span>';
                            }
                            elseif($this->session->userdata('jobtitle_status')==0){
                                echo 'Need Your Approval';
                            }
                            else{
                                echo 'Need Director and Manager Approval';
                            }
                        }?>
                    </span>
                </td>							
                <td align="right">								
                    <span class="form-title"><?=$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" style="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 } ?>
            <?php if($detail->TransStatus==7 and $app_over_limit == false and $app_over_due==false){ ?>
        	<div class="blanket"></div>
            <div class="status-box"><b>Preference was not complete.</b></div>
            <?php } ?>
        	<form id="frm_purchase_journal" name="frm_purchase_journal" method="post">
            <input type="hidden" name="detail" id="detail" />
            <input type="hidden" 	name="hdn_inv_type" id="hdn_inv_type" />
            <input type="hidden" name="hdn_cust_curr" id="hdn_cust_curr" value="<?php echo $detail->CurrencyCode;?>"/>
            <input type="hidden" name="hdn_cust_curr_rate" id="hdn_cust_curr_rate" value="<?php echo $detail->PInvCurrRate;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" readonly />
            <input type="hidden" name="hdn_fiscal_rate" id="hdn_fiscal_rate" value="<?php echo $detail->PInvFiscalRate;?>"class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" readonly />
            <input type="hidden" name="hdn_fiscal_status" id="hdn_fiscal_status" value="<?php echo $detail->PPnFiscalStatus;?>"/>
            <input type="hidden" name="hdn_inv_amount" id="hdn_inv_amount" value="<?php echo $detail->PInvTotalAmount;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" readonly/>
            <input type="hidden" name="hdn_inv_owing" id="hdn_inv_owing" value="<?php echo $detail->PPayTotalOwing;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" readonly/>
            <input type="hidden" name="hdn_rec_amount" id="hdn_rec_amount" value="<?php echo $detail->PPayTotalAmount;?>" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" readonly/>
            <input type="hidden" name="hdn_saldo_partial" id="hdn_saldo_partial" class="easyui-numberbox" value="<?php echo $detail->SaldoDPPartial;?>" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" readonly/>
            <input type="hidden" name="id" id="id" class="textbox" style="width:257px;height:18px;text-align:center;" value="<?php echo $detail->PPayNumber; ?>" readonly />
            	<!-- Form Header -->
                <table width="100%" height="141" cellpadding="0" cellspacing="0">
                <tr>
                	<td width="50%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">
                        <tr height="20">
                            <td width="120"><b>Branch Name</b></td>
                            <td width="10"><b>:</b></td>
                            <td>
                                <select class="easyui-combogrid" name="cbg_branch" id="cbg_branch" readonly style="width:252px;height:22px;" required <?=(($this->session->userdata("branch_status")==1)?"disabled":'') ?> editable="false"
                                    data-options="
                                        panelWidth:400,
                                        value:'<?= $this->session->userdata("branch") ?>',
                                        idField: 'BranchCode',
                                        textField: 'BranchName',
                                        url: '<?=base_url()?>custom/get_data/branch',
                                        method: 'get',
                                        columns: [[
                                            {field:'BranchCode',title:'Branch No',width:100,halign:'center'},
                                            {field:'BranchName',title:'Branch Name',width:161,halign:'center'}
                                        ]],
                                        fitColumns: true
                                    ">
                                </select>
                            </td>
                        </tr>
                        <tr height="20">
                        	<td width="120"><b>Paid To</b></td>
                            <td width="10"><b>:</b></td>
                            <td>
                            	<select class="easyui-combogrid" name="cbg_vendor" id="cbg_vendor" style="width:252px;height:22px;" required readonly
                                    data-options="
                                        panelWidth:400,
                                        value:'<?php echo $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="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-sales'" onClick="select_purchase();" disabled>Select PInv.</a>	
                            </td>
                        </tr>
                        <tr height="20">
                        	<td valign="top" style="padding-top:4px;"><b>Address</b></td>
                            <td valign="top" style="padding-top:4px;"><b>:</b></td>
                            <td>
                            	<textarea name="txa_address" id="txa_address" rows="4" style="width:246px;resize:none;" readonly><?php echo $detail->VendorAddress; ?>, <?php echo $detail->VendorCity; ?></textarea>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">
                    	<table width="100%" cellpadding="0" cellspacing="1">
                         <tr height="20">
                            <td width="312" align="right" style="padding-right:15px;"><b>Payment No.</b></td>
                            <td width="10"><b>:</b></td>
                            <td colspan="3">
                                <input type="text" name="txt_sr_no" id="txt_sr_no" class="textbox" style="width:257px;height:18px;text-align:center;" value="<?php echo $detail->PPayNumber; ?>" readonly />
                            </td>
                        </tr>
                        <tr>
                        	<td colspan="2" width="350">&nbsp;</td>
                            <td width="120"><b>Payment Date</b></td>
                            <td width="10"><b>:</b></td>
                            <td>
                                <input name="txt_sr_date" id="txt_sr_date" type="text" class="easyui-datebox validBackward" readonly value='<?php echo $detail->PPayDate; ?>' style="width:127px;height:22px;" required editable="false" />
                            </td>
                        </tr>
                        
                        <tr height="47"valign="middle"></tr>

                                
                        </table>
                    </td>
                </tr>
                <tr><td colspan="8"><hr/></td></tr>
                <tr>
                	<td width="50%" valign="top">
                    	<table width="100%" cellpadding="0" cellspacing="1">
                        <tr height="20">
                        	<td width="135"><b>Account Name</b></td>
                            <td width="14"><b>:</b></td>
                            <td width="495">
                            	<select class="easyui-combogrid" id="cbg_bank" name="cbg_bank" readonly
                                	required editable="false" 
                                	style="width:252px;height:22px;" 
                                    data-options="
                                        panelWidth: 400,
                                        value:'<?php echo $detail->BankPayment; ?>',
                                        idField: 'AccountNumber',
                                        textField: 'AccountName',
                                        url: '<?=base_url()?>list/purchase_expense/ajax_account_expense',
                                        method: 'get',
                                        columns: [[
                                            {field:'AccountNumber',title:'Account Number',width:110,halign:'center',hidden:true}, 
                                            {field:'AccountName',title:'Account Name',width:190,halign:'center'}, 
                                            {field:'CurrencyCode',title:'Currency',width:80,halign:'center',align:'center'}
                                        ]],
                                        fitColumns: true
                                    ">
                                </select>
                            </td>
                        </tr>
                        
                        <tr height="20">
                        	<td width="135" valign="top" style="padding-top:4px;"><b>Memo</b></td>
                            <td width="14" valign="top" style="padding-top:4px;"><b>:</b></td>
                            <td>
                            	<textarea id="txa_sr_desc" name="txa_sr_desc" rows="4" style="width:246px;resize:none;" <?=(in_array($detail->TransStatus,array(0,6,7,1)))?'':'readonly'?>><?php echo $detail->PPayDesc; ?></textarea>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">
                    	
                    </td>
                </tr>
                </table>

                <!-- End of form header -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">		
                    <div id="tab_item" title="Invoice">
                    	<table id="dtg_item" class="easyui-<?=(in_array($detail->TransStatus,array(0,1,2,3,9)) || ($detail->CreatedBy != $this->session->userdata('username')))?'datagrid':'edatagrid'?>"
                        	url="<?=base_url() . $menu_link . "/ajax_expense_for_edit/".$detail->PPayNumber;?>"
                            toolbar="#toolbar" idField="id"
                            rownumbers="true" fitColumns="true" 
                            singleSelect="true" style="height:236px;"
                        >
                            <thead frozen="true">
                            <tr>
                                <th rowspan="2" resizable="false" field="Invoice_Type"     width="50"  halign="center" align="center" editor="{type:'validatebox'}" hidden>Type</th>
                                <th rowspan="2" resizable="false" field="Invoice_Number"   width="255" halign='center' align="left"   editor="{type:'validatebox',options:{required:true}}" >Invoice No.</th>
                                <th rowspan="2" resizable="false" field="Invoice_Date"     width="100"  halign='center' align="center" editor="{type:'validatebox',options:{required:true}}" formatter="formatDate">Date</th>
                                <th colspan="1">Invoice Amount</th>
                                <th colspan="1">Invoice Owing</th>
                                <th colspan="1">Payment Amount</th>
                                
                                <th rowspan="2" resizable="false" field="ItemCategoryName" width="150" halign="center" align="center" editor="text" >Category Name</th>
                                <th rowspan="2" resizable="false" field="ItemCategoryID"   width="50"  halign="center" align="left" editor="text" hidden>Category ID</th>
                                <th rowspan="2" resizable="false" field="ItemCategoryCode"   width="95"  halign="center" align="left" editor="text" hidden>Category Code</th>
                                <th rowspan="2" resizable="false" field="InvoiceCurrCode"   width="50"  data-options="halign:'center',align:'right'" editor="{type:'text', disabled:'true'}" hidden>Invoice Currency Code</th>
                                <th rowspan="2" resizable="false" field="InvoiceCurrRate"   width="50"  data-options="halign:'center',align:'right'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" hidden>Invoice Currency Rate</th>
                            	<th rowspan="2" resizable="false" field="InvoiceFiscalRate" width="85"  data-options="halign:'center',align:'right'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" hidden>Fiscal Rate</th>
                                
                                <th rowspan="2" resizable="false" field="PPnFiscalStatus"   width="60" halign='center' align="right"  editor="text" hidden>PPN Fiscal Status</th>
                                <th rowspan="2" resizable="false" field="InvoiceTypeID"     width="50"  halign="center" align="center" editor="{type:'validatebox'}" hidden>Type ID</th>
                                <th rowspan="2" resizable="false" field="InvoicePaymentID"  width="50"  halign="center" align="center" editor="{type:'validatebox'}" hidden>Invoice Payment ID</th>
                                <th field="InvoiceAmountCopy"   width="215" halign='center' align="right"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" formatter="formatRp" hidden>Invoice Amount Copy</th>
                                <th rowspan="2" resizable="false" field="PPayDetailID"   width="50"  halign="center" align="left" editor="text" hidden>PPay Detail ID</th>
                            </tr>
                            <tr>
                            	<th field="Invoice_Amount"   width="245" halign='center' align="right"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" formatter="formatRp"><span class="spn_customer_curr_code">(IDR)</span></th>
                                <th field="Invoice_Owing"    width="245" halign='center' align="right"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" formatter="formatRp"><span class="spn_customer_curr_code">(IDR)</span></th>
                                
                                <th field="Payment_Amount"   width="245" halign="center" align="right" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0}}" formatter="formatRp"><span class="spn_customer_curr_code">(IDR)</span></th>                                

                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <!-- End Item Grid -->
            </form>
        </div>
     </div>
     <div id="form-footer" data-options="region:'south',border:false">
    	<table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td>&nbsp;</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_pexp(2);" <?= ($this->session->userdata("jobtitle_status") != 0 || (date('Y-m-d') < date('Y-m-d', strtotime($detail->PPayDate))) || !in_array($detail->TransStatus,array(5,6))) ? 'disabled' : ''?>>App. Dir</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-ok" onclick="approval_pexp(1);" <?= ($this->session->userdata("jobtitle_status") != 1 || (date('Y-m-d') < date('Y-m-d', strtotime($detail->PPayDate))) || !in_array($detail->TransStatus,array(4,6))) ? 'disabled' : ''?>>App. Mgr</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" <?php if($detail->TransStatus != 6 || ($detail->AppLevel1Status == 1 || $detail->AppLevel2Status == 1) ){ echo " disabled "; } ?> onclick="update_data();" <?php echo $cek_autority_save;?>>Save</a> 								
                    <!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="link_print('<?=$menu_link?>/to_print_detail/<?=$detail->PPayNumber?>');" <?=((in_array($detail->TransStatus,array(3,9)))?'disabled="true"':'')?>>Preview & Print</a>  -->
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="parent.tab_add('Form <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_print_detail/<?=$detail->PPayNumber?>');" <?=(in_array($detail->TransStatus,array(1,2,3,,9,6,5,4)))?'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,6,5)))?'disabled="true"':'')?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
                </td>
            </tr>
        </table>
    </div>
</div>



<script type="text/javascript">

$(document).ready(function(){
	
	var currency_code = '<?php echo $detail->CurrencyCode;?>';
	$('#cbg_branch').combogrid({
		onSelect:function(rowIndex, rowData){
			$('#cbg_vendor').combogrid('setValue','');
			$('#cbg_bank').combogrid('setValue','');
			$('#txa_address').val('');
												
			$('#cbg_vendor').combogrid('grid').datagrid('load',{
				BranchCode : rowData.BranchCode,
				CompanyCode : rowData.CompanyCode
			});
		}
	});	
	
	/*
		Combo grid customer
	*/
	$('#cbg_vendor').combogrid({
		onSelect:function(rowIndex, rowData){
			
			/*
				Jika customer adalah usd maka tombol fiscal nyala
			*/
			if(rowData.CurrencyCode == 'USD'){
				if(rowData.ItemCategoryName == 'PPn Fiscal'){
					$('#chk_fiscal_payment').prop('checked',true);
					$('#chk_fiscal_payment').prop('disabled',true);
				}
			}
			/*===============End=====================================*/
			
			/*
				Tampung currency ke textbox 
			*/
			$('#hdn_cust_curr').val(rowData.CurrencyCode);
			$('#txa_address').val(rowData.VendorAddress);
			/*==============End=====================*/
			
			
			/*
				Merubah label di invoice amount,owinf dan receipt
			*/
			$('.spn_customer_curr_code').html('('+rowData.CurrencyCode+')');
			
			//$('#spn_cust_curr').text(rowData.CurrencyCode);
			/*================End================================*/
			
			/*
				Load pop up by customer
			*/
			$('#tt_choose').datagrid({
				url:'<?=base_url()?>list/purchase_expense/get_detail_invoice/'+rowData.VendorCode
			 });
			/*===============End==============================*/
		}		
	});	
	/*============================End================================*/
	
	/*=============Function editor grid=============================*/
	editoy_grid();
	tab_pop_up();
	
	if($('#hdn_fiscal_status').val() == 1){
		$('.spn_customer_curr_code').html('(IDR)');
	}
	else{
		$('.spn_customer_curr_code').html('('+currency_code+')');
	}
	/*====================End=========================================*/
	
	/*
		Save Row
	*/
	$('#frm_purchase_journal').click(function(){
		$('#dtg_item').edatagrid('saveRow');
	});
	/*=================End================*/
});

function editoy_grid(){
	$('#dtg_item').datagrid({
		onBeginEdit:function(rowIndex){
			editors = $('#dtg_item').datagrid('getEditors', rowIndex);
			InvoiceType		 	= $(editors[0].target);
			InvoiceNumber 	 	= $(editors[1].target);
			InvoiceDate 	 	= $(editors[2].target);
			InvoiceAmount 		= $(editors[3].target);
			InvoiceOwing 		= $(editors[4].target);
			PaymentAmount 		= $(editors[5].target);
			ItemCategoryName 	= $(editors[6].target);
			ItemCategoryID		= $(editors[7].target);
			ItemCategoryCode 	= $(editors[8].target);
			InvoiceCurrCode 	= $(editors[9].target);
			InvoiceCurrRate 	= $(editors[10].target);
			InvoiceFiscalRate 	= $(editors[11].target);
			PPnFiscalStatus 	= $(editors[12].target);
			InvoiceAmountCopy 	= $(editors[15].target);
			
			InvoiceNumber.prop('readonly',true);
			InvoiceType.prop('readonly',true);
			InvoiceDate.prop('readonly',true);
			ItemCategoryName.prop('readonly',true);
			
			InvoiceAmount.numberbox('disable');
			InvoiceOwing.numberbox('disable');
			
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			$('.save-button').linkbutton('disable');
			/*=================================end============================================================*/
			
			PaymentAmount.numberbox({
				onChange:function(){
					
					InvoiceAmount   = parseFloat(InvoiceAmountCopy.numberbox('getValue'));
					PaymentAmount   = parseFloat(PaymentAmount.numberbox('getValue'));
					
					if(isNaN(InvoiceAmount)){InvoiceAmount = 0;}
					
					if(PaymentAmount > InvoiceAmount){
						$.messager.alert('Maaf','Payment Amount tidak boleh lebih besar dari Invoice Amount','error',function(){
							//PaymentAmount.numberbox('setValue', 0);
							$('#dtg_item').datagrid('reload'); 
						});
					}
					else{
						owing   = InvoiceAmount - PaymentAmount;
						InvoiceOwing.numberbox('setValue', owing);
					}
				}
			});
		},
		onEndEdit:function(rowIndex, rowData, changes){
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			$('.save-button').linkbutton('enable');
			/*=================================end============================================================*/
			dtg_item 		= $('#dtg_item').datagrid('getRows');
			payment_amount 	= 0;
			total_payment 	= 0;
			owing 			= 0;
			total_owing = 0;
			$.each(dtg_item, function(index, value) {
					payment_amount 			= parseFloat(value.Payment_Amount);
					total_owing 					= parseFloat(value.InvoiceAmountCopy) - parseFloat(value.Payment_Amount);
					
					if(isNaN(payment_amount)){payment_amount = 0;}
					total_payment   += payment_amount;
			});
			
			$('#hdn_rec_amount').numberbox('setValue', total_payment);
			$('#hdn_inv_owing').numberbox('setValue', total_owing);
		}
	});
}

function tab_pop_up(){
	$('#tab_purchase_req').tabs({
		border:true,
		onSelect:function(title){
			if(title == 'Select Purchase Invoice'){
				var vendor_code = $('#cbg_vendor').combogrid('grid').datagrid('getSelected').VendorCode;
				$('#tt_choose').datagrid({
					url:'<?=base_url()?>list/purchase_expense/get_detail_invoice/'+vendor_code
				 });
			}
			else{
				 var vendor_code = $('#cbg_vendor').combogrid('grid').datagrid('getSelected').VendorCode;
				 $('#tt_choose_dp').datagrid({
					url:'<?=base_url()?>list/purchase_expense/get_data_dp/'+vendor_code
				 });
			}
		}
	});
}

function select_purchase() {
	var Vendor			= $('#cbg_vendor').combogrid('grid');	// get datagrid object
	var SelectedCustomer	= Vendor.datagrid('getSelected'); // get the selected row

	if(SelectedCustomer == null ){
		$.messager.alert('Maaf','Silahkan pilih customer terlebih dahulu','warning',function(){});
	}
	else{
		modal_open('Purchase Journal','dialog-sq');
	}		
}

function choose_item_dp(){
	var si				 	= $('#tt_choose_dp').datagrid('getSelected').Invoice_Number;
	var Currencycode	 	= $('#tt_choose_dp').datagrid('getSelected').InvoiceCurrCode;
	var ItemCategoryName 	= $('#tt_choose_dp').datagrid('getSelected').ItemCategoryName;
	var PPnFiscalStatus  	= $('#tt_choose_dp').datagrid('getSelected').PPnFiscalStatus;
	var InvoiceType  		= $('#tt_choose_dp').datagrid('getSelected').Invoice_Type;
	var InvoiceFiscalRate  	= $('#tt_choose_dp').datagrid('getSelected').InvoiceFiscalRate;
	var InvoiceCurrRate  	= $('#tt_choose_dp').datagrid('getSelected').InvoiceCurrRate;
	var InvoiceAmount  		= $('#tt_choose_dp').datagrid('getSelected').Invoice_Amount;
	var InvoiceOwing  		= $('#tt_choose_dp').datagrid('getSelected').Invoice_Owing;
	
	$('#hdn_inv_amount').numberbox('setValue',InvoiceAmount);
	$('#hdn_inv_owing').numberbox('setValue',InvoiceOwing);
	$('#hdn_fiscal_status').val(PPnFiscalStatus);
	$('#hdn_inv_type').val(InvoiceType);
	$('#hdn_cust_curr_rate').numberbox('setValue', InvoiceCurrRate);
	$('#hdn_fiscal_rate').numberbox('setValue', InvoiceFiscalRate);
	
	/*
		Load datagrid detail
	*/
	$('#dtg_item').datagrid('load',{
		invoice_type : 0,
		invoice_name : InvoiceType,
		si_number: si
	});
	
	/*
	cek by type invoice, fiscal or dp
	*/
	if(ItemCategoryName == 'PPn Fiscal'){
		$('.spn_customer_curr_code').html('(IDR)');
	}
	else{
		$('.spn_customer_curr_code').html('('+Currencycode+')');
	}
	/*==================End============================================*/
			
	modal_close('dialog-sq');
}

function choose_item_sq(){
	var si				 	= $('#tt_choose').datagrid('getSelected').Invoice_Number;
	var Currencycode	 	= $('#tt_choose').datagrid('getSelected').InvoiceCurrCode;
	var ItemCategoryName 	= $('#tt_choose').datagrid('getSelected').ItemCategoryName;
	var PPnFiscalStatus  	= $('#tt_choose').datagrid('getSelected').PPnFiscalStatus;
	var InvoiceType  		= $('#tt_choose').datagrid('getSelected').Invoice_Type;
	var InvoiceFiscalRate  	= $('#tt_choose').datagrid('getSelected').InvoiceFiscalRate;
	var InvoiceCurrRate  	= $('#tt_choose').datagrid('getSelected').InvoiceCurrRate;
	var InvoiceAmount  		= $('#tt_choose').datagrid('getSelected').Invoice_Amount;
	var InvoiceOwing  		= $('#tt_choose').datagrid('getSelected').Invoice_Owing;
	
	$('#hdn_inv_amount').numberbox('setValue',InvoiceAmount);
	$('#hdn_inv_owing').numberbox('setValue',InvoiceOwing);
	$('#hdn_fiscal_status').val(PPnFiscalStatus);
	$('#hdn_inv_type').val(InvoiceType);
	$('#hdn_cust_curr_rate').numberbox('setValue', InvoiceCurrRate);
	$('#hdn_fiscal_rate').numberbox('setValue', InvoiceFiscalRate);
	
	/*
		Load datagrid detail
	*/
	
	if(ItemCategoryName == 'PPn Fiscal'){
		$('#dtg_item').datagrid('load',{
			invoice_type : 1,
			invoice_name : InvoiceType,
			si_number: si
		});
	}
	else{
		$('#dtg_item').datagrid('load',{
			invoice_type : 0,
			invoice_name : InvoiceType,
			si_number: si
		});
	}
	
	/*
	cek by type invoice, fiscal or dp
	*/
	if(ItemCategoryName == 'PPn Fiscal'){
		$('.spn_customer_curr_code').html('(IDR)');
	}
	else{
		$('.spn_customer_curr_code').html('('+Currencycode+')');
	}
	/*==================End============================================*/
			
	modal_close('dialog-sq');
}

function update_data(){
	
	var url             = '<?= base_url();?>custom/custom/checking_update';
	var no_transaksi    = $('#txt_sr_no').val();
	var trans_status 	= '<?=$detail->TransStatus?>';
		
	dtg_item = $('#dtg_item').datagrid('getRows');
	si_total_amount 	= 0;
	invoice_amount 		= 0;
	
	$.each(dtg_item,function(index,value){
			si_total_amount 	= parseFloat(value.Payment_Amount);
			invoice_amount 		= value.Invoice_Amount;
	});
	
	if($('#hdn_fiscal_status').val() == 1){
		if(si_total_amount != invoice_amount){
			$.messager.alert('Informasi','Maaf transaksi anda gagal, silahkan isi nilai sesuai Invoice Amount untuk Fiscal Payment','info');
			return false;
		}
		else{
			if(si_total_amount == 0){
				$.messager.alert('Informasi','Maaf transaksi anda gagal, nilai payment tidak boleh kosong','info');
				return false;
			}
			else{
				var i       = $('#dtg_item').datagrid('getRows');
				var detail  = JSON.stringify(i);
			
				$("#detail").val(detail);	
				edit_transaction('list/purchase_expense','#frm_purchase_journal', no_transaksi, url, trans_status);
			}
		}
	}
	else{
		if(si_total_amount == 0){
			$.messager.alert('Informasi','Maaf transaksi anda gagal, nilai payment tidak boleh kosong','info');
			return false;
		}
		else{
			var i       = $('#dtg_item').datagrid('getRows');
			var detail  = JSON.stringify(i);
		
			$("#detail").val(detail);	
			
			edit_transaction('list/purchase_expense','#frm_purchase_journal', no_transaksi, url, trans_status);
		}
	}
		
}

function tab_pop_up(){
	$('#tab_purchase_req').tabs({
		border:true,
		onSelect:function(title){
			if(title == 'Select Sales Invoice'){
				var vendor_code = $('#cbg_vendor').combogrid('grid').datagrid('getSelected').VendorCode;
				
				$('#tt_choose').datagrid({
					url:'<?=base_url()?>list/purchase_expense/get_detail_invoice/'+vendor_code
				 });
			}
			else{
				var vendor_code = $('#cbg_vendor').combogrid('grid').datagrid('getSelected').VendorCode;

				 $('#tt_choose_dp').datagrid({
					url:'<?=base_url()?>list/purchase_expense/get_data_dp/'+vendor_code
				 });
			}
		}
	});
}

function approval_pexp($status) {
	var url_check           = '<?= base_url();?>custom/custom/checking_approval';
	var no_transaksi    	= $('#txt_sr_no').val();
	modal_open('Progress Bar','dlg_loading');
	
	$.post(url_check, {no_transaksi:no_transaksi}, function(result){
		if (result.status === false){
			approval($status);
		} 
		else{
			$.messager.alert('Unseccessfull',result.message,'error',function(){
				location.reload();
			});
		}
	},'json');
}
	
function approval($status){
    var url         = base_url + 'list/purchase_expense/approval';
	var i           = $('#dtg_item').datagrid('getRows');

	var PPayNumber  	= $("#txt_sr_no").val();
	var VendCode    	= $('#cbg_vendor').combogrid('getValue');
	var Detail      	= JSON.stringify(i);
	var PPayDate 		= $('#txt_sr_date').datebox('getValue');
	var CurrencyRate 	= $('#hdn_cust_curr_rate').numberbox('getValue');
	var DPPartial 		= $('#hdn_saldo_partial').numberbox('getValue');
	var BranchCode  	= $("#cbg_branch").val();
	
	var TotalRecipt 	= $('#hdn_rec_amount').numberbox('getValue');
	var Cust_curr_code 	= $('#hdn_cust_curr').val();
	var Status 			= $status;
	
	$.post(url, {Status:Status,BranchCode:BranchCode,DPPartial:DPPartial, PPayNumber:PPayNumber, VendCode:VendCode, Detail:Detail, PPayDate:PPayDate, CurrencyRate:CurrencyRate, TotalRecipt:TotalRecipt, Cust_curr_code:Cust_curr_code}, function(result){
		if (result.status == true){
			$.messager.alert('Success',result.message,'info',function(){
				location.reload();						                    
			});	
			modal_close('dlg_loading'); 						
		} 
		else {
			$.messager.alert('Error',result.message,'error',function(){
				location.reload();						                    
			});				
		}
	},'json');
}
	
function suspend(type){
	var url             = '<?= base_url();?>custom/custom/checking_suspend';
	suspend_data_new_check('F', type, '<?=$menu_link?>', $('#txt_sr_no').val(), 'Purchase Journal', url);
} 
</script>