<!---- 
Author 	: Herpan / 12-08-2014	
Revisi 	: Ferry / 12-01-2014
-->

	<?php
			//---------Untuk privellege jika dia ada tombol save----------
				if($group_user->SavePrivillage == 1){
					$cek_autority_save  = "";
				}
				else{
					$cek_autority_save 	= "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">
                        <a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="parent.tab_add('New Purchase Order', '<?=$menu_link?>', 'icon-add','add');">New</a>
                        <a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload();">Refresh</a>
                    </td>

                    <td align="right">
                        <span class="form-title"><?=$menu_label?></span>
                    </td>
                </tr>
            </table>		     	
        </div>			
    </div>
    <!-- End of top view -->
        
    <!-- center view -->
    <div id="form-body" data-options="region:'center',border:false">
        <div id="form-wrapper" class="easyui-panel" fit="true" style="padding:5px;">
            <form id="fm_purchase_order" name="fm_purchase_order" method="post">
                <input type="hidden" name="detail" id="detail"/>
                <input type="hidden" name="hdn_currency_code" id="hdn_currency_code"/>
                <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_pph23_pcnt" id="hdn_pph23_pcnt"/>
                
                <!-- Form Header -->
                <table width="100%" height="140" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="57%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr height="20">
                                    <td width="168"><b>Vendor Name</b></td>
                                    <td width="14"><b>:</b></td>
                                    <td colspan="5">
                                        <select name="cbg_vendor" class="combo-grid" id="cbg_vendor" style="width:175px;height:20px" required 
                                            data-options="
                                                panelWidth: 445,
                                                idField: 'VendorCode',
                                                textField: 'VendorName',
                                                url: '<?php echo base_url(); ?>custom/get_data/vendor',
                                                method: 'post',
                                                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'" onClick="select_pr();" >Select PR</a>
                                        <input type="checkbox" name="chk_taxtable" id="chk_taxtable" onClick="hideppn();" value="1">Taxable								  

                                        <span class="disableme" style="display:none;">
                                            <input type="checkbox" name="chk_inclusive" id="chk_inclusive" onClick="calculate_item_intax();" value="1">Inclusive Tax
                                        </span>
                                    </td>
                                </tr>
                                
                                <tr id="row_currency_rate" >
                                    <td><b>Rate</b></td>
                                    <td><b>:</b></td>
                                    
                                    <td colspan="5">
                                        <input type="text" class="easyui-numberbox currency" name="txt_currency_rate" id="txt_currency_rate" style="width:70px;text-align:right;" value="" readonly
                                            data-options=" min:1, precision:2, decimalSeparator:',', groupSeparator:'.'"/>
                                        <span id="currency" style="font-weight:bold"></span>
                                    </td>
                                </tr>
                                
                                <tr height="20">
                                    <td><b>Address</b></td>
                                    <td width="14"><b>:</b></td>
                                    <td width="80">&nbsp;</td>
                                    <td width="168"><b>Shipping Address</b></td>
                                    <td width="14"><b>:</b></td>
                                    <td width="81">&nbsp;</td>
                                    <td width="184" rowspan="2">&nbsp;</td>
                                </tr>
                                
                                <tr height="20">
                                    <td colspan="3">
                                        <textarea name="txa_address" cols="30" rows="4" id="txa_address" style="resize:none;" readonly></textarea>
                                    </td>
                                    <td colspan="3">
                                        <textarea name="txa_ship_to" cols="30" rows="4" id="txa_ship_to" class="easyui-validatebox" style="resize:none;" data-options="required:true"><?php echo $branch->BranchAddress; ?></textarea>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        
                        <td width="43%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
                                <tr height="20">
                                    <td rowspan="7" valign="top"><input type="checkbox" id="chk_vendorneeds" name="chk_vendorneeds" value='1' onClick="hidedp();"/> Vendor needs DP</td>
                                    <!-- <td width="190" style="background:#333399;text-align:center;color:#FFF;">PR. No.</td> -->
                                    <td></td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">PO. Date</td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">Terms</td>
                                </tr>
                                
                                <tr height="20">
                                    <td><input type="hidden" name="txt_preq_no" id="txt_preq_no" style="width:190px;height:18px;text-align:center" class="easyui-validatebox textbox" required readonly /></td>
                                    <td><input name="txt_pord_date" id="txt_pord_date" type="text" class="easyui-datebox validBackward" style="width:122px;height:20px" value='<?=$po_date?>' required editable="false" /></td>

                                    <td>
                                        <select class="combo-grid" required="required"
                                            name="cbo_terms" id="cbo_terms" 
                                            style="width:122px;height:20px;" 
                                            data-options="
                                                panelWidth: 250,
                                                idField: 'TermspaymentID',
                                                textField: 'TermDesc',
                                                url:'<?=base_url()?>custom/get_data/termspayment',                                        
                                                method: 'get',
                                                columns: [[
                                                    {field:'TermspaymentID',title:'Terms payment ID',width:90,halign:'center'},
                                                    {field:'TermDesc',title:'Term Desc',width:90,halign:'center'}
                                                ]],
                                                fitColumns: true
                                            ">
                                        </select>
                                    </td>
                                </tr>
                        
                                <tr height="20">
                                    <!-- <td style="background:#333399;text-align:center;color:#FFF;">PR. Date</td> -->
                                    <td></td>
                                    <td style="background:#333399;text-align:center;color:#FFF;">Expected Date</td>
                                    <td style="background:#333399;text-align:center;color:#FFF;">FOB</td>
                                </tr>

                                <tr height="20">
                                    <td><input name="txt_preq_date" id="txt_preq_date" type="hidden" class="easyui-validatebox textbox" style="width:190px;height:18px;text-align:center" required readonly /></td>
                                    <td><input name="txt_expected_date" id="txt_expected_date" type="text" class="easyui-datebox validBackward" value="today" style="width:122px;height:20px" editable="false" /></td>

                                    <td>
                                    	<select class="combo-grid" required="required" readonly
                                            name="cbo_fob" id="cbo_fob" 
                                            style="width:122px;height:20px;" 
                                            data-options="
                                                value:'1',
                                                panelWidth: 250,
                                                idField: 'FobID',
                                                textField: 'FobName',
                                                url:'<?=base_url()?>custom/get_data/fob',                                     
                                                method: 'get',
                                                columns: [[
                                                    {field:'FobID',title:'FOB ID',width:90,halign:'center'},
                                                    {field:'FobName',title:'FOB Name',width:90,halign:'center'}
                                                ]],
                                                fitColumns: true
                                            ">
                                        </select>
                                    </td>
                                </tr>
                        
                                <tr height="20">
                                    <td>&nbsp;</td>
                                    <td ></td>
                                    <td style="background:#333399;text-align:center;color:#FFF;">Ship Via</td>
                                </tr>

                                <tr height="20">
                                    <td>&nbsp;</td>
                                    <td></td>
                                    
                                    <td>
                                    	<select class="combo-grid" required="required"
                                            name="cbo_ship_via" id="cbo_ship_via" readonly
                                            style="width:122px;height:20px;" 
                                            data-options="
                                                value:'1',
                                                panelWidth: 250,
                                                idField: 'ShipmentID',
                                                textField: 'ShipmentName',
                                                url:'<?=base_url()?>custom/get_data/shipment',                                     
                                                method: 'get',
                                                columns: [[
                                                    {field:'ShipmentID',title:'Shipment ID',width:90,halign:'center'},
                                                    {field:'ShipmentName',title:'Shipment Name',width:90,halign:'center'}
                                                ]],
                                                fitColumns: true
                                            ">
                                        </select>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
                <!-- End of form header -->
                
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div title="Item">
                        <table toolbar="#tb_dtg_item" id="dtg_item" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" style="height:250px;" 
                            url="<?php echo base_url().$menu_link."/ajax_item"; ?>"
                        >                        
                            <thead>
                                <tr>
                                    <th field="PReqNumber"      width="40"  data-options="align:'left',halign:'center'" editor="{type:'text'}">Purchase Req. No.</th>
                                    <th field="PReqDate"       	width="70"  data-options="align:'left',halign:'center'" hidden>Purchase Req. Date.</th>
                                    <th field="PReqDesc"       	width="70"  data-options="align:'left',halign:'center'" hidden>Purchase Req. Desc.</th>
                                    
                                    <th field="ItemCode"         width="50"  data-options="align:'left',halign:'center'" editor="{type:'text'}">Item</th>
                                    <th field="ItemCodeVendor"   width="30"  data-options="align:'center',halign:'center'" editor="{type:'text',options:{required:true}}" ><?php echo label_grid('no_seri');?></th>
                                    <th field="ItemDesc"         width="150" data-options="align:'left',halign:'center'">Description</th>
                                    <th field="ItemQty"          width="30"  data-options="align:'center',halign:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true},min:0.01}" formatter="formatRp">Qty</th>
                                    <th field="ItemUnit"         width="30"  data-options="align:'center',halign:'center'" >Unit</th>
                                    <th field="ItemPrice"        width="40"  data-options="align:'right',halign:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Unit Price</th>
                                    <th field="ItemDisc"         width="40"  data-options="align:'right',halign:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp">Discount %</th>
                                    <th field="ItemAmount"       width="40"  data-options="align:'right',halign:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Amount</th>
                                    
                                    <th field="ItemMax"          width="20"  data-options="align:'center',halign:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp" hidden>Item Max</th>
                                    
                                    <th field="Item_PPn10"       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>Item PPn 10</th>
                                    <th field="Item_PPh22"       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>Item PPh 22</th>
                                    <th field="Item_PPh23"       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>Item PPh 23</th>
                                    
                                    <th field="ItemTotalAmount"  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>Item Total Amount</th>
                                    
                                    <th field="ItemType"         width="50"  data-options="align:'center',halign:'center'" editor="{type:'numberbox',options:{required:true,min:0,disabled:true}}" hidden>Item Type</th>
                                    <th field="ItemPPh22Status"  width="50"  data-options="align:'right',halign:'center'"  editor="{type:'numberbox',options:{required:true,min:0,disabled:true}}" hidden>Item PPh22 Status</th>
                                    <th field="ItemPPh23Status"  width="70"  data-options="align:'left',halign:'center'"   editor="{type:'numberbox',options:{required:true,min:0,disabled:true}}" hidden>Item PPh23 Status</th>
                                    <th field="ItemAdvNetDueIn"  width="70"  data-options="align:'left',halign:'center'"   hidden>Adv NetDue In</th>
                                    <th field="PReqDetailID"     width="70"  data-options="align:'left',halign:'center'"   hidden>PReq ID</th>
                                    <th field="ItemCategoryID"   width="70"  data-options="align:'left',halign:'center'"   hidden>Item Category ID</th>
                                    <th field="IntaxStatus"      width="50"  data-options="align:'right',halign:'center'"  hidden>Intax Status</th>
                                    <th field="ItemPriceNTax"    width="50"  data-options="align:'right',halign:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',disabled:true}}" formatter="formatRp" hidden>Item Price NTax</th>
                                    <th field="ItemCategoryCode" width="50"  data-options="align:'left',halign:'center'"   hidden>Item Category Code</th>
                                    <th field="ItemStatus"       width="50"  data-options="align:'center',halign:'center'" hidden>Item Status</th>
                                    
                                     <!--
                                        Amount Disc hide loss tidak ada koma
                                        Amount hide loss tidak ada koma
                                    -->
                                	<th width="30"  halign='center'	field="AmountDisc"  		editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}" hidden>Amount Disc</th>
                                    
                                    <th width="30"  halign='center'	field="ItemAmount_Hide"  	editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}" hidden>Amount Hide</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>
                <!-- 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 name="txa_description" id="txa_description" rows="4" style="width:335px;resize:none;"></textarea>
                                    </td>
                                </tr>
                                
                                <tr>
                                    <td><span class="dp" style="display:none" ><b>Downpayment</b></span></td>
                                    <td><span class="dp" style="display:none" ><b>:</b></span></td>

                                    <td>
                                        <span class="dp" style="display:none" >
                                            <input type="numberbox" min="0" name="txt_downpayment" id="txt_downpayment" class="easyui-numberbox" value="0" style="width:171px;text-align:right;" 
                                                data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        
                        <td width="50%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1">
                                <tr>
                                    <td rowspan="7">&nbsp;</td>
                                    <td width="120"><b>Sub Total</b></td>
                                    <td width="10"><b>:</b></td>
                                    
                                    <td width="171">
                                        <input type="text" id="txt_sub_total" name="txt_sub_total" class="easyui-numberbox" value="0" style="text-align:right;" 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><b>Discount</b></td>
                                    <td><b>:</b></td>
                                
                                    <td>
                                        <input type="text" min="0" name="txt_discount" id="txt_discount" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                        
                                         <input type="hidden" id="txt_discount_hide" name="txt_discount_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"></span>
                                    </td>

                                    <td><b>:</b></td>
                                
                                    <td>
                                        <input type="text" name="txt_ppn10" id="txt_ppn10" class="easyui-numberbox" value="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"></span>
                                    </td>

                                    <td><b>:</b></td>
                                
                                    <td>
                                        <input type="text" 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>
                                        <span id="lbl_pph23" style="font-weight:bold">PPh23 (2%)</span>
                                    </td>
                                    
                                    <td><b>:</b></td>

                                    <td>
                                        <input type="text" id="txt_pph23" name="txt_pph23" class="easyui-numberbox" value="0" style="text-align:right;" readonly
                                            data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                        <input type="hidden" id="txt_pph23_hide" name="txt_pph23_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><b>Est. Freight</b></td>
                                    <td><b>:</b></td>

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

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

                                    <td>
                                        <input type="text" name="txt_total_purchase" id="txt_total_purchase" class="easyui-numberbox" value="0" style="text-align:right;" readonly 
                                            data-options="precision:2,decimalSeparator:',',groupSeparator:'.'"/>
                                        <input type="hidden" id="txt_total_purchase_hide" name="txt_total_purchase_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" onclick="" plain="true">Help</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="insert_data();" <?php echo $cek_autority_save;?>>Save</a> 								
                    
                    <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="parent.tab_close('tt');">Close</a>				
                </td>
            </tr>
        </table>
    </div>
