<!---- 
    Author 	: Ladur
    Tanggal : 12-08-2014	
    Revisi 	: Fachri
-->
<?php 
//---------Untuk privellege jika dia ada tombol save,suspen,jurnal----------
	if($group_user->SavePrivillage == 1){
		$cek_autority_save  = "";
	}
	else{
		$cek_autority_save 	= "disabled";
	}
	
	if($group_user->JournalPrivillage == 1){
		$cek_autority_journal  = "";
	}
	else{
		$cek_autority_journal 	= "disabled";
	}
	
	if($group_user->DeletePrivillage == 1){
		$cek_autority_delete  = "";
	}
	else{
		$cek_autority_delete 	= "disabled";
	}
	
	if($detail->TransStatus == 4) {
		$txt_ship_to = "";
		$txt_desc = "";
		$btn_delete = "";
	}
	else {
		$txt_ship_to = "readonly";
		$txt_desc = "readonly";
		$btn_delete = "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" width="30%">
					<input type="checkbox" name="chk_suspended" id="chk_suspended" value="3" onClick="suspend(1);" style="margin-top:0px;margin-right:1px;" <?php if($detail->TransStatus == 3){ echo"checked"; } ?> <?=((!in_array($detail->TransStatus,array(0,6,4)))?"disabled":"")?> <?php echo $cek_autority_delete;?>/>
                    <span style="display:inline-block;margin-top:2px;<?=(($detail->AppLevel1Status!=1)?'color:gray;':'')?>"><?=(($detail->TransStatus!=3)?"Suspend":"Suspend")?> </span>
                	<a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="parent.tab_add('Preview Journal <?=$menu_label?>', '<?php echo $menu_link; ?>', 'icon-print', 'to_preview_journal/<?php echo $detail->SRetNumber ?>')" <?php echo $cek_autority_journal;?>>Journal</a>  
                    <a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload()">Refresh</a>
                </td>
                <td align="center" width="40%"><span id="approval_information">
                <?php
				if($detail->TransStatus==4){
					if($this->session->userdata('jobtitle_status')==1){
						echo 'Need Your Approval';
					}
					else{
						echo 'Need Manager Approval';
					}
				}
				else if($detail->TransStatus==1){
					echo 'On Progress';
				}
				?>
                </span></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">
        	<?php if(in_array($detail->TransStatus,array(2,3,9,8))){ ?>
        	<div class="blanket"></div>
            <div class="status-box"><b><?php if($detail->TransStatus==2){ echo 'Finished'; }elseif($detail->TransStatus==3){ echo 'Suspended'; }elseif($detail->TransStatus==9){ echo 'Canceled by Dir.'; }elseif($detail->TransStatus==8){ echo 'Suspended Item'; }else{ echo 'Unknown'; } ?></b></div>
            <?php } ?>
            
            <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" value="<?=$detail->CurrencyCode?>"/>
                <input type="hidden" 	name="txt_ppn_rate" 		id="txt_ppn_rate" class="easyui-numberbox" value="<?=$detail->SRetPPNPcnt?>"/>
                <input type="hidden" 	name="id" 					id="id" value="<?php echo $detail->SRetNumber; ?>"/>
                <input type="hidden" 	name="branch_code" 			id="branch_code" value="<?php echo $detail->BranchCode; ?>"/>
                <input type="hidden" 	name="detail_id" 			id="detail_id">
                <input type="hidden" 	name="detail_qty" 			id="detail_qty">
                <!-- 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="easyui-combogrid" id="cmb_customer" readonly
                                    name="cmb_customer" required="required" 
                                    style="width:230px;height:20px;" 
                                    data-options="
                                    	value:'<?=$detail->CustomerCode?>',
                                        panelWidth: 329,
                                        idField: 'CustomerCode',
                                        textField: 'CustomerName',
                                        url: '<?php echo base_url(); ?>custom/get_data/customer',
                                        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();" disabled>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><?=$detail->BillingAddress?></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"<?php echo $txt_ship_to;?>><?=$detail->ShippingAddress?></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="93" rowspan="7" valign="top">&nbsp;</td>
                            <td width="49">&nbsp;</td>
                            <td width="195" style="background:#333399;text-align:center;color:#FFF;">SRet. No.</td>
                            <td width="190" style="background:#333399;text-align:center;color:#FFF;">SRet. Date</td>
                        </tr>
                        <tr height="20">
                            <td height="20" width="49" align="center" valign="middle">&nbsp;</td>
                            <td width="195" valign="middle">
                                <input type="text" name="txt_sr_no" id="txt_sr_no" class="easyui-validatebox textbox" style="width:221px;height:18px" value="<?php echo $detail->SRetNumber; ?>" required readonly />
                            </td>
                            <td>
                                <input name="txt_sr_date" id="txt_sr_date" type="text" class="easyui-datebox validBackward" style="width:190px;height:20px" required editable="false" readonly value="<?=convert_to_dmy($detail->SRetdate)?>"/>
                            </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:221px;height:18px" required readonly value="<?php echo $detail->SInvNumber;?>"/></td>
                            <td><input type="text" name="txt_si_date" id="txt_si_date" class="easyui-datebox validBackward" style="width:190px;height:20px"  readonly editable="false" value="<?php echo convert_to_dmy($detail->SInvDate);?>"/></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:221px;text-align:right;" value="<?php echo $detail->CurrencyRate;?>" 
                                    data-options="min:1,precision:2,groupSeparator:'.',decimalSeparator:','" <?=($detail->CurrencyCode=='IDR')?'readonly':''?> <?php echo $txt_desc;?>
                                />
                            </td>
                            <td><input type="text" name="txt_fiscal_rate" id="txt_fiscal_rate" class="easyui-numberbox currency" style="width:190px;text-align:right;" readonly value="<?php echo $detail->FiscalRate;?>"
                                    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"  class="easyui-<?=(in_array($detail->TransStatus,array(0,4,7,1)))?'edatagrid':'datagrid'?>"
                        url="<?php echo base_url().$menu_link."/ajax_item_for_edit/".$detail->SRetNumber; ?>"
						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" halign='center' field="SalesmanCode"	data-options="align:'left'" hidden="true">Salesman Code</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="SRetDetailID" 		data-options="align:'left'" 	hidden>SRet Detail ID</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:',',disabled:true}}" 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' data-options="align:'center'"	field="Item_Amount_Hide" 	ditor="{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();" <?php echo $btn_delete;?>>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;" <?php echo $txt_desc;?>><?php echo $detail->SRetDesc;?></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="<?php echo $detail->SRetSubTotal;?>" 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="<?php echo $detail->SRetSubTotal;?>" 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="numberbox" name="ppn" id="ppn" value="<?php echo $detail->SRetPPNOut;?>" 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="<?php echo $detail->SRetPPNOut;?>" 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="<?php echo $detail->SRetTotalAmount;?>" 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="<?php echo $detail->SRetTotalAmount;?>" 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 href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-ok" onclick="approval_sret();" <?=($detail->TransStatus==4 and $this->session->userdata('jobtitle_status')==1 and date('d-m-Y')>=date('d-m-Y', strtotime($detail->SRetdate)))?'':'disabled'?>>App. Mgr</a>					
                    <?php
					if(($group_user->ReversePrivillage == 1)){
					?>
					<a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-reload" onclick="app_reverse()" <?=(($this->session->userdata("jobtitle_status") == 0) && (in_array($detail->TransStatus,array(1,2,8))))?'':'disabled'?>>Reverse</a>  
					<?php
					}
					?>
                    <a id="save_button" href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="update_data();" <?=(in_array($detail->TransStatus,array(0,1,2,3)))?'disabled':''?> <?php echo $cek_autority_save;?>>Save</a> 								
                    <!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="link_print('<?php echo $menu_link ?>/to_print_detail/<?php echo $detail->SRetNumber ?>');" >Preview & Print</a>   -->
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="parent.tab_add('Form <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_print_detail/<?=$detail->SRetNumber?>');" <?=(in_array($detail->TransStatus,array(3,9,2,1,4,5,6)))?'':'disabled'?>>Preview & Print</a>  
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="<?=($this->session->userdata('jobtitle_status')==0)?'suspend(2)':'parent.tab_close(\'tt\')'?>" <?=($this->session->userdata('jobtitle_status')==0 && !in_array($detail->TransStatus,array(0,4,7)))?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
            </td>
        </tr>
        </table>
    </div>
</div>

<div id="dialog-si" class="easyui-dialog" style="width:665px;height:565px;top:5px;background-color:#F8F8F8;padding:0px;" closed="true" data-options="modal:true, iconCls:'icon-edit'" buttons="#dialog-buttons">
    <table id="tt_choose" class="easyui-datagrid" 
        url="<?php echo base_url() ?>list/sales_invoice/ajax_filter" 
        singleSelect="true" pagination="true" 
        pageSize="20" rowNumbers="true" 
        remoteSort="true" fit="true"
    >
        <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>
</div>

<!-- Dialog Button -->
<div id="dialog-buttons" style="border:none;">
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_item_si();">OK</a>
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-si');">Cancel</a>
</div>
<?php $this->load->view('v_custom_pop_up');?>
<script>
/*========================deklar variabel array for remove===================*/
var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
var array_item 		= [];
var array_qty 		= [];
ppn10 				= '<?= $taxes_ppn10->TaxesRate ?>';
/*==============================end=========================================*/

$(document).ready(function(){	
	$( "#fm_sales_return" ).click(function() {
		$('#dg_item').edatagrid('saveRow');
	});
	
	tax_status      = '<?=$detail->SRetTaxesStatus?>';
	intax_status    = '<?=$detail->SRetInTaxStatus?>';
	currency_code   = '<?=$detail->CurrencyCode?>';
	
	if(currency_code != 'IDR'){
		$('#row_currency_rate').show();
		$('#row_fiscal_rate').show();
	}
	else{
		$('#row_currency_rate').show();
		$('#row_fiscal_rate').show();
	}
	
	if(tax_status == 1){
		//$('.disableme').css('display','');                
		$('#chk_taxtable').prop('checked',true);
	
		if(intax_status == 1){
			$('.hide_inclusive').css('display','');                
			$('#chk_inclusive').prop('checked',true);
		}
		else {
			$('#chk_inclusive').prop('checked',false);
			$('.hide_inclusive').css('display','');                
		}	
	}
	else {
		//$('.disableme').css('display','none');                
		$('#chk_taxtable').prop('checked',false);
		$('#chk_inclusive').prop('checked',false);
	}
	
	//when customer selected
	$('#cmb_customer').combogrid({
		onSelect:function(rowIndex, rowData){
			$('#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');
			}
			
			if(rowData.CurrencyCode != 'IDR'){
				$('#row_currency_rate').show();
				$('#row_fiscal_rate').show();
			}
			else{
				$('#row_currency_rate').hide();
				$('#row_fiscal_rate').hide();
			}
				
			$('#tt_choose').datagrid('load',{
				cust_code : rowData.CustomerCode
			});		
  		}
	});	
	
	//when so selectted
	$('#tt_choose').datagrid({
		onDblClickRow:function(){		
			var si=$('#tt_choose').datagrid('getSelected').SInvNumber;
			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;
			$('#txt_currency_code').val(CurrencyCode);
			
			$('#dg_item').datagrid('load',{
				si_no: si
			});
			
			if(SInvTaxesStatus == 0) {
				$('.chk_tax').css('display','none');
				$('#chk_taxtable').prop( "checked", false );
			}
			else {
				$('.chk_tax').css('display','block');
				$('#chk_taxtable').prop( "checked", true );
				
				if(SInvInTaxStatus == 0) {
					$('.hide_inclusive').css('display','none');
					$('#chk_inclusive').prop( "checked", false );
				}
				else {
					$('.hide_inclusive').css('display','block');
					$('#chk_inclusive').prop( "checked", true );
				}
			}
			
			$('#txt_si_no').val(si);
			//$('#cmb_salesman').combobox('select',sales);
			
			modal_close('dialog-si');
			$('#disc_persent').removeAttr('disabled');
		}
	});
	
	$('#dg_item').datagrid({
		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
			
			var qty = n1.numberbox('getValue');
			
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			save_button_begendedit(SavePrivillage);
			/*=================================end============================================================*/
			
			n1.numberbox({
				onChange:function(){
					
					total_qty 		= parseFloat(n1.numberbox('getValue')) + parseFloat(n9.numberbox('getValue'));
					total_qty_book 	= parseFloat(max.numberbox('getValue')) - parseFloat(total_qty);
					
					if(parseFloat(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);	
						});
						//n1.numberbox('setValue',qty);
					}
					else {
						var cost = n1.numberbox('getValue')*n2.numberbox('getValue');
						var cost_cogs = n1.numberbox('getValue')*n6.numberbox('getValue');
						var total_qty = max.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;
			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);
		}
	});

    $('#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 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;
	
	$('#txt_currency_code').val(CurrencyCode);
	
	$('#dg_item').datagrid('load',{
		si_no: si
	});
	
	if(SInvTaxesStatus == 0) {
		$('.chk_tax').css('display','none');
		$('#chk_taxtable').prop( "checked", false );
	}
	else {
		$('.chk_tax').css('display','block');
		$('#chk_taxtable').prop( "checked", true );
		
		if(SInvInTaxStatus == 0) {
			$('.hide_inclusive').css('display','none');
			$('#chk_inclusive').prop( "checked", false );
		}
		else {
			$('.hide_inclusive').css('display','block');
			$('#chk_inclusive').prop( "checked", true );
		}
	}
	
	$('#txt_si_no').val(si);
	//$('#cmb_salesman').combobox('select',sales);
	
	modal_close('dialog-si');
	$('#disc_persent').removeAttr('disabled');
}

function update_data() {
	var url             = '<?= base_url();?>custom/custom/checking_update';
	var no_transaksi    = $('#txt_sr_no').val();
	var trans_status 	= '<?=$detail->TransStatus?>';
	
	var created_by 		= '<?php echo $detail->CreatedBy;?>';
	var login_as 		= '<?php echo$this->session->userdata('username');?>';
	var job_title 		= '<?php echo $this->session->userdata('jobtitle_status');?>';
	
	$('#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);
		edit_transaction_check('<?=$menu_link?>','#fm_sales_return', no_transaksi, url, trans_status,created_by, login_as, job_title);
	}							
}

function remove_row(){
	var item = $('#dg_item').datagrid('getData').total;

	if(item <= 1){
		$.messager.alert('Warning','Anda tidak dapat menghapus list item, minimum list item adalah satu (1)','error');
	}
	else {
		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){
					array_item.push(selectedrow.SRetDetailID);
					array_qty.push(selectedrow.SInvDetailID, selectedrow.ItemQty);
					
                   	$("#detail_id").val(JSON.stringify(array_item));
					$("#detail_qty").val(JSON.stringify(array_qty));
                   	$('#dg_item').datagrid('deleteRow', row_index);	
					calculate_item_tax();
					save_button_endedit(SavePrivillage);
				}
			}
		);        
					
	}            
}

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

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(ppn10);
		item_price 	= parseFloat(item_price - (item_price * 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);        
}

