<!---- 
    Author 	: Ladur
    Tanggal : 12-08-2014	
    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 cellpadding="0" cellspacing="0" width="100%">
            <tr>
                <td align="left" valign="middle">
                    <a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="parent.tab_add('New Sales Return', '<?=$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 of top view -->
        
    <!-- center view -->
    <div id="form-body" data-options="region:'center',border:false">
        <div id="form-wrapper" class="easyui-panel" style="padding:5px;" fit="true">
            <form id="fm_sales_return" name="fm_sales_return" method="post">
				<input type="hidden" name="detail" id="detail" />	
                <input type="hidden" name="txt_currency_code" id="txt_currency_code" />
                <input type="hidden" name="txt_ppn_rate" id="txt_ppn_rate" class="easyui-numberbox"/>
                <input type="hidden" name="hdn_ppn10_pcnt" id="hdn_ppn10_pcnt"/>
                
                <!-- Form Header -->
                <table width="100%" height="140" cellpadding="0" cellspacing="0">
                <tr>
                    <td width="59%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">
                        <tr height="20">
                            <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" data-options="plain:true,iconCls:'icon-sales'" onClick="select_sales();">Select SInv.</a>	
                                <input type="checkbox" name="chk_taxtable" id="chk_taxtable" onClick="hideppn();" value="1"  />Taxable &nbsp;	
                                <span class="hide_inclusive" style="display:none;">
                                    <input type="checkbox" name="chk_inclusive" id="chk_inclusive" onClick="calculate_item_tax();" value="1">Inclusive Tax
                                </span>
								
                            </td>
                        </tr>
                        
                        <tr height="20">
                            <td><b>Billing Address</b></td>
                            <td width="10"><b>:</b></td>
                            <td width="43">&nbsp;</td>
                            <td width="146"><b>Shipping Address</b></td>
                            <td width="10"><b>:</b></td>
                            <td width="43">&nbsp;</td>
                            <td width="229" rowspan="2">&nbsp;</td>
                        </tr>
                        <tr height="20">
                            <td colspan="3">
                                <textarea name="txa_address" id="txa_address" rows="4" style="width:95%;resize:none;" readonly></textarea>
                            </td>
                            <td colspan="3">
                                <textarea name="txa_ship_to" id="txa_ship_to" rows="4" style="width:95%;resize:none;" data-options="required:true" class="easyui-validatebox"></textarea>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="41%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
                        <tr height="20">
                            <td width="115" rowspan="7" valign="top">&nbsp;</td>
                            <td width="77">&nbsp;</td>
                            <td width="195" ></td>
                            <td width="140" style="background:#333399;text-align:center;color:#FFF;">SRet. Date</td>
                        </tr>
                        <tr height="20">
                            <td height="20" width="77" align="center" valign="middle">&nbsp;</td>
                            <td width="195" align="center" valign="middle">
                                
                            </td>
                            <td>
                                <input name="txt_sr_date" id="txt_sr_date" type="text" class="easyui-datebox validBackward" style="width:145px;height:20px" required editable="false" value="<?php echo $date_now;?>"/>
                            </td>
                        </tr>
                        <tr height="20">
                            <td>&nbsp;</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">SInv. No.</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">SInv. Date</td>
                        </tr>
                        <tr height="20">
                            <td></td>
                            <td><input type="text" name="txt_si_no" id="txt_si_no" class="easyui-validatebox textbox" style="width:210px;height:18px" required readonly /></td>
                            <td><input type="text" name="txt_si_date" id="txt_si_date" class="textbox" style="width:145px;height:20px"  readonly editable="false" /></td>
                        </tr>
                         <tr height="20">
                            <td>&nbsp;</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Currency Rate</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Fiscal Rate</td>
                        </tr>
                        <tr height="20">
                            <td></td>
                            <td>
                            <input type="text" name="txt_currency_rate" id="txt_currency_rate" class="easyui-numberbox currency" style="width:210px;text-align:right;" value="0" 
                                    data-options="min:1,precision:2,groupSeparator:'.',decimalSeparator:','"
                                />
                            </td>
                            <td><input type="text" name="txt_fiscal_rate" id="txt_fiscal_rate" class="easyui-numberbox currency" style="width:145px;text-align:right;" readonly value="0"
                                    data-options="min:1,precision:2,groupSeparator:'.',decimalSeparator:','"
                                />
                            </td>
                        </tr>
                        </table>
                    </td>
                </tr>
                </table>

                <!-- End of form header -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div id="tab_item" title="Items">
                        <table id="dg_item"   
                        url="<?php echo base_url().$menu_link."/ajax_item/"; ?>"
						toolbar="#toolbar" idField="id"
						rownumbers="true" fitColumns="true" singleSelect="true" 
                        style="height:250px;"
                        >
                            <thead>
                            <tr>
                                <th width="30" halign='center' field="ItemCode" 	data-options="align:'left'">Item</th>
                                <th width="65" halign='center' field="ItemDesc" 	data-options="align:'left'" 	editor="description">Description</th>
                                <th width="25" halign='center' field="max_item" 	data-options="align:'center'"	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, disabled:true}}" formatter="formatRp">Qty Invoice</th>
                                <th width="25" halign='center' field="ItemQty" 		data-options="align:'center'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp">Qty Return</th>
                                <th width="30" halign='center' field="ItemUnit" 	data-options="align:'left'" 	editor="unit" >Unit</th>
                                <th width="40" halign='center' field="ItemPrice" 	data-options="align:'right'"   	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Item Price</th>
                                <th width="40" halign='center' field="ItemDiscPcnt"	data-options="align:'center'"	formatter="formatRp" >Discount %</th>
                                <th width="40" halign='center' field="ItemAmount" 	data-options="align:'right'"  	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Return Amount</th>								
                                <th width="65" hidden="true"   field="SalesmanCode" data-options="align:'left'">Salesman</th>
                                <th width="65" halign='center' field="SalesmanName" data-options="align:'left'">Salesman</th>
                                
                                <th width="40" halign='center' field="ItemTax" 				data-options="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>Tax Amount</th>	
                                <th width="40" halign='center' field="ItemDiscount" 		data-options="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>Disc Amount</th>
                                <th width="50"  halign='center' field="IntaxStatus" 		data-options="align:'right'" 		editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" hidden>InTax Status</th> 
                                <th width="50"  halign='center' field="ItemCategoryID" 		data-options="align:'right'" hidden>Item Category ID</th> 
                                <th width="50"  halign='center' field="ItemCategoryCode" 	data-options="align:'right'" hidden>Item Category Code</th> 
                                <th width="40" halign='center' field="ItemTotalAmount" 		data-options="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>Return Total Amount</th>
                                <th width="65" halign='center' field="SInvDetailID" 		data-options="align:'left'" hidden>Sinv Detail Id</th>
                                <th width="25" halign='center' field="ItemQtyRet"	 		data-options="align:'center'" 		editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, min:0.00}}" formatter="formatRp" hidden>Qty Return Copy</th>
                                <th width="40" halign='center' field="ItemPriceCogs" 		data-options="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>Item Price Cogs</th>
                                
                                <th width="40" halign='center' field="ItemAmountCogs" data-options="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>Return Amount Cogs</th>
                                
                                <th width="25" halign='center' data-options="align:'center'" field="max_item_copy" 		editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, min:0.00}}" formatter="formatRp" hidden>Qty Invoice Copy</th>
                                <th width="25" halign='center' data-options="align:'center'" field="ItemQtyBookRet" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, min:0.00}}" formatter="formatRp" hidden>Qty Return Book</th>
                                
                                
                                <th width="40" halign='center' field="Item_Amount_Hide" data-options="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>Item Amount</th>
                                
                                <th width="40" halign='center' field="Total_Amount_Hide" data-options="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>Total Amount</th>
                                <th width="40" halign='center' data-options="align:'center'" field="ItemType" hidden>Item Type</th>
                                <th width="40" halign='center' data-options="align:'center'" field="ItemStatus" hidden>Item Status</th>
                                
                            </tr>
                            </thead>
						</table>
                        
                        <div id="toolbar">
                            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row()">Delete</a>								
                        </div>
                    </div>
                </div>
                <!-- End Item Grid -->
                
                <table width="100%" cellpadding="0" cellspacing="0">                
                <tr>
                	<td width="50%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">                        
                        <tr>
                            <td width="120" valign="top" style="padding-top:4px;"><b>Description</b></td>
                            <td width="10" valign="top" style="padding-top:4px;"><b>:</b></td>
                            <td>
                                <textarea id="txa_description" name="txa_description" rows="4" style="width:323px;resize:none;"></textarea>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">
                    	<table width="100%" cellpadding="0" cellspacing="1">
                        <tr>
                            <td>&nbsp;</td>
                            <td width="120"><b>Sub Total</b></td>
                            <td width="10"><b>:</b></td>
                            <td width="171">
                                <input type="numberbox" min="0" name="txt_total_return" id="txt_total_return" class="easyui-numberbox dp" value="0" readonly
                                	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" style="text-align:right;" 
                                />
                                
                                <input type="hidden" id="txt_total_return_hide" name="txt_total_return_hide" value="0" class="easyui-numberbox" style="text-align:right;" readonly
                                    data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    " 
                                />
                            </td>
                        </tr>
                        
                        <tr>
                        	<td>&nbsp;</td>
                            <td>
                                <span id="lbl_ppn10" style="font-weight:bold">PPn (<?= $taxes_ppn10->TaxesRate ?>%)</span>
                            </td>
                            <td ><b>:</b></td>
                            <td>
                                <input type="" name="ppn" id="ppn" value="0" class="easyui-numberbox" style="text-align:right" readonly
                                	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                                
                                <input type="hidden" id="ppn_hide" name="ppn_hide" value="0" class="easyui-numberbox" style="text-align:right;" readonly
                                    data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    " 
                                />
                            </td>
                        </tr>
                        <tr>
                        	<td>&nbsp;</td>
                            <td><b>Total Return</b></td>
                            <td><b>:</b></td>
                            <td>
                                <input type="numberbox" name="txt_total_amount" id="txt_total_amount" value="0" class="easyui-numberbox" style="text-align:right" readonly
                                	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                                
                                <input type="hidden" id="txt_total_amount_hide" name="txt_total_amount_hide" value="0" class="easyui-numberbox" style="text-align:right;" readonly
                                    data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    " 
                                />
                            </td>
                        </tr>
                        </table>
                    </td>
               	</tr>
                </table>
            </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-document" onclick="show_legend();" plain="true">Legend</a>
            	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-help" plain="true">Help</a>					
                <a id="save_button" 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="parent.tab_close('tt')">Close</a>
            </td>
        </tr>
        </table>
    </div>
