<!---- 
    Author 	: Wahyu
    Tanggal : 12-08-2014	
    Revisi 	:
-->
<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="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="" disabled>Journal</a>
						</td>							
						<td height="25" align="right" valign="middle">								
							<span class="form-title">
								<?php echo $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:1180%;height:548px;padding:5px;" fit='true'>
			<form id="fm_payment_karyawan" name="fm_payment_karyawan" method="post" action="<?php echo base_url(); ?><?php echo"activities/payment_karyawan/insert"; ?>">
                
                <table cellpadding="0" cellspacing="3 width="100%" height="100%" border="0">
					<tr>
					    <input name="txt_piutang_no" id="txt_piutang_no" type="hidden" style="width:100px" />
					    <input name="txt_total_piutang" id="txt_total_piutang" type="hidden" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" style="width:100px" />
                        <input type="hidden" id="hide_new_index" name="hide_new_index" />
                        <input type="hidden" id="payment_balance" name="payment_balance" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                        <input type="hidden" id="txt_new_status" name="txt_new_status" />
                        
                        <input type="hidden" id="detail" name="detail" />
                        <input type="hidden" id="total_balance" name="total_balance" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                        
						<td valign="top" height="22" width="70" align="left">
							 <label>Payment for</label></td>
						<td valign="top" align="left"  width="768">
							 <input name="txt_payment_for" id="txt_payment_for" type="text" style="width:200px" class="disabled" readonly/>	
							 <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-sales" onclick="modal_open('Payment List','dialog-payment-list')" style="width:110px;" plain="true">List Payment</a>
						</td>
						<td width="117" align="left" valign="top">&nbsp;</td>
					</tr>
					<tr>
						<td valign="top" height="22" width="70" align="left">
							 <label>Transfer To</label></td>
						<td valign="top" align="left"  width="768">
							<select name="cmb_to_company" class="easyui-combogrid" id="cmb_to_company" required="required" style="width:202px;height:20px" data-options="
								panelWidth: 210,
								idField: 'BranchCode',
								textField: 'BranchName',
								url: '<?php echo base_url(); ?><?php echo"activities/piutang_karyawan"; ?>/get_company',            
								columns: [[
								{field:'BranchName',title:'Company Name',width:140}
								]],
								fitColumns: true
								">
							</select>
							<select name="cmb_to_bank" id="cmb_to_bank" class="easyui-combogrid" required="required" editable="false" style="width:200px;height:20px;">
								
							</select>							
						</td>
						<td  align="left" valign="middle">Payment No.</td>
						<td width="200" align="left" valign="top"><input type="text" name="txt_payment_no" id="txt_payment_no" class="easyui-validatebox disabled" style="width:200px;" readonly  required="required" /></td>
					</tr>
					<tr>
						<td valign="top" height="22" align="left">
							 From</td>
						<td valign="top" align="left">
							<input name="txt_karyawan" id="txt_karyawan" type="hidden" style="width:200px" />
							<input name="txt_karyawan_name" id="txt_karyawan_name" type="text" style="width:200px" />
							<!--<select name="cmb_from_bank" id="cmb_from_bank" class="easyui-combogrid" style="width:200px;height:20px;" required="required">
								
							</select>-->
						</td>
						<td valign="top" align="left">Payment Date</td>
						<td valign="top" align="left">
						   <input name="txt_payment_date" id="txt_payment_date" type="text" value='<?php echo $date_now;?>' class="easyui-datebox validBackward" style="width:150px;height:20px;" required editable="false"/>
						</td>
					</tr>
					
						<input name="txt_cheque_no" id="txt_cheque_no" type="hidden" style="width:100px" />							
						<input name="txt_cheque_date" id="txt_cheque_date" type="hidden"  style="width:100px;height:20px;" />
                        
					<tr>
						<td valign="top" height="51" align="left">
							  Description</td>
						<td valign="top" align="left"><textarea class="textbox" style="resize:none;" name="txa_description" id="txa_description" cols="48" rows="3"></textarea></td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr>
					  <td height="22" valign="top" align="left">Amount</td>
					  <td valign="top" height="22" align="left">
						<input name="txt_amount_rp" id="txt_amount_rp" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" autoComplete="off" style="width:334px;" required="required" readonly />
						<input name="txt_amount" id="txt_amount" type="hidden" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'"/>
						<a href="#" class="easyui-linkbutton" id="idchoose_cicilan" data-options="iconCls:'icon-calculator',size:'small'" onClick="choose_cicilan()"></a>
					  </td>
					  <td valign="top" align="left">&nbsp;</td>
				    </tr>					
				</table>
				<table id="dtg_payment_history" class="easyui-edatagrid"
				title="Payment History" idField="id"
				rownumbers="true" fitColumns="true" singleSelect="true" style="height:290px;" toolbar="#tb_dtg_pay_piutang">
					<thead>
						<tr>
							<th formatter="formatRp" data-options="field:'LoanPayment',width:75,halign:'center',align:'right', editor:{type:'numberbox',options:{precision:2,decimalSeparator:',', disabled:true}}">Loan Payment</th>
							<th data-options="field:'PaymentPeriod',width:15,halign:'center',align:'center', editor:{type:'numberbox',options:{disabled:true}}" hidden="true">Period</th>
							<th formatter="formatRp" data-options="field:'PaymentPerPeriod',width:75,halign:'center',align:'right', editor:{type:'numberbox',options:{precision:2,decimalSeparator:','}}">Payment Per Period</th>
							<th formatter="formatRp" data-options="field:'PaymentBalance',width:75,halign:'center',align:'right', editor:{type:'numberbox',options:{precision:2,decimalSeparator:',', disabled:true}}">Payment Balance</th>
                            <th data-options="field:'EInsNumber',width:75,halign:'center',align:'right', editor:{type:'textbox'}" hidden="true">Eins Number</th>
						</tr>
					</thead>
				</table>
			</form>
		</div>
        <div id="tb_dtg_pay_piutang">
            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addNewRow()">New</a>
        </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" iconCls="icon-save" onclick="save_data();">Save</a> 								
                         <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="" disabled>Preview & Print</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>


