<!---- 
Author  : Ferry / Tanggal : 02-02-2015  
-->
    
   <?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 width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td align="left" width="30%">
					<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,5)))?"disabled":"")?> <?php echo $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" plain="true" iconCls="icon-currency" onclick="to_transaction()" <?=(in_array($detail->TransStatus,array(1)))?'':'disabled'?>>To Purchase Payment</a>
                    <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 top view -->
    
    <!-- center 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(1,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==1){ echo 'On Progres'; }elseif($detail->TransStatus==9){ echo 'Canceled by Dir.'; }else{ echo 'Unknown'; } ?></b></div>
            <?php } ?>
            
            <form id="fm_purchase_payment" name="fm_purchase_payment" method="post">
                <input type="hidden" name="detail" id="detail"/>
                
                <input type="hidden" name="hdn_vend_curr_code" id="hdn_vend_curr_code" value="<?=$detail->CurrencyCode?>"/>
                <input type="hidden" name="hdn_bank_curr_code" id="hdn_bank_curr_code" value="<?=$detail->BankCurrCode?>"/>
                <input type="hidden" name="hdn_payment_status" id="hdn_payment_status"/>
                
                <input type="hidden" name="txt_vendor_rate" id="txt_vendor_rate" class="easyui-numberbox" value="<?=$detail->BankCurrRate?>" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                 
                <input type="hidden" name="hdn_total_currency" id="hdn_total_currency" class="easyui-numberbox" value="<?=$detail->PGirTotalAmount?>" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                                                        
                <input type="hidden" name="hdn_branch_for"      id="hdn_branch_for" value="<?= $this->session->userdata("branch") ?>"/>
                
                <input type="hidden" name="hdn_po_status"       class="easyui-numberbox" id="hdn_po_status" value="0"/>
                <input type="hidden" name="hdn_pi_status"       class="easyui-numberbox" id="hdn_pi_status" value="0"/>
				
                <input type="hidden" name="hdn_transstatus"       class="easyui-numberbox" id="hdn_transstatus" value="<?=$detail->TransStatus?>"/>
                
                <!-- Form Header -->
                <table width="100%" height="141" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="72%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr height="20">
                                    <td width="137"><b>Branch Name</b></td>
                                    <td width="13"><b>:</b></td>
                                    
                                    <td width="797">
                                        <select class="combo-grid" name="cbg_branch" id="cbg_branch" style="width:252px;height:22px;" required <?=(($this->session->userdata("branch_status")==1)?"disabled":'') ?> editable="false" disabled
                                            data-options="
                                                panelWidth:400,
                                                value: '<?=$detail->BranchPaidFor?>',
                                                idField: 'BranchCode',
                                                textField: 'BranchName',
                                                url: '<?=base_url()?>custom/get_data/branch_no_filter',
                                                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="137"><b>Paid To</b></td>
                                    <td width="13"><b>:</b></td>
                                    
                                    <td>
                                        <select class="combo-grid" name="cbg_vendor" id="cbg_vendor" style="width:252px;height:22px;" required disabled
                                            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>
                                    </td>
                                </tr>

                                <tr height="20">
                                    <td width="137" valign="top" style="padding-top:4px;"><b>Payee</b></td>
                                    <td width="13" valign="top" style="padding-top:4px;"><b>:</b></td>
                                    
                                    <td>
                                        <textarea name="txa_address" id="txa_address" rows="4" style="width:246px;resize:none;" required readonly><?=$detail->VendorAddress?></textarea>
                                    </td>
                                </tr>                                
                            </table>
                        </td>
                    
                        <td width="28%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                
                                <tr valign="middle">
                                    <td colspan="2" width="322">&nbsp;</td>
                                    <td width="120"><b>Payment No.</b></td>
                                    <td width="10"><b>:</b></td>

                                    <td>
                                       <input type="text" name="txt_pgir_no" id="txt_pgir_no" class="easyui-validatebox" required="true" value="<?=$detail->PGirNumber?>" style="width:257px;text-align:center;" readonly />
                                    </td>
                                </tr>
                                <tr valign="middle">
                                    <td colspan="2" width="322">&nbsp;</td>
                                    <td width="120"><b>Payment Date</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <input name="txt_pgir_date" id="txt_pgir_date" type="text" class="easyui-datebox validBackward" style="width:259px;" value='<?=date('d-m-Y',strtotime($detail->PGirDate))?>' required editable="false" readonly/>
                                    </td>
                                </tr>
                                <tr valign="middle">
                                    <td colspan="2" width="322">&nbsp;</td>
                                    <td width="120"><b>Date Giro.</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <input name="txt_date_giro" id="txt_date_giro" type="text" class="easyui-datebox validBackward" style="width:259px;" value='<?=date('d-m-Y',strtotime($detail->DateGiro))?>' required editable="false" />
                                    </td>
                                </tr>
                                
                                <tr height="47"valign="middle"></tr>

                                <tr>
                                    <td colspan="2" width="322">&nbsp;</td>
                                    <td colspan="2" width="322">&nbsp;</td>
                                    
                                    <td height="20">
                                        
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <tr>
                        <td colspan="8"><hr/></td>
                    </tr>

                    <tr>
                        <td width="72%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr height="20">
                                    <td width="137"><b>Bank Payment</b></td>
                                    <td width="11"><b>: </b></td>
                                    
                                    <td width="781">
                                        <select class="easyui-combogrid" name="cbg_bank" id="cbg_bank" style="width:252px;height:22px;" required editable="false" disabled
                                            data-options="
                                                panelWidth:400, 
                                                value: '<?=$detail->BankPayment?>', 
                                                idField: 'AccountNumber',
                                                textField: 'AccountName',
                                                url: '<?=base_url()?>list/purchases_payment/ajax_bank_account',
                                                method: 'post',
                                                columns: [[
                                                    {field:'AccountName',title:'Bank Code',width:45,halign:'center'},
                                                    {field:'AccountNumber',title:'Bank Name',width:100,halign:'center'}						
                                                ]],
                                                fitColumns: true
                                            ">
                                        </select>
                                    </td>
                                </tr>
                                
                                <tr height="20">
                                    <td width="137"><b>Currency Rate</b></td>
                                    <td width="11"><b>:</b></td>
                                    
                                    <td>
                                        <input type="text" name="txt_bank_curr_rate" id="txt_bank_curr_rate" class="easyui-numberbox" required="true" value="<?=$detail->BankCurrRate?>" style="width:70px;text-align:right;"
                                            data-options="min:1, precision:2, groupSeparator:'.', decimalSeparator:','" 
                                        />
                                        
                                        <span id="currency" style="font-weight:bold"></span>
                                    </td>
                                </tr>
                                
                                <tr height="20">
                                    <td width="137" valign="top" style="padding-top:4px;"><b>Memo</b></td>
                                    <td width="11" valign="top" style="padding-top:4px;"><b>:</b></td>
                                    
                                    <td>
                                        <textarea name="txa_description" id="txa_description" rows="4" style="width:246px;resize:none;"><?=$detail->PGirDesc?></textarea>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        
                        <td width="28%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                
                                                                
                                <tr>
                                    <td width="209"><b>Cheque No</b></td>
                                    <td width="13"><b>:</b></td>
                                    
                                    <td>
                                        <input type="text" name="txt_cheque_no" id="txt_cheque_no" class="easyui-validatebox" style="width:160px;text-align:right;"  required
                                            value="<?=$detail->ChequeNumber?>"
                                        />
                                    </td>
                                </tr>
                                
                                <tr>
                                    <td width="209"><span id="lbl_payment_curr" style="font-weight:bold">Total Payment (<?php echo $detail->BankCurrCode;?>)</span></td>
                                    <td width="13"><b>:</b></td>
                                    
                                    <td>
                                        <input type="text" name="txt_total_amount" id="txt_total_amount" class="easyui-numberbox" value='0,00' style="width:162px;text-align:right;" readonly 
                                            data-options="min:0, precision:2, groupSeparator:'.', decimalSeparator:','"
                                        />
                                    </td>
                                </tr>                                
                            </table>
                        </td>
                    </tr>
                </table>
                <!-- End of form header -->
                
                <!--Item Grid -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin-top:5px;">       
                    <div id="tab_item" title="Payment">
                        <table id="dtg_item" class="easyui-edatagrid" title="" iconCls="icon-edit" singleSelect="true" rowNumbers="true" fitColumns="true" style="height:240px"
                            url="<?=base_url()?>list/purchase_giro/ajax_item_for_edit/<?=$detail->PGirNumber?>" 
                        >
                            <thead frozen="true">
                                <tr>
                                    <th rowspan="2" field="Paid"              width="80"  data-options="halign:'center',align:'center'" resizable='false' editor="{type:'checkbox',options:{on:'Yes',off:'No'}}">Paid</th>
                                    <th rowspan="2" field="Invoice_Type"      width="90"  data-options="halign:'center',align:'center'" resizable='false' editor="{type:'validatebox'}" hidden>Invoice Type</th>
                                    <th rowspan="2" field="Invoice_Number"    width="360" data-options="halign:'center',align:'left'"   resizable="false" editor="{type:'validatebox',options:{required:true,disabled:true}}" >Invoice No.</th>
                                    <th rowspan="2" field="Invoice_Date"      width="220"  data-options="halign:'center',align:'center'" resizable="false" editor="{type:'validatebox',options:{required:true,disabled:true}}" formatter="formatDate">Inv. Date</th>
                                    <th colspan="1" hidden>Invoice Amount</th>
                                    <th colspan="1" hidden>Invoice Owing</th>
                                    <th rowspan="1">Rounding</th>
                                    <th colspan="2">Payment Amount</th>
                                    <th rowspan="2" field="ItemCategoryCode"  width="150" data-options="halign:'center',align:'center'" resizable="false" editor="{type:'text', disabled:'true'}" >Category Code</th>
                                    
                                </tr>
                                <tr>
                                    <th field="Invoice_Amount"   width="150" data-options="halign:'center',align:'right'" resizable="false" 
                                    editor="{type:'numberbox',options:{decimalSeparator:',',required:true,disabled:true,
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden><span class="spn_vend_curr">(IDR)</span></th>
                                    <th field="Invoice_Owing"    width="150" data-options="halign:'center',align:'right'" resizable="false" 
                                    editor="{type:'numberbox',options:{decimalSeparator:',',required:true,disabled:true,
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden><span class="spn_vend_curr">(IDR)</span></th>
                                    <th field="Load_Rounding"    width="150" data-options="halign:'center',align:'right'" resizable="false" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp"><span class="spn_vend_curr">(IDR)</span></th>

                                    <th field="Payment_Amount"   width="150" data-options="halign:'center',align:'right'" resizable="false" editor="{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',required:true}}" formatter="formatRp"><span class="spn_vend_curr">(IDR)</span></th>
                                    <th field="Payment_Currency" width="150" data-options="halign:'center',align:'right'" resizable="false" editor="{type:'numberbox',options:{min:0,precision:2,decimalSeparator:',',required:true}}" formatter="formatRp"><span class="spn_bank_curr">(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_pgir(2);" <?= ($this->session->userdata("jobtitle_status") != 0 || (date('Y-m-d') < date('Y-m-d', strtotime($detail->PGirDate))) || !in_array($detail->TransStatus,array(5,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" <?php if($detail->TransStatus != 5 || ($detail->AppLevel1Status == 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->PGirNumber?>');" <?=((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->PGirNumber?>');" <?=(in_array($detail->TransStatus,array(1,2,3,6,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,5)))?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
                </td>
            </tr>
        </table>
    </div>
</div>

<script type="text/javascript">
    var SavePrivillage  = '<?php echo $group_user->SavePrivillage;?>';
	
	$(document).ready(function(){
		$('#hdn_payment_status').val(0);
		var vend_curr_code      	= $('#hdn_vend_curr_code').val();
        var bank_curr_code      	= $('#hdn_bank_curr_code').val();
		
		if(vend_curr_code == 'IDR'){
			if(bank_curr_code == 'IDR'){
				$('#txt_total_amount').numberbox('setValue', '<?=$detail->PGirTotalAmount?>');
			}
			else{
				$('#txt_total_amount').numberbox('setValue', '<?=$detail->PGirTotalCurrency?>');
			}
		}
		else{
			if(bank_curr_code == 'USD'){
				$('#txt_total_amount').numberbox('setValue', '<?=$detail->PGirTotalAmount?>');
			}
			else{
				$('#txt_total_amount').numberbox('setValue', '<?=$detail->PGirTotalCurrency?>');
			}
		}
		
		$('#cbg_bank').combogrid('grid').datagrid('load',{
            CurrencyCode : vend_curr_code
        });
		
		if(vend_curr_code != 'IDR'){
            $('#currency').html(vend_curr_code + ' / IDR');
        }
        else{
            $('#currency').html(bank_curr_code + ' / IDR');
        }
		
		if(($('#hdn_bank_curr_code').val() == '') || ($('#hdn_vend_curr_code').val() == $('#hdn_bank_curr_code').val())){
			$('#dtg_item').datagrid('hideColumn', 'Payment_Currency');
			$('#hdn_payment_status').val(0);
		}
		else{
			$('#dtg_item').datagrid('showColumn', 'Payment_Currency');
			$('#hdn_payment_status').val(1);
		}
		
		if((bank_curr_code == vend_curr_code) && (vend_curr_code == 'IDR')){
			$('#txt_bank_curr_rate').prop('disabled', true);
		}
		else{
			$('#txt_bank_curr_rate').prop('disabled', false);
		}
				
		$('#dtg_item').datagrid({
			onBeginEdit:function(rowIndex,rowDatax){
				editors = $('#dtg_item').datagrid('getEditors', rowIndex);
				
				paid_editor                 = $(editors[0].target); //Paid Editor
				invoice_type_editor         = $(editors[1].target); //Invoice Type
				invoice_no_editor           = $(editors[2].target); //Invoice Number
				invoice_date_editor         = $(editors[3].target); //Invoice Date
				invoice_amount_editor       = $(editors[4].target); //Invoice Amount
                invoice_owing_editor        = $(editors[5].target); //Owing Amount
				invoice_rounding            = $(editors[6].target); //rounding 
                invoice_payment_editor      = $(editors[7].target); //Payment Amount
                invoice_paycurr_editor      = $(editors[8].target);//Payment Currency
				ItemCategoryCode      		= $(editors[9].target);//Item Category Code
				
				$(invoice_type_editor).prop('readonly', true);
				$(invoice_no_editor).prop('readonly', true);
				$(invoice_date_editor).prop('readonly', true);
				$(invoice_payment_editor).prop('readonly', true);
				$(invoice_paycurr_editor).prop('readonly', true);
				$(invoice_rounding).prop('readonly', true);
				$(ItemCategoryCode).prop('readonly', true);
				
				if($('#cbg_bank').combogrid('getValue') == ''){
					$(paid_editor).val('No');                    
					$.messager.alert('Warning','Silahkan pilih Bank Payment terlebih dahulu...!!','warning');                    
				}
				else{
					if($(paid_editor).is(':checked')){
						
						if($('#hdn_vend_curr_code').val() == "IDR"){
							if($('#hdn_bank_curr_code').val() == "IDR"){
								$(invoice_rounding).prop('readonly', true);
							}
							else{
								$(invoice_rounding).prop('readonly', false);
							}
						}
						else{
							if($('#hdn_bank_curr_code').val() == "IDR"){
								$(invoice_rounding).prop('readonly', true);
							}
							else{
								$(invoice_rounding).prop('readonly', true);
							}
						}
						
						if($('#hdn_payment_status').val() == 0){
							$(invoice_payment_editor).prop('readonly', false);
							$(invoice_paycurr_editor).prop('readonly', true);
						}
						else{
							$(invoice_payment_editor).prop('readonly', true);                        
							$(invoice_paycurr_editor).prop('readonly', false);                            
						}
					}
					
					$(paid_editor).click(function(){
						if($(this).is(':checked')){
							if($('#hdn_vend_curr_code').val() == "IDR"){
								if($('#hdn_bank_curr_code').val() == "IDR"){
									$(invoice_rounding).prop('readonly', true);
								}
								else{
									$(invoice_rounding).prop('readonly', false);
								}
							}
							else{
								if($('#hdn_bank_curr_code').val() == "IDR"){
									$(invoice_rounding).prop('readonly', true);
								}
								else{
									$(invoice_rounding).prop('readonly', true);
								}
							}
                            

                            if($('#hdn_payment_status').val() == 0){
                                $(invoice_payment_editor).prop('readonly', false);
                                $(invoice_paycurr_editor).prop('readonly', true);
                            }
                            else{
                                $(invoice_payment_editor).prop('readonly', true);                        
                                $(invoice_paycurr_editor).prop('readonly', false);                            
                            }        

                            $(invoice_payment_editor).numberbox('setValue', 0);
                            $(invoice_paycurr_editor).numberbox('setValue', 0);
                        }
                        else{
                            invoice_amount = parseFloat($(invoice_amount_editor).numberbox('getValue'));

                            $(invoice_payment_editor).prop('readonly', true);
                            $(invoice_paycurr_editor).prop('readonly', true);
                            $(invoice_rounding).prop('readonly', true);
                           
						    $(invoice_owing_editor).numberbox('setValue', invoice_amount);
                            
							$(invoice_payment_editor).numberbox('setValue', 0);
                            $(invoice_paycurr_editor).numberbox('setValue', 0);
                            $(invoice_rounding).numberbox('setValue', 0);
                        }
                    });
					
					$(invoice_payment_editor).numberbox({
                        onChange:function(){
                            if(($(paid_editor).is(':checked') == true) && ($('#hdn_payment_status').val() == 0)){
                                payment_amount          = parseFloat($(invoice_payment_editor).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
                                
                                if(isNaN(payment_amount)){payment_amount = 0;}
                                if(isNaN(currency_rate)){currency_rate = 1;}
                                
                                payment_currency    = currency_payment(currency_rate, payment_amount);
								
                                $(invoice_paycurr_editor).numberbox('setValue', payment_currency);  
                            }
                        }
                    }),
					
					$(invoice_paycurr_editor).numberbox({
                        onChange:function(){
                            if(($(paid_editor).is(':checked') == true) && ($('#hdn_payment_status').val() == 1)){
                                paycurr_amount          = parseFloat($(invoice_paycurr_editor).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
                                
                                if(isNaN(paycurr_amount)){paycurr_amount = 0;}
                                
                                payment_amount          = amount_payment(currency_rate, paycurr_amount);
                                
								$(invoice_payment_editor).numberbox('setValue', payment_amount);
                            }
                        }
                    });
				}
			},
			
			onEndEdit:function(rowIndex, rowData, changes){
                item                    = $('#dtg_item').datagrid('getRows');
                total_dp                = 0;
                total_payment_amount    = 0;
                total_payment_currency  = 0;
                total_invoice           = 0;
                total_owing             = 0;
                total_disc              = 0;
                loop_index_row_pi       = 0;
                loop_index_row_po       = 0;
                
                rate                    = $('#txt_bank_curr_rate').numberbox('getValue');
                /*====================on beg in edit saat grid di klik maka tombol save disable===================*/
                save_button_endedit(SavePrivillage);
                /*=================================end============================================================*/
				
				$.each(item, function(index, value) {
                    payment_amount      = parseFloat(value.Payment_Amount);
                    payment_currency    = parseFloat(value.Payment_Currency);
                   

                    if(isNaN(payment_amount)){payment_amount = 0;}
                    if(isNaN(payment_currency)){payment_currency = 0;}
                    
                    if(value.Paid == 'Yes'){
                        total_payment_amount    += payment_amount;
                        total_payment_currency  += payment_currency;
                    }
                });
				
				$('#hdn_total_currency').numberbox('setValue',total_payment_currency);
				
				if($('#hdn_vend_curr_code').val() == 'IDR'){
					if($('#hdn_bank_curr_code').val() == 'IDR'){
						total_payment_curr = total_payment_amount;
						$('#txt_total_amount').numberbox('setValue', total_payment_curr);
					}
					else{
						total_payment_curr = total_payment_currency;
						$('#txt_total_amount').numberbox('setValue', total_payment_curr);
					}
				}
				else{
					if($('#hdn_bank_curr_code').val() == 'IDR'){
						total_payment_curr = total_payment_currency;
						
						$('#txt_total_amount').numberbox('setValue', total_payment_curr);
					}
					else{
						total_payment_curr = total_payment_amount;
						$('#txt_total_amount').numberbox('setValue', total_payment_curr);
					}
				}
            }
		});
		
		$("#fm_purchase_payment").click(function() {
            $('#dtg_item').edatagrid('saveRow');
    	});
		
			$('.spn_vend_curr').text('('+vend_curr_code+')');
	});
	
	 $('#cbg_branch').combogrid({
		onSelect:function(rowIndex, rowData){
			$('#cbg_vendor').combogrid('setValue','');
			$('#cbg_bank').combogrid('setValue','');
			$('#txa_address').val('');

			$('#currency').html('IDR / IDR');
			$('#txt_bank_curr_rate').numberbox('setValue', 1);
		   
			$('#hdn_branch_for').val(rowData.BranchCode);
			
			$('#txt_bank_balance').numberbox('setValue', 0);
			$('#txt_total_amount').numberbox('setValue', 0);
												
			$('#cbg_vendor').combogrid('grid').datagrid('load',{
				BranchCode : rowData.BranchCode,
				CompanyCode : rowData.CompanyCode
			});
			
			$('#cbg_bank').combogrid('grid').datagrid('load',{
				CurrencyCode : rowData.Vnd_CurrencyCode
			});
			
			$('#dtg_item').datagrid('load',{
				VendorCode : ''
			});
		},onLoadSuccess:function(data){
		   $('#cbg_branch').combogrid('setValue',BranchCode);
		}
    }); 
	
	$('#cbg_vendor').combogrid({
		onSelect:function(rowIndex, rowData){
			var vend_address            = rowData.VendorAddress;
			var vend_curr_code          = rowData.Vnd_CurrencyCode;
			var exchange_rate           = rowData.ExchangeRate;
			
			$('#hdn_vend_curr_code').val(vend_curr_code);
			$('.spn_vend_curr').text('(' + vend_curr_code + ')');
			
			$('#currency').html(vend_curr_code + ' / IDR');
			$('#txt_bank_curr_rate').numberbox('setValue', exchange_rate);
			$('#txt_vendor_rate').numberbox('setValue', exchange_rate);

			$('#txa_address').val(vend_address);
			
			$('#cbg_bank').combogrid('setValue', '');
			$('#hdn_bank_curr_code').val('');
			
			$('#hdn_lock_status').val(rowData.LockStatus);
			
			$('#txt_cheque_no').val('');
			
			if(($('#hdn_bank_curr_code').val() == '') || ($('#hdn_vend_curr_code').val() == $('#hdn_bank_curr_code').val())){
				$('#dtg_item').datagrid('hideColumn', 'Payment_Currency');
				$('#hdn_payment_status').val(0);
			}
			else{
				$('#dtg_item').datagrid('showColumn', 'Payment_Currency');
				$('#hdn_payment_status').val(1);
			}

			if(vend_curr_code == 'IDR'){
				$('#txt_bank_curr_rate').prop('disabled', true);
			}
			else{
				$('#txt_bank_curr_rate').prop('disabled', false);                  
			}

			$('#dtg_item').datagrid('load',{
				VendorCode  : rowData.VendorCode,
				PPnFiscal   : 0
			});
			
			$('#cbg_bank').combogrid('grid').datagrid('load',{
				CurrencyCode : rowData.Vnd_CurrencyCode
			});
		},onLoadSuccess:function(data){
			$('#cbg_vendor').combogrid('setValue',VendorCode);
		}
    }); 
	
	$('#cbg_bank').combogrid({
		onSelect:function(rowIndex, rowData){
			var ppay_date       = $('#txt_pgir_date').datebox('getValue');
			var vend_curr_code  = $('#hdn_vend_curr_code').val();
			var bank_curr_code  = rowData.CurrencyCode;
			
			$('#hdn_bank_curr_code').val(bank_curr_code);
			$('#lbl_payment_curr').html('Total Payment (' + bank_curr_code + ')');
			
			
			$('.spn_bank_curr').text('(' + bank_curr_code + ')');
				
			if(($('#hdn_vend_curr_code').val() == '') || ($('#hdn_vend_curr_code').val() == $('#hdn_bank_curr_code').val())){
				$('#dtg_item').datagrid('hideColumn', 'Payment_Currency');
				$('#hdn_payment_status').val(0);
			}
			else{
				$('#dtg_item').datagrid('showColumn', 'Payment_Currency');
				$('#hdn_payment_status').val(1);
			}
			
			if((bank_curr_code == vend_curr_code) && (vend_curr_code == 'IDR')){
				$('#txt_bank_curr_rate').prop('disabled', true);
			}
			else{
				$('#txt_bank_curr_rate').prop('disabled', false);
			}
				
			
			if($('#hdn_vend_curr_code').val() != 'IDR'){
				$('#currency').html(vend_curr_code + ' / IDR');
			}
			else{
				$('#currency').html(vend_curr_code + ' / ' + bank_curr_code);                    
			}

			if(vend_curr_code == 'IDR'){
				$('#txt_bank_curr_rate').numberbox('setValue', rowData.CurrencyRate);
				$('#chk_fiscal_payment').prop('disabled', true);
			}
			else{
				if($('#hdn_bank_curr_code').val() == 'IDR'){
					$('#txt_bank_curr_rate').numberbox('setValue', $('#txt_vendor_rate').numberbox('getValue'));
					//$('#txt_bank_curr_rate').prop('disabled', true);
				}
				else{
					$('#txt_bank_curr_rate').numberbox('setValue', rowData.CurrencyRate);
					//$('#txt_bank_curr_rate').prop('disabled', false);
				}
			}
			
			$('#txt_total_amount').numberbox('setValue', 0);
			$('#dtg_item').datagrid('reload'); 
		}
    });
	
	 $('#txt_bank_curr_rate').numberbox({
        onChange:function(){
            var item    = $('#dtg_item').datagrid('getRows');
            curr_rate   = $('#txt_bank_curr_rate').numberbox('getValue');
            amount      = $('#txt_total_amount').numberbox('getValue');
            total_payment_amount    = 0;
            total_payment_currency  = 0;
            
            $.each(item, function(index, value){
                if(value.Paid == 'Yes'){
                    payment_amount      = parseFloat(value.Payment_Amount);
                    payment_currency    = parseFloat(value.Payment_Currency);

                    if(isNaN(payment_amount)){payment_amount = 0;}
                    if(isNaN(payment_currency)){payment_currency = 0;}
                        
                    if($('#hdn_payment_status').val() == 0) {
                        if($('#hdn_vend_curr_code').val() == 'IDR'){                
                            payment_currency    = payment_amount;
                        }
                        else{
                             payment_currency    = payment_amount * curr_rate;
                        }
                    }
                    else{
                        if($('#hdn_vend_curr_code').val() == 'IDR'){
                            payment_currency    = payment_amount / curr_rate;
                        }
                        else{
                            payment_currency    = payment_amount * curr_rate;
                        }
                    }                        

                    $('#dtg_item').datagrid('updateRow',{
                        index:index,
                        row:{Payment_Currency    : 0,
                                Payment_Amount   : 0,
                                Load_Rounding    : 0,
                                Invoice_Owing:value.InvoiceAmountCopy}
                    }); 
                        
                     
                    //$('#dtg_item').datagrid('reload');   
                    
                    total_payment_amount    += payment_amount;
                    total_payment_currency  += payment_currency;                                          
                }
            }); 
            $('#txt_total_amount').numberbox('setValue', 0);
        }
    });
	
	function amount_payment(currency_rate, payment_curr){  
	    if($('#hdn_payment_status').val() == 0){
            if($('#hdn_vend_curr_code').val() == 'IDR'){                
                payment = payment_curr;
            }
            else{
                payment = payment_curr / currency_rate;
            }
        }
        else{
            if($('#hdn_vend_curr_code').val() == 'IDR'){

                payment = payment_curr * currency_rate;
            }
            else{
               payment = payment_curr / currency_rate;                             
            }
        }

        return payment;
    }
	
	function update_data(){
		var url             = '<?= base_url();?>custom/custom/checking_update';
		var no_transaksi    = $('#txt_pgir_no').val();
		var trans_status 	= '<?=$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');?>';
		  	
		$('#dtg_item').edatagrid('saveRow');
	
		item            = $('#dtg_item').datagrid('getRows');
		total_row       = $('#dtg_item').datagrid('getData').total;
		
		selected_status 	= false;
		amount_lessnull 	= false;
		flag_total_amount 	= false;
		
		pi_total_amount 	= 0;
		pi_total_amount_new = 0;
		var BankCurrncyCode = $('#hdn_bank_curr_code').val();
		
		pi_total_amount_new_sum = 0;
		pi_total_amount_sum 	= 0;
		invoice_amount_sum 		= 0;

		if(total_row <= 0){
			$.messager.alert('Warning','Purchase Payment tidak dapat disimpan, karena tidak ditemukan data pada list item','warning');
		}
		else {            
			$.each(item, function(index, value) {
				if(value.Paid == 'Yes'){
					selected_status 	= true;
					pi_total_amount 	= parseFloat(pi_total_amount) + parseFloat(value.Invoice_Amount);
					pi_total_amount_new = parseFloat(value.Load_Rounding) + parseFloat(value.Payment_Amount);
					
					invoice_amount 		= parseFloat(value.Invoice_Amount);
					
					pi_total_amount_new_sum += pi_total_amount_new;
					pi_total_amount_sum 	+= pi_total_amount;
					invoice_amount_sum +=invoice_amount;
					
					total_all_payment 	= (parseFloat(value.Load_Rounding) + parseFloat(value.Payment_Amount));
					
					if(total_all_payment > parseFloat(value.Invoice_Amount).toFixed(2)){
						flag_total_amount 	= true;
						no_invoice 			= value.Invoice_Number; 
					}
				}
			});
			
			if(BankCurrncyCode == 'IDR'){
				total_pi 		= pi_total_amount_sum;
				total_payment 	= $('#txt_total_amount').numberbox('getValue');
			}
			else{
				total_pi 	 	= pi_total_amount_new_sum;
				total_payment 	= invoice_amount_sum;
			}
		
			
			if(selected_status == false){
				$.messager.alert('Warning','Tidak ada item yang dipilih untuk disimpan','warning');
			}
			else if(amount_lessnull){
				$.messager.alert('Warning','Payment Amount tidak boleh lebih kecil atau sama dengan nol','warning');
			}
			else{
				
				detail  = JSON.stringify(item);
				$("#detail").val(detail);
				
				edit_transaction_check('<?=$menu_link?>','#fm_purchase_payment', no_transaksi, url, trans_status,created_by, login_as, job_title);
			}
		}	
    }
	
	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_pgir_no').val(), 'Purchase Giro', url, created_by, login_as, job_title);
	}
	
	function approval_pgir($status) {
		var url_check           = '<?= base_url();?>custom/custom/checking_approval';
		var no_transaksi    	= $('#txt_pgir_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_giro/approval';
		var item            = $('#dtg_item').datagrid('getRows');
		
		var PGirNumber      = $("#txt_pgir_no").val();
		var Detail          = JSON.stringify(item);

        $.post(url, {PGirNumber:PGirNumber, Detail:Detail}, 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 app_reverse(){
		var no_transaksi    = $('#txt_pgir_no').val();
	
		checking_reverse(no_transaksi,function(check){
			
			if(check.status == true){
				var i       = $('#dtg_item').datagrid('getRows');
				var detail  = JSON.stringify(i);
		
				$("#detail").val(detail);
				reverse_data_by_detail('<?php echo $menu_link?>','#fm_purchase_payment');
			}else{
			   $.messager.alert('Unseccessfull',check.message,'error',function(){
					location.reload();
				});
			}
		});
	}
	
	function currency_payment(currency_rate, payment){  
        if($('#hdn_payment_status').val() == 0){
            if($('#hdn_vend_curr_code').val() == 'IDR'){                
                payment_curr = payment;
            }
            else{
                payment_curr = payment * currency_rate;
            }
        }
        else{
            if($('#hdn_vend_curr_code').val() == 'IDR'){
                payment_curr = payment / currency_rate;
            }
            else{
                payment_curr = payment * currency_rate;                                
            }
        }
        return payment_curr;
    }
	
	function to_transaction(){

        var appfinished     = '<?=$detail->TransStatus;?>';
        var no_transaksi    = $('#txt_pgir_no').val();
		var cbg_branch    	= $('#cbg_branch').combogrid('getValue');
        var vendor_code     = $('#cbg_vendor').combogrid('getValue');
        var no_trans        = no_transaksi.replace(/\//g,"__");
        var vendor_code     = vendor_code.replace(/\//g,"__");
		var bank_curr_code 	= '<?=$detail->BankCurrCode?>';
		var txt_cheque_no      = $('#txt_cheque_no').val();
		var no_chk        = txt_cheque_no.replace(/\//g,"__");
		
		var txt_rate_numberbox = $('#txt_bank_curr_rate').numberbox('getValue');
		
        if(appfinished == 1){
           parent.tab_add('New Purchase Payment','list/purchases_payment','icon-add','add/'+no_trans+'/'+cbg_branch+'/'+vendor_code+'/'+bank_curr_code+'/'+no_chk+'/'+txt_rate_numberbox);
        }else{
            $.messager.alert('Unseccessfull','TransStatus Finished. Transaksi selesai.','error',function(){
                //location.reload();
            });
        }
        
    }
</script>