</div>

<!----------------------------------------------Batas Awal Dialog Purchase Invoice-------------------------------------------------->
<div id="dialog-si" 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_purchase_req" class="easyui-tabs" style="width:835px;height:485px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
            <div title="Item / Expense" style="padding:10px" >
            
             <table id="tt_choose" class="easyui-datagrid" 
                url="<?php echo base_url() ?>list/sales_invoice/ajax_filter" 
                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="SInvNumber" width="200" sortable="true">SInv. Number</th>
                        <th field="SInvDate" width="80" formatter="formatDate" sortable="true">SInv. Date</th>
                        <th field="SInvDesc" width="306">Description</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="choose_item_si();">&nbsp; OK &nbsp; &nbsp;</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-si');">Cancel</a>
            </div>
            <!-- End of Dialog Button for Dialog Item-->
            </div>
         </div>
</div>
<!---------------------------------------------Batas Akhir Dialog Purchase Invoice------------------------------------------------>
<?php $this->load->view('v_custom_pop_up');?>
<script>
var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
$(document).ready(function(){	
	ppn10 				= '<?= $taxes_ppn10->TaxesRate ?>';
	$('#hdn_ppn10_pcnt').val('<?= $taxes_ppn10->TaxesRate ?>');
	
	//when customer selected
	$('#cmb_customer').combogrid({
		onSelect:function(rowIndex, rowData){
			$('#tt_choose').datagrid('load',{
				cust_code : rowData.CustomerCode
			});	
			
			$('#dg_item').datagrid('load',{
				si_no: ''
			});
			
			var Address = rowData.CustomerAddress + ' ' + rowData.CustCity + ' ' + rowData.CustState + ' ' + rowData.CustCountry;
			
			$('#txa_address').val( Address );
			$('#txa_ship_to').val( Address );
			//$('.div_fiscal').css('display','block');	
			
			if(rowData.TaxIncludedStatus == 1) {
				$('#chk_taxtable').attr('checked', true);
				$('.chk_tax').css('display','block');	
			}
			else {
				$('#chk_taxtable').removeAttr('checked');
				$('.chk_tax').css('display','none');
			}
			
			$('#txt_currency_rate').numberbox('setValue', rowData.ExchangeRate);
            $('#txt_fiscal_rate').numberbox('setValue', rowData.ExchangeRate);
			
			if(rowData.CurrencyCode == 'IDR' ){
				$('#txt_currency_rate').prop('disabled', true);
			}
			else{
				$('#txt_currency_rate').prop('disabled', false);
			}
			
			if(rowData.CurrencyCode != 'IDR'){
				$('#row_currency_rate').show();
				$('#row_fiscal_rate').show();
				
			}
			else{
				$('#row_currency_rate').show();
				$('#row_fiscal_rate').show();
			}
			
			$('#ppn').numberbox('setValue', 0);
			$('#ppn_hide').numberbox('setValue', 0);
			$('#txt_total_return').numberbox('setValue', 0);
			$('#txt_total_return_hide').numberbox('setValue', 0);
			$('#txt_total_amount').numberbox('setValue', 0);
			$('#txt_total_amount_hide').numberbox('setValue', 0);
  		}
	});	
	
	$('#dg_item').edatagrid({
		onLoadSuccess: function(){
			dg          	= $('#dg_item').datagrid('getRows');
			sub_total   	= 0;
			item_tax   		= 0;
			total_return 	= 0;
			
			$.each(dg, function(index, value){
				
				if(value.ItemAmount == null){
					item_amount = 0;
				}
				else{
					item_amount = value.ItemAmount;
				}
				sub_total = parseFloat(sub_total) + parseFloat(item_amount);
				item_tax = parseFloat(item_tax) + parseFloat(value.ItemTax);
				//sub_semua = value.ItemAmount;
			});
			
			total_return = sub_total + item_tax;
		},
			
		onBeginEdit:function(rowIndex){
			var editors = $('#dg_item').datagrid('getEditors', rowIndex);
			var max = $(editors[1].target);
			var n1 = $(editors[2].target);
			var n2 = $(editors[4].target);
			var n3 = $(editors[5].target); //item amount
			var n4 = $(editors[6].target); //item tax amount
			var n5 = $(editors[9].target); //item total amount
			var n6 = $(editors[11].target); //item price cogs
			var n7 = $(editors[12].target); //item amount cogs
			var n8 = $(editors[13].target); //item invoice copy
			var n9 = $(editors[14].target); //item qty book
			
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			save_button_begendedit(SavePrivillage);
			/*=================================end============================================================*/
				
			var qty = n1.numberbox('getValue');
			n1.numberbox({
				onChange:function(){
					total_qty 		= parseFloat(n1.numberbox('getValue')) + parseFloat(n9.numberbox('getValue'));
					total_qty_book 	= parseFloat(n1.numberbox('getValue')) - parseFloat(n9.numberbox('getValue'));
					
					if(total_qty > parseFloat(max.numberbox('getValue'))) {
						$.messager.alert('Error','Qty Return tidak boleh lebih dari Qty Invoice','error',function(){
							$('#dg_item').datagrid('reload'); 	
							save_button_endedit(SavePrivillage);	
						});
					}
					else {
						var cost 			= n1.numberbox('getValue')*n2.numberbox('getValue');
						var cost_cogs 		= n1.numberbox('getValue')*n6.numberbox('getValue');
						var invoice_total 	= n8.numberbox('getValue') - n1.numberbox('getValue');
						
						n3.numberbox('setValue',cost);
						n7.numberbox('setValue',cost_cogs);
						
						$('#dg_item').edatagrid('saveRow');
						calculate_item_tax();
					}	
				}
			})
		},
		onEndEdit:function(rowIndex, rowData, changes){
			var item = $('#dg_item').datagrid('getRows');
			sub_total 		= 0;
			sub_tax 		= 0;
			total_amount 	= 0;
			item_ppn 		= 0;
			
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			save_button_endedit(SavePrivillage);
			/*=================================end============================================================*/
				
			$.each(item, function( index, value ) {
				sub_total		+= parseFloat(value.Item_Amount_Hide);
				item_ppn		+= parseFloat(value.ItemTax);
				total_amount	+= parseFloat(value.Total_Amount_Hide);	
			});
			
			$('#txt_total_return').numberbox('setValue', sub_total);
			$('#txt_total_return_hide').numberbox('setValue', sub_total);
			
			$('#ppn').numberbox('setValue', item_ppn);
			$('#ppn_hide').numberbox('setValue', item_ppn);
			
			$('#txt_total_amount').numberbox('setValue', total_amount);
			$('#txt_total_amount_hide').numberbox('setValue', total_amount);
		}
	});
	
	$("#fm_sales_return").click(function() {
            $('#dg_item').edatagrid('saveRow');
	});   

     $('#txt_si_no').on('mouseover',function(){
        $(this).css({'color':'blue','font-weight':'bold','cursor':'pointer'});
    }).on('mouseout',function(){
        $(this).css({'color':'#545454','font-weight':'normal'});
    }).on('click',function(){
        var TransNumber = $(this).val();
        parent.tab_edit('Edit Sales Invoice','list/sales_invoice', 'icon-edit', 'edit',TransNumber) ;
    });
	
	datagrid_item_type_status("dg_item");//untuk warna grid  
});	

