<!---- 
Author 	: ??? / 25-08-2014 	
Revisi 	:
-->

	<?php
			//---------Untuk privellege jika dia ada tombol save----------
				if($group_user->SavePrivillage == 1){
					$cek_autority_save  = "";
				}
				else{
					$cek_autority_save 	= "disabled";
				}
				
				if($group_user->DeletePrivillage == 1){
					$cek_autority_delete  = "";
				}
				else{
					$cek_autority_delete 	= "disabled";
				}
				
				if($group_user->JournalPrivillage == 1){
					$cek_autority_journal  = "";
				}
				else{
					$cek_autority_journal 	= "disabled";
				}
				
				//-------------end----------------------------
	?>

<style>
.datagrid-header-row [field='ck'] input{
	display:none;
}
</style>

<div class="easyui-layout" data-options="fit:true,border:false">
    <!-- top view-->
    <div id="form-header" data-options="region:'north',border:false" >
        <div id="form-header-wrapper">
            <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td align="left" 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->TransStatus==3)?'color:gray;':'color:black')?>">Suspend</span>
                        
                        <a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="parent.tab_add('Journal <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_preview_journal/<?=$detail->PRetNumber?>');" <?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')=='MGR'){
                                    echo 'Need Your Approval';
                                }
                                else{
                                    echo 'Need Manager Approval';
                                }
                            }
                            ?>
                        </span>
                    </td>
                    
                    <td align="right" width="30%">
                        <span class="form-title"><?=$menu_label?></span>							
                    </td>
                </tr>
            </table>		     	
        </div>			
    </div>
    <!-- end top view -->	

    <!-- center view -->
    <div id="form-body" data-options="region:'center',border:false">
        <div id="form-wrapper" class="easyui-panel" fit="true" style="padding:5px;">
            <?php if(in_array($detail->TransStatus,array(2,3,9))){ ?>
                <div class="blanket"></div>
                <div class="status-box">
                    <b><?php 
                    if($detail->TransStatus == 3){echo 'Suspended';}
                    elseif($detail->TransStatus == 9){echo 'Canceled by Dir.';}
                    elseif($detail->TransStatus == 2){echo 'Finished';}
                    else{echo 'Unknown';} 
                    ?></b>
                </div>
            <?php } ?>
        	
            <form id="fm_purchase_return" name="fm_purchase_return" method="post">
                <input type="hidden" name="detail" id="detail" />
                <input type="hidden" name="detail_id" id="detail_id">
                
                <input type="hidden" name="hdn_ppn10_pcnt" id="hdn_ppn10_pcnt"/>
                <input type="hidden" name="hdn_pph22_pcnt" id="hdn_pph22_pcnt"/>
                
                <input type="hidden" name="hdn_currency_code" id="hdn_currency_code"/>
                <input type="hidden" name="hdn_taxes_status" id="hdn_taxes_status"/>
                <input type="hidden" name="hdn_intax_status" id="hdn_intax_status"/>

                <table width="100%" height="140" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="60%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr height="20">
                                    <td width="120"><b>Vendor Name</b></td>
                                    <td width="10"><b>:</b></td>

                                    <td height="20">
                                        <select name="cbg_vendor" id="cbg_vendor" class="easyui-combogrid" style="width:180px;height:20px;" required readonly 
                                            data-options="
                                                panelWidth: 300, 
                                                value:'<?=$detail->VendorCode?>',
                                                idField: 'VendorCode',
                                                textField: 'VendorName',
                                                url: '<?=base_url()?>custom/get_data/vendor',
                                                method: 'get',
                                                columns: [[
                                                    {field:'VendorCode',title:'Vendor No',halign:'center',align:'center',width:110},
                                                    {field:'VendorName',title:'Vendor Name',halign:'center', width:250}
                                                ]],
                                                fitColumns: true
                                            ">
                                        </select>
                                        
                                        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-sales'" disabled>Select PI</a>
										<input type="checkbox" name="chk_taxtable" id="chk_taxtable" value="1" onClick="hideppn();">Taxable
                                        <span class="disableme" style="display:none;">
                                            <input type="checkbox" name="chk_inclusive" id="chk_inclusive" value="1" onClick="calculate_item_tax();">Inclusive Tax
                                        </span>                                                                                
                                        
                                        <span style="display:none;">
                                            <input type="checkbox" name="chk_vendor_dp" id="chk_vendor_dp" value='1' disabled hidden/>Vendor needs DP
                                        </span>                                                                                                                        
                                    </td>
                                </tr>

                                <tr id="row_currency_rate" style="display:none">
                                    <td><b>Currency Rate</b></td>
                                    <td><b>:</b></td>
                                    
                                    <td colspan="5">
                                        <input type="text" name="txt_currency_rate" id="txt_currency_rate" class="easyui-numberbox currency" valule="<?= $detail->CurrencyRate ?>" style="width:70px;text-align:right;" 
                                            data-options=" min:0.01, precision:2, decimalSeparator:',', groupSeparator:'.'"
                                        />
                                        
                                        <span id="currency" style="font-weight:bold"></span>
                                    </td>
                                </tr>

                                <tr id="row_fiscal_rate" style="display:none;">
                                    <td><b>Fiscal Rate</b></td>
                                    <td><b>:</b></td>
                                    
                                    <td colspan="5">
                                        <input type="text" name="txt_fiscal_rate" id="txt_fiscal_rate" class="easyui-numberbox currency" value="<?= $detail->FiscalRate ?>" style="width:70px;text-align:right;" disabled
                                            data-options=" min:1, precision:2, decimalSeparator:',', groupSeparator:'.'"
                                        />
                                        
                                        <span id="fiscal" style="font-weight:bold"></span>
                                    </td>
                                </tr>
                                
                                <tr height="20">
                                    <td valign="top" style="padding-top:4px;"><b>Vendor Address </b></td>
                                    <td valign="top" style="padding-top:4px;"><b>:</b></td>

                                    <td colspan="2">
                                        <textarea name="txa_address" id="txa_address" rows="4" style="width:254px;resize:none;" readonly><?= $detail->VendorAddress ?></textarea>
                                    </td>
                                </tr>						
                            </table>
                        </td>

                        <td width="40%" valign="top" >
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr height="20">
                                    <td rowspan='5'>&nbsp;</td>
                                    <td width="190" style="background:#333399;text-align:center;color:#FFF;">PRet. No.</td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">PRet. Date</td>
                                </tr>

                                <tr height="20">
                                    <td>
                                        <input type="text" name="txt_pret_no" id="txt_pret_no" class="easyui-validatebox textbox" value='<?= $detail->PRetNumber ?>' style="width:190px;height:18px;text-align:center;" required readonly />
                                    </td>

                                    <td>
                                        <input type="text" name="txt_pret_date" id="txt_pret_date" class="easyui-datebox validBackward" value='<?= $detail->PRetDate ?>' style="width:122px;height:20px" required readonly />
                                    </td>
                                </tr>

                                <tr height="20">
                                    <td style="background:#333399;text-align:center;color:#FFF;">PInv. No.</td>
                                    <td style="background:#333399;text-align:center;color:#FFF;">PInv. Date</td>
                                </tr>

                                <tr height="20">
                                    <td align="center">
                                        <input type="text" name="txt_pinv_no" id="txt_pinv_no" value='<?= $detail->PInvNumber ?>' class="easyui-validatebox textbox" style="width:190px;height:18px;text-align:center;" required="required" text-align="center" readonly />
                                    </td>
                                    
                                    <td textalign="center">
                                        <input type="text" name="txt_pinv_date" id="txt_pinv_date" value='<?= $detail->PInvDate ?>' class="easyui-datebox" style="width:122px;height:20px" editable="false" readonly />
                                    </td>
                                </tr>
                            </table>						
                        </td>
                    </tr>
                </table>

                <!--Datagrid-->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div id="tab_general" title="Item">
                    	<table toolbar="#tb_dtg_item" id="dtg_item" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" style="height:250px;" 
                             url="<?=base_url() . $menu_link . '/ajax_item_for_edit/' . $detail->PRetNumber . '~' . $detail->PInvNumber ?>"
                        > 
                            <thead>
                                <tr>
                                    <th field="PRecNumber"       width="70"  data-options="halign:'center',align:'left'"    >RI. No.</th>
                                    <th field="ItemCode"         width="50"  data-options="halign:'center',align:'left'"    >Item</th>
                                    <th field="ItemDesc"         width="150" data-options="halign:'center',align:'left'"    >Description</th>
                                    <th field="InvoiceQty"       width="30"  data-options="align:'center',halign:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Qty</th>
                                    <th field="Item_Qty"         width="35"  data-options="halign:'center',align:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp">Qty Return</th>
                                    <th field="ItemUnit"         width="30"  data-options="halign:'center',align:'center'," >Unit</th>
                                   
                                    <th field="ItemPrice"        width="40"  data-options="halign:'center',align:'right'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,required:true,disabled:true}}" formatter="formatRp">Unit Price</th>
                                    <th field="ItemDisc"        width="40"  data-options="halign:'center',align:'right'"    editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0,required:true,disabled:true}}" formatter="formatRp" hidden>Item Disc</th>
                                    <th field="Item_Amount"      width="50"  data-options="halign:'center',align:'right'," 
                                    editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>Item Amount</th>
                                    
                                    <th field="Item_TaxPPn10"    width="30"  data-options="halign:'center',align:'right'"   
                                    editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>Item Tax PPn</th>                                    
                                    <th field="Item_TaxPPh22"    width="30"  data-options="halign:'center',align:'right'"   
                                    editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>Item Tax PPh22</th>
                                    <th field="Item_TotalAmount" width="50"  data-options="halign:'center',align:'right',"  
                                    editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>Total Amount</th>
                                   
                                    <th field="ItemPPh22Status"  width="30"  data-options="halign:'center',align:'right'"   editor="{type:'numberbox',options:{min:0,disabled:true}}" hidden>Item Tax PPh22</th>
                                    <th field="ItemCategoryID"   width="50"  data-options="halign:'center',align:'center'"  editor="{type:'numberbox',options:{disabled:true}}" hidden>Category ID</th>
                                    <th field="ItemCategoryCode" width="50"  data-options="halign:'center',align:'center'"  hidden>Category Code</th>
                                    <th field="PInvDetailID"     width="50"  data-options="halign:'center',align:'center'"  hidden>PInv Detail ID</th>
                                    <th field="PRetDetailID"     width="50"  data-options="halign:'center',align:'center'"  hidden>PRet Detail ID</th>
                                    <th field="PInvReturnQty"    width="50"  data-options="halign:'center',align:'center'"  hidden>PInv Qty Return</th>                                    
                                    <th field="Item_Code"        width="50"  data-options="halign:'center',align:'left'"    editor="{type:'text'}" hidden>Item Code</th>
                                    <th field="ItemAssetStatus"  width="50"  data-options="halign:'center',align:'center'"  editor="{type:'text'}" hidden>Asset Status</th>
                                    <th field="ItemAssetCode"    width="75"  data-options="halign:'center',align:'left'"    editor="{type:'text'}">Asset Code</th>
                                    
                                    <th field="ItemPrice_Hide"     width="50"  data-options="align:'right',halign:'center'"  
                                    editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}"
                                    hidden>ItemPrice Hide</th>
                                    <th field="ItemStatus"        width="50"  data-options="halign:'center',align:'left'"    editor="{type:'text'}" hidden>Item Status</th>
                                    <th field="ItemType"          width="50"  data-options="halign:'center',align:'left'"    editor="{type:'text'}" hidden>Item Type</th>
                                    <th field="PRecNumber_Edit"       width="70"  data-options="halign:'center',align:'left'"     editor="{type:'text'}" hidden>RI. No.</th>
                                    
                                </tr>
                            </thead>
                        </table>
                        <div id="tb_dtg_item">
                            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row();" >Delete</a>								
                        </div>
                    </div>					
                </div>

                <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:335px;resize:none;"><?= $detail->PRetDesc ?></textarea>
                                    </td>
                                </tr>

                                <tr style="display:none;">
                                    <td><b>Total DP</b></td>
                                    <td><b>:</b></td>

                                    <td>
                                        <input type="text" name="txt_total_dp" id="txt_total_dp" class="easyui-numberbox" value="0" style="text-align:right;" readonly hidden 
                                            data-options="min:0,precision:2,groupSeparator:'.',decimalSeparator:','"
                                        />
                                    </td>
                                </tr>                                
                            </table>
                        </td>

                        <td width="50%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr>
                                    <td rowspan="8">&nbsp;</td>
                                    <td width="120"><b>Sub Total</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td width="170">
                                        <input type="text" id="txt_sub_total" name="txt_sub_total" class="easyui-numberbox" value="0" style="text-align:right;width:173px;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"   
                                        />
                                        
                                        <input type="hidden" id="txt_sub_total_hide" name="txt_sub_total_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>
                                        <span id="lbl_ppn10" style="font-weight:bold">PPn (10%)</span>
                                    </td>
                                    
                                    <td width="10"><b>:</b></td>

                                    <td>
                                        <input type="numberbox" name="txt_ppn10" id="txt_ppn10" class="easyui-numberbox" value="0" min="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"
                                        />
                                        
                                        <input type="hidden" id="txt_ppn10_hide" name="txt_ppn10_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>
                                        <span id="lbl_pph22" style="font-weight:bold">PPh22 (2,5%)</span>
                                    </td>

                                    <td><b>:</b></td>

                                    <td align="right">
                                        <input type="numberbox" name="txt_pph22" id="txt_pph22" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                        />
                                        
                                        <input type="hidden" id="txt_pph22_hide" name="txt_pph22_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 colspan="3"><hr/></td></tr>

                                <tr>
                                    <td><b>Total Return</b></td>
                                    <td><b>:</b></td>

                                    <td>
                                        <input type="numberbox" name="txt_total_return" id="txt_total_return" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"
                                        />
                                        
                                        <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>
                            </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_pret();" <?=($this->session->userdata('jobtitle_status') != 1 || substr($this->session->userdata('department'),-3) != '005' || $detail->TransStatus != 4 || (date('Y-m-d') < date('Y-m-d', strtotime($detail->PRetDate))))?'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 href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onClick="update_data();" <?=(!in_array($detail->TransStatus,array(0,4)))?'disabled':''?> <?php echo $cek_autority_save;?>>Save</a>
                    <!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" id="print_button" <?=(in_array($detail->TransStatus,array(3,9)))?'disabled':''?>>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->PRetNumber?>');" <?=(in_array($detail->TransStatus,array(1,2,3,6,4,5)))?'':'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\')'?>" <?=(in_array($detail->TransStatus,array(3,9)) )?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
    		</td>
            </tr>
        </table>
    </div>
