
<!---- 
    Author 	: Wahyu
    Tanggal : 12-08-2014	
    Revisi 	:
-->
<?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 cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
					<tr>
						<td align="left" valign="middle">
							<a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="location.reload()">New</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="location.reload()">Refresh</a>
							<!-- <a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="" disabled>Journal</a> -->
						</td>							
						<td height="25" align="right" valign="middle">								
							<span class="form-title">
								<?= $menu_label; ?>
							</span>
						</td>
					</tr>
				</table>		     	
		 </div>			
	</div>
	<!-- end top view -->	
	<!-- center view -->
	<div id="form-body" data-options="region:'center',border:false">
		<div id="form-wrapper" class="easyui-panel"  style="width:1180px;height:526px;padding:5px;" fit='true'>
			<form id="fm_sales_journal" name="fm_sales_journal" method="post">
                <table cellpadding="0" cellspacing="3" width="100%" height="100%" border="0">
					<tr>
						<td width="143"><b>Customer</b></td>
                        <td width="10"><b>:</b></td>
                        <td colspan="5">
                            <select class="combo-grid" id="cmb_customer" 
                                name="cmb_customer" required="required" 
                                style="width:230px;height:20px;" 
                                data-options="
                                    panelWidth: 329,
                                    idField: 'CustomerCode',
                                    textField: 'CustomerName',
                                    url: '<?php echo base_url(); ?>custom/get_data/customer_with_rate',
                                    method: 'get',
                                    columns: [[
                                    {field:'CustomerCode',title:'Customer Code',width:110},
                                    {field:'CustomerName',title:'Customer Name',width:190}
                                    ]],
                                    fitColumns: true
                                "
                            >
                            </select>
                            <a href="#" class="easyui-linkbutton" iconCls="icon-sales" onclick="select_sales_journal()" style="width:110px;" plain="true">List Invoice</a>
                        </td>
						<td align="left" valign="middle">&nbsp;</td>
						<td rowspan="6" align="left" valign="top">
							<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
								<tr>
									<td align="right" valign="top">
										<table cellpadding="0" cellspacing="1" width="100%" border="0">
											<tr>
												<td height="20">&nbsp;</td>
												<!-- <td width="190" align="center" valign="middle" bgcolor="#333399"><span style="color: #fff">Payment Afiliasi No.</span></td> -->
												<td width="122" align="center" valign="middle" bgcolor="#333399"><span style="color:#fff;">Sales Journal Date</span></td>
											</tr>
											<tr>
												<td>&nbsp;</td>
												<!-- <td height="20" align="left" valign="top"> -->
												<!-- <input type="hidden" name="payment_karyawan_no" id="payment_karyawan_no" class="easyui-validatebox" style="width:190px;background-color:#E3E2E2;text-align:center;" required readonly /> -->
												<!-- </td> -->
												<td align="right" valign="top"><input name="txt_payment_date" id="txt_payment_date" type="text" class="easyui-datebox validBackward" style="width:122px;height:20px" required editable="false" value='<?= $date_now;?>'/></td>
											</tr>
										</table>
									</td>
								</tr>
							</table>
						</td>
					</tr>
                    <tr>    
                        <td valign="middle" height="22" width="180" align="left"><b>No Trans From.</b></td>
                        <td><b>:</b></td>
						<td valign="top" align="left" width="800">
							<input name="txt_payment_for" id="txt_payment_for" type="text" style="width:227px;background-color:#E3E2E2;" readonly />
						</td>
					</tr>
					<tr>
						<td valign="top" height="51" align="left" style="padding-top:4px;"><b>Memo</b></td>
                        <td valign="top" style="padding-top:4px;"><b>:</b></td>
						<td valign="top" align="left">
							<textarea class="textbox" name="txa_memo" id="txa_memo" rows="4" style="width:362px;resize:none;white-space:normal;"></textarea>
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr style="display:none">
						<td height="22" valign="top" align="left"><b>Rate</b></td>
                        <td width="10"><b>:</b></td>
						<td valign="top" height="22" align="left">
							<input name="txt_rate" id="txt_rate" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" autoComplete="off" style="width:200px;" required="required" />
							<strong>Currency :</strong> <span id="from_currency"></span> <span>TO</span> <span id="to_currency"></span>
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr>
						<td height="22" valign="top" align="left"><b>Invoice Owing</b></td>
                        <td width="10"><b>:</b></td>
						<td valign="top" height="22" align="left">
							<input name="owing_amount" id="owing_amount" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:185px;" required="required" />
							~ <input name="txt_equal_invoice"  	 id="txt_equal_invoice" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:162px;" value="0" required="required" />
                            
                            <input name="txt_amount" id="txt_amount" type="hidden" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" />
							<input type="hidden" id="detail" name="detail" />
							<input type="hidden" id="fiscal_rate" name="fiscal_rate" />
							<input type="hidden" id="inv_rate" name="inv_rate" />
							<input type="hidden" id="currency_code" name="currency_code" />
							<input type="hidden" id="type_fiscal" name="type_fiscal" />
							<input type="hidden" id="customer_code" name="customer_code" />
							<input type="hidden" id="InvoicePaymentID" name="InvoicePaymentID" />
                            <input type="hidden" 			  id="txt_status_customer" name="txt_status_customer" />
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr height="20" style="display:none">
                        <td width="150" align="left"><b>Bank Balance (<span class='bank_balance_currency'></span>)</b></td>
                        <td width="10"><b>:</b></td>
                        <td >
                            <input name="txt_bank_balance" id="txt_bank_balance" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="text-align:right;width:362px" readonly />
                        </td>
                    </tr>					
				</table>
                
                <!-- Item Grid -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div title="Item">
                        <table toolbar="#tb_dtg_sales_journal" id="dtg_list_invoice" 
                        class="easyui-edatagrid" title="Payment History" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" style="height:250px;"
                        data-options = "
                        	onBeginEdit:function(rowIndex,rowData){
								save_button_begendedit('<?=$group_user->SavePrivillage;?>');

								editors = $('#dtg_list_invoice').datagrid('getEditors',rowIndex);
								var account_name	= $(editors[0].target);
                                var CurrCode        = $(editors[1].target);
                                var RecAmount       = $(editors[2].target);
                                var JrnRate         = $(editors[3].target);
                                var PrimeAmount     = $(editors[4].target);
                                var Memo            = $(editors[5].target);

                                /*================= Currency COde Customer ===============================*/
                                var CurrCustCode    = $('#currency_code').val();
                                /*========================================================================*/

                                /*================= Currency Code Account ===============================*/
                                var CurrAccountCode = CurrCode.val();
                                /*========================================================================*/

                                var type_fiscal     = index_tab;

                                if(type_fiscal == 1 || CurrCustCode == 'IDR'){
                                    if(CurrAccountCode == 'IDR'){
                                        $(JrnRate).prop('readonly',true);
                                    }
                                }
								
                                $(CurrCode).prop('readonly',true);
                                $(PrimeAmount).prop('readonly',true);
                                $(account_name).prop('readonly',true);
                                $(account_name).click(function(){
                                    open_list_gl(rowIndex);
                                }).mouseover(function(){
                                    $(this).css('cursor','pointer'); 
                                });
								
                                $(RecAmount).change(function(){
                                    if(CurrCustCode != 'IDR'){
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val()); 
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val());
                                            } 
                                        }
                                    }else{
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val());
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(JrnRate.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat($(this).val());
                                            } 
                                        }
                                    }
									//alert(PrimeAmount_Con);
                                    $(PrimeAmount).numberbox('setValue', PrimeAmount_Con);
                                });  

                                $(JrnRate).change(function(){
                                    if(CurrCustCode != 'IDR'){
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            } 
                                        }
                                    }else{
                                        if(type_fiscal != 1){
                                            if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            }
                                        }else{
                                           if(CurrAccountCode != 'IDR'){
                                                var PrimeAmount_Con =  parseFloat($(this).val()) * parseFloat(RecAmount.numberbox('getValue'));
                                            }else{
                                                var PrimeAmount_Con =  parseFloat(RecAmount.numberbox('getValue'));
                                            } 
                                        }
                                    }
                                   $(PrimeAmount).numberbox('setValue', PrimeAmount_Con);
                                });  
					          
							},
							onEndEdit:function(){
								save_button_endedit('<?=$group_user->SavePrivillage;?>');
							}
                        "
                        >
                            <thead>
                                <tr>
                                	<th data-options="field:'AccountHutang',halign:'center',align:'left',width:200" hidden="true">Account Hutang</th>
                                	<th align="center" valign="middle" data-options="field:'GLAccount',width:200,align:'left'" editor="{type:'AccountName',options:{required:true}}">GL Account</th>
                                    <th align="center" valign="middle" data-options="field:'CurrencyCode',width:80,align:'left'"  editor="{type:'text',options:{required:true}}">Currency</th>
                                    <th data-options="field:'PaymentAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Receipt Amount</th>
                                    <th data-options="field:'SJrnRate',width:150,halign:'center',align:'right',editor:{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Rate</th>
                                    <th data-options="field:'PrimeAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',disabled:'true',options:{precision:2,decimalSeparator:',',min:0}}" formatter="formatRp">Equal(~)</th>
                                    <th data-options="field:'Memo',halign:'center',align:'left',width:250,editor:{type:'text'}">Memo</th>
                                </tr>
                            </thead>
                        </table>
                        
                        <div id="tb_dtg_sales_journal">
                            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addNewRow()">New</a>	
                            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row()">Delete</a>							
                        </div>
                    </div>
                </div>
                <!-- End of item grid -->
            </form>
		</div>
	</div>
    <div id="form-footer" data-options="region:'south',border:false">
        <table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
             <tr>
               <td align="left">
               </td>
                <td align="right">                              
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-help" onclick="" plain="true">Help</a>
                     <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="save_me()" <?= $cek_autority_save;?>>Save</a>
                     <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="parent.tab_close('tt')">Cancel</a>
                </td>
             </tr>
        </table>				
    </div>	
