<!---- 
    Author 	: Ladur \ 12-08-2014	
    Revisi 	: Ferry \ 05-03-2015
    Revisi 	: Fachri 
-->

<?php
		//---------Untuk privellege jika dia ada tombol save----------
			if($group_user->SavePrivillage == 1){
				$cek_autority_save  = "";
			}
			else{
				$cek_autority_save 	= "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" >
                    <a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="parent.tab_add('New Sales Receipts', '<?=$menu_link?>', 'icon-add', 'add');">New</a>							
                	<a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload();">Refresh</a>
                </td>							
                <td align="right">								
                    <span class="form-title"><?=$menu_label?></span>
                </td>
            </tr>
            </table>		     	
        </div>			
    </div>
    <!-- end top view -->
    
    <div id="form-body" data-options="region:'center',border:false">
    	<div id="form-wrapper" class="easyui-panel" fit="true" style="padding:5px;">
        	<form id="fm_purchase_payment" name="fm_purchase_payment" method="post">
        		<input type="hidden" name="detail" id="detail"/>
                <input type="hidden" name="hdn_cust_saldo_dp" id="hdn_cust_saldo_dp" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                            
                <input type="hidden" name="hdn_bank_number" id="hdn_bank_number"/>
                
                <input type="hidden" name="hdn_cust_curr_code" id="hdn_cust_curr_code"/>
                <input type="hidden" name="hdn_bank_curr_code" id="hdn_bank_curr_code"/>
                <input type="hidden" name="hdn_receive_status" id="hdn_receive_status"/>
                
                <input type="hidden" name="txt_customer_rate" id="txt_customer_rate" class="easyui-numberbox" value="0" 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="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                
                <input type="hidden" name="hdn_SRecTotalAmount" id="hdn_SInvTotalAmount" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                            
                <input type="hidden" name="hdn_SRecTotalOwing" id="hdn_SRecTotalOwing" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                            
              <input type="hidden" name="hdn_SRecTotalDPUsed" id="hdn_SRecTotalDPUsed" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                
                <input type="hidden" name="hdn_SRecTotalDiscount" id="hdn_SRecTotalDiscount" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                            
                <input type="hidden" name="hdn_lock_status"     id="hdn_lock_status"/>
                
                <input type="hidden" name="hdn_so_status"     	class="easyui-numberbox" id="hdn_so_status" value="0"/>
                <input type="hidden" name="hdn_si_status"     	class="easyui-numberbox" id="hdn_si_status" value="0"/>
                
                <!-- 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>Department</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <select class="easyui-combogrid" id="cbg_department" 
                                            name="cbg_department" required readonly editable="false" 
                                            style="width:252px;height:22px;" 
                                            data-options="
                                                panelWidth: 400,
                                                value: '<?=$this->session->userdata('department')?>',
                                                idField: 'DepartmentCode',
                                                textField: 'DepartmentName',
                                                url: '<?=base_url()?>custom/get_data/department',
                                                method: 'get',
                                                columns: [[
                                                    {field:'DepartmentCode',title:'Department Code',width:110, halign:'center'},
                                                    {field:'DepartmentName',title:'Department Name',width:190, 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="combo-grid" id="cbg_customer" 
                                            name="cbg_customer" 
                                            required 
                                            style="width:252px; height:22px;" 
                                            data-options="
                                                panelWidth: 400,
                                                idField: 'CustomerCode',
                                                textField: 'CustomerName',
                                                url: '<?=base_url()?>custom/get_data/customer_with_rate',
                                                method: 'get',
                                                columns: [[
                                                    {field:'CustomerCode',title:'Customer Code',width:130, halign:'center'},
                                                    {field:'CustomerName',title:'Customer Name',width:190, halign:'center'}
                                                ]],
                                                fitColumns: true
                                            "
                                        >
                                        </select>
                                    </td>
                                </tr>

                                <tr height="20">
                                    <td width="120" valign="top" style="padding-top:4px;"><b>Payee</b></td>
                                    <td width="10" 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></textarea>
                                    </td>
                                </tr>                                
                            </table>
                        </td>
                    
                        <td width="50%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                
                                
                                <tr valign="middle">
                                    <td colspan="2" width="322">&nbsp;</td>
                                    <td width="120"><b>Receipt Date</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <input name="txt_srec_date" id="txt_srec_date" type="text" class="easyui-datebox validBackward" style="width:259px;" value='<?=$srec_date?>' required editable="false" />
                                    </td>
                                </tr>
                                <tr valign="middle">
                                    <td colspan="2" width="322">&nbsp;</td>
                                    <td width="120"><b>Cheque No.</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <input type="text" name="txt_cheque_no" id="txt_cheque_no" class="easyui-validatebox" style="width:257px;" />
                                    </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">
                                        <input type="checkbox" name="chk_fiscal_payment" id="chk_fiscal_payment" onClick="fiscal_payment();" value="1" disabled="disabled">Fiscal Payment
                                    </td>
                                </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="120"><b>Bank Payment</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <select class="combo-grid" name="cbg_bank" id="cbg_bank" style="width:252px;height:22px;" required editable="true"
                                            data-options="
                                                panelWidth:400,
                                                idField: 'AccountNumber',
                                                textField: 'AccountName',
                                                url: '<?=base_url()?>list/sales_receipt/ajax_bank_account',
                                                method: 'post',
                                                fitColumns: true,
                                                columns: [[
                                                    {field:'AccountName',title:'Account Bank Name',width:100, halign:'center'},						
                                                    {field:'CurrencyCode',title:'Currency Name',width:100, halign:'center'}						
                                                ]]                                                
                                            ">
                                        </select>
                                    </td>
                                </tr>
                                
                                <tr height="20">
                                    <td width="120"><b>Currency Rate</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td>
                                        <input type="text" name="txt_bank_curr_rate" id="txt_bank_curr_rate" class="easyui-numberbox" required="true" value="1" 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="120" valign="top" style="padding-top:4px;"><b>Memo</b></td>
                                    <td width="10" valign="top" style="padding-top:4px;"><b>:</b></td>
                                    
                                    <td>
                                        <textarea name="txa_description" id="txa_description" rows="4" style="width:246px;resize:none;"></textarea>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        
                        <td width="50%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr>
                                    <td width="293" rowspan="5">&nbsp;</td>
                                    <td>
                                        <span id="lbl_balance_curr" style="font-weight:bold">Balance (IDR)</span>
                                    </td>
                                    <td width="13"><b>:</b></td>
                                    
                                    <td width="129">
                                        <input type="numberbox" name="txt_bank_balance" id="txt_bank_balance" class="easyui-numberbox" value='0,00'  style="width:127px;text-align:right;" readonly
                                            data-options="precision:2, groupSeparator:'.', decimalSeparator:','" 
                                        />
                                    </td>
                                </tr>
                            
                               
                                <tr>
                                   <td>
                                        <input type="hidden" name="txt_cust_dp_part" id="txt_cust_dp_part" class="easyui-numberbox" value='0,00' style="width:127px;text-align:right;" readonly
                                            data-options="min:0, precision:2, groupSeparator:'.', decimalSeparator:','"
                                        />
                                    </td>
                                </tr>
                                <tr>
                                   <td width="209"><b>Saldo DP Partial</b></td>
                                   <td width="13"><b>:</b></td>
                                   <td>
                                        <input type="text" name="txt_cust_dp_part_payment" id="txt_cust_dp_part_payment" class="easyui-numberbox" value='0,00' style="width:127px;text-align:right;" readonly
                                            data-options="min:0, precision:2, groupSeparator:'.', decimalSeparator:','"
                                        />
                                    </td>
                                </tr>
                                <tr>
                                	<td width="209"><b>Saldo DP Payment</b></td>
                                    <td width="13"><b>:</b></td>
                                    <td>
                                        <input type="text" name="txt_cust_dp_return" id="txt_cust_dp_return" class="easyui-numberbox" value='0,00' style="width:127px;text-align:right;" readonly 
                                            data-options="min:0, precision:2, groupSeparator:'.', decimalSeparator:','"
                                        />
                                    </td>
                                </tr>
                                
                                <tr>
                                    <td width="209"><span id="lbl_payment_curr" style="font-weight:bold">Total Payment (IDR)</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:127px;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="Item">
                        <table id="dtg_item" class="easyui-edatagrid" title="" iconCls="icon-edit" singleSelect="true" rowNumbers="true" fitColumns="true" style="height:240px"
                            url="<?=base_url() . $menu_link . '/ajax_item/'?>"
                        >
                            <thead frozen="true">
                                <tr>
                                    <th rowspan="2" field="Paid"              width="40"  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="50"  data-options="halign:'center',align:'center'" resizable='false' editor="{type:'validatebox'}" hidden>Invoice Type</th>
                                    <th rowspan="2" field="Invoice_Number"    width="160" 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="87"  data-options="halign:'center',align:'center'" resizable="false" editor="{type:'validatebox',options:{required:true,disabled:true}}" formatter="formatDate">Inv. Date</th>
                                    <th colspan="1">Invoice Amount</th>
                                    <th colspan="1">Invoice Owing</th>
                                    <th colspan="1">Downpayment</th>
                                    <th colspan="1">Discount</th>                                        
                                    <th rowspan="1">Rounding</th>
                                    <th colspan="2">Receipt Amount</th>                                    

                                    <th rowspan="2" field="ItemCategoryCode"  width="115" data-options="halign:'center',align:'center'" resizable="false" editor="{type:'text', disabled:'true'}" >Category Code</th>
                                    <th rowspan="2" field="ItemCategoryID"    width="70"  data-options="halign:'center',align:'center'" resizable="false" editor="{type:'text', disabled:'true'}" hidden>Category ID</th>
                                    <th rowspan="2" field="InvoiceCurrCode"   width="50"  data-options="halign:'center',align:'right'"  resizable="false" editor="{type:'text', disabled:'true'}" hidden>Invoice Currency Code</th>
                                    <th rowspan="2" field="InvoiceCurrRate"   width="50"  data-options="halign:'center',align:'right'"  resizable="false" editor="{type:'text', disabled:'true'}" hidden>Invoice Currency Rate</th>
                                    <th rowspan="2" field="InvoiceFiscalRate" width="80"  data-options="halign:'center',align:'right'"  resizable="false" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" formatter="formatRp" hidden>Fiscal Rate</th>
                                    <th rowspan="2" field="InvoiceAmountCopy" width="115" data-options="halign:'center',align:'right'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,disabled:true}}" resizable="false" halign='center' align="right" formatter="formatRp" hidden>Invoice Copy</th>
                                    <th rowspan="2" field="Select_DP" 		  width="100"  data-options="halign:'center',align:'right'"	editor="{type:'text'}" >Select DP</th>
                                    <th rowspan="2" field="InvoiceOwingHidden" width="115" data-options="halign:'center',align:'right'"  
                                    editor="{type:'numberbox',options:{decimalSeparator:',',required:true,disabled:true,
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>Owing Copy</th>
                                    
                                    <th rowspan="2" field="InvoiceOwingHiddenNew" width="115" data-options="halign:'center',align:'right'"  
                                    editor="{type:'numberbox',options:{decimalSeparator:',',required:true,disabled:true,
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>Invoice Owing Temp</th>
                                </tr>
                                
                                <tr>
                                    <th field="Invoice_Amount"   width="127" data-options="halign:'center',align:'right'" resizable="false" editor="{type:'numberbox',options:{min:0,precision:2,decimalSeparator:','}}" formatter="formatRp"><span class="spn_vend_curr">(IDR)</span></th>
                                    <th field="Invoice_Owing"    width="127" data-options="halign:'center',align:'right'" resizable="false" editor="{type:'numberbox',options:{min:0,precision:2,decimalSeparator:','}}" formatter="formatRp"><span class="spn_vend_curr">(IDR)</span></th>
                                    <th field="Receipt_DP"       width="127" 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="Receipt_Discount" width="127" 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="Load_Rounding" 	 width="127" 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="Receipt_Amount"   width="127" 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="Receipt_Currency" width="127" 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>
            </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 save-button" iconCls="icon-save" onclick="insert_data();" <?php echo $cek_autority_save;?>>Save</a> 								
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="">Cancel</a>
                </td>
            </tr>
        </table>
    </div>
</div>

<!----------------------------------------------------Batas Awal Dialog DP------------------------------------------------------->
<div id="dialog_asset" class="easyui-dialog" style="width:850px;height:510px;background-color:#F8F8F8;padding:0px;" closed="true" data-options="modal:true, iconCls:'icon-edit'" buttons="#dialog-buttons">
    <div id="tab_purchase_req" class="easyui-tabs" style="width:835px;height:485px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
        <div title="List Down Payment" style="padding:10px" >
             <input type="hidden" name="hdn_sord_number" id="hdn_sord_number" />
             
            <table id="tt_choose_dp" class="easyui-edatagrid" rowNumbers="true" fitColumns="true" singleSelect="true" style="width:813px;height:375px;"
                url="<?=base_url()?>list/sales_receipt/get_sordetail_dp_new"                            
            >
                <thead>
                    <tr>
                        <th field='Status'        width="35"  data-options="halign:'center',align:'center'" editor="{type:'checkbox',options:{on:'Yes',off:'No'}}">Status</th>
                        <th field="SOrdNumber"    width="110" data-options="halign:'center',align:'center'">So. Number.</th>
                        <th field="ReceiptAmount_SUM" width="65"  data-options="halign:'center',align:'center'" editor="{options:{precision:2,decimalSeparator:',',groupSeparator:'.',disabled:false}}" formatter="formatRp">Dp Balance</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

<div id="dialog-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_dp();">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog_asset');">Cancel</a>
</div>
<!--------------------------------------------------Batas Akhir Dialog DP---------------------------------------------------->
<script type="text/javascript">
	var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
    /*==================== Daswan =========================*/
    var SInvNumber      = '<?=$SInvNumber;?>';
    var CustomerCode    = '<?=$CustomerCode;?>';
    var CurrencyCode    = '<?=$CurrencyCode;?>';

    var load            = 0;
    if(SInvNumber !=''){
        SInvNumber          = SInvNumber.replace(/\__/g,"/");
        SInvNumber          = SInvNumber.replace(/\_/g,"-");
        CustomerCode        = CustomerCode.replace(/\__/g,"/");
        CustomerCode        = CustomerCode.replace(/\_/g,"-");
    }
    /*=================== end Daswan =========================*/

	$(document).ready(function(){
        $('#dtg_item').datagrid('hideColumn', 'Receipt_Currency');
        $('#dtg_item').datagrid('showColumn', 'ItemCategoryCode');
        $('#hdn_receive_status').val(0);

        $('#cbg_customer').combogrid({
            onSelect:function(rowIndex, rowData){
                var cust_address    		= rowData.CustomerAddress;
                var cust_curr_code  		= rowData.CurrencyCode;
                var exchange_rate   		= rowData.CurrencyRate;
                var saldodp_balance 		= rowData.SaldoDPBalance;
				
                $('#hdn_cust_curr_code').val(cust_curr_code);
                $('.spn_vend_curr').text('(' + cust_curr_code + ')');
                
                $('#currency').html(cust_curr_code + ' / IDR');
                $('#txt_bank_curr_rate').numberbox('setValue', exchange_rate);
				$('#txt_customer_rate').numberbox('setValue', exchange_rate);

                $('#txa_address').val(cust_address);
				
				/*Function get invoice dp*/
				//get_po_detail_dp_invoice(rowData.CustomerCode);
				
				/*Fuunction get pordetail*/
				get_po_detail_dp(rowData.CustomerCode);
				get_po_detail_dp_patial(rowData.CustomerCode);
				
                $('#cbg_bank').combogrid('setValue', '');
                $('#hdn_bank_curr_code').val('');
				
				$('#txt_cust_dp_part').numberbox('setValue', rowData.SaldoDPPartial);
				$('#hdn_lock_status').val(rowData.LockStatus);
				
                $('#txt_cheque_no').val('');
                $('#txt_cheque_amount').numberbox('setValue', '');
                $('#chk_fiscal_payment').prop('checked', false);
				
                
                if(($('#hdn_bank_curr_code').val() == '') || ($('#hdn_cust_curr_code').val() == $('#hdn_bank_curr_code').val())){
                    $('#dtg_item').datagrid('hideColumn', 'Receipt_Currency');
                    $('#dtg_item').datagrid('showColumn', 'ItemCategoryCode');
                    $('#hdn_receive_status').val(0);
                }
                else{
                    $('#dtg_item').datagrid('showColumn', 'Receipt_Currency');
                    $('#dtg_item').datagrid('hideColumn', 'ItemCategoryCode');
                    $('#hdn_receive_status').val(1);
                }

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

                $('#dtg_item').datagrid('load',{
                    CustomerCode  : rowData.CustomerCode,
                    PPnFiscal   : 0
                });
                
                $('#cbg_bank').combogrid('grid').datagrid('load',{
                    CurrencyCode : rowData.CurrencyCode
                });
            },onLoadSuccess:function(data){
                if(SInvNumber !=''){
                    $('#cbg_customer').combogrid('setValue',CustomerCode);
                }
            }
	});	
        
	$('#cbg_bank').combogrid({
            onSelect:function(rowIndex, rowData){
                var srec_date       = $('#txt_srec_date').datebox('getValue');
                var cust_curr_code  = $('#hdn_cust_curr_code').val();
                var bank_curr_code  = rowData.CurrencyCode;
                var bank_out_code   = rowData.BankOutCode;
				
                $('#hdn_bank_number').val(bank_out_code);
                $('#hdn_bank_curr_code').val(bank_curr_code);
                $('#lbl_balance_curr').html('Balance (' + bank_curr_code + ')');
				$('#lbl_payment_curr').html('Total Payment (' + bank_curr_code + ')');
				
                $('#txt_bank_balance').numberbox('setValue', rowData.BankBalance);
				if($('#chk_fiscal_payment').is(':checked')){
					if($('#hdn_bank_curr_code').val() == 'IDR'){
						$('#dtg_item').datagrid('hideColumn', 'Receipt_Currency');
						$('#dtg_item').datagrid('showColumn', 'ItemCategoryCode');
						$('#hdn_receive_status').val(0);
					}
					else{
						$('#dtg_item').datagrid('showColumn', 'Receipt_Currency');
						$('#dtg_item').datagrid('hideColumn', 'ItemCategoryCode');
						$('#hdn_receive_status').val(1);
					}
					$('.spn_bank_curr').text('(' + bank_curr_code + ')');
					
					if(cust_curr_code == 'IDR'){
						if(bank_curr_code == 'IDR'){
							$('#txt_bank_curr_rate').prop('disabled', true);
						}
						else{
							$('#txt_bank_curr_rate').prop('disabled', false);
						}
					}
					else{
						if(bank_curr_code == 'IDR'){
							$('#txt_bank_curr_rate').prop('disabled', true);
						}
						else{
							$('#txt_bank_curr_rate').prop('disabled', false);
						}
					}
				}
				else{	
					$('.spn_bank_curr').text('(' + bank_curr_code + ')');
					
					if(($('#hdn_cust_curr_code').val() == '') || ($('#hdn_cust_curr_code').val() == $('#hdn_bank_curr_code').val())){
						$('#dtg_item').datagrid('hideColumn', 'Receipt_Currency');
						$('#dtg_item').datagrid('showColumn', 'ItemCategoryCode');
						$('#hdn_receive_status').val(0);
					}
					else{
						$('#dtg_item').datagrid('showColumn', 'Receipt_Currency');
						$('#dtg_item').datagrid('hideColumn', 'ItemCategoryCode');
						$('#hdn_receive_status').val(1);
					}
					
					if((bank_curr_code == cust_curr_code) && (cust_curr_code == 'IDR')){
						$('#txt_bank_curr_rate').prop('disabled', true);
					}
					else{
						$('#txt_bank_curr_rate').prop('disabled', false);
					}
				}	
				
                if($('#hdn_cust_curr_code').val() != 'IDR'){
                    $('#currency').html(cust_curr_code + ' / IDR');
                }
                else{
                    $('#currency').html(cust_curr_code + ' / ' + bank_curr_code);                    
                }

                if(cust_curr_code == 'IDR'){
                    $('#txt_bank_curr_rate').numberbox('setValue', rowData.CurrencyRate);
					$('#chk_fiscal_payment').prop('disabled', true);
                }
				else{
					$('#chk_fiscal_payment').prop('disabled', false);
					if($('#chk_fiscal_payment').is(':checked')){
						if($('#hdn_bank_curr_code').val() == 'IDR'){
							$('#txt_bank_curr_rate').numberbox('setValue', rowData.CurrencyRate);
							//$('#txt_bank_curr_rate').prop('disabled', true);
						}
						else{
							$('#txt_bank_curr_rate').numberbox('setValue', rowData.CurrencyRate);
							//$('#txt_bank_curr_rate').prop('disabled', false);
						}
					}
					else{
						if($('#hdn_bank_curr_code').val() == 'IDR'){
							$('#txt_bank_curr_rate').numberbox('setValue', $('#txt_customer_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'); 
            },onLoadSuccess:function(data){
                if(SInvNumber !=''){
                    $.each(data.rows,function(ind,val){
                        console.log(val.CurrencyCode+' vs '+CurrencyCode);
                        if(val.CurrencyCode == CurrencyCode){
                            $('#cbg_bank').combogrid('setValue',val.AccountNumber);
                            return;
                        }
                    });
                }
            }
	});
	
	$('#txt_bank_curr_rate').numberbox({
		onChange:function(){
			var item    = $('#dtg_item').datagrid('getRows');
			curr_rate   = $('#txt_bank_curr_rate').numberbox('getValue');
			total_receipt_amount 	= 0;
			total_receipt_currency 	= 0;
			
			$.each(item, function(index, value){
				if(value.Paid == 'Yes'){
                    receipt_amount      = parseFloat(value.Receipt_Amount);
                    receipt_currency    = parseFloat(value.Receipt_Currency);

                    if(isNaN(receipt_amount)){receipt_amount = 0;}
                    if(isNaN(receipt_currency)){receipt_currency = 0;}
						
					if($('#hdn_receive_status').val() == 0) {
						if($('#hdn_cust_curr_code').val() == 'IDR'){                
							receipt_currency    = receipt_amount;
						}
						else{
							 if($('#chk_fiscal_payment').is(':checked')){
								if($('#hdn_cust_curr_code').val() == 'IDR'){
									receipt_currency = receipt_amount * curr_rate;
								}
								else{
									receipt_currency = receipt_amount / curr_rate;
								}
							}
							else{
								receipt_currency    = receipt_amount * curr_rate;
							} 
						}
					}
					else{
						if($('#hdn_cust_curr_code').val() == 'IDR'){
							receipt_currency    = receipt_amount / curr_rate;
						}
						else{
							if($('#chk_fiscal_payment').is(':checked')){
								if($('#hdn_bank_curr_code').val() == 'IDR'){
									receipt_currency 		= receipt_amount * curr_rate;
								}
								else{
									receipt_currency = receipt_amount / curr_rate;
								}
							}
							else{
								receipt_currency    = receipt_amount * curr_rate;
							} 
						}
					}                        

					$('#dtg_item').datagrid('updateRow',{
						index:index,
						row:{Receipt_Currency : 0,
								Receipt_Amount:0,
								Receipt_DP : 0,
								Receipt_Discount :0,
								Load_Rounding :0,
								Select_DP 		 : '',
								Invoice_Owing:value.InvoiceAmountCopy,
								InvoiceOwingHiddenNew:value.InvoiceAmountCopy}
					}); 
					total_receipt_amount    += receipt_amount;
                    total_receipt_currency  += receipt_currency; 
				}
			}); 
			
			$('#txt_total_amount').numberbox('setValue', 0);
		}
	});
	
	$('#tt_choose_dp').datagrid({
		onLoadSuccess:function(rowIndex){
			grid_dp   	 = $('#tt_choose_dp').datagrid('getRows');
			dp_array     = $('#hdn_sord_number').val();
			dp_code      = dp_array.split(',');

			for($ii=0; $ii<dp_code.length; $ii++){
				$.each(grid_dp, function(index, value) {
					if(dp_code[$ii] == value.SOrdNumber){
						$('#tt_choose_dp').datagrid('updateRow',{
							index   : index,
							row     : {Status : 'Yes'}
						});
					}
				});                    
			}
		 }
	});     
		
	$('#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_dp_editor           = $(editors[6].target); //DP Amount
                invoice_disc_editor         = $(editors[7].target); //Discount Amount
				invoice_rounding    		= $(editors[8].target); //rounding 
				
                invoice_receipt_editor      = $(editors[9].target); //Receipt Amount
                invoice_reccur_editor       = $(editors[10].target);//Receipt Currency
                invoice_category_editor     = $(editors[11].target);//Category Code
				invoice_amount_editor_hide  = $(editors[16].target);//InvoiceAmountCopy
				invoice_select_dp  			= $(editors[17].target);//SelectDP
				invoice_owing_temp 			= $(editors[19].target);//Owing Temp
				
                $(invoice_dp_editor).numberbox('setValue', $(invoice_dp_editor).numberbox('getValue') == 0 ? 0 : $(invoice_dp_editor).numberbox('getValue'));
                $(invoice_disc_editor).numberbox('setValue', $(invoice_disc_editor).numberbox('getValue') == 0 ? 0 : $(invoice_disc_editor).numberbox('getValue'));

                category_code   	= $(invoice_category_editor).val();
                invoice_type    	= $(invoice_type_editor).val();
                customer_dp       	= parseFloat($('#txt_cust_dp_return').numberbox('getValue'));
				customer_dp_hide  	= parseFloat($('#hdn_cust_saldo_dp').numberbox('getValue'));
				
                if(isNaN(customer_dp)){customer_dp = 0;}
				if(isNaN(customer_dp_hide)){customer_dp_hide = 0;}
				
				/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
				save_button_begendedit(SavePrivillage);
				/*=================================end============================================================*/
			
                $(invoice_type_editor).prop('readonly', true);
                $(invoice_no_editor).prop('readonly', true);
                $(invoice_date_editor).prop('readonly', true);
                $(invoice_amount_editor).prop('readonly', true);
                $(invoice_owing_editor).prop('readonly', true);
                $(invoice_dp_editor).prop('readonly', true);
                $(invoice_category_editor).prop('readonly', true);                    

                $(invoice_disc_editor).prop('readonly', true);
                $(invoice_receipt_editor).prop('readonly', true);
                $(invoice_reccur_editor).prop('readonly', true);
				$(invoice_rounding).prop('readonly', true);
				$(invoice_select_dp).prop('disabled',true);

                 /*====================== Daswan ===========================*/
                $(invoice_no_editor).click(function(){
                    var TransNo             = rowDatax.Invoice_Number;
                    var arrTransNo          = TransNo.split('/');
                    var string_ext          = arrTransNo[1];
                    var res                 = string_ext.substring(6,4);
                    if(res == 'SI'){
                        parent.tab_edit('Edit Sales Invoice','list/sales_invoice', 'icon-edit', 'edit',TransNo);
                    }else if(res == 'SO'){
                        parent.tab_edit('Edit Sales Order','list/sales_order', 'icon-edit', 'edit',TransNo);
                    }          
                });
                /*====================== End Daswan ===========================*/

                

                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(invoice_type == 'SO'){
                            $(invoice_dp_editor).prop('disable', true);
                            $(invoice_disc_editor).prop('readonly', true);
							$(invoice_select_dp).prop('disabled',true);
							
							if($('#hdn_cust_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);
								}
							}
                        }
						else if(category_code == 'PPn Fiscal'){
							$(invoice_dp_editor).prop('disable', true);
                            $(invoice_disc_editor).prop('readonly', true);
							$(invoice_select_dp).prop('disabled',true);
							
							if($('#hdn_cust_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', false);
								}
							}
						}
                        else{
                            $(invoice_dp_editor).prop('readonly', true);
                            $(invoice_disc_editor).prop('readonly', false);
							$(invoice_select_dp).prop('disabled',false);
							
							if($('#hdn_cust_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_receive_status').val() == 0){
                            $(invoice_receipt_editor).prop('readonly', false);                        
                            $(invoice_reccur_editor).prop('readonly', true);                                                        
                        }
                        else{
                            $(invoice_receipt_editor).prop('readonly', true);                        
                            $(invoice_reccur_editor).prop('readonly', false);                            
                        }
                    }
                    else{
						var hdn_so_status = $('#hdn_so_status').val();
						var hdn_si_status = $('#hdn_si_status').val();
						
						if(hdn_so_status > 0){
							if(invoice_type == 'SI'){
								$(paid_editor).prop('disabled', true);  
							}
						}
						else if(hdn_si_status > 0){
							if(invoice_type == 'SO'){
								$(paid_editor).prop('disabled', true);  
							}
						}
						
                        $(invoice_reccur_editor).prop('readonly', true);                            
                        $(invoice_receipt_editor).prop('readonly', true);   
                    }        
                    
                    $(paid_editor).click(function(){
						if($(this).is(':checked')){
                            if((invoice_type == 'SO')){
                                $(invoice_dp_editor).prop('disable', true);
                                $(invoice_disc_editor).prop('readonly', true);
								$(invoice_select_dp).prop('disabled',true);
								
								if($('#hdn_cust_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);
									}
								}
                            }
							else if(category_code == 'PPn Fiscal'){
								$(invoice_dp_editor).prop('disable', true);
                                $(invoice_disc_editor).prop('readonly', true);
								$(invoice_select_dp).prop('disabled',true);
								
								if($('#hdn_cust_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', false);
									}
								}
							}
                            else{
                                $(invoice_dp_editor).prop('readonly', true);
                                $(invoice_disc_editor).prop('readonly', false);
								$(invoice_select_dp).prop('disabled',false);
								
								if($('#hdn_cust_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_receive_status').val() == 0){
                                $(invoice_receipt_editor).prop('readonly', false);
                                $(invoice_reccur_editor).prop('readonly', true);
                            }
                            else{
                                $(invoice_receipt_editor).prop('readonly', true);                        
                                $(invoice_reccur_editor).prop('readonly', false);                            
                            }        

                            $(invoice_receipt_editor).numberbox('setValue', 0);
                            $(invoice_reccur_editor).numberbox('setValue', 0);
                        }
                        else{
                            invoice_amount = parseFloat($(invoice_amount_editor_hide).numberbox('getValue'));

                            $(invoice_disc_editor).prop('readonly', true);
                            $(invoice_receipt_editor).prop('readonly', true);
                            $(invoice_reccur_editor).prop('readonly', true);
							$(invoice_rounding).prop('readonly', true);
							$(invoice_dp_editor).prop('readonly', true);
							$(invoice_select_dp).prop('disabled',true);

                            $(invoice_owing_editor).numberbox('setValue', invoice_amount);
                            $(invoice_dp_editor).numberbox('setValue', 0);
                            $(invoice_disc_editor).numberbox('setValue', 0);
                            $(invoice_receipt_editor).numberbox('setValue', 0);
                            $(invoice_reccur_editor).numberbox('setValue', 0);
							$(invoice_rounding).numberbox('setValue', 0);
							(invoice_select_dp).val('');
                        }
                    });

                    $(invoice_dp_editor).numberbox({
                        onChange:function(){
                            if($(paid_editor).is(':checked')){
                                invoice_amount          = parseFloat($(invoice_amount_editor).numberbox('getValue'));
                                downpayment_amount      = parseFloat($(invoice_dp_editor).numberbox('getValue'));
                                discount_amount         = parseFloat($(invoice_disc_editor).numberbox('getValue'));
								load_rounding         	= parseFloat($(invoice_rounding).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
								payment_editor         	= parseFloat($(invoice_receipt_editor).numberbox('getValue'));
								paymentcurr_editor      = parseFloat($(invoice_reccur_editor).numberbox('getValue'));
								invoice_amount_hide     = parseFloat($(invoice_amount_editor_hide).numberbox('getValue'));
								

                                if(isNaN(invoice_amount)){invoice_amount = 0;}
                                if(isNaN(downpayment_amount)){downpayment_amount = 0;}
                                if(isNaN(discount_amount)){discount_amount = 0;}
                                if(isNaN(currency_rate)){currency_rate = 0;}
								if(isNaN(load_rounding)){load_rounding = 0;}
								if(isNaN(payment_editor)){payment_editor = 0;}
								if(isNaN(paymentcurr_editor)){paymentcurr_editor = 0;}
								if(isNaN(invoice_amount_hide)){invoice_amount_hide = 0;}
								
								total_amount  = (downpayment_amount + discount_amount + load_rounding + payment_editor);
								
                                if(downpayment_amount > vendor_dp_hide){
                                    $.messager.alert('Warning','DownPayment tidak boleh lebih besar dari Total Saldo DP','warning',function(){
                                        $(invoice_dp_editor).numberbox('setValue', 0);
										$(invoice_disc_editor).numberbox('setValue', 0);
                                        $(invoice_receipt_editor).numberbox('setValue', 0);
                                        $(invoice_reccur_editor).numberbox('setValue', 0); 
										$(invoice_rounding).numberbox('setValue', 0);                                   
                                    });
                                }
								else if(downpayment_amount > invoice_amount_hide){
									$.messager.alert('Warning','Downpayment tidak boleh lebih besar dari Invoice Amount','warning',function(){
										$(invoice_dp_editor).numberbox('setValue', 0);
										$(invoice_disc_editor).numberbox('setValue', 0);
                                        $(invoice_receipt_editor).numberbox('setValue', 0);
                                        $(invoice_reccur_editor).numberbox('setValue', 0);
										$(invoice_rounding).numberbox('setValue', 0);
									});
								}
								/*else if(total_amount > invoice_amount_hide){
									$.messager.alert('Warning','Total amount tidak boleh lebih besar dari Invoice Amount','warning',function(){
										$(invoice_dp_editor).numberbox('setValue', 0);
										$(invoice_disc_editor).numberbox('setValue', 0);
                                        $(invoice_payment_editor).numberbox('setValue', 0);
                                        $(invoice_paycurr_editor).numberbox('setValue', 0);
										$(invoice_rounding).numberbox('setValue', 0);
									});
								}*/
								
                                //payment_amount      = invoice_amount - (downpayment_amount + discount_amount);
                                //payment_currency    = currency_payment(currency_rate, payment_amount);
                                owing_amount        = invoice_amount_hide - (downpayment_amount + discount_amount + load_rounding + payment_editor);
								
                                $(invoice_owing_editor).numberbox('setValue', owing_amount);
								$(invoice_owing_temp).numberbox('setValue', owing_amount);
								
                                //$(invoice_payment_editor).numberbox('setValue', payment_amount);
                                //$(invoice_paycurr_editor).numberbox('setValue', payment_currency);
                            }
                        }
                    }),

                    $(invoice_disc_editor).numberbox({
                        onChange:function(){
                            if($(paid_editor).is(':checked')){
                                invoice_amount          = parseFloat($(invoice_amount_editor).numberbox('getValue'));
                                downpayment_amount      = parseFloat($(invoice_dp_editor).numberbox('getValue'));
                                discount_amount         = parseFloat($(invoice_disc_editor).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
								load_rounding         	= parseFloat($(invoice_rounding).numberbox('getValue'));
								payment_editor         	= parseFloat($(invoice_receipt_editor).numberbox('getValue'));
								paymentcurr_editor      = parseFloat($(invoice_reccur_editor).numberbox('getValue'));
								invoice_amount_hide     = parseFloat($(invoice_amount_editor_hide).numberbox('getValue'));

                                if(isNaN(invoice_amount)){invoice_amount = 0;}
                                if(isNaN(downpayment_amount)){downpayment_amount = 0;}
                                if(isNaN(discount_amount)){discount_amount = 0;}
                                if(isNaN(currency_rate)){currency_rate = 0;}
								if(isNaN(load_rounding)){load_rounding = 0;}
								if(isNaN(payment_editor)){payment_editor = 0;}
								if(isNaN(paymentcurr_editor)){paymentcurr_editor = 0;}
								if(isNaN(invoice_amount_hide)){invoice_amount_hide = 0;}
								
								total_amount  = (downpayment_amount + discount_amount + load_rounding + payment_editor);
								/*if(total_amount > invoice_amount_hide){
									$.messager.alert('Warning','Total amount tidak boleh lebih besar dari Invoice Amount','warning',function(){
										$(invoice_dp_editor).numberbox('setValue', 0);
										$(invoice_disc_editor).numberbox('setValue', 0);
                                        $(invoice_payment_editor).numberbox('setValue', 0);
                                        $(invoice_paycurr_editor).numberbox('setValue', 0);
										$(invoice_rounding).numberbox('setValue', 0);
									});
								}*/
                               /* payment_amount          = invoice_amount - (downpayment_amount + discount_amount);
                                payment_currency        = currency_payment(currency_rate, payment_amount);*/
                                owing_amount            = invoice_amount_hide - (downpayment_amount + discount_amount + load_rounding + payment_editor);

                                $(invoice_owing_editor).numberbox('setValue', owing_amount);
								$(invoice_owing_temp).numberbox('setValue', owing_amount);
                                //$(invoice_payment_editor).numberbox('setValue', payment_amount);
                                //$(invoice_paycurr_editor).numberbox('setValue', payment_currency);
                            }
                        }
                    }),
					
					$(invoice_rounding).numberbox({
						 onChange:function(){
						 	if($(paid_editor).is(':checked')){
								invoice_amount          = parseFloat($(invoice_amount_editor).numberbox('getValue'));
                                downpayment_amount      = parseFloat($(invoice_dp_editor).numberbox('getValue'));
                                discount_amount         = parseFloat($(invoice_disc_editor).numberbox('getValue'));
								load_rounding       	= parseFloat($(invoice_rounding).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
								payment_editor         	= parseFloat($(invoice_receipt_editor).numberbox('getValue'));
								paymentcurr_editor      = parseFloat($(invoice_reccur_editor).numberbox('getValue'));
								invoice_amount_hide     = parseFloat($(invoice_amount_editor_hide).numberbox('getValue'));
								
								if(isNaN(invoice_amount)){invoice_amount = 0;}
                                if(isNaN(downpayment_amount)){downpayment_amount = 0;}
                                if(isNaN(discount_amount)){discount_amount = 0;}
								if(isNaN(currency_rate)){currency_rate = 0;}
								if(isNaN(load_rounding)){load_rounding = 0;}
								if(isNaN(payment_editor)){payment_editor = 0;}
								if(isNaN(paymentcurr_editor)){paymentcurr_editor = 0;}
								if(isNaN(invoice_amount_hide)){invoice_amount_hide = 0;}
								
								total_amount  = (downpayment_amount + discount_amount + load_rounding + payment_editor);
								/*if(total_amount > invoice_amount_hide){
									$.messager.alert('Warning','Total amount tidak boleh lebih besar dari Invoice Amount','warning',function(){
										$(invoice_dp_editor).numberbox('setValue', 0);
										$(invoice_disc_editor).numberbox('setValue', 0);
                                        $(invoice_payment_editor).numberbox('setValue', 0);
                                        $(invoice_paycurr_editor).numberbox('setValue', 0);
										$(invoice_rounding).numberbox('setValue', 0);
									});
								}*/
								//payment_amount          = invoice_amount - (downpayment_amount + discount_amount + load_rounding);
                                //payment_currency        = currency_payment(currency_rate, payment_amount);
                                owing_amount            = invoice_amount_hide - (downpayment_amount + discount_amount + load_rounding + payment_editor);

                                $(invoice_owing_editor).numberbox('setValue', owing_amount);
								$(invoice_owing_temp).numberbox('setValue', owing_amount);
                                //$(invoice_payment_editor).numberbox('setValue', payment_amount);
                                //$(invoice_paycurr_editor).numberbox('setValue', payment_currency);
							}
						 }
					}),
					
                    $(invoice_receipt_editor).numberbox({
                        onChange:function(){
                            if(($(paid_editor).is(':checked')) && ($('#hdn_receive_status').val() == 0)){
                                invoice_amount          = parseFloat($(invoice_amount_editor).numberbox('getValue'));
                                downpayment_amount      = parseFloat($(invoice_dp_editor).numberbox('getValue'));
                                discount_amount         = parseFloat($(invoice_disc_editor).numberbox('getValue'));
                                payment_amount          = parseFloat($(invoice_receipt_editor).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
                                load_rounding       	= parseFloat($(invoice_rounding).numberbox('getValue'));
								invoice_amount_hide     = parseFloat($(invoice_amount_editor_hide).numberbox('getValue'));
								
                                if(isNaN(invoice_amount)){invoice_amount = 0;}
                                if(isNaN(downpayment_amount)){downpayment_amount = 0;}
                                if(isNaN(discount_amount)){discount_amount = 0;}
                                if(isNaN(payment_amount)){payment_amount = 0;}
                                if(isNaN(currency_rate)){currency_rate = 1;}
								if(isNaN(load_rounding)){load_rounding = 0;}
								if(isNaN(invoice_amount_hide)){invoice_amount_hide = 0;}

                                total_amount            = invoice_amount_hide - (downpayment_amount + discount_amount + load_rounding);
								
								owing               = invoice_amount_hide - (downpayment_amount + discount_amount + payment_amount);
								payment_currency    = currency_payment(currency_rate, payment_amount);
								
								$(invoice_owing_editor).numberbox('setValue', owing);
								$(invoice_owing_temp).numberbox('setValue', owing);
								$(invoice_reccur_editor).numberbox('setValue', payment_currency);  
                            }
                        }
                    }),
					
					$(invoice_select_dp).click(function(){
						
						customer_code 	= $('#cbg_customer').combogrid('getValue');
						sord_number  	= $(invoice_select_dp).val();
						
						$('#tt_choose_dp').datagrid('load',{
							CustomerCode : customer_code
						});

						$('#hdn_sord_number').val(sord_number);
						
						modal_open('Sales Down Payment','dialog_asset'); 
					}),
				
                    $(invoice_reccur_editor).numberbox({
                        onChange:function(){
                            if(($(paid_editor).is(':checked')) && ($('#hdn_receive_status').val() == 1)){
                                invoice_amount          = parseFloat($(invoice_amount_editor).numberbox('getValue'));
                                downpayment_amount      = parseFloat($(invoice_dp_editor).numberbox('getValue'));
                                discount_amount         = parseFloat($(invoice_disc_editor).numberbox('getValue'));
                                paycurr_amount          = parseFloat($(invoice_reccur_editor).numberbox('getValue'));
                                currency_rate           = parseFloat($('#txt_bank_curr_rate').numberbox('getValue'));
								invoice_amount_hide     = parseFloat($(invoice_amount_editor_hide).numberbox('getValue'));

                                if(isNaN(invoice_amount)){invoice_amount = 0;}
                                if(isNaN(downpayment_amount)){downpayment_amount = 0;}
                                if(isNaN(discount_amount)){discount_amount = 0;}
                                if(isNaN(paycurr_amount)){paycurr_amount = 0;}
								if(isNaN(invoice_amount_hide)){invoice_amount_hide = 0;}

                                total_amount            = invoice_amount_hide - (downpayment_amount + discount_amount);
                                payment_amount          = amount_payment(currency_rate, paycurr_amount);
                                $(invoice_receipt_editor).numberbox('setValue', payment_amount);
								
								owing = invoice_amount_hide - (downpayment_amount + discount_amount + payment_amount);
                                $(invoice_owing_editor).numberbox('setValue', owing);
								$(invoice_owing_temp).numberbox('setValue', owing);
                            }
                        }
                    });
                }
            },
            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) {
                    receipt_dp          = parseFloat(value.Receipt_DP);
                    payment_amount      = parseFloat(value.Receipt_Amount);
                    payment_currency    = parseFloat(value.Receipt_Currency);
					invoice_amount    	= parseFloat(value.Invoice_Amount);
					invoice_owing    	= parseFloat(value.Invoice_Owing);
					payment_disc    	= parseFloat(value.Receipt_Discount);

                    if(isNaN(receipt_dp)){receipt_dp = 0;}
                    if(isNaN(payment_amount)){payment_amount = 0;}
                    if(isNaN(payment_currency)){payment_currency = 0;}
					
					if(value.Paid == 'Yes'){
						total_dp                += receipt_dp;
						total_payment_amount    += payment_amount;
						total_payment_currency  += payment_currency;
						total_invoice 			+= invoice_amount;
						total_owing 			+= invoice_owing;
						total_disc				+= payment_disc;
						
						if(value.Invoice_Type == 'SO'){
							loop_index_row_po 			= loop_index_row_po +1;
						}
						else{
							loop_index_row_pi 			= loop_index_row_pi +1;
						}
					}
                });

                new_balance_dp = parseFloat($('#hdn_cust_saldo_dp').numberbox('getValue')) - parseFloat(receipt_dp);
                
               // $('#txt_vendor_dp_return').numberbox('setValue', new_balance_dp);
                
				$('#hdn_si_status').numberbox('setValue',loop_index_row_pi);
				$('#hdn_so_status').numberbox('setValue',loop_index_row_po);
				
                $('#hdn_total_currency').numberbox('setValue',total_payment_currency);
				$('#hdn_SInvTotalAmount').numberbox('setValue', total_invoice);
				$('#hdn_SRecTotalOwing').numberbox('setValue', total_owing);
				//$('#hdn_PPayTotalDPUsed').numberbox('setValue', total_dp);
				$('#hdn_SRecTotalDiscount').numberbox('setValue', total_disc);
				
				
				if($('#chk_fiscal_payment').is(':checked')){
					if($('#hdn_cust_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_cust_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');
	});
    });
	
	function get_po_detail_dp(customer_code){
		url	= base_url + 'list/sales_receipt/get_pordetail_dp_return';  
		
		$.post(url, {customer_code:customer_code}, function(result){
			
			if((isNaN(result.dp_customer)) || (result.dp_customer == null)){
				payment_amount_dp = 0;
			}
			else{
				payment_amount_dp = result.dp_customer;
			}
			
			$('#txt_cust_dp_return').numberbox('setValue', payment_amount_dp);
			$('#hdn_cust_saldo_dp').numberbox('setValue',payment_amount_dp);
			$('#hdn_SRecTotalDPUsed').numberbox('setValue',payment_amount_dp);
			
		},'json');
	}
	
	function get_po_detail_dp_patial(customer_code){
		url	= base_url + 'list/sales_receipt/get_pordetail_dp_return_partial';  
		
		$.post(url, {customer_code:customer_code}, function(result){
			
			if((isNaN(result.dp_customer_partial)) || (result.dp_customer == null)){
				payment_amount_dp = 0;
			}
			else{
				payment_amount_dp = result.dp_customer_partial;
			}
			
			$('#txt_cust_dp_part_payment').numberbox('setValue', payment_amount_dp);
			
		},'json');
	}
	
	function fiscal_payment(){
        if($('#chk_fiscal_payment').is(':checked')){
            
			bank_curr_code = $('#hdn_bank_curr_code').val();
			cust_curr_code = $('#hdn_cust_curr_code').val();
			
			$('#dtg_item').datagrid('showColumn', 'InvoiceFiscalRate');
			$('#dtg_item').datagrid('hideColumn', 'Invoice_Date');
			
			$('#dtg_item').datagrid('load',{
                CustomerCode      : $('#cbg_customer').combogrid('getValue'),
                PPnFiscalStatus : 1
            });
					
			if($('#hdn_bank_curr_code').val() == 'IDR'){
				$('.spn_vend_curr').text('(' + $('#hdn_bank_curr_code').val() + ')');
				$('#dtg_item').datagrid('hideColumn', 'Receipt_Currency');
				$('#dtg_item').datagrid('showColumn', 'ItemCategoryCode');
				$('#hdn_receive_status').val(0);
			}
			else{
				$('.spn_vend_curr').text('(' + 'IDR' + ')');
				$('#dtg_item').datagrid('showColumn', 'Receipt_Currency');
				$('#dtg_item').datagrid('hideColumn', 'ItemCategoryCode');
				$('#hdn_receive_status').val(1);
			}
			
			if(cust_curr_code == 'IDR'){
				if(bank_curr_code == 'IDR'){
					$('#txt_bank_curr_rate').prop('disabled', true);
				}
				else{
					$('#txt_bank_curr_rate').prop('disabled', false);
				}
			}
			else{
				if(bank_curr_code == 'IDR'){
					$('#txt_bank_curr_rate').prop('disabled', true);
					$('#txt_bank_curr_rate').numberbox('setValue', 1);
				}
				else{
					$('#txt_bank_curr_rate').prop('disabled', false);
				}
			}
        }
        else{
            location.reload();      
        }
    }
    
    function currency_payment(currency_rate, payment){  
        if($('#hdn_receive_status').val() == 0){
            if($('#hdn_cust_curr_code').val() == 'IDR'){                
                payment_curr = payment;
            }
            else{
                payment_curr = payment * currency_rate;
            }
        }
        else{
            if($('#hdn_cust_curr_code').val() == 'IDR'){
                payment_curr = payment / currency_rate;
            }
            else{
                payment_curr = payment * currency_rate;                                
            }
        }
        return payment_curr;
    }

    function amount_payment(currency_rate, payment_curr){  
        if($('#hdn_receive_status').val() == 0){
            if($('#hdn_cust_curr_code').val() == 'IDR'){                
                payment = payment_curr;
            }
            else{
                payment = payment_curr / currency_rate;
            }
        }
        else{
            if($('#hdn_cust_curr_code').val() == 'IDR'){
                payment = payment_curr * currency_rate;
            }
            else{
				if($('#chk_fiscal_payment').is(':checked')){
					payment = payment_curr * currency_rate;
				}
				else{
					payment = payment_curr / currency_rate; 
				}                             
            }
        }

        return payment;
    }
	
	function choose_dp(){
       $('#tt_choose_dp').edatagrid('saveRow');
        $('#dtg_item').edatagrid('saveRow');
        
        var selectedrow     		= $('#dtg_item').datagrid('getSelected');
		var selected_row_tt_dp     	= $('#tt_choose_dp').datagrid('getSelected');
        var row_index       		= $('#dtg_item').datagrid('getRowIndex', selectedrow);
        var list_dp      			= $('#tt_choose_dp').datagrid('getRows');
		var list_dtg_grid   		= $('#dtg_item').datagrid('getRows');
		 
        var pord_number     = new Array();
		var dp_payment     	= 0;
		var dp_payment_real = 0;
		var invoice_owing 	= 0;
		var owing_back 		= 0;
        var dp_select    	= 0;
        var return_qty      = $('#hdn_qty_return').val();
        var flag 			= true;
		
		$.each(list_dtg_grid, function(index,value){
			if((selected_row_tt_dp.SOrdNumber == value.Select_DP) && (selected_row_tt_dp.Status == 'Yes')){
				$.messager.alert('Unseccessfull','Maaf No Po Sudah terpakai silahkan ganti No PO yang lain.','error',function(){	
					//$('#tt_choose_dp').datagrid('reload');
					//$('#dtg_item').datagrid('reload'); 
					$('#dtg_item').datagrid('updateRow',{
						index   : row_index,
						row     : {
							Select_DP 			: '',
							Receipt_DP 			: 0,
							Receipt_Discount 	: 0,
							Load_Rounding 		: 0,
							Receipt_Amount 		: 0,
							Receipt_Currency 	: 0,
							Invoice_Owing 		: selectedrow.InvoiceAmountCopy,
							InvoiceOwingHiddenNew 	: selectedrow.InvoiceAmountCopy
						}                  
					});
					
				});
				var flag 			= false;
			}
		});	
									
		if(flag != false){
			$.each(list_dp, function(row_index, value) {
				if(value.Status == 'Yes'){
					pord_number.push(value.SOrdNumber);
					dp_payment 	= parseFloat(value.ReceiptAmount_SUM);
					
					if(parseFloat(dp_payment) > parseFloat(selectedrow.InvoiceOwingHiddenNew)){
						dp_payment_real_grid = parseFloat(selectedrow.InvoiceAmountCopy - selectedrow.Receipt_Discount - selectedrow.Receipt_Amount);
					}
					else{
						dp_payment_real_grid = parseFloat(dp_payment);
					}
					
					owing_back 		= parseFloat(selectedrow.InvoiceAmountCopy);
					invoice_owing 	= parseFloat(selectedrow.InvoiceAmountCopy) - (parseFloat(dp_payment_real_grid) + parseFloat(selectedrow.Receipt_Discount) + parseFloat(selectedrow.Receipt_Amount));
					if(invoice_owing > 0){
						invoice_owing_real = invoice_owing;
					}
					else{
						invoice_owing_real = 0;
					}
				
					dp_payment_real = parseFloat(dp_payment_real_grid);
					
					
					payment_dp      = parseFloat(value.ReceiptAmount_SUM);
					if(isNaN(payment_dp)){payment_dp = 0;}
					total_dp  += payment_dp;
					
					
					dp_select++;
				}
				else{
					
					if(selectedrow.InvoiceAmountCopy > 0){
						owing_back 		= parseFloat(selectedrow.InvoiceAmountCopy);
					}
					else{
						owing_back = 0;
					}
				
				}
			});
			
			if(dp_select <= 0){
				$('#dtg_item').datagrid('updateRow',{
					index   : row_index,
					row     : {
						Select_DP 				: '',
						Receipt_DP 				: 0,
						Receipt_Discount 		: 0,
						Load_Rounding 			: 0,
						Receipt_Amount 			: 0,
						Receipt_Currency 		: 0,
						Invoice_Owing 			: owing_back,
						InvoiceOwingHiddenNew 	: owing_back
					}                  
				});
	
				modal_close('dialog_asset');
			}
			else if(dp_select != 1){
				$.messager.alert('Warning','Jumlah Sales Order Number tidak boleh lebih dari satu (1)','warning');
			}
			else{
				pord_number 	= pord_number.join();
				$('#dtg_item').datagrid('updateRow',{
					index   : row_index,
					row     : {
						Select_DP 		: pord_number,
						Receipt_DP 		: dp_payment_real,
						Invoice_Owing 	: invoice_owing_real,
						InvoiceOwingHiddenNew : invoice_owing_real
					}                  
				});
				
				$('#hdn_SRecTotalDPUsed').numberbox('setValue', total_dp);
				
				modal_close('dialog_asset');
			}
		}
    }
	
	function insert_data(){
        $('#dtg_item').edatagrid('saveRow');
        
        total_row       	= $('#dtg_item').datagrid('getData').total;
        selected_status 	= false;
        amount_lessnull 	= false;
		
		flag_total_amount 	= false;
		no_invoice 			= "";
		
		var BankCurrncyCode = $('#hdn_bank_curr_code').val();
		pi_total_amount 	= 0;
		pi_total_amount_new = 0;
		pi_total_amount_new_sum = 0;
		pi_total_amount_sum = 0;
		invoice_amount_sum 	= 0;
		
        if(total_row <= 0){
            $.messager.alert('Warning','Sales Receipt tidak dapat disimpan, karena tidak ditemukan data pada list item','warning');
        }
        else {
            item    = $('#dtg_item').datagrid('getRows');
            
            $.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.Receipt_Amount);
					
					pi_total_amount_new_sum += pi_total_amount_new;
					pi_total_amount_sum += pi_total_amount;
					
					invoice_amount 		= parseFloat(value.Invoice_Amount);
					invoice_amount_sum +=invoice_amount;
					total_all_payment 	= (parseFloat(value.Receipt_DP) + parseFloat(value.Receipt_Discount) + parseFloat(value.Load_Rounding) + parseFloat(value.Receipt_Amount));
					
					if((total_all_payment) > parseFloat(value.InvoiceAmountCopy).toFixed(2)){
						flag_total_amount 	= true;
						no_invoice 			= value.Invoice_Number; 
					}
					
					if(value.Receipt_DP > 0){
						amount_lessnull = false;
					}
					else{
						if((value.Receipt_Amount <= 0) || (value.Receipt_Currency <= 0)) {
							amount_lessnull = true;
						}
					}
                }
            });
			
			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(flag_total_amount != false){
				$.messager.alert('Warning','Receipt Amount melebihi jumlah owing yang harus dibayar, No Invoice : '+no_invoice+'','warning',function(){
					//$('#dtg_item').datagrid('reload'); 
					$('#txt_total_amount').numberbox('setValue', 0); 
				});	
			}
            else if(amount_lessnull){
                $.messager.alert('Warning','Receipt Amount tidak boleh lebih kecil atau sama dengan nol','warning');
            }
			else if($('#hdn_lock_status').val() == 1){
				$.messager.alert('Warning','Maaf masih ada transaksi yang belum di approve di Sales Receipt, untuk customer ini','warning');
			}
            else{
				if($('#chk_fiscal_payment').is(':checked')){
					if(total_pi != total_payment){
						$.messager.alert('Informasi','Maaf transaksi anda gagal, silahkan isi nilai sesuai Invoice Amount untuk Fiscal Payment','info');
						return false;
					}
					else{
						var item    = $('#dtg_item').datagrid('getRows');
						var detail  = JSON.stringify(item);
		
						$("#detail").val(detail);
						save_transaction('<?=$menu_link?>','#fm_purchase_payment');
					}
				}
				else{
					var item    = $('#dtg_item').datagrid('getRows');
					var detail  = JSON.stringify(item);
	
					$("#detail").val(detail);
					save_transaction('<?=$menu_link?>','#fm_purchase_payment');
				}
            }
        }
    }
</script>