<!-- Dialog Payment List -->
<div id="dialog-payment-list" class="easyui-dialog" style="width:765px; left:150px; top:50px; background-color:#F8F8F8; height:300px; padding: 0 0px 0 0px" closed="true" data-options="modal:true" buttons="#dialog-buttons">
	<table id="dtg_payment_list" class="easyui-datagrid"  style="width:750px;" 
        url="<?php echo base_url(); ?><?php echo"activities/payment_karyawan"; ?>/get_piutang"
        singleSelect="true"
        idField="" >
		<thead>
			<tr>
				<th colspan="2">Dari</th>
				<th rowspan="2" field="EDebtAmount" formatter="formatRp" width="135" align="right" halign="center">Amount</th>
                <th rowspan="2" field="EmployeeName" width="120" align="center">Kepada</th>
                <th rowspan="2" field="outstanding" width="130" formatter="formatRp" align="right" halign="center">Sisa Hutang</th>	
                <th rowspan="2" field="EdebtIsLock" align="right" width="90"  halign="center" >Status</th>				
			</tr>
			<tr>
				<th field="BranchName" width="120" align="center">Perusahaan</th>
				<th field="AccountName" width="120" align="center">Bank</th>
				<th field="EDebtNumber" hidden="true" width="50" align="center">No Piutang</th>
					
                <th field="BranchCode" hidden="true" width="120" align="center">Branch Code</th>			
			</tr>
		</thead>
	</table>
	<div id="dialog-buttons">
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_piutang_karyawan()">OK</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-payment-list')">Cancel</a>
	</div>
</div>

<script type="text/javascript">
$(document).ready(function(){
        $('#txt_payment_no').val('<?php echo $payment_karyawan; ?>');
        $('#txt_payment_date').datebox({
            onChange:function(){
                url             = base_url + 'activities/payment_karyawan/get_payment_karyawan_number';                
                var Payment_karyawan_date   = $('#txt_payment_date').datebox('getValue');
                
                $.post(url, {Payment_karyawan_date:Payment_karyawan_date}, function(result){
                    if (result.status === true){
                        $('#txt_payment_no').val(result.number);
                    } 
                },'json');
            }
        }); 
         
         $('#dtg_payment_history').datagrid({
            onClickRow:function(){
                 var selected_data=$('#dtg_payment_history').datagrid('getSelected');
                 var no_paymen = $('#txt_payment_no').val();
                 if(selected_data.EInsNumber != no_paymen){
                     $.messager.alert('Unseccessfull','Data tidak sama dengan Nomor payment afiliasi','error',function(){	
                    $('#dtg_payment_history').datagrid('reload');
                    $('#txt_new_status').val(0);
                    });
                 }
            }
        });     
    });