function select_sales() {
	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-si');
	}		
}

function choose_item_si(){
	var si				= $('#tt_choose').datagrid('getSelected').SInvNumber;
	var si_date 		= $('#tt_choose').datagrid('getSelected').SInvDate;
	var sales			= $('#tt_choose').datagrid('getSelected').SalesmanCode;
	var SInvTaxesStatus = $('#tt_choose').datagrid('getSelected').SInvTaxesStatus;
	var SInvInTaxStatus = $('#tt_choose').datagrid('getSelected').SInvInTaxStatus;
	var CurrencyCode 	= $('#tt_choose').datagrid('getSelected').CurrencyCode;
	var CurrencyRate 	= $('#tt_choose').datagrid('getSelected').CurrencyRate;
	var FiscalRate 		= $('#tt_choose').datagrid('getSelected').FiscalRate;
	var SInvPPn10Pcnt 	= $('#tt_choose').datagrid('getSelected').SInvPPnPcnt;
	
	if(SInvTaxesStatus == 1){
		ppn10_pcnt  = SInvPPn10Pcnt;
		$('#lbl_ppn10').text('PPn (' + ppn10_pcnt + '%)');
		$('#hdn_ppn10_pcnt').val(SInvPPn10Pcnt);
	}
	else{
		$('#lbl_ppn10').text('PPn (' + 0 + '%)');
		$('#hdn_ppn10_pcnt').val(0);
	}
		
	$('#txt_currency_code').val(CurrencyCode);
	
	$('#dg_item').datagrid('load',{
		si_no: si
	});
	
	if(SInvTaxesStatus == 1){
		$('.chk_tax').css('display','');
		$('#chk_taxtable').prop('checked',true);
		
		if(SInvInTaxStatus == 1){
			$('.hide_inclusive').css('display','');
			$('#chk_inclusive').prop('checked',true);
		}
		else{
			if($('#chk_taxtable').is(':checked')){
				$('.hide_inclusive').css('display','');		
			}
			else{
				$('.hide_inclusive').css('display','none');
				$("#chk_inclusive").prop("checked",false);
			}
		}
	}
	else{
		$('.chk_tax').css('display','None');                
		$('.hide_inclusive').css('display','None');
		$('#chk_taxtable').prop('checked',false);
		$('#chk_inclusive').prop('checked',false);
	}
	
	$('#txt_si_no').val(si);
	
	sd_split = si_date.split('-');
	sd_split = sd_split[2] +'-'+ sd_split[1] +'-'+ sd_split[0];
				
	$('#txt_si_date').val(sd_split);
	$('#txt_currency_rate').numberbox('setValue',CurrencyRate);
	$('#txt_fiscal_rate').numberbox('setValue',FiscalRate);
	//$('#cmb_salesman').combobox('select',sales);
	
	modal_close('dialog-si');
	$('#disc_persent').removeAttr('disabled');
}