</div>

<!---------------------------------------------Batas Awal Dialog Sales Invoice------------------------------------------------>
<div id="dialog-list-invoice" class="easyui-dialog" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-buttons" style="width:860px;height:532px;top:27px;background-color:#F8F8F8;padding:5px;"> 
        <div id="tab_invoice" class="easyui-tabs" style="width:835px;height:485px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
            <div title="Sales Invoice" style="padding:10px" >
             <table id="tb_invoice_list" class="easyui-datagrid" 
                url="<?= base_url().$menu_link; ?>/get_invoice" 
                remoteSort="false"
                pageSize="150"
                fitColumns="true" 
                rowNumbers="true"
                singleSelect="true"
                style="width:812px;height:400px" 
                data-options = "border:true,view:scrollview,autoRowheight:false"
            >
				<thead>
					<tr>
						<th field="BranchName" 		width="306">Branch</th>
                        <th field="InvoiceNumber" 	width="200" sortable="true">Trans. Number</th>
                        <th field="Invoice_Owing" 	width="180" editor="{type:'numberbox',options:{precision:2,decimalSeparator:','}}" formatter="formatRp" sortable="true">Invoice Owing</th>
                    	
					</tr>
				</thead>
			</table>
           <!-- Dialog Button for Dialog Item-->
            <div style="border:none; margin-top:10px; float:right;">
                 <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="get_invoice();">&nbsp; OK &nbsp; &nbsp;</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-list-invoice');">Cancel</a>
            </div>
            <!-- End of Dialog Button for Dialog Item-->
            </div>
            <div title="Fiscal Invoice" style="padding:10px" >
             <table id="tb_invoice_fiscal" class="easyui-datagrid" 
                url="<?= base_url().$menu_link; ?>/get_invoice_fiscal" 
                remoteSort="false"
                pageSize="150"
                fitColumns="true" 
                rowNumbers="true"
                singleSelect="true"
                style="width:812px;height:400px" 
                data-options = "border:true,view:scrollview,autoRowheight:false"
            >
				<thead>
					<tr>
						<th field="BranchName" 		width="306">Branch</th>
                        <th field="InvoiceNumber" 	width="200" sortable="true">Trans. Number</th>
                        <th field="Invoice_Owing" 	width="180" editor="{type:'numberbox',options:{precision:2,decimalSeparator:','}}" formatter="formatRp" sortable="true">Invoice Owing</th>
                    	<th field="InvoiceFiscalRate" width="130" formatter="formatRp" align="right" halign="center">FiscalRate</th>	
					</tr>
				</thead>
			</table>
            
           <!-- Dialog Button for Dialog Item-->
            <div style="border:none; margin-top:10px; float:right;">
                 <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="get_invoice();">&nbsp; OK &nbsp; &nbsp;</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-list-invoice');">Cancel</a>
            </div>
            <!-- End of Dialog Button for Dialog Item-->
            </div>
         </div>