function addNewRow(){
	var loan_value 			= parseFloat($('#txt_total_piutang').numberbox('getValue'));
    if(loan_value == "" || isNaN(loan_value)){
		$.messager.alert('Info','Piutang belum dipilih','error',function(){
			return false;
		});
	}
    else if($('#txt_new_status').val() == 1){
    	$.messager.alert('Info','Tidak Boleh Memilih Lebih Dari Satu','error',function(){
			return false;
		});
    }
    else{
    	$('#txt_new_status').val(1);
    	var txt_payment_for		= $('#txt_payment_for').val();
		var period 				= 1;
		var payment_perperiod 	= 0;
		var payment_balance 	= 0;
		var nomer_eins = $('#txt_payment_no').val();
        
		var dg_rows = $('#dtg_payment_history').datagrid('getRows');
		for(var i=0; i<dg_rows.length; i++){
			if(isNaN(dg_rows[i].PaymentPeriod)){ dg_rows[i].PaymentPeriod = 1; }
			if(isNaN(dg_rows[i].PaymentBalance)){ dg_rows[i].PaymentBalance = 0; }
			if(isNaN(dg_rows[i].PaymentPerPeriod)){ dg_rows[i].PaymentPerPeriod = 0; }
			period = ++period;
			payment_perperiod += parseInt(dg_rows[i].PaymentPerPeriod);
			payment_balance += parseFloat(dg_rows[i].PaymentBalance);
			var newIndex = i+1;
			$('#hide_new_index').val(newIndex);
        }
        if(payment_balance != ""){
			if(loan_value == payment_perperiod){
				$.messager.alert('Info','Pembayaran piutang sudah balance');
				return false;
			}
			else{
				$('#dtg_payment_history').datagrid('appendRow',{
					LoanPayment: loan_value,
                    EInsNumber: nomer_eins,
					PaymentPeriod: period
				});
			}
		}
		else{
			$('#dtg_payment_history').datagrid('appendRow',{
				LoanPayment: loan_value,
                EInsNumber: nomer_eins,
				PaymentPeriod: period
			});
			var dg_rows = $('#dtg_payment_history').datagrid('getRows');
			for(var i=0; i<dg_rows.length; i++){
				var newIndex = i;
			}
			$('#hide_new_index').val(newIndex);
		}
		var ed = $('#dtg_payment_history').datagrid('beginEdit', newIndex);
		var ed2 = $('#dtg_payment_history').edatagrid('getEditor',{index:newIndex,field:'PaymentPerPeriod'});
		$(ed2.target).focus();
    }
}    	
function choose_piutang_karyawan(){
	var selected_data=$('#dtg_payment_list').datagrid('getSelected');
	if(selected_data.EdebtIsLock=='Locked'){
		$.messager.alert('Info','Tidak bisa memilih Transaksi yang di-Lock');
	}
	else{
        $('#txt_new_status').val(0);
        $('#cmb_to_company').combogrid('setValue', selected_data.BranchCode);
        
        var ComCode = selected_data.BranchCode; 
        $('#cmb_to_bank').combogrid({
                delay: 300,
                url: '<?php echo base_url(); ?><?php echo"activities/piutang_karyawan"; ?>/get_akun_bank/'+ComCode,
                idField: 'AccountNumber',
                textField: 'AccountName',
                columns: [[
                    {field:'AccountName',title:'AccountName',width:400,sortable:true}
                ]]
        });
    
        $('#cmb_to_bank').combogrid('setValue', selected_data.BankTransfer); 
        $('#txt_karyawan').val(selected_data.EmplRecpCode);
        $('#txt_karyawan_name').val(selected_data.EmployeeName);
        $('#txt_piutang_no').val(selected_data.EDebtNumber);
        $('#txt_total_piutang').numberbox('setValue',selected_data.EDebtAmount);
        
        $('#txt_payment_for').val(selected_data.EDebtNumber);
        
        var piutang_no = selected_data.EDebtNumber;
        $('#dtg_payment_history').datagrid({
            url:'<?php echo base_url(); ?><?php echo'activities/payment_karyawan'; ?>/get_history_payment/'+piutang_no,
        });
                
        modal_close('dialog-payment-list');
    }
}

$('#dtg_payment_list').datagrid({
	onDblClickRow:function(){
		var selected_data=$('#dtg_payment_list').datagrid('getSelected');
        if(selected_data.EdebtIsLock=='Locked'){
			$.messager.alert('Info','Tidak bisa memilih Transaksi yang di-Lock');
        }
        else{
        	choose_piutang_karyawan();
         }
     }
});