function suspend(type){
	var created_by 			= '<?php echo $detail->CreatedBy;?>';
	var login_as 			= '<?php echo$this->session->userdata('username');?>';
	var job_title 			= '<?php echo $this->session->userdata('jobtitle_status');?>';
	
	var url             = '<?= base_url();?>custom/custom/checking_suspend';
	suspend_check_trans('F', type, '<?=$menu_link?>', $('#txt_sr_no').val(), 'Sales Return', url, created_by, login_as, job_title);
}

function approval_sret() {
	var url_check           = '<?= base_url();?>custom/custom/checking_approval';
	var no_transaksi    	= $('#txt_sr_no').val();
	
	checking_approval(no_transaksi,function(check){
		if(check.status == false){
			approve_transaction();
		}else{
			$.messager.alert('Unseccessfull',check.message,'error',function(){
				location.reload();
			});
		}
	});
}

function approve_transaction(){
	var item 	= $('#dg_item').datagrid('getRows');
	var detail 	= JSON.stringify(item);
	$("#detail").val(detail);
	proses_custom_data('<?=$menu_link?>/approval_mgr','#fm_sales_return');
}

function app_reverse(){
	var no_transaksi    = $('#txt_sr_no').val();

	checking_reverse(no_transaksi,function(check){
		
		if(check.status == true){
			var i       = $('#dg_item').datagrid('getRows');
			var detail  = JSON.stringify(i);
	
			$("#detail").val(detail);
			reverse_data_by_detail('<?php echo $menu_link?>','#fm_sales_return');
		}else{
		   $.messager.alert('Unseccessfull',check.message,'error',function(){
				location.reload();
			});
		}
	});
}
</script>