</div>

<!----------------------------------------------------Batas Awal Dialog Asset------------------------------------------------------->
<div id="dialog_asset" class="easyui-dialog" style="width:850px;height:510px;background-color:#F8F8F8;padding:0px;" closed="true" data-options="modal:true, iconCls:'icon-edit'" buttons="#dialog-buttons">
    <div id="tab_purchase_req" class="easyui-tabs" style="width:835px;height:485px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
        <div title="Asset Item" style="padding:10px" >
        <input type="hidden" name="hdn_qty_return" id="hdn_qty_return" />
        <input type="hidden" name="hdn_asset_code" id="hdn_asset_code" />

        <div style="padding:5px;padding-bottom:5px;" data-options="region:'center',border:false">
            <table id="tt_choose_asset" class="easyui-edatagrid" rowNumbers="true" fitColumns="true" singleSelect="true" style="width:805px;height:375px;"
                url='<?Php echo base_url()?>list/purchases_return/ajax_for_choose_asset'                           
            >
                <thead>
                    <tr>
                        <th field='Status'       width="35"  data-options="halign:'center',align:'center'" editor="{type:'checkbox',options:{on:'Yes',off:'No'}}"></th>
                        <th field="AssetCode"    width="110" data-options="halign:'center',align:'center'">Asset Code</th>
                        <th field="ItemDesc"  width="200" data-options="halign:'center',align:'left'">Description</th>
                        <th field="ReceiptDate"  width="65"  data-options="halign:'center',align:'center'" formatter="formatDate">Receipt Date</th>
                        <th field="UsageDate"    width="65"  data-options="halign:'center',align:'center'" formatter="formatDate">Usage Date</th>
                        <th field="ItemAverage"  width="80"  data-options="halign:'center',align:'Right'"  editor="{options:{precision:2,decimalSeparator:',',groupSeparator:'.',disabled:false}}" formatter="formatRp">Average</th>
                    </tr>
                </thead>
            </table>
        </div>
        </div>
    </div>