</div>

<div id="dialog-pr" class="easyui-dialog" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-buttons" style="width:860px;height:532px;top:27px;background-color:#F8F8F8;padding:5px;"> 
        <div id="tab_purchase_req" class="easyui-tabs" style="width:835px;height:485px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
            <div title="Item / Expense / Services" style="padding:10px" >
            
             <table id="tt_choose_pr" class="easyui-datagrid" 
                url="<?php echo base_url() ?>list/purchases_order/ajax_preg_item"     
                remoteSort="false"
                pageSize="150"
                fitColumns="true" 
                rowNumbers="true"
                style="width:812px;height:400px" 
                data-options = "border:true,view:scrollview,autoRowheight:false"
            >                      
                <thead>
                    <tr>
                        <th field="ck" checkbox="true"></th>
                        <th field="PReqNumber" width="170" halign='center' align='center' sortable="true">PR. No.</th>
                        <th field="PReqDate" width="90" halign='center' align='center' sortable="true" formatter="formatDate">PR. Date</th>
                        <th field="PReqDesc" width="465" halign="center" align="left">Description</th>
                    </tr>
                </thead>
            </table>
            <!-- Dialog Button for Dialog Item-->
            <div style="border:none; margin-top:10px; float:right;">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_pr(false);">&nbsp; OK &nbsp; &nbsp;</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-pr');">Cancel</a>
            </div>
            <!-- End of Dialog Button for Dialog Item-->
            </div>
            
            <div title="Adv. Payment" style="padding:10px">
            
            <table id="tt_choose_advance" class="easyui-datagrid" 
                url="<?php echo base_url() ?>list/purchases_order/ajax_preg_adv"   
                remoteSort="false"
                pageSize="150"
                fitColumns="true" 
                rowNumbers="true"
                style="width:812px;height:400px" 
                data-options = "border:true,view:scrollview,autoRowheight:false"
            >                   
                <thead>
                    <tr>
                        <th field="ck" checkbox="true"></th>
                        <th field="PReqNumber" width="170" halign='center' align='center' sortable="true">PR. No.</th>
                        <th field="PReqDate" width="90" halign='center' align='center' sortable="true" formatter="formatDate">PR. Date</th>
                        <th field="PReqDesc" width="465" halign="center" align="left">Description</th>
                    </tr>
                </thead>
            </table>
             <!-- Dialog Button for Dialog servis-->
            <div style="border:none; margin-top:10px; float:right;">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_adv();">&nbsp; OK &nbsp; &nbsp;</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-pr');">Cancel</a>
            </div>
            <!-- End of Dialog Button for Dialog Item-->
            </div>
         </div>