function choose_cicilan(){
    var newIndex 		= $('#hide_new_index').val();
	var dg_rows 		= $('#dtg_payment_history').datagrid('getEditors', newIndex);
	
	var loanPayment		= $(dg_rows[0].target);
	var payPerPeriod	= $(dg_rows[2].target);
	var payBalance		= $(dg_rows[3].target);
	
	if(newIndex == 0){
		var balance = loanPayment.numberbox('getValue')-payPerPeriod.numberbox('getValue');
		payBalance.numberbox('setValue', balance);
	}
	
	$('#txt_amount_rp').numberbox('setValue', payPerPeriod.numberbox('getValue'));
	$('#txt_amount').numberbox('setValue',payPerPeriod.numberbox('getValue'));
	$('#total_balance').numberbox('setValue',balance);
	$('#payment_balance').numberbox('setValue',balance);
	
	var cek = $('#dtg_payment_history').datagrid('getRows');
	$('#dtg_payment_history').datagrid('endEdit', newIndex);
	var loan_payment 		= 0;
	var payment_perperiod 	= 0;

	for(var i=0; i<cek.length; i++){
		if(isNaN(cek[i].LoanPayment)){ cek[i].LoanPayment = 0; }
		loan_payment 	= parseFloat(cek[i].LoanPayment);
		if(isNaN(cek[i].PaymentPerPeriod)){ cek[i].PaymentPerPeriod = 0; }
		payment_perperiod += parseFloat(cek[i].PaymentPerPeriod);
		if(isNaN(cek[i].PaymentBalance)){ cek[i].PaymentBalance = 0; }
	}
	
	if(payment_perperiod > loan_payment){
		$.messager.alert('Unseccessfull','Pembayaran melebihi sisa nilai pinjaman','error',function(){
			$('#txt_amount_rp').numberbox('setValue','');
			$('#txt_amount').numberbox('setValue', 0);
            $('#dtg_payment_history').datagrid('reload');
            $('#txt_new_status').val(0);
			return false;
		});
	}
	else{
		var newIndex2 		= $('#hide_new_index').val();
		$('#dtg_payment_history').datagrid('beginEdit', newIndex2);
		var dg_rows2 		= $('#dtg_payment_history').datagrid('getEditors', newIndex2);
		
		var payBalance		= $(dg_rows2[3].target);
		
		var countBalance	= loan_payment-payment_perperiod;
		payBalance.numberbox('setValue', countBalance);
		
		$('#dtg_payment_history').datagrid('endEdit', newIndex2);
		
		var valAmount 	= $('#txt_amount_rp').numberbox('getValue');
		var convAmount 	= toAngka(valAmount);
		if(isNaN(convAmount) || convAmount == 0 || convAmount == ''){
			$('#calc_validate').linkbutton('enable');
			$('#txt_amount_rp').numberbox('setValue','');
			$('#txt_amount').val('');
		}
		else{
			$('#payment_balance').numberbox('setValue',countBalance);
			//$('#calc_validate').linkbutton('disable');
		}
	}
}

function cek_amount(value){
	var total = toAngka(value);
	$("#txt_amount").val(total);
}

function save_data(){
	$('#dtg_payment_history').edatagrid('saveRow');
	var cek = $('#dtg_payment_history').datagrid('getRows');
	var total = parseFloat($("#txt_amount").numberbox('getValue'));	
	var t_piutang = $('#txt_total_piutang').numberbox('getValue');
	var tt_piutang = parseFloat(t_piutang);
     var loan_payment 		= 0;
    var payment_perperiod 	= 0;
	
    for(var i=0; i<cek.length; i++){
        if(isNaN(cek[i].LoanPayment)){ cek[i].LoanPayment = 0; }
        loan_payment 	= parseFloat(cek[i].LoanPayment);
        if(isNaN(cek[i].PaymentPerPeriod)){ cek[i].PaymentPerPeriod = 0; }
        if(i==(cek.length-1)) payment_perperiod += parseFloat(cek[i].PaymentPerPeriod);
    }
    
  
	if(total < 1){
		$.messager.alert('Unseccessfull','Transaksi Belum Lengkap','error');
		return false;
	}
    else if(total > tt_piutang){		
        $.messager.alert('Unseccessfull','Pembayaran melebihi sisa nilai pinjaman','error',function(){
        	$('#txt_amount_rp').numberbox('setValue','');
			$('#txt_amount').numberbox('setValue', 0);
        	$('#dtg_payment_history').datagrid('reload');
            $('#txt_new_status').val(0);
        return false;
        });
	}	
    else if(payment_perperiod != total){
        $.messager.alert('Unseccessfull','Payment Per Period Tidak Sama Dengan Amount, Silahkan Klik Tombol Kalkulator','error',function(){
            $('#dtg_payment_history').datagrid('reload');
            $('#txt_new_status').val(0);
            return false;
        });
    }
	else {
	    //$("#fm_payment_karyawan").submit();
		//$('#dtg_payment_history').edatagrid('reload');
		//save_payment('<?php echo"$menu_link"; ?>', '#fm_payment_karyawan','','#dtg_payment_history');
		
        $('#dtg_payment_history').edatagrid('saveRow');
        var i=$('#dtg_payment_history').datagrid('getRows');
        var detail = JSON.stringify(i);
        $("#detail").val(detail);
        
        save_transaction('<?php echo"$menu_link"; ?>', '#fm_payment_karyawan','1');
		
	}

}
</script>