</div>
<!---------------------------------------------Batas Akhir Dialog Purchase Invoice------------------------------------------------>



<!--  Tagor Dialog Payment AccountName -->
<div id="dialog-gl-account" class="easyui-dialog" style="width:850px;height:523px;top:27px;background-color:#F8F8F8;padding:0px" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-buttons-account-payment">
    <table width="100%" align="left" border="0">
        
        <tr>
            <td><b>Account Number</b></td>
            <td width="10"><b>:</b></td>
            
            <td>
                <input type="text" style="width:705px;height:20px" name="txt_AccountNumber" id="txt_AccountNumber" class="easyui-validatebox" placeholder="Account Number" onkeyup="get_account_gl();" />
            </td>
        </tr>
        
        <tr>
            <td><b>Account Name</b></td>
            <td><b>:</b></td>
        
            <td>
                <input type="text" style="width:705px;height:20px" name="txt_AccountName" id="txt_AccountName" class="easyui-validatebox" placeholder="Account Name" onkeyup="get_account_gl();" />
            </td>
        </tr>
        
        <tr>
            <td colspan="3">
                <table id="tt_choose_payment" class="easyui-datagrid" singleSelect="true"  rownumbers="true" style="width:828px;height:387px;"
                    pageSize="150" 
                    data-options = "border:true,view:scrollview,autoRowheight:false" 
                >
                    <thead>
                        <tr bgcolor="">
                           	<th field="AccountNumber" width="150" sortable="true" formatter="format_acc">Account Number</th>
                            <th field="AccountName" width="304" sortable="true" formatter="format_acc">Account Name</th>
                            <th field="SubtypeName" width="300" sortable="true" >Type Name</th>
                            <th field="CurrencyCode" width="460" sortable="true" hidden="true">Currency Code</th>
                            <th field="AccountLevel" width="460" sortable="true" hidden="true">Account Level</th>
                        </tr>
                    </thead>
                </table>
            </td>
        </tr>
    </table>