function insert_data() {
	$('#dg_item').edatagrid('saveRow');
	var cek = $('#dg_item').datagrid('getRows');
	
	err_qty = 0;
	fleg = true;
	
	$.each(cek, function( index, value ) {
		if(value.ItemQty == 0) {
			fleg = false;
		}
		else {
			if(parseFloat(value.ItemQty) > parseFloat(value.max_item)) {
				err_qty++;
			}
		}
	});
	
	if(err_qty > 0) {
		$.messager.alert('Error','Qty tidak boleh lebih dari Qty SI','error',function(){	
			
		})	
	}
	else if(fleg == false){
		$.messager.alert('Unseccessfull','Qty Return Tidak Boleh Bernilai 0.','error',function(){	
				
		});
	}
	else {
		var i=$('#dg_item').datagrid('getRows');
		var detail = JSON.stringify(i);
		$("#detail").val(detail);
		save_transaction('<?php echo $menu_link?>','#fm_sales_return', 0);			
	}							
}

function hideppn(){
	if($('#chk_taxtable').is(':checked')){
		$('.hide_inclusive').css('display','');	
		$('#lbl_ppn10').text('PPn (' + ppn10 + '%)');	
		$('#hdn_ppn10_pcnt').val(ppn10);
	}
	else{
		$('.hide_inclusive').css('display','none');
		$("#chk_inclusive").prop("checked",false);
		$('#ppn').numberbox('setValue', 0);
		$('#lbl_ppn10').text('PPn (' + 0 + '%)');
		$('#hdn_ppn10_pcnt').val(0);
	}
	calculate_item_tax();
}