</div>

<?php $this->load->view('v_custom_pop_up');?>
<script type="text/javascript">

    var dbl_ppn10 		= '<?= $taxes_ppn10->TaxesRate ?>';
    var dbl_pph22 		= '<?= $taxes_pph22->TaxesRate ?>';
    var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
	
    $('#hdn_currency_code').val('IDR');
    $('#hdn_ppn10_pcnt').val(dbl_ppn10);
    $('#hdn_pph22_pcnt').val(dbl_pph22);
    $('#hdn_pph23_pcnt').val(2);

    function select_pr(){
        var $vendor_code = $('#cbg_vendor').combogrid('getValue');

        if($vendor_code == '') {
            $.messager.alert('Warning', 'Silahkan pilih Vendor Name terlebih dahulu...!!', 'error');                
        }
        else{
            modal_open('Purchase Requisition', 'dialog-pr');        
        }    
    }

    function choose_pr(val){
        var pr          = $('#tt_choose_pr').datagrid('getChecked');
        var pr_no       = new Array();
        var pr_date 	= new Array();			
		var pr_desc 	= new Array();			

        $.each(pr, function(index, value) {
            item_type = value.ItemType;
            
            if(value.PReqNumber != undefined){
                pr_no.push(value.PReqNumber);
                pr_date.push(value.PReqDate);	
				pr_desc.push(value.PReqDesc);					
            }
        });

        $('#dtg_item').datagrid('load',{
            pr_no: pr_no
        });

        if($('input[name="rdo_PRToggle"]:checked').val() == 2){
            $('#txt_freight').attr('readonly',true);
        }
        else{
            $('#txt_freight').attr('readonly',false);            
        }

        $('#txt_preq_no').val(pr_no.array_unique());
        $('#txt_preq_date').val(pr_date.array_unique());
		$('#txa_description').val(pr_desc.array_unique());
		 
        $("#chk_inclusive").prop("checked",false);

        $('#txt_sub_total').numberbox('setValue', 0);
        $('#txt_discount').numberbox('setValue', 0);
        $('#txt_ppn10').numberbox('setValue', 0);
        $('#txt_pph22').numberbox('setValue', 0);
        $('#txt_pph23').numberbox('setValue', 0);
        $('#txt_freight').numberbox('setValue', 0);
        $('#txt_total_purchase').numberbox('setValue', 0);

        modal_close('dialog-pr');
    }
	
    
	function choose_adv(){
        var pr          = $('#tt_choose_advance').datagrid('getChecked');
        var pr_no       = new Array();
        var pr_date 	= new Array();
		var pr_desc 	= new Array();						

        $.each(pr, function(index, value) {
            item_type = value.ItemType;
            
            if(value.PReqNumber != undefined){
                pr_no.push(value.PReqNumber);
                pr_date.push(value.PReqDate);
				pr_desc.push(value.PReqDesc);					
            }
        });

        $('#dtg_item').datagrid('load',{
            pr_no: pr_no
        });

        if($('input[name="rdo_PRToggle"]:checked').val() == 2){
            $('#txt_freight').attr('readonly',true);
        }
        else{
            $('#txt_freight').attr('readonly',false);            
        }

        $('#txt_preq_no').val(pr_no.array_unique());
        $('#txt_preq_date').val(pr_date.array_unique());
		$('#txa_description').val(pr_desc.array_unique());
		
        $("#chk_inclusive").prop("checked",false);

        $('#txt_sub_total').numberbox('setValue', 0);
        $('#txt_discount').numberbox('setValue', 0);
        $('#txt_ppn10').numberbox('setValue', 0);
        $('#txt_pph22').numberbox('setValue', 0);
        $('#txt_pph23').numberbox('setValue', 0);
        $('#txt_freight').numberbox('setValue', 0);
        $('#txt_total_purchase').numberbox('setValue', 0);

        modal_close('dialog-pr');
    }

    /*==================== Daswan =========================*/
    var PReqNumber  = '<?=$PReqNumber;?>';
    var VendorCode  = '<?=$VendorCode;?>';
    var load        = 0;
    if(PReqNumber !=''){
        PReqNumber      = PReqNumber.replace(/\__/g,"/");
        PReqNumber      = PReqNumber.replace(/\_/g,"-");
        VendorCode      = VendorCode.replace(/\__/g,"/");
        VendorCode      = VendorCode.replace(/\_/g,"-");
    }
    /*=================== end Daswan =========================*/

    $(document).ready(function(){
        $('#tt_choose_pr').datagrid('load',{
            PReqType: 'item/expense'
        });
        
        $('#lbl_ppn10').text('PPn (' + dbl_ppn10 + '%)');
        $('#lbl_pph22').text('PPh22 (' + dbl_pph22 + '%)');

        $('#cbg_vendor').combogrid({
            onSelect:function(rowIndex, rowData){
				/*===================Cek vendor status badan or perseorangan===================================*/
                vendor_status       = rowData.VendorStatus;
                vendor_taxnumber    = rowData.VendorTaxNumber;
                vendor_currcode     = rowData.CurrencyCode;
				/*===============================End===========================================================*/
				
				$('#dtg_item').datagrid('load',{
                    ItemQty: ''
                });
				
                $('#hdn_currency_code').val(vendor_currcode);
                $('#txt_currency_rate').numberbox('setValue', rowData.ExchangeRate);
                $('#currency').text(vendor_currcode + ' / IDR');
                
                $('#txa_address').val(rowData.VendorAddress);                 
                $('#cbo_terms').combogrid('setValue', rowData.TermsPaymentID);
                
                if(rowData.TaxIncludedStatus == 1){
                    $('#chk_taxtable').prop('checked',true);
                }
                else{
                    $('#chk_taxtable').prop('checked',false);
                }
		
                if(rowData.CurrencyCode != 'IDR'){
                    //$('#row_currency_rate').show();
                    $('#txt_currency_rate').attr('readonly',false);
                }
                else{
                    //$('#row_currency_rate').hide();
                    $('#txt_currency_rate').attr('readonly',true);
                }

                var url = '<?php echo base_url(); ?>' + 'list/purchases_order/get_vendor_taxes';

                if(vendor_status == 0){
                    if((vendor_taxnumber != '') && (vendor_taxnumber != null)){
                        taxes_code = 'PPH23-1';
                    }
                    else{
                        taxes_code = 'PPH23-2';
                    }
					taxes_pph23 = 'PPh23';
                }
                else{
                    if((vendor_taxnumber != '') && (vendor_taxnumber != null)){
                        taxes_code = 'PPH23-3';
                    }
                    else{
                        taxes_code = 'PPH23-4';
                    }
					taxes_pph23 = 'PPh21';
                }

                $.post(url, {TaxesCode:taxes_code}, function(result){
                    dbl_pph23 = result.taxes;

                    $('#hdn_pph23_pcnt').val(dbl_pph23);
                    $('#lbl_pph23').text(''+ taxes_pph23 +' (' + dbl_pph23 + '%)');
                },'json');

                hideppn();
				
				$('#tt_choose_pr').datagrid('reload');
				$('#tt_choose_adv').datagrid('reload');
				
				$('#txt_sub_total').numberbox('setValue', 0);
				$('#txt_discount').numberbox('setValue', 0);
				$('#txt_ppn10').numberbox('setValue', 0);
				$('#txt_pph22').numberbox('setValue', 0);
				$('#txt_pph23').numberbox('setValue', 0);
				$('#txt_freight').numberbox('setValue', 0);
				$('#txt_total_purchase').numberbox('setValue', 0);
            },
            onLoadSuccess:function(data){
                if(PReqNumber !=''){
                    $('#cbg_vendor').combogrid('setValue',VendorCode);
                }
            }		
        });
		
        $('input[name="rdo_PRToggle"]').click(function(){
            $('#tt_choose_pr').datagrid('loadData', {"rows":[]});            
            
            if($(this).is(':checked') && $(this).val()==1){
                $('#tt_choose_pr').datagrid('load',{
                    PReqType: 'item/expense'
                });
            }
            else if($(this).is(':checked') && $(this).val()==2){
                $('#tt_choose_pr').datagrid('load',{
                    PReqType: 'advance'
                });
            }
        });
	
	$('#dtg_item').edatagrid({
            onBeginEdit:function(rowIndex,rowDatax){
                var editors = $('#dtg_item').datagrid('getEditors', rowIndex);
                var n0  = $(editors[0].target);  // PReqNumber
                var n01 = $(editors[1].target);  // ItemCode
                var n1  = $(editors[3].target);  // ItemQty
                var n2  = $(editors[4].target);  // ItemPrice
                var n10 = $(editors[5].target);  // ItemDisc
				var n3  = $(editors[6].target);  // ItemAmount
                var n4  = $(editors[7].target);  // ItemMax
                var n5  = $(editors[12].target);  // ItemType
                var n6  = $(editors[13].target);  // ItemPPh22Status
                var n7  = $(editors[14].target); // ItemPPh23Status
                var n8  = $(editors[15].target); // ItemPriceNTax
				
				/*==================Disc Loss No Percision=====================*/
				var n11 = $(editors[16].target); // AmountDisc
				var n12 = $(editors[17].target); // ItemAmount Hide
				/*===============End==========================================*/
                
				/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
				save_button_begendedit(SavePrivillage);
				/*=================================end============================================================*/
				
				
                var item_type = n5.numberbox('getValue');
                if(item_type == 2){$(n1).prop('readonly', true);}

                $(n0).prop('readonly', true);
                $(n0).click(function(){
                    var TransNo             = rowDatax.PReqNumber;
                    parent.tab_edit('Edit Purchase Requisition','list/purchases_requisition', 'icon-edit', 'edit',TransNo);
                });

                $(n01).prop('readonly', true);
                
                
                n1.numberbox({
                    onChange:function(){
                        var item_qty            = n1.numberbox('getValue');
                        var item_price          = n2.numberbox('getValue');
                        var item_max            = n4.numberbox('getValue');
                        var item_type           = n5.numberbox('getValue');
                        var item_pph22status    = n6.numberbox('getValue');
                        var item_pph23Status    = n7.numberbox('getValue');
						var Item_disc    		= n10.numberbox('getValue');

                        if(parseFloat(item_qty) > parseFloat(item_max)){
                            $.messager.alert('Warning', 'Quantity tidak boleh lebih dari ' + item_max, 'error', function(){
                                $('#dtg_item').datagrid('reload');
								
                                $('#txt_sub_total').numberbox('setValue', 0);
                                $('#txt_discount').numberbox('setValue', 0);
                                $('#txt_ppn10').numberbox('setValue', 0);
                                $('#txt_pph22').numberbox('setValue', 0);
                                $('#txt_pph23').numberbox('setValue', 0);
                                $('#txt_freight').numberbox('setValue', 0);
                                $('#txt_total_purchase').numberbox('setValue', 0);
                                
                                item_qty.numberbox('setValue', 1);
                                $('#dtg_item').edatagrid('saveRow');
                            });
                        }
                        else {
                            var item_amount 	 = parseFloat(item_qty) * parseFloat(item_price);
							var Disc 			 = parseFloat(item_amount) * parseFloat(Item_disc) / 100;
							var total_item_price = parseFloat(item_amount) - parseFloat(Disc);
							        
                            //n3.numberbox('setValue', item_amount);
							//n11.numberbox('setValue', Disc);
							//n12.numberbox('setValue', item_amount);
							
                            $('#dtg_item').edatagrid('saveRow');
                            if(item_qty == ""){
								n1.numberbox('setValue, 0');
							}
							else{
								calculate_item_pph(rowIndex, item_type, item_pph22status, item_pph23Status, item_qty, item_price, 1, Item_disc);
							}
                            
                            //calculate_total();
                        }					
                    }
                });

                n2.numberbox({
                    onChange:function(){
                        var item_qty            = n1.numberbox('getValue');
                        var item_price          = n2.numberbox('getValue');
                        var item_type           = n5.numberbox('getValue');
                        var item_pph22status    = n6.numberbox('getValue');
                        var item_pph23status    = n7.numberbox('getValue');
						var Item_disc    		= n10.numberbox('getValue');

                        var item_amount = parseFloat(item_qty) * parseFloat(item_price);
						var Disc 		= parseFloat(item_amount) * parseFloat(Item_disc) / 100;
						var total_item_price = parseFloat(item_amount) - parseFloat(Disc);
						
                        //n3.numberbox('setValue', item_amount);
                        n8.numberbox('setValue', item_price);
						//n11.numberbox('setValue', Disc);
						//n12.numberbox('setValue', item_amount);
                        $('#dtg_item').edatagrid('saveRow');
						
						 if(item_price == ""){
							n2.numberbox('setValue, 0');
						 }
						 else{
							calculate_item_pph(rowIndex, item_type, item_pph22status, item_pph23status, item_qty, item_price, 1, Item_disc);
						 }
							
                        
                        //calculate_total();
                    }
                });
				
				n10.numberbox({
                    onChange:function(){
                        var item_qty            = n1.numberbox('getValue');
                        var item_price          = n2.numberbox('getValue');
                        var item_type           = n5.numberbox('getValue');
                        var item_pph22status    = n6.numberbox('getValue');
                        var item_pph23status    = n7.numberbox('getValue');
						var Item_disc    		= n10.numberbox('getValue');
						
						if(parseFloat(Item_disc) > 100){
							$.messager.alert('Warning', "Maaf Discount tidak boleh melebihi 100% per Item", 'info');
							n10.numberbox('setValue', 0);
						}
						else{
							var item_amount = parseFloat(item_qty) * parseFloat(item_price);
							var Disc 		= parseFloat(item_amount) * parseFloat(Item_disc) / 100;
							
							//n3.numberbox('setValue', item_amount);
							n8.numberbox('setValue', item_price);
							//n11.numberbox('setValue', Disc);
							//n12.numberbox('setValue', item_amount);
							
							$('#dtg_item').edatagrid('saveRow');
							if(Item_disc == ""){
								n10.numberbox('setValue, 0');
							 }
							 else{
								calculate_item_pph(rowIndex, item_type, item_pph22status, item_pph23status, item_qty, item_price, 1, Item_disc);
							 }
							
							//calculate_discount();
						}
                    }
                });
            },
			onEndEdit: function(){
                var selectedrow     = $('#dtg_item').datagrid('getSelected');
				
				/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
				save_button_endedit(SavePrivillage);
				/*=================================end============================================================*/
				
            },onLoadSuccess:function(){
                $('#tt_choose_pr').datagrid({
                    onLoadSuccess:function(data){
                        /*==============Daswan======================*/
                        if(PReqNumber!=''){
                            if(load == 0){
                                load            = 1;
                                var data_pr     = $('#tt_choose_pr').datagrid('getRows');
                                var ind_preq    = findWithAttr(data_pr,'PReqNumber',PReqNumber);
                                if(typeof ind_preq == 'undefined'){
                                    var data_adv    = $('#tt_choose_advance').datagrid('getRows');
                                    ind_preq        = findWithAttr(data_adv,'PReqNumber',PReqNumber);
                                    $('#tt_choose_advance').datagrid('checkRow',ind_preq);
                                    choose_adv();
                                }else{
                                    $('#tt_choose_pr').datagrid('checkRow',ind_preq);
                                    choose_pr(true);
                                }
                            }
                        }
                        /*============ end Daswan =========================*/
                    }
                });
            }
        });
 
    	$('#fm_purchase_order').click(function(){
            $('#dtg_item').edatagrid('saveRow');
    	});

        $('#txt_freight').numberbox({
            onChange:function(){
                freight = $('#txt_freight').numberbox('getValue');

                if(isNaN(freight) || freight == ''){
                    $('#txt_freight').numberbox('setValue', 0);
                }
                
                calculate_es_freight();
            }
        });
        datagrid_item_type("dtg_item");//untuk warna grid
    });

    function hidedp(){
	if($('#chk_vendorneeds').is(':checked')){
            $('.dp_line').css('display','');			
            $('.dp').css('display','');			
	}
	else{
            $('.dp_line').css('display','none');
            $('.dp').css('display','none');
            $('#txt_downpayment').numberbox('setValue',0);
	}
    }

    function hideppn(){
		
	if($('#chk_taxtable').is(':checked')){
            $('.disableme').css('display','');		
	}
	else{
            $('.disableme').css('display','none');
            $("#chk_inclusive").prop("checked",false);
	}
	
	calculate_item_tax();
    }   

    function  calculate_item_intax(){
         var item = $('#dtg_item').datagrid('getRows');
        flag = true;
        $.each(item, function(index, value){
			if(value.ItemPrice == 0){
				flag = false;
			}
		});
		
		if(flag != false){
			var item = $('#dtg_item').datagrid('getData').total;
	
			if(item == 0){
				$.messager.alert('Warning', "Silahkan pilih 'Select PR' terlebih dahulu...!!", 'error');
				$("#chk_inclusive").prop("checked",false);
			}
			else{
				calculate_item_tax();
			}
		}
		else{
			$.messager.alert('Warning', "Maaf silahkan isi terlebih dahulu item price di Purchase Order", 'error');
			$("#chk_inclusive").prop("checked",false);
		}
    }

    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.ItemQty;
			
			dbl_ppn10 	= parseFloat(dbl_ppn10);
			
			total_price = parseFloat(item_price - (item_price * item_disc) / 100);
			total_disc 	= parseFloat((item_qty * item_price) * (item_disc / 100));
			
            if(item_price >= 0 || item_price !== null){
				
                if($('#chk_taxtable').is(':checked')){
                    /*
						Perhitungan Inclusive Tax
					*/
					if($('#chk_inclusive').is(':checked')){
                        //item_ppn    = parseFloat((item_price / 1.1) * (dbl_ppn10 / 100).toFixed(9));
						total_price 	= parseFloat((100 / (100 + dbl_ppn10) * total_price).toFixed(9)); 
						
                        //item_price  = parseFloat((item_ppn - item_ppn).toFixed(9));
                        intax = 1;
                    }
                    else{
                        if(value.IntaxStatus == 1){item_price = value.ItemPriceNTax;}
                        intax   = 0;
                    }
                    /*==============================End============================================*/
					
					/*
						Perhitungan PPH 22 Jika Di klik taxable
					*/
                    item_amount = parseFloat(value.ItemQty) * parseFloat(total_price);
                    item_ppn10  = parseFloat((item_amount * (dbl_ppn10 / 100)).toFixed(9));
					
					if (value.ItemPPh22Status == 1){
						item_pph22 = parseFloat((item_amount * (dbl_pph22 / 100)).toFixed(9));
					}
					else{
						item_pph22  = 0;
					}
					/*====================End====================================================*/
                }
                else{
                    if(value.IntaxStatus == 1){
                        item_price  = parseFloat(item_price) + parseFloat((item_price * (dbl_ppn10 / 100)).toFixed(9));
                        intax       = 0;
                    }
					
                    item_amount = parseFloat(total_price) * parseFloat(value.ItemQty);
                    item_ppn10  = 0;  
					
					/*
						Perhitungan PPH 22 Jika Di klik taxable
					*/
					if (value.ItemPPh22Status == 1){
						item_pph22 = parseFloat((item_amount * (dbl_pph22 / 100)).toFixed(9));
					}
					else{
						item_pph22  = 0;
					}                    
                }
                
                item_amount = isNaN(item_amount) ? 0 : parseFloat(item_amount);
                item_ppn10  = isNaN(item_ppn10) ? 0 : parseFloat(item_ppn10);
				item_pph22  = isNaN(item_pph22) ? 0 : parseFloat(item_pph22);

                if ((value.ItemType == 1) && (value.ItemPPh23Status == 1)){
                    dbl_pph23   = $('#hdn_pph23_pcnt').val();
                    item_pph23  = parseFloat((item_amount * (dbl_pph23 / 100)).toFixed(9));
                }
                else{
                    item_pph23  = 0;
                }

                item_totalamount    = parseFloat(item_amount + item_ppn10 + item_pph22 - item_pph23);

                $('#dtg_item').datagrid('updateRow',{
                    index:index,
                    row:{//ItemPrice          : (item_price == 0) ? '0.00' : item_price,
                         ItemAmount         : (item_amount == 0) ? '0.00' : item_amount,
                         Item_PPn10         : item_ppn10,
                         Item_PPh22         : item_pph22,
                         Item_PPh23         : item_pph23,
                         ItemTotalAmount    : item_totalamount,
						 ItemAmount_Hide    : (item_amount == 0) ? '0.00' : item_amount,
						 AmountDisc 		: total_disc,
                         IntaxStatus        : intax}
                });
            }
	});
	
	calculate_total();
    }

    function calculate_item_pph(rowIndex, item_type, item_pph22status, item_pph23Status, item_qty, item_price, status, Item_disc){
        item_ppn10  = 0;
        intax       = 0;
		dbl_ppn10 	= parseFloat(dbl_ppn10);
		
		total_price = parseFloat(item_price - ((item_price * Item_disc) / 100));
		
        item_amount = parseFloat(item_qty * total_price);
		total_disc 	= parseFloat((item_qty * item_price) * (Item_disc / 100));
		
        if($('#chk_taxtable').is(':checked')){//PPn10
            if($('#chk_inclusive').is(':checked') && status == 1){
                //item_ppn    = parseFloat((((item_price - Disc) / 1.1) * (dbl_ppn10 / 100)).toFixed(9));
                item_ppn 	= parseFloat(total_price * (100 / (100 + dbl_ppn10)).toFixed(9)); 
				//item_price  = parseFloat((item_price - total_price) - item_ppn);
                item_amount = parseFloat(item_qty) * parseFloat(item_ppn);
				total_disc 	= parseFloat((item_qty) * parseFloat(item_price) * (Item_disc / 100));
				
                intax       = 1;
            }

            item_ppn10  	= parseFloat((item_amount) * (dbl_ppn10 / 100));
			
			if(item_pph22status == 1){//Import
				item_pph22          = parseFloat((item_amount * (dbl_pph22 / 100)).toFixed(9));
				item_totalamount    = parseFloat(item_amount + item_ppn10 + item_pph22);
	
				$('#dtg_item').edatagrid('updateRow',{
					index:rowIndex, 
					row:{ItemPrice          : item_price,
						 ItemAmount         : item_amount,
						 Item_PPn10         : item_ppn10,
						 Item_PPh22         : item_pph22,
						 ItemTotalAmount    : item_totalamount,
						 AmountDisc 		: total_disc,
					 	 ItemAmount_Hide 	: item_amount,
						 IntaxStatus        : intax}
				});
			}
        }
        
		if(item_pph22status == 1){//Import
			item_pph22          = parseFloat((item_amount * (dbl_pph22 / 100)).toFixed(9));
			item_totalamount    = parseFloat(item_amount + item_ppn10 + item_pph22);

			$('#dtg_item').edatagrid('updateRow',{
				index:rowIndex, 
				row:{ItemPrice          : item_price,
					 ItemAmount         : item_amount,
					 Item_PPn10         : item_ppn10,
					 Item_PPh22         : item_pph22,
					 ItemTotalAmount    : item_totalamount,
					 AmountDisc 		: total_disc,
					 ItemAmount_Hide 	: item_amount,
					 IntaxStatus        : intax}
			});
		}
			
        if((item_type == 1) && (item_pph23Status == 1)) {//Expense
            dbl_pph23           = $('#hdn_pph23_pcnt').val();
            item_pph23          = parseFloat((item_amount * (dbl_pph23 / 100)).toFixed(9));
            item_totalamount    = parseFloat(item_amount + item_ppn10 - item_pph23);
			total_disc 	= parseFloat((item_qty * item_price) * (Item_disc / 100));
            
			$('#dtg_item').edatagrid('updateRow',{
                index:rowIndex, 
                row:{ItemPrice          : item_price,
                     ItemAmount         : item_amount,
                     Item_PPn10         : item_ppn10,
                     Item_PPh23         : item_pph23,
                     ItemTotalAmount    : item_totalamount,
					 AmountDisc 		: total_disc,
					 ItemAmount_Hide 	: item_amount,
					 IntaxStatus        : intax}
            });
        }
        else{
            item_totalamount    = parseFloat(item_amount + item_ppn10);
            
            $('#dtg_item').edatagrid('updateRow',{
                index:rowIndex, 
                row:{ItemPrice          : item_price,
                     ItemAmount         : item_amount,
                     Item_PPn10         : item_ppn10,
                     ItemTotalAmount    : item_totalamount,
					 AmountDisc 		: total_disc,
					 ItemAmount_Hide 	: item_amount,
                     IntaxStatus        : intax}
            });
        }
        
        calculate_total();
    }
    
	function calculate_discount(){
		$('#dtg_item').edatagrid('saveRow');
		var item        = $('#dtg_item').datagrid('getRows');
		var total       = 0;
        var item_amount  = 0;

        var sub_total   = 0;
        var sub_ppn10   = 0;
        var sub_pph22   = 0;
        var sub_pph23   = 0;
		var sub_disc   	= 0;
		$.each(item, function(index, value) {   
			
		   item_amount  = isNaN(value.ItemAmount_Hide) ? 0 : value.ItemAmount_Hide;

           sub_total += parseFloat(item_amount);
           sub_ppn10 += parseFloat(value.Item_PPn10);
           sub_pph22 += parseFloat(value.Item_PPh22);
           sub_pph23 += parseFloat(value.Item_PPh23);
			         
           sub_disc  += parseFloat(value.AmountDisc);
		});
		sub_disc 			= isNaN(sub_disc) ? 0 : parseFloat(sub_disc);
		
		var sub_discount    	 = $('#txt_discount').numberbox('setValue', sub_disc);	
		var sub_discount_hide    = $('#txt_discount_hide').numberbox('setValue', sub_disc);	
		var sub_freight     	 = $('#txt_freight').numberbox('getValue');	
		
		total =  parseFloat(sub_total) + parseFloat(sub_ppn10) + parseFloat(sub_pph22) - parseFloat(sub_pph23) + parseFloat(sub_freight);
		total = isNaN(total) ? 0 : parseFloat(total);
		
		$('#txt_total_purchase').numberbox('setValue', total);
		$('#txt_total_purchase_hide').numberbox('setValue', total);
	}
	
	function calculate_es_freight(){
		$('#dtg_item').edatagrid('saveRow');
		var item        = $('#dtg_item').datagrid('getRows');
		var total       = 0;
        var item_amount  = 0;

        var sub_total   = 0;
        var sub_ppn10   = 0;
        var sub_pph22   = 0;
        var sub_pph23   = 0;
		var sub_disc   	= 0;
		$.each(item, function(index, value) {   
			
		   item_amount  = isNaN(value.ItemAmount_Hide) ? 0 : value.ItemAmount_Hide;

           sub_total += parseFloat(item_amount);
           sub_ppn10 += parseFloat(value.Item_PPn10);
           sub_pph22 += parseFloat(value.Item_PPh22);
           sub_pph23 += parseFloat(value.Item_PPh23);
			         
           sub_disc  += parseFloat(value.AmountDisc);
		});
		sub_disc 			= isNaN(sub_disc) ? 0 : parseFloat(sub_disc);
		
		var sub_discount    	 = $('#txt_discount').numberbox('setValue', sub_disc);	
		var sub_discount_hide    = $('#txt_discount_hide').numberbox('setValue', sub_disc);	
		var sub_freight     	 = $('#txt_freight').numberbox('getValue');	
		
		total =  parseFloat(sub_total) + parseFloat(sub_ppn10) + parseFloat(sub_pph22) - parseFloat(sub_pph23) + parseFloat(sub_freight);
		total = isNaN(total) ? 0 : parseFloat(total);
		
		$('#txt_total_purchase').numberbox('setValue', total);
		$('#txt_total_purchase_hide').numberbox('setValue', total);
	}
	
    function calculate_total(){
	$('#dtg_item').edatagrid('saveRow');

	var item        = $('#dtg_item').datagrid('getRows');

        var total       = 0;
        var item_amount  = 0;

        var sub_total   = 0;
        var sub_ppn10   = 0;
        var sub_pph22   = 0;
        var sub_pph23   = 0;
		var sub_disc   	= 0;
	
	$.each(item, function(index, value) {            
            item_amount  = isNaN(value.ItemAmount_Hide) ? 0 : value.ItemAmount_Hide;

            sub_total += parseFloat(item_amount);
            sub_ppn10 += parseFloat(value.Item_PPn10);
            sub_pph22 += parseFloat(value.Item_PPh22);
            sub_pph23 += parseFloat(value.Item_PPh23);
			
			sub_disc  += parseFloat(value.AmountDisc);
	});
	
	/*if($('#chk_taxtable').is(':checked')){//PPn10
		if($('#chk_inclusive').is(':checked')){
			$('#txt_sub_total').numberbox('setValue', sub_total);
			$('#txt_sub_total_hide').numberbox('setValue', sub_total);
		}
		
		$('#txt_sub_total').numberbox('setValue', sub_total );
		$('#txt_sub_total_hide').numberbox('setValue', sub_total );
	}
	else{
		$('#txt_sub_total').numberbox('setValue', sub_total + sub_disc);
		$('#txt_sub_total_hide').numberbox('setValue', sub_total + sub_disc);
	}*/
	
	$('#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);
	
	$('#txt_pph23').numberbox('setValue', sub_pph23);
	$('#txt_pph23_hide').numberbox('setValue', sub_pph23);
	
	$('#txt_discount').numberbox('setValue', sub_disc);	
	$('#txt_discount_hide').numberbox('setValue', sub_disc);	
		
	var sub_freight     = $('#txt_freight').numberbox('getValue');	
	
	total =  parseFloat(sub_total) + parseFloat(sub_ppn10) + parseFloat(sub_pph22) - parseFloat(sub_pph23) + parseFloat(sub_freight);
	total = isNaN(total) ? 0 : parseFloat(total);
	
	$('#txt_total_purchase').numberbox('setValue', total);
	$('#txt_total_purchase_hide').numberbox('setValue', total);
	
    }
    
	 
		
    function remove_row(){
        var selectedrow     = $('#dtg_item').datagrid('getSelected');
        var row_index       = $('#dtg_item').datagrid('getRowIndex', selectedrow);
		var item_row        = $('#dtg_item').datagrid('getRows');
		
		var pr_no       	= new Array();
        var pr_date 		= new Array();
		var pr_desc 		= new Array();
	
        $.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.ItemCode + '"?',  
            function(r){
                if (r){
                    var item = $('#dtg_item').datagrid('getData').total;

                    if(item == 0){
                        $("#chk_inclusive").prop("checked",false);
                    }
                    
                    $('#dtg_item').datagrid('deleteRow', row_index);
                    calculate_total();
					
					$.each(item_row, function(index, value) {
						if(value.PReqNumber != undefined){
							pr_no.push(value.PReqNumber);
							pr_date.push(value.PReqDate);
							pr_desc.push(value.PReqDesc);
						}
					});
					
					$('#txt_preq_no').val(pr_no.array_unique());
        			$('#txt_preq_date').val(pr_date.array_unique());
					$('#txa_description').val(pr_desc.array_unique());
					
					/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
					$('.save-button').linkbutton('enable');
					/*=================================end============================================================*/
                }
            }
        );
    }

    function insert_data(){
        var amount  = true;
		var flag 	= true;
		
        var item    = $('#dtg_item').datagrid('getRows');
	
        $.each(item, function( index, value ) {
            if(value.ItemPrice == undefined || value.ItemPrice == 0 ){
                amount = false;
            }		
			
			if(value.ItemType == 2){
				if(value.ItemQty != 1){
					flag = false;
				}
			}
        });
	
        if(amount == false){
           $.messager.alert('Unseccessfull','Masih ada price yang kosong','error',function(){});
        }
		else if(flag == false){
			$.messager.alert('Unseccessfull','Maaf Item Qty Tidak Boleh Lebih/Kurang Dari (1) Satu, Untuk Adv. Payment','error',function(){		
                $('#dtg_item').edatagrid('reload');
            });
		}
        else if($('#txt_downpayment').numberbox('getValue') == 0 && $('#chk_vendorneeds').is(':checked')){
            $.messager.alert('Unseccessfull','Vendor Needs DP telah Anda checklist, silahkan isi nominal DP','error',function(){		
                $('#txt_downpayment').numberbox().focus();
            });
        }
        else if(parseFloat($('#txt_downpayment').numberbox('getValue')) > parseFloat($('#txt_sub_total').numberbox('getValue'))){
            $.messager.alert('Unseccessfull','Down Payment tidak boleh lebih besar dari pada sub total','error',function(){		
                $('#txt_downpayment').numberbox().focus();
            });
        }
        else {
            if(check_qty()){
                $('#dtg_item').edatagrid('saveRow');		

                var i       = $('#dtg_item').datagrid('getRows');
                var detail  = JSON.stringify(i);

                $("#detail").val(detail);		
                save_transaction('<?=$menu_link?>','#fm_purchase_order');
            }    
        }		
    }

    function check_qty(){		
        var item=$('#dtg_item').datagrid('getRows');
        var check_status=true;
	
        $.each(item, function(index, value) {		   
            if(parseFloat(value.ItemQty)>parseFloat(value.max)){
                $.messager.alert('Informasi','Item '+value.ItemDesc+' tidak boleh lebih dari '+value.max,'warning',function(){});            
                check_status=false;
            }
        });

        return check_status;
    }
</script>