</div>

<div id="dialog-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_asset();">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog_asset');">Cancel</a>
</div>
<!----------------------------------------------------Batas Akhir Dialog Asset----------------------------------------------------->
<?php $this->load->view('v_custom_pop_up');?>
<script>
	var array_qty  = [];
	var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
	
    $(document).ready(function(){
        vendor_currcode = '<?= $detail->CurrencyCode ?>';
        taxes_status    = '<?= $detail->PRetTaxesStatus ?>';
        intax_status    = '<?= $detail->PRetInTaxStatus ?>';
        ppn10_pcnt      = '<?= $detail->PRetPPn10Pcnt ?>';
        pph22_pcnt      = '<?= $detail->PRetPPh22Pcnt ?>';
        total_dp        = '<?= $detail->PRetTotalDP ?>';
		
		ppn10 				= '<?= $taxes_ppn10->TaxesRate ?>';
		ppn22 				= '<?= $taxes_pph22->TaxesRate ?>';

        ppn10_pcnt_span = ppn10_pcnt == 0 ? 0 : ppn10_pcnt;
        pph22_pcnt_span = pph22_pcnt == 0 ? 0 : pph22_pcnt;

        $('#hdn_currency_code').val(vendor_currcode);
        $('#txt_currency_rate').numberbox('setValue', <?= $detail->CurrencyRate ?>);
        $('#txt_fiscal_rate').numberbox('setValue', <?= $detail->FiscalRate ?>);
        $('#hdn_taxes_status').val(taxes_status);                
        $('#hdn_intax_status').val(intax_status);                
        
        $('#hdn_ppn10_pcnt').val(ppn10_pcnt);
        $('#hdn_pph22_pcnt').val(pph22_pcnt);
        $('#lbl_ppn10').text('PPn (' + ppn10_pcnt_span + '%)');
        $('#lbl_pph22').text('PPh22 (' + pph22_pcnt_span + '%)');

        if(taxes_status == 1){
            $('.disableme').css('display','');
            $('#chk_taxtable').prop('checked',true);

            if(intax_status == 1){
                $('.disableme1').css('display','');
                $('#chk_inclusive').prop('checked',true);
            }
            else{
                $('.disableme1').css('display','none');
                $('#chk_inclusive').prop('checked',false);
            }	
        }
        else{
            $('.disableme').css('display','None');                
            $('.disableme1').css('display','None');                
            $('#chk_taxtable').prop('checked',false);
            $('#chk_inclusive').prop('checked',false);
        }

        if(total_dp > 0){
            $('.disableme2').css('display','');                
            $('#chk_vendor_dp').prop('checked',true);
            $('#txt_total_dp').numberbox('setValue', total_dp);
        }
        else{
            $('.disableme2').css('display','None');                
            $('#chk_vendor_dp').prop('checked',false);
            $('#txt_total_dp').numberbox('setValue', 0);
        }

        if(vendor_currcode != 'IDR'){
            $('#row_currency_rate').show();
            $('#row_fiscal_rate').show();
        }
        else{
            $('#row_currency_rate').hide();
            $('#row_fiscal_rate').hide();
        }
        
        
        $('#txt_sub_total').numberbox('setValue', '<?= $detail->PRetSubTotal ?>');
		$('#txt_sub_total_hide').numberbox('setValue', '<?= $detail->PRetSubTotal ?>');
		
        $('#txt_ppn10').numberbox('setValue', '<?= $detail->PRetPPn10 ?>');
		$('#txt_ppn10_hide').numberbox('setValue', '<?= $detail->PRetPPn10 ?>');
        
		$('#txt_pph22').numberbox('setValue', '<?= $detail->PRetPPh22 ?>');
		$('#txt_pph22_hide').numberbox('setValue', '<?= $detail->PRetPPh22 ?>');
        
		$('#txt_total_return').numberbox('setValue', '<?= $detail->PRetTotalAmount ?>');
		$('#txt_total_return_hide').numberbox('setValue', '<?= $detail->PRetTotalAmount ?>');

		$('#tt_choose_asset').datagrid({
            onLoadSuccess:function(rowIndex){
                grid_asset      = $('#tt_choose_asset').datagrid('getRows');
                asset_array     = $('#hdn_asset_code').val();
                asset_code      = asset_array.split(',');

                for($ii=0; $ii<asset_code.length; $ii++){
                    $.each(grid_asset, function(index, value) {
                        if(asset_code[$ii] == value.AssetCode){
                            $('#tt_choose_asset').datagrid('updateRow',{
                                index   : index,
                                row     : {Status : 'Yes'}
                            });
                        }
                    });                    
                }
             }
        });        
        
        $('#dtg_item').edatagrid({
            onBeginEdit:function(rowIndex){
                editors = $('#dtg_item').datagrid('getEditors', rowIndex);

                invoice_qty_editor          = $(editors[0].target);
                item_qty_editor             = $(editors[1].target);
                item_price_editor           = $(editors[2].target);
				item_disc_editor            = $(editors[3].target);
                item_amount_editor          = $(editors[4].target);
                item_ppn10_editor           = $(editors[5].target);
                item_pph22_editor           = $(editors[6].target);
                item_total_amount_editor    = $(editors[7].target);
                item_pph22_status_editor    = $(editors[8].target);
                item_category_id_editor     = $(editors[9].target);
                item_code_editor            = $(editors[10].target);
                asset_status_editor         = $(editors[11].target);
                asset_code_editor           = $(editors[12].target);
				
				ItemPrice_Hide              = $(editors[13].target);
				itemstatus           		= $(editors[14].target);
				ri_number           		= $(editors[16].target);
				
				/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
				save_button_begendedit(SavePrivillage);
				/*=================================end============================================================*/
					
                //$(item_qty_editor).prop('readonly', true);
                //$(asset_code_editor).prop('readonly', true);
                
                $(item_ppn10_editor).numberbox('setValue', $(item_ppn10_editor).numberbox('getValue') == 0 ? 0 : $(item_ppn10_editor).numberbox('getValue'));
                $(item_pph22_editor).numberbox('setValue', $(item_pph22_editor).numberbox('getValue') == 0 ? 0 : $(item_pph22_editor).numberbox('getValue'));
                $(item_amount_editor).numberbox('setValue', $(item_amount_editor).numberbox('getValue') == 0 ? 0 : $(item_amount_editor).numberbox('getValue'));
                $(item_total_amount_editor).numberbox('setValue', $(item_total_amount_editor).numberbox('getValue') == 0 ? 0 : $(item_total_amount_editor).numberbox('getValue'));

                item_category_id = $(item_category_id_editor).numberbox('getValue');

                if($(itemstatus).val() == 1){
					$(asset_code_editor).prop('readonly', false);
				}
				else{
					$(asset_code_editor).prop('readonly', true);
				}
				
				//$(asset_code_editor).val('');		
				/*$(paid_editor).click(function(){
                    if($(this).is(':checked')){
                        if(item_category_id > 0){
                            $(item_qty_editor).prop('readonly', false);
                            $(unpaid_editor).val(0);
                        }
                        else{
                            $.messager.alert('Warning', 'Item yang dapat diplih adalah hanya Inventories','warning');
                            $(paid_editor).prop('checked', false);    
                        }
                    }
                    else{
                        $(item_qty_editor).prop('readonly', true);
                        $(item_qty_editor).numberbox('setValue', 0);
                        $(asset_code_editor).val('');
                        $(unpaid_editor).val(1);
                    }                        
                });*/
                
                $(item_qty_editor).numberbox({
                    onChange:function(){
                        item_qty        = parseFloat(item_qty_editor.numberbox('getValue'));
                        invoice_qty     = parseFloat(invoice_qty_editor.numberbox('getValue'));
                        item_price      = parseFloat(ItemPrice_Hide.numberbox('getValue'));
                        pph22_status    = parseInt($(item_pph22_status_editor).numberbox('getValue'));
						item_disc      = parseFloat(item_disc_editor.numberbox('getValue'));
                            
                        //if($(paid_editor).is(':checked')){ 
						if(item_qty > 0){                        
                            if(item_qty > invoice_qty) {
                                $.messager.alert('Warning','Qty tidak boleh lebih besar dari (' + invoice_qty + ')','warning',function(){
                                    item_qty_editor.numberbox('setValue', 0);
                                });						
                            }
                            else{
                                calculate_amount(rowIndex, item_qty, item_price, pph22_status, item_disc);
                            }
                        }
                        else{
                            $(asset_code_editor).val('');                            
                            calculate_amount(rowIndex, 0, 0, pph22_status, 0);
                        }                        
                    }
                });
                
                $(asset_code_editor).click(function(){
                    //if($(paid_editor).is(':checked')){
                        item_qty    = parseFloat(item_qty_editor.numberbox('getValue'));
                        item_code   = $(item_code_editor).val();
                        item_asset  = $(itemstatus).val();
                        asset_code  = $(asset_code_editor).val();
						ri_number  	= $(ri_number).val();

                        if(item_qty > 0){
                            if(item_asset == 1){                            
                                $('#tt_choose_asset').datagrid('load',{
                                    ItemCode : item_code,
									RINumber : ri_number
                                });

                                $('#hdn_qty_return').val(item_qty);
                                $('#hdn_asset_code').val(asset_code);

                                modal_open('Inventory Assets','dialog_asset');
                            }
                        }
                        else{
                            $.messager.alert('Warning','Qty Return tidak boleh lebih kecil atau sama dengan Nol (0);', 'warning');
                        }
                   // }                   
                });
            },
			onEndEdit: function(){
				/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
				save_button_endedit(SavePrivillage);
				/*=================================end============================================================*/
            }
        });

        $("#fm_purchase_return").click(function() {
            $('#dtg_item').edatagrid('saveRow');
		});
        datagrid_item_type("dtg_item");//untuk warna grid
    });	

    function choose_asset(){
        $('#tt_choose_asset').edatagrid('saveRow');
        $('#dtg_item').edatagrid('saveRow');
        
        var selectedrow     = $('#dtg_item').datagrid('getSelected');
        var row_index       = $('#dtg_item').datagrid('getRowIndex', selectedrow);
        var item_asset      = $('#tt_choose_asset').datagrid('getRows');
        
        var asset_code      = new Array();
        var asset_select    = 0;
        var return_qty      = $('#hdn_qty_return').val();
        
        $.each(item_asset, function(index, value) {
            if(value.Status == 'Yes'){
                asset_code.push(value.AssetCode);
                asset_select++;
            }
        });

        if(asset_select <= 0){
            $.messager.alert('Warning', 'Tidak ada data Asset Code yang dipilih','warning');
        }
        else if(asset_select != return_qty){
            $.messager.alert('Warning','Jumlah Qty Asset Code (' + asset_select + '), harus sama dengan jumlah Qty Return (' + return_qty + ')','warning');
        }
        else{
            asset_code = asset_code.join();

            $('#dtg_item').datagrid('updateRow',{
                index   : row_index,
                row     : {ItemAssetCode : asset_code}                  
            });

            modal_close('dialog_asset');
        }
    }
    
	function hideppn(){
		
		if($('#chk_taxtable').is(':checked')){
				$('.disableme').css('display','');	
				$('#hdn_taxes_status').val(1);
				$('#lbl_ppn10').text('PPn (' + ppn10 + '%)');
		}
		else{
				$('.disableme').css('display','none');
				$("#chk_inclusive").prop("checked",false);
				$('#hdn_taxes_status').val(0);
				$('#lbl_ppn10').text('PPn (' + 0 + '%)');
		}
		
		calculate_item_tax();
    }
	
	function calculate_item_tax(){
		
    	$('#dtg_item').edatagrid('saveRow');
        var item = $('#dtg_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.ItemDisc;
			item_qty  	= value.Item_Qty;
			
            ppn10_val       = parseFloat(ppn10_pcnt);
        	pph22_val       = parseFloat(pph22_pcnt);
			
			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(9));
						$('#hdn_intax_status').val(1);
					}
					else{
						total_price = parseFloat(item_price - (item_price * item_disc) / 100);
						$('#hdn_intax_status').val(0);
					}
				}
				else{
					total_price = parseFloat(item_price - (item_price * item_disc) / 100);
					$('#hdn_intax_status').val(0);
				}
				
				item_amount     = parseFloat(item_qty * total_price);  
				
				item_ppn10      = $('#chk_taxtable').is(':checked') ? parseFloat(item_amount * (ppn10_val / 100)) : 0;                                    
        		item_pph22      = value.Item_TaxPPh22 != 0 ? parseFloat(item_amount * (pph22_val / 100)) : 0;
        		item_total      = item_amount + item_ppn10 + item_pph22;
				
				$('#dtg_item').datagrid('updateRow',{
					index:index,
					row:{
						 Item_Amount        : item_amount,
						 Item_TaxPPn10      : item_ppn10,
						 Item_TaxPPh22      : item_pph22,
						 Item_TotalAmount   : (item_total).toFixed(9)}
				});
			}
		});
		calculate_total();
	}
	
    function calculate_amount(rowIndex, item_qty, item_price, pph22_status, item_disc){
        ppn10_val       = parseFloat($('#hdn_ppn10_pcnt').val());
        pph22_val       = parseFloat($('#hdn_pph22_pcnt').val());
        
		if($('#chk_taxtable').is(':checked')){
			if($('#chk_inclusive').is(':checked')){
				total_price 	= parseFloat((100 / (100 + ppn10_val) * item_price).toFixed(9));
			}
			else{
				total_price = parseFloat(item_price - (item_price * item_disc) / 100);
			}
		}
		else{
			total_price = parseFloat(item_price - (item_price * item_disc) / 100);
		}
		
        item_amount     = parseFloat(item_qty * total_price);
		                                
        item_ppn10      = $('#chk_taxtable').is(':checked') ? parseFloat(item_amount * (ppn10_val / 100)) : 0;                                    
        item_pph22      = pph22_status == 1 ? parseFloat(item_amount * (pph22_val / 100)) : 0;
        item_total      = item_amount + item_ppn10 + item_pph22;
		
		$('#dtg_item').edatagrid('saveRow');
        $('#dtg_item').edatagrid('updateRow',{
            index:rowIndex,
            row:{
                 Item_Amount        : item_amount,
                 Item_TaxPPn10      : item_ppn10,
                 Item_TaxPPh22      : item_pph22,
                 Item_TotalAmount   : (item_total).toFixed(9)}
        });
		
		/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
		$('.save-button').linkbutton('enable');
		/*=================================end============================================================*/
        calculate_total();
    }
    
    function calculate_total(){
        $('#dtg_item').edatagrid('saveRow');
        var item        = $('#dtg_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) ? 0 : value.Item_Amount;
            item_ppn10    = isNaN(value.Item_TaxPPn10) ? 0 : value.Item_TaxPPn10;
            item_pph22    = isNaN(value.Item_TaxPPh22) ? 0 : value.Item_TaxPPh22;

            sub_total       += parseFloat(item_amount);
            sub_ppn10       += parseFloat(item_ppn10);
            sub_pph22       += parseFloat(item_pph22);
        });
        
        $('#txt_sub_total').numberbox('setValue', sub_total);
		$('#txt_sub_total_hide').numberbox('setValue', sub_total);
		
        $('#txt_ppn10').numberbox('setValue', sub_ppn10);
		$('#txt_ppn10_hide').numberbox('setValue', sub_ppn10);
		
        $('#txt_pph22').numberbox('setValue', sub_pph22);
		$('#txt_pph22_hide').numberbox('setValue', sub_pph22);

        total = sub_total + sub_ppn10 + sub_pph22;
        $('#txt_total_return').numberbox('setValue', total);  
		$('#txt_total_return_hide').numberbox('setValue', total);        
    }
	
	function approval_pret() {
		var url_check           = '<?= base_url();?>custom/custom/checking_approval';
		var no_transaksi    	= $('#txt_pret_no').val();
		modal_open('Progress Bar','dlg_loading');
		
		$.post(url_check, {no_transaksi:no_transaksi}, function(result){
			if (result.status === false){
				approval();
			} 
			else{
				$.messager.alert('Unseccessfull',result.message,'error',function(){
					location.reload();
				});
			}
		},'json');
	}
	
    function approval(){
	var url         = base_url + 'list/purchases_return/approval';

        item            = $('#dtg_item').datagrid('getRows');
		Detail          = JSON.stringify(item);
        
        PRetNumber      	= $('#txt_pret_no').val();
        PInvNumber      	= $('#txt_pinv_no').val();
        VendorCode      	= $('#cbg_vendor').combogrid('getValue');
		CurrencyRate 		= $('#txt_currency_rate').numberbox('getValue');
		CurrencyCode      	= $('#hdn_currency_code').val();
		FiscalRate      	= $('#txt_fiscal_rate').numberbox('getValue');
		Ppn10 				= $('#txt_ppn10').numberbox('getValue');
		Pph22				= $('#txt_pph22').numberbox('getValue');
		
		
        TotalReturn     	= parseFloat($('#txt_total_return_hide').numberbox('getValue'));
		
		SubTotal     		= parseFloat($('#txt_sub_total_hide').numberbox('getValue'));
		
        TotalReturn_real     	= parseFloat($('#txt_total_return').numberbox('getValue'));
		
		SubTotal_real     		= parseFloat($('#txt_sub_total').numberbox('getValue'));

	$.post(url, {TotalReturn_real:TotalReturn_real,SubTotal_real:SubTotal_real, Ppn10:Ppn10, Pph22:Pph22, SubTotal:SubTotal, VendorCode:VendorCode, PRetNumber:PRetNumber, PInvNumber:PInvNumber, TotalReturn:TotalReturn, Detail:Detail, CurrencyRate:CurrencyRate, CurrencyCode:CurrencyCode, FiscalRate:FiscalRate}, function(result){
            if (result.status == true){
                $.messager.alert('Success',result.message,'info',function(){
                    location.reload();						                    
                });		
				modal_close('dlg_loading'); 				
            } 
            else {
                $.messager.alert('Error',result.message,'error',function(){
                    location.reload();						                    
                });				
            }
	},'json');
    }
    
    function update_data() {
       	var url             = '<?= base_url();?>custom/custom/checking_update';
		var no_transaksi    = $('#txt_pret_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');?>';
		
	    $('#dtg_item').edatagrid('saveRow');
        
        var item        = $('#dtg_item').datagrid('getRows');
        var detail      = JSON.stringify(item);        

        item_result     = true;
        qty_result      = true;
        item_count      = 0;
        return_qty      = 0;
        return_asset    = 0;

        $.each(item, function(index, value){
            return_qty      = value.Item_Qty;
                asset_string    = value.ItemAssetCode;
                qty_result      = return_qty == 0 ? false : qty_result == false ? false : true;
                
                if(value.ItemAssetStatus == 1){
                    asset_code      = asset_string.split(',');
                    return_asset    = asset_string == '' ? 0 : asset_code.length;
                    if(return_qty != return_asset){item_result = false;}
                }
                
                item_count++;
        });

        if(item_count > 0){
            if(qty_result == false){
                $.messager.alert('Warning', 'Jumlah Qty Return harus lebih besar dari Nol (0)', 'warning');
            }
            else if(item_result == false){
                $.messager.alert('Warning', 'Jumlah Qty Return tidak sama dengan jumlah Asset Code yang dipilih', 'warning');
            }            
            else{
                $("#detail").val(detail);
				edit_transaction_check('<?=$menu_link?>','#fm_purchase_return', no_transaksi, url, trans_status,created_by, login_as, job_title);
            }
        }
        else{
            $.messager.alert('Warning', 'Tidak ada item yang dipilih untuk disimpan', 'warning');
        }
    }
	
	function app_reverse(){
		var no_transaksi    = $('#txt_pret_no').val();
	
		checking_reverse(no_transaksi,function(check){
			
			if(check.status == true){
				var i       = $('#dtg_item').datagrid('getRows');
				var detail  = JSON.stringify(i);
		
				$("#detail").val(detail);
				reverse_data_by_detail('<?php echo $menu_link?>','#fm_purchase_return');
			}else{
			   $.messager.alert('Unseccessfull',check.message,'error',function(){
					location.reload();
				});
			}
		});
	}
	
	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_pret_no').val(), 'Purchase Returns', url, created_by, login_as, job_title);
	}
	
	function remove_row(){
		var item = $('#dtg_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     = $('#dtg_item').datagrid('getSelected');
			var row_index       = $('#dtg_item').datagrid('getRowIndex', selectedrow);
	
			$.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.ItemCode + '"',  
				function(r){
					if (r){
						array_qty.push(selectedrow.PRetDetailID);
						
						$("#detail_id").val(JSON.stringify(array_qty));
					
						$('#dtg_item').datagrid('deleteRow', row_index);
						calculate_total();
						
						/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
						save_button_endedit(SavePrivillage);
						/*=================================end============================================================*/
						
						/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
						$('.app-button').linkbutton('disable');
						/*=================================end============================================================*/
					}
				}
			);        
						
		}            
	}
</script>