</div>

<!-- Dialog Button -->
<div id="dialog-buttons-account-payment">
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_account_gl();">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-gl-account');">Cancel</a>
</div>



<script type="text/javascript">

	var SavePrivillage 	= '<?=$group_user->SavePrivillage;?>';
	var index_tab 		= 0;
    var indChoAccount   = 0;

	$(document).ready(function(){

		$('#fm_sales_journal').click(function(){
			calculate_amount();
			var rownumbers = $('.datagrid-cell-rownumber').length;
			for(var x = 0; x < rownumbers; x++){
				$('.datagrid-cell-rownumber').eq(x).html(x+1);
				
			}
	    });


	    $('#tab_invoice').tabs({
	    	onSelect:function(titel,index){
	    		index_tab = index;
	    	}
	    })

	});
	
	function format_acc(val,row){
		return '<span style="padding-left:'+row.AccountLevel+'em;">'+val+'</span>';	
	}

	function get_invoice(){
		
		if(index_tab == 0){
			var rows = $('#tb_invoice_list').datagrid('getSelected');
		}else{
			var rows = $('#tb_invoice_fiscal').datagrid('getSelected');
		}
		
		var BranchName 			= rows.BranchName;
		var CustomerCode 		= rows.CustomerCode;
		var InvoiceNumber 		= rows.InvoiceNumber;
		var InvoiceAmount 		= rows.Invoice_Amount;
		var InvoiceOwing 		= rows.Invoice_Owing;
		var InvoiceCurrCode 	= rows.InvoiceCurrCode;
		var BranchCode 			= rows.BranchCode;
		var InvoiceCurrRate 	= rows.InvoiceCurrRate;
		var InvoiceFiscalRate 	= rows.InvoiceFiscalRate;
		var InvoicePaymentID 	= rows.InvoicePaymentID;

		

		//var url_gl_Account 				= '<?= base_url().$menu_link; ?>/get_gl_account/'+InvoiceCurrCode;

		//var dg 							= $('#dtg_list_invoice');

		// var revenue 					= dg.datagrid('getColumnOption','GLAccount');
		// revenue.editor.options.url 		= url_gl_Account;
		// revenue.editor.options.required = true;
		
		$('#dtg_list_invoice').datagrid('loadData',{'total':0,'rows':[]});
		$('#dtg_list_invoice').datagrid('reload');

		get_master_rate(InvoiceCurrCode);
		$('#fiscal_rate').val(InvoiceFiscalRate);
		$('#inv_rate').val(InvoiceCurrRate);
		$('#customer_code').val(CustomerCode);
		//$('#hutang_code').val(LFAccount);
		//$('#hutang_name').val(AccountName);
		$('#txt_payment_for').val(InvoiceNumber);
		//$('#txa_memo').html(LFDesc);
		$('#currency_code').val(InvoiceCurrCode);
		$('#InvoicePaymentID').val(InvoicePaymentID);

		$('#txt_amount').numberbox('setValue',0);
		$('#owing_amount').numberbox('setValue',InvoiceOwing);
		$('#type_fiscal').val(index_tab);
		$('#txt_status_customer').val(rows.LockStatus);
		
		/*================= COnvert Owing to IDR ======================*/
		if(index_tab == 0){
			if(InvoiceCurrCode != 'IDR'){
				var convert_owing   = parseFloat(InvoiceCurrRate) * parseFloat(InvoiceOwing);
				var rate_owing      = InvoiceCurrRate;
			}else{
				var convert_owing   = InvoiceOwing;
				var rate_owing      = InvoiceCurrRate;
			}
		}else{
			 if(InvoiceCurrCode != ''){
				var convert_owing   = InvoiceOwing;
				var rate_owing      = 1;
			}else{
				var convert_owing = InvoiceOwing;
				var rate_owing      = 1;
			}
		}

		//var LblEquelOwing = "<b>~ "+convert_owing+"<i> @"+rate_owing+"</i></b>";
		$('#txt_equal_invoice').numberbox('setValue',convert_owing);
		/*================= End COnvert Owing to IDR ======================*/

		// if(InvoiceCurrCode == 'IDR'){
		// 	 $('#txt_rate').numberbox({disabled:true});
		// 	 $('#from_currency').html(InvoiceCurrCode);
		// 	 $('#to_currency').html('IDR');
		// }else{
		// 	 $('#txt_rate').numberbox({disabled:false});
		// 	 $('#from_currency').html(InvoiceCurrCode);
		// 	 $('#to_currency').html('IDR');
		// }

		modal_close('dialog-list-invoice');
            
		
	}

	function addNewRow(){

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

        $.each(row,function(ind,val){
            if(val.GLAccount == ''){
                errGLAccount++;
            }
        });

		/*======================== tambahkan 1 row ke datagrid payment history ===============================*/
		if(no_piutang == ''){
			$.messager.alert('Warning','Silahkan pilih Invoice terlebih dahulu','Warning');
		}else{

            if(errGLAccount > 1 && row.length > 0){
                $.messager.alert('Warning','GLAccount Masih kosong','Warning');
            }else{
                var CurrencyCode = $('#currency_code').val();
                var master_rate  = $('#txt_rate').numberbox('getValue');
                
				$('#dtg_list_invoice').edatagrid('addRow',{
					//index: 1,
					row: {
						PaymentAmount       : 0,
						PrimeAmount 		: 0,
						GLAccount           : '',
						SJrnRate            : master_rate,
						CurrencyCode        : CurrencyCode,
					}
				});

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

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

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

	    var selectedrow         = $('#dtg_list_invoice').datagrid('getSelected');
	    var row_index           = $('#dtg_list_invoice').datagrid('getRowIndex', selectedrow);
	    
	    $.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.GainAccount + '"?',  
	        function(r){
	            if (r){

	                $('#dtg_list_invoice').datagrid('deleteRow', row_index);
	                calculate_amount();
	            }
	        }
	    );
	}

	function calculate_amount(){

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

		/*===================== save row & get all rows =======================*/
		$('#dtg_list_invoice').edatagrid('saveRow');	
		var row_payment 	= $('#dtg_list_invoice').datagrid('getRows');
        var CurrCustCode    = $('#currency_code').val();

		var total_piutang  	= parseFloat($('#owing_amount').numberbox('getValue'));
		var total_payment 	= 0;

		/*============== looing item datagrid payment history ===================*/
		$.each(row_payment, function( index,value){
	        total_payment 	+= convert_payment(index_tab,CurrCustCode,value.CurrencyCode,value.PaymentAmount,value.SJrnRate);
	    });

        total_payment   = Number(total_payment.toFixed(2));
        total_piutang   = Number(total_piutang.toFixed(2));

	    if(total_payment > total_piutang){
	    	$.messager.alert('Warning','Pembayaran melebihi sisa nilai pinjaman','error',function(){
				$('#txt_amount').numberbox('setValue',0);
			});
	    }else{
	    	$('#txt_amount').numberbox('setValue',total_payment);
	    }
	}

    function convert_payment(type_fiscal,CurrCustCode,CurrAccountCode,Amount,rate){
        if(CurrCustCode != 'IDR'){
            if(type_fiscal != 1){
                if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount);
                }else{
                    return parseFloat(Amount) / parseFloat(rate);   
                }
            }else{
               if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount) * parseFloat(rate);
                }else{
                    return parseFloat(Amount);
                } 
            }
        }else{
            if(type_fiscal != 1){
                if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount) * parseFloat(rate);
                }else{
                    return parseFloat(Amount);   
                }
            }else{
               if(CurrAccountCode != 'IDR'){
                    return parseFloat(Amount) * parseFloat(rate);
                }else{
                    return parseFloat(Amount);
                } 
            }
        }
    }

	function save_me(){

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

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

		var total_payment  	= 0;
		var owing_amount 	= parseFloat($('#owing_amount').numberbox('getValue'));
        var CurrCustCode    = $('#currency_code').val();

		/*============== looing item datagrid payment history ===================*/
		$.each(row_payment, function( index,value) {
	        total_payment 	+= convert_payment(index_tab,CurrCustCode,value.CurrencyCode,value.PaymentAmount,value.SJrnRate);
	    });

        var sisa_owing      = owing_amount - total_payment;
        //var limit_owing     = calculate_amount_pembulatan();

	    if(sisa_owing < 0){
	    	$.messager.alert('Unseccessfull','Pembayaran melebihi Invoice owing','error',function(){
				$('#txt_amount').numberbox('setValue',0);
				$('#dtg_list_invoice').datagrid('reload'); 
			});
	    }
		else if($('#txt_status_customer').val() == "Locked"){
			$.messager.alert('Maaf','Maaf Customer sedang di Lock, silahkan proses Transaksi yang berada di Sales Receipt atau Sales DP Journal','warning',function(){	
			
			});
		}
		else{

	    	var detail 			= JSON.stringify($('#dtg_list_invoice').datagrid('getRows'));
	    	$('#detail').val(detail);

	    	if(total_payment > 0){
	    		//if(sisa_owing <= limit_owing){
                if((sisa_owing >= -0.01) && (sisa_owing <= 0.01 )){
					save_transaction('<?= $menu_link?>','#fm_sales_journal');	
				}else{
					$.messager.alert('Unseccessfull','Total Payment Amount harus sama dengan Invoice Owing.','error',function(){
					
					});
				}
			}else{
				$.messager.alert('Unseccessfull','Belum ada detail transaksi payment.','error',function(){

				});
			}
	    }
	}

    function calculate_amount_pembulatan(){
        var row                 = $('#dtg_list_invoice').datagrid('getRows');
        var total_row           = row.length;
        var total               = 0;
        var CurrCustCode        = $('#currency_code').val();
        var owing               = parseFloat($('#owing_amount').numberbox('getValue'));

        /*============== looing item datagrid payment history ===================*/
        $.each(row, function( index,value){
            if((index+1)<total_row){
                total   += convert_payment(index_tab,CurrCustCode,value.CurrencyCode,value.PaymentAmount,value.SJrnRate);
            }else{
                var Amount          = owing - total;
                var PaymentAmount   = value.PaymentAmount;
                var CurrAccountCode = value.CurrencyCode;
                var rate            = value.SJrnRate;
                var sisa            = 0;
                var type_fiscal     = index_tab;

                if(CurrCustCode != 'IDR'){
                    if(type_fiscal != 1){
                        if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount);
                        }else{
                            sisa = parseFloat(Amount) * parseFloat(rate);   
                        }
                    }else{
                       if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount) / parseFloat(rate);
                        }else{
                            sisa = parseFloat(Amount);
                        } 
                    }
                }else{
                    if(type_fiscal != 1){
                        if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount) / parseFloat(rate);
                        }else{
                            sisa = parseFloat(Amount);   
                        }
                    }else{
                       if(CurrAccountCode != 'IDR'){
                            sisa = parseFloat(Amount) / parseFloat(rate);
                        }else{
                            sisa = parseFloat(Amount);
                        } 
                    }
                }

                sisa            = parseFloat(sisa.toFixed(2));
                total           += convert_payment(index_tab,CurrCustCode,value.CurrencyCode,sisa,value.SJrnRate);
            }
        });

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

	function choose_account_gl() {
	    var selected_data = $('#tt_choose_payment').datagrid('getSelected');
		//$('#dtg_list_invoice').edatagrid('saveRow');
        //var CurrencyCode = $('#currency_code').val();
        get_master_rate_on_grid(selected_data.CurrencyCode,function(MstRate){
            if(index_tab == 1){
                if(selected_data.CurrencyCode == 'IDR'){
                    $('#dtg_list_invoice').datagrid('updateRow',{
                        index: indChoAccount,
                        row: {
                            PaymentAmount       : 0,
                            GLAccount           : selected_data.AccountName,
                            SJrnRate            : MstRate.value,
                            CurrencyCode        : 'IDR',
                        }
                    });
                    // var ed = $('#dtg_list_invoice').datagrid('getEditor', {index:indChoAccount,field:'SJrnRate'});
                    // $(ed.target).prop('readonly',true);
                }else{
                    $('#dtg_list_invoice').datagrid('updateRow',{
                        index: indChoAccount,
                        row: {
                            PaymentAmount       : 0,
                            GLAccount           : selected_data.AccountName,
                            SJrnRate            : MstRate.value,
                            CurrencyCode        : selected_data.CurrencyCode
                        }
                    });
                }
            }else{
                $('#dtg_list_invoice').datagrid('updateRow',{
                    index: indChoAccount,
                    row: {
                        PaymentAmount       : 0,
                        GLAccount           : selected_data.AccountName,
                        SJrnRate            : MstRate.value,
                        CurrencyCode        : selected_data.CurrencyCode
                    }
                });
            }
			
			$('#dtg_list_invoice').edatagrid('beginEdit', indChoAccount);
        });
        

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

	// $.extend($.fn.datagrid.defaults.editors, {
	//     Payment_Account_Name: {
	//         init: function(container, options){
	//             var input = $('<input type="text" class="gl_account" style="height:18px;" readonly/>').appendTo(container);
	//             return input.validatebox(options);
	//         },
	//         destroy: function(target){
	//             $(target).remove();
	//         },
	//         getValue: function(target){
	//             return $(target).val();
	//         },
	//         setValue: function(target, value){
	//             $(target).val(value);
	//         },
	//         resize: function(target, width){
	//             $(target)._outerWidth(width);
	//         }
	//     }
	// });

	function open_list_gl(indexRow) { 
        indChoAccount = indexRow;
	    modal_open('Account List','dialog-gl-account');
	}

	function get_account_gl(){
		$('#tt_choose_payment').datagrid('load', {
	        AccountNo: $('#txt_AccountNumber').val(),
	        AccountName: $('#txt_AccountName').val(),
	        CurrencyCode:$('#currency_code').val()
	    });
	}
	
	function select_sales_journal(){
		var Customer = $('#cmb_customer').combogrid('grid');	// get datagrid object
		var SelectedCustomer = Customer.datagrid('getSelected');// get the selected row
		if(SelectedCustomer == null ){
			$.messager.alert('Maaf','Silahkan pilih customer terlebih dahulu','warning',function(){		
			});
		}
		else{
			modal_open('Select Sales Invoice','dialog-list-invoice');
		}
	}
	
	$('#cmb_customer').combogrid({
		onSelect:function(rowIndex, rowData){
			$('#tb_invoice_list').datagrid('load',{
				cust_code : rowData.CustomerCode
			});	
			
			$('#tb_invoice_fiscal').datagrid('load',{
				cust_code : rowData.CustomerCode
			});	
			
			search_account(rowData.CurrencyCode);
			
			$('#txt_rate').numberbox('setValue', rowData.CurrencyRate);
			
			if(rowData.CurrencyCode == 'IDR' ){
				$('#txt_rate').prop('disabled', true);
			}
			else{
				$('#txt_rate').prop('disabled', false);
			}
		}
	});	
	
	function search_account(CurrencyCode){
		$('#tt_choose_payment').datagrid({
			url: '<?= base_url().$menu_link; ?>/get_gl_account/'+CurrencyCode
		});
	}
	
	$.extend($.fn.datagrid.defaults.editors, {
		AccountName: {
			init: function(container, options){
				var input = $('<input type="text" class="AccountName" style="height:18px;" readonly/>').appendTo(container);
				return input.validatebox(options);
			},
			destroy: function(target){
				$(target).remove();
			},
			getValue: function(target){
				 return $(target).val();
			},
			setValue: function(target, value){
				  $(target).val(value);
			},
			resize: function(target, width){
				   $(target)._outerWidth(width);
			}
		}
	});
	
</script>