function remove_row(){
	var selectedrow     = $('#dg_item').datagrid('getSelected');
	var row_index       = $('#dg_item').datagrid('getRowIndex', selectedrow);

	$.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.ItemCode + '"?',  
		function(r){
			if (r){
				var item = $('#dg_item').datagrid('getData').total;
				
				if(item == 0){
					$("#chk_inclusive").prop("checked",false);
				}
				
				$('#dg_item').datagrid('deleteRow', row_index);
				calculate_item_tax();
				save_button_endedit(SavePrivillage);
			}
		}
	);
}

function calculate_item_tax(){
	$('#dg_item').edatagrid('saveRow');
	var item = $('#dg_item').datagrid('getRows');
	
	$.each(item, function(index, value){
		intax       = 0;
		item_ppn    = 0;
		item_ppn10  = 0;
		item_pph22  = 0;
		item_pph23  = 0;
		item_amount = 0;
		item_price  = value.ItemPrice;
		item_disc  	= value.ItemDiscPcnt;
		item_qty  	= value.ItemQty;
		ppn10_val   = parseFloat($('#hdn_ppn10_pcnt').val());
		item_price 	= parseFloat(item_price * ((100 - item_disc) / 100));
		
		if(item_price >= 0 || item_price !== null){
			if($('#chk_taxtable').is(':checked')){
				if($('#chk_inclusive').is(':checked')){
					total_price 	= parseFloat((100 / (100 + ppn10_val) * item_price).toFixed(15));
				}
				else{
					total_price = parseFloat(item_price);
				}
			}
			else{
				total_price = parseFloat(item_price);
			}
			
			item_amount     = parseFloat(item_qty * total_price);
			item_ppn10      = $('#chk_taxtable').is(':checked') ? parseFloat(item_amount * (ppn10_val / 100)) : 0;     
			
			item_total      = parseFloat(item_amount + item_ppn10).toFixed(15);
			$('#dg_item').datagrid('updateRow',{
				index:index,
				row:{
					 ItemAmount   		: item_amount,
					 Item_Amount_Hide   : item_amount,
					 ItemTax      		: item_ppn10,
					 Total_Amount_Hide  : item_total}
			});  
		}
	});
	
	calculate_total();
}
	
function calculate_total(){
	$('#dg_item').edatagrid('saveRow');
	var item        = $('#dg_item').datagrid('getRows');

	var total       = 0;
	var sub_total   = 0;
	var sub_ppn10   = 0;
	var sub_pph22   = 0;

	$.each(item, function(index, value) {
		item_amount   = isNaN(value.Item_Amount_Hide) ? 0 : value.Item_Amount_Hide;
		item_ppn10    = isNaN(value.ItemTax) ? 0 : value.ItemTax;

		sub_total       += parseFloat(item_amount);
		sub_ppn10       += parseFloat(item_ppn10);
	});
	
	$('#txt_total_return').numberbox('setValue', sub_total);
	$('#txt_total_return_hide').numberbox('setValue', sub_total);
	 
	$('#ppn').numberbox('setValue', sub_ppn10);
	$('#ppn_hide').numberbox('setValue', sub_ppn10);

	total = sub_total + sub_ppn10;
	$('#txt_total_amount').numberbox('setValue', total);
	$('#txt_total_amount_hide').numberbox('setValue', total);        
}
</script>