<!-- Author : Ferry / 12-01-2015 -->

	<?php
			//---------Untuk privellege jika dia ada tombol save----------
				if($group_user->SavePrivillage == 1){
					$cek_autority_save  = "";
				}
				else{
					$cek_autority_save 	= "disabled";
				}
				
				if($group_user->JournalPrivillage == 1){
					$cek_autority_journal = "";
				}
				else{
					$cek_autority_journal = "disabled";
				}
				
				if($group_user->DeletePrivillage == 1){
					$cek_autority_delete  = "";
				}
				else{
					$cek_autority_delete 	= "disabled";
				}
				
				//-------------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="journal_tab();" <?php echo $cek_autority_delete;?>>Journal</a>
                        <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-currency" onclick="to_transaction()" <?=(in_array($detail->TransStatus,array(1)))?'':'disabled'?>>To Purchase Invoice</a>
                        <a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload();">Refresh</a>
                    </td>

                    <td align="center" width="40%">
                        <span id="approval_information">
                            <?php 
                                if($detail->TransStatus==4){
                                    if($this->session->userdata('jobtitle_status')==1){
                                        echo 'Need Your Approval';
                                    }
                                    else{
                                        echo 'Need Manager Approval';
                                    }
                                }
                                elseif($detail->TransStatus==1){
                                    echo 'On Progress';
                                }
                            ?>
                        </span>
                    </td>

                    <td align="right" width="30%">
                        <span class="form-title"><?=$menu_label?></span>							
                    </td>
                </tr>
            </table>		     	
        </div>			
    </div>
    <!-- End of top 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==2){ echo 'Finished'; }elseif($detail->TransStatus==3){ echo 'Suspended'; }elseif($detail->TransStatus==9){ echo 'Canceled by Dir.'; }else{ echo 'Unknown'; } ?></b></div>
            <?php } ?>
        
            <form id="fm_receive_item" name="fm_receive_item" 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_currency_rate" id="hdn_currency_rate"/>
                <input type="hidden" name="hdn_ppn10_pcnt" id="hdn_ppn10_pcnt"/>
                
                <input type="hidden" name="detail_id" id="detail_id">
                <input type="hidden" name="detail_qty" id="detail_qty">
                
                <!-- Form Header -->
                <table width="100%" height="141" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="50%" 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 width="270">
                                        <select name="cbg_vendor" id="cbg_vendor" class="easyui-combogrid" style="width:260px;height:20px" required readonly
                                            data-options="
                                                panelWidth: 445,
                                                value:'<?php echo $detail->VendorCode ?>', 
                                                idField: 'VendorCode',
                                                textField: 'VendorName',
                                                url: '<?php echo 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>
                                    </td>
                            
                                    <td>
                                        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-sales'" onClick="select_po();" disabled >Select PO</a>
                                    </td>
                                </tr>
                                
                                <tr height="20">
                                    <td width="120" valign="top" style="padding-top:4px;"><b>Vendor Address</b></td>
                                    <td width="10" valign="top" style="padding-top:4px;"><b>:</b></td>

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

                                    <td>&nbsp;</td>
                                </tr>
                            </table>
                        </td>
                    
                        <td width="50%" valign="top">
                            <table width="100%" cellpadding="0" cellspacing="1" style="margin-top:4px;">
                                <tr height="20">
                                    <td rowspan="7" valign="top">&nbsp;</td>
                                    <td width="190" style="background:#333399;text-align:center;color:#FFF;">RI. No.</td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">RI. Date</td>
                                    <td width="122" style="background:#333399;text-align:center;color:#FFF;">Terms</td>
                                </tr>
                                
                                <tr height="20">
                                    <td><input type="text" name="txt_prec_no" id="txt_prec_no" value="<?php echo $detail->PRecNumber ?>" style="width:190px;height:18px;text-align:center;" class="easyui-validatebox textbox" required readonly /></td>
                                    <td><input type="text" name="txt_prec_date" id="txt_prec_date" class="easyui-datebox" style="width:122px;height:20px" required editable="false" readonly /></td>

                                    <td>
                                        <select class="combo-grid" required="required"
                                            name="cbo_terms" id="cbo_terms" 
                                            style="width:122px;height:20px;" 
                                            <?=(!in_array($detail->TransStatus,array(0,4)))?'disabled':''?>
                                            data-options="
                                                panelWidth: 250,
                                                value:'<?=$detail->TermsPaymentID?>',
                                                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;">PO. No.</td> -->
                                    <td style="background:#333399;text-align:center;color:#FFF;">Vendor DO. No.</td>
                                    <!-- <td style="background:#333399;text-align:center;color:#FFF;">PO. Date</td> -->
                                    <td style="background:#333399;text-align:center;color:#FFF;">Ship Date</td>
                                    <td style="background:#333399;text-align:center;color:#FFF;">FOB</td>
                                </tr>

                                <tr height="20">
                                    <!--<td>--><input type="hidden" name="txt_pord_no" id="txt_pord_no" value="<?php echo $detail->POrdNumber ?>" 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="hidden" class="easyui-validatebox textbox" value="<?php echo $detail->POrdDate ?>" style="width:120px;height:18px" required readonly /><!--</td>-->
                                    <td><input type="text" name="txt_vendor_do_no" id="txt_vendor_do_no" value="<?php echo $detail->VendorDONumber ?>" style="width:190px;height:18px;text-align:center;text-transform:uppercase;" class="easyui-validatebox textbox" <?=(!in_array($detail->TransStatus,array(0,4)))?'readonly':''?> /></td>
                                    <td><input name="txt_ship_date" id="txt_ship_date" type="text" class="easyui-datebox" style="width:122px;height:20px" editable="false" <?=(!in_array($detail->TransStatus,array(0,4)))?'readonly':''?> /></td>
                                    <td>
                                        <select class="easyui-combogrid" required="required"
                                            name="cbo_fob" id="cbo_fob" 
                                            style="width:122px;height:20px;" 
                                            <?=(!in_array($detail->TransStatus,array(0,4)))?'readonly':''?>
                                            data-options="
                                                panelWidth: 250,
                                                value:'<?php echo $detail->FOBID; ?>',
                                                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 style="background:#333399;text-align:center;color:#FFF;">Vendor DO. No.</td> -->
                                    <td></td>
                                    <!-- <td style="background:#333399;text-align:center;color:#FFF;">Ship Date</td> -->
                                    <td></td>
                                    <td style="background:#333399;text-align:center;color:#FFF;">Ship Via</td>
                                </tr>
                                
                                <tr height="20">
                                    <td></td>
                                    <td></td>
                                    <td>
                                        <select class="combo-grid" required="required"
                                            name="cbo_ship_via" id="cbo_ship_via" 
                                            style="width:122px;height:20px;" 
                                            <?=(!in_array($detail->TransStatus,array(0,4)))?'disabled':''?>
                                            data-options="
                                                panelWidth: 250,
                                                value:'<?=$detail->ShipmentID?>',
                                                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 -->
                
                <!--Item Grid -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div title="Item">
                        <table id="dtg_item" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" toolbar="#tb_dtg_item" style="height:250px;" 
                            url="<?php echo base_url().$menu_link."/ajax_item_for_edit/".$detail->PRecNumber; ?>" 
                        >
                            <thead>
                                <tr>
                                    <th field="POrdNumber"       width="40"  data-options="halign:'center',align:'left'" editor="{type:'text'}">PO. Number</th>
                                    <th field="ItemCode"         width="40"  data-options="halign:'center',align:'left'">Item</th>
                                    <th field="ItemCodeVendor"         width="40"  data-options="halign:'center',align:'left'"><?php echo label_grid('no_seri');?></th>
                                    <th field="ItemDesc"         width="120" data-options="halign:'center',align:'left'">Description</th>
                                    <th field="ItemQty"          width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true},min:1}" formatter="formatRp">Qty</th>
                                    <th field="ItemUnit"         width="20"  data-options="halign:'center',align:'center'" >Item Unit</th>
                                    
                                    <th field="ItemPrice"        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>Unit Price</th>
                                    <th field="ItemAmount"       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 Amount</th>
                                    <th field="ItemMax"          width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp" hidden>Item Max</th>
                                    <th field="ItemTaxPPn10"     width="20"  data-options="halign:'center',align:'center'" 
                                    editor="{type:'numberbox',options:{decimalSeparator:',',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    }}" 
                                    hidden>Item Tax PPn10</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="PRecDetailID"     width="30"  data-options="halign:'center',align:'center'" editor="{type:'numberbox'}" hidden>PRec ID</th>
                                    <th field="POrdDetailID"     width="30"  data-options="halign:'center',align:'center'" editor="{type:'numberbox'}" hidden>POrd ID</th>
                                    <th field="ItemCategoryID"   width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox'}" hidden>Item Category ID</th>
                                    <th field="ItemType"         width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox'}" hidden>Item Type</th>
                                    <th field="POrdQtyRI"        width="30"  data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp" hidden>POrd Qty RI</th>
                                    <th field="ItemQty_Old"      width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp" hidden>Item Qty Old</th>
                                    <th field="Modus_Type"       width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox'}" hidden>Modus Type</th>
                                    <th field="ItemCategoryCode" width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox'}" hidden>Item Category Code</th>
                                    <th field="ItemStatus"       width="20"  data-options="halign:'center',align:'center'" editor="{type:'text'}" hidden>Item Status</th>
                                    <th field="ItemDisc"         width="20"  data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,min:0}}" formatter="formatRp" hidden>Item Disc</th>
                                </tr>
                            </thead>
                        </table>
                        
                        <div id="tb_dtg_item">
                            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row();" <?= in_array($detail->TransStatus,array(0,1,2,3,9))? 'disabled' : '' ?>>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 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;" <?=(!in_array($detail->TransStatus,array(0,4)))?'readonly':''?>><?=$detail->PRecDesc?></textarea>
                                    </td>
                                </tr>
                            </table>
                        </td>

                        <td width="50%" valign="top">
                            <input type="checkbox" name="chk_taxtable" id="chk_taxtable" value="1" hidden>
                            <input type="checkbox" name="chk_inclusive" id="chk_inclusive" value="1" hidden>
                            
                            <input type="text" id="txt_sub_total" name="txt_sub_total" class="easyui-numberbox" value="0" style="text-align:right;" 
                            data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                            formatter:function(v){
                                return v;
                            },
                            parser:function(s){
                                var v = parseFloat(s);
                                return v;
                            }
                            "
                            hidden readonly 
                            />
                            <input type="text" min="0" name="txt_ppn10" id="txt_ppn10" class="easyui-numberbox" value="0" 
                            data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                            formatter:function(v){
                                return v;
                            },
                            parser:function(s){
                                var v = parseFloat(s);
                                return v;
                            }
                            " 
                            hidden readonly  style="text-align:right;" />
                            <input type="text" name="txt_total_purchase" id="txt_total_purchase" class="easyui-numberbox" value="0" style="text-align:right;" 
                            data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                            formatter:function(v){
                                return v;
                            },
                            parser:function(s){
                                var v = parseFloat(s);
                                return v;
                            }
                            "
                           hidden readonly />
                        </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 app-button" iconCls="icon-ok" onClick="approval();" <?=($this->session->userdata["jobtitle_status"] != 1 || $detail->TransStatus != 4 || (date('Y-m-d') < date('Y-m-d', strtotime($detail->PRecDate)))) ? '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" <?php if($detail->AppLevel1Status == 1){echo " disabled ";}?> onclick="update_data();" <?=(!in_array($detail->TransStatus,array(0,4)))?'disabled':''?> <?php echo $cek_autority_delete;?> <?php echo $cek_autority_save;?>/>Save</a> 								
                    <!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onClick="link_print('<?php echo $menu_link ?>/to_print_detail/<?php echo $detail->PRecNumber ?>');" <?=(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->PRecNumber?>');" <?=(in_array($detail->TransStatus,array(1,2,3,4,5,6,9)))?'':'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)) || $detail->AppLevel1Status==1)?'disabled':''?>><?= ($this->session->userdata('jobtitle_status') == 0)?'Cancel':'Close'?></a>
                </td>
            </tr>
        </table>
    </div>
</div>

<div id="dialog-po" class="easyui-dialog" style="width:725px;height:525px;background-color:#F8F8F8;padding:0px;" closed="true" data-options="modal:true, iconCls:'icon-edit'" buttons="#dialogpo-buttons">
    <table id="tt_choose_po" class="easyui-datagrid" remoteSort="false" singleSelect="true" pagination="true" pageSize="40" fit="true" fitColumns="true" rowNumbers="true"
        url="<?=base_url() . $menu_link . "/ajax_for_choose_po"?>" 
    >
        <thead>
            <tr>            
                <th field="ck" checkbox="true"></th>
                <th field="POrdNumber" width="147" halign='center' align='center' sortable="true">PO. Number</th>
                <th field="PODate" width="90" halign='center' align='center' sortable="true">PO. Date</th>
                <th field="POrdDesc" width="300" halign="center" align="left">Description</th>
            </tr>
        </thead>
    </table>
</div>

<!-- Dialog Button -->
<div id="dialogpo-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_po();">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-po');">Cancel</a>
</div>
<?php $this->load->view('v_custom_pop_up');?>
<script> 
	/*========================deklar variabel array for remove===================*/
	var array_item = [];
	var new_array_item = {'a':[],'b':[],'c':[]};
	/*==============================end=========================================*/
	var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';
	       
    $(document).ready(function(){
        taxable_val         = '<?=$detail->PRecTaxesStatus?>';
        intax_val           = '<?=$detail->PRecInTaxStatus?>';
        tax_pcnt            = '<?=$detail->PRecPPn10Pcnt?>';
        tax_val             = '<?=$detail->PRecPPn10?>';
        sub_total           = '<?=$detail->PRecSubTotal?>';
        total_purchase      = '<?=$detail->PRecTotalAmount?>';        

        $('#hdn_currency_code').val('<?=$detail->CurrencyCode?>');
        $('#hdn_currency_rate').val('<?=$detail->CurrencyRate?>');
        $('#hdn_ppn10_pcnt').val('<?=$detail->PRecPPn10Pcnt?>');

		//$('#cbo_terms').combobox('select','<?php echo $detail->TermsPaymentID ?>');
        //$('#cbo_ship_via').combobox('select','<?php echo $detail->ShipmentID ?>'); 
		//$('#cbo_fob').combobox('select','<?php echo $detail->FOBID ?>');

		$('#txt_prec_date').datebox('setValue', '<?= date("d-m-Y", strtotime($detail->PRecDate))?>');
		$('#txt_pord_date').val('<?= date("d-m-Y", strtotime($detail->POrdDate))?>');
		$('#txt_ship_date').datebox('setValue', '<?= date("d-m-Y", strtotime($detail->ShipmentDate))?>');

        if (taxable_val == 1) {$("#chk_taxtable").prop("checked", true)};
        if (intax_val == 1) {$("#chk_inclusive").prop("checked", true)};

        $('#txt_sub_total').numberbox('setValue', sub_total);
        $('#txt_ppn10').numberbox('setValue', tax_val);
        $('#txt_total_purchase').numberbox('setValue', total_purchase);

	$('#dtg_item').edatagrid({
            onBeginEdit:function(rowIndex,rowDatax){
                var editors     = $('#dtg_item').datagrid('getEditors', rowIndex);	
                var n0          = $(editors[0].target);  // POrdNumber      		
                var n1          = $(editors[1].target); //Item QTy
                var n2          = $(editors[2].target); //Item Price
                var n3          = $(editors[3].target); //Item Amount
                var n4          = $(editors[4].target); //Item Max
                var n5          = $(editors[5].target); //Item PPn10
                var n6          = $(editors[6].target); //Item Total Amount
				var n7          = $(editors[16].target); //Item Total Amount
				var n8          = $(editors[10].target); //Item Type
				
				var item_type  	= n8.text('getData').val();
				if(item_type == 2){
					$(n1).prop('readonly',true);
				}

                $(n0).prop('readonly', true);
                $(n0).click(function(){
                    var TransNo             = rowDatax.POrdNumber;
                    parent.tab_edit('Edit Purchase Order','list/purchases_order', 'icon-edit', 'edit',TransNo);
                });
				
				if('<?= in_array($detail->TransStatus,array(4))?>'){
					/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
					save_button_begendedit(SavePrivillage);
					/*=================================end============================================================*/
				}
					
                TransStatus = '<?=$detail->TransStatus?>';

                if(!(TransStatus == 0 || TransStatus == 4)){
                    $(n1).prop('readonly', true);
                }

                $(n1).numberbox({
                    onChange:function(){
                        var jml 	= n1.numberbox('getValue');
                        var price 	= n2.numberbox('getValue');
                        var jml_max     = n4.numberbox('getValue');
						var disc     = n7.numberbox('getValue');
					
                        if(parseFloat(jml) > parseFloat(jml_max)){
                            $.messager.alert('Maaf','Quantity tidak boleh lebih dari ' + jml_max, 'error', function(){		
								n1.numberbox('setValue', jml_max);
								
                                n3.numberbox('setValue', 0);
                                $('#dtg_item').edatagrid('saveRow');
                                calculate_total();
                            });
                        }
                        else {
                            var ppn10_pcnt  = $('#hdn_ppn10_pcnt').val();
							ppn10_pcnt 			= parseFloat(ppn10_pcnt);
							/*
								Harga dikurangi discount
							*/
							var total_price = (parseFloat(price) - (parseFloat(price) * disc / 100)); 
                            /*==========================End=========================================*/
							
							/*
								Jika dia inclusive
							*/
							if($('#chk_taxtable').is(':checked')){
								 if($('#chk_inclusive').is(':checked')){
									total_price 	= parseFloat((100 / (100 + ppn10_pcnt) * total_price)); 
								}
							}
							/*===============END=======================*/
							
							var amount      = (parseFloat(jml) * parseFloat(total_price).toFixed(9));
                            var ppn         = 0;
                            if($('#chk_taxtable').is(':checked')){
                                ppn = (parseFloat(amount) * (ppn10_pcnt / 100).toFixed(9));
                            }

                            n3.numberbox('setValue', amount);
                            n5.numberbox('setValue', ppn);
                            n6.numberbox('setValue', parseFloat(amount + ppn));
                            calculate_total();
                        }
                    }
                });
            },
            
            onEndEdit:function(rowIndex, rowData, changes){
                var item        = $('#dtg_item').datagrid('getRows');
                var sub_total   = 0;
				
				if('<?= in_array($detail->TransStatus,array(4))?>'){
					/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
					save_button_endedit(SavePrivillage);
					/*=================================end============================================================*/
				}
					
                $.each(item, function(index, value) {
                    if(value.ItemAmount != undefined){
                        sub_total+= parseFloat(value.ItemAmount);
                    }				
                });

                $('#txt_sub_total').numberbox('setValue', sub_total);
            }
        });
        
        
        $('#fm_receive_item').click(function(){
            $('#dtg_item').edatagrid('saveRow');
        });
        datagrid_item_type("dtg_item");//untuk warna grid
    });

    function calculate_total(){
        $('#dtg_item').edatagrid('saveRow');

        var item            = $('#dtg_item').datagrid('getRows');
        var sub_total       = 0;
        var sub_ppn10       = 0;
        var total_amount    = 0;

        $.each(item, function(index, value) {
            if(value.ItemAmount != undefined){
                sub_total       += parseFloat(value.ItemAmount);
                sub_ppn10       += parseFloat(value.ItemTaxPPn10);
                total_amount    += parseFloat(value.ItemTotalAmount);
            }				
        });

        $('#txt_sub_total').numberbox('setValue', sub_total);
        $('#txt_ppn10').numberbox('setValue', sub_ppn10);
        $('#txt_total_purchase').numberbox('setValue', total_amount);
    }
	
    function select_po(){
        var Vendor          = $('#cbg_vendor').combogrid('grid');   // get datagrid object
        var SelectedVendor  = Vendor.datagrid('getSelected');       // get the selected row
	
        if(SelectedVendor == null ){
            $.messager.alert('Maaf','Silahkan pilih Vendor dulu','warning');
        }
        else{
            modal_open('Select Purchase Orders', 'dialog-po');
        }		
    }
	
    function choose_po(){		
        flag	= true;
        po      = $('#tt_choose_po').datagrid('getSelected');		
        po_grid = $('#dtg_item').datagrid('getRows');
	
        if(po_grid.length >= 1){
            POrdNumber = $('#dtg_item').datagrid('getRows')[0].POrdNumber;
            
            if(po.POrdNumber!=POrdNumber){
                flag = false;
            }
        }
		
        if(flag == false){
            $.messager.alert('Maaf','Tidak bisa membuat Receive Item dari Purchase Order yang berbeda','error',function(){});
        }
        else{
            $('#dtg_item').datagrid('load',{
                Number: po.POrdNumber	
            });
			
            $('#txt_pord_no').val(po.POrdNumber);
            $('#txt_pord_date').val(po.POrdDate);
            $('#cbo_ship_via').combobox('setValue', po.ShipmentID);
            $('#cbo_terms').combobox('setValue', po.TermsPaymentID);
            $('#cbo_fob').combobox('setValue', po.FOBID);

            if (po.POrdTaxesStatus == 1) {$("#chk_taxtable").prop("checked", true);}
            if (po.POrdInTaxStatus == 1) {$("#chk_inclusive").prop("checked", true);}
			
            $('#txt_sub_total').numberbox('setValue', po.POrdSubTotal);
            $('#txt_ppn10').numberbox('setValue', po.POrdTaxes);
            $('#txt_total_purchase').numberbox('setValue', po.POrdTotalAmount);

            modal_close('dialog-po');
        }              
    }
	
	function app_reverse(){
		var no_transaksi    = $('#txt_prec_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_receive_item');
			}else{
			   $.messager.alert('Unseccessfull',check.message,'error',function(){
					location.reload();
				});
			}
		});
	}
	
	function approval() {
		var url_check           = '<?= base_url();?>custom/custom/checking_approval';
		var no_transaksi    	= $('#txt_prec_no').val();
		
		checking_approval(no_transaksi,function(check){
			if(check.status == false){
				var i       = $('#dtg_item').datagrid('getRows');
				var detail  = JSON.stringify(i);
		
				$("#detail").val(detail);
				approved_data('<?php echo $menu_link?>','#fm_receive_item');
			}else{
				$.messager.alert('Unseccessfull',check.message,'error',function(){
					location.reload();
				});
			}
		});
	}

	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_item.push(selectedrow.PRecDetailID);
						new_array_item.a.push(selectedrow.POrdDetailID);
                   		new_array_item.b.push(selectedrow.POrdQtyRI);
						new_array_item.c.push(selectedrow.ItemQty_Old);
						
						$("#detail_id").val(JSON.stringify(array_item));
						$("#detail_qty").val(JSON.stringify(new_array_item));
					
						$('#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============================================================*/
					}
				}
			);        
						
		}            
	}
	
    function update_data(){
		var url             = '<?= base_url();?>custom/custom/checking_update';
		var no_transaksi    = $('#txt_prec_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 i       = $('#dtg_item').datagrid('getRows');
		var detail  = JSON.stringify(i);

		$("#detail").val(detail);
		edit_transaction_check('<?=$menu_link?>','#fm_receive_item', no_transaksi, url, trans_status,created_by, login_as, job_title);
    }   
	
	function journal_tab(){
		ItemType = '<?php echo $detail->ItemType;?>';
		if(ItemType == '2'){
			$.messager.alert('Warning','Maaf untuk transaksi Advance Payment tidak mempunyai journal, silahkan membuat purchase invoice','info');
		}
		else{
			parent.tab_add('Journal <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_preview_journal/<?=$detail->PRecNumber?>');
		}
	}
	
	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_prec_no').val(), 'Receive Items', url, created_by, login_as, job_title);
	}

    function to_transaction(){

        var no_transaksi    = $('#txt_pord_no').val();
        var vendor_code     = $('#cbg_vendor').combogrid('getValue');
        var no_trans        = no_transaksi.replace(/\//g,"__");
        var vendor_code     = vendor_code.replace(/\//g,"__");

        checking_transstatus(no_transaksi,function(check){
            if(check.status == true){
                 parent.tab_add('New Purchase Invoice','list/purchases_invoice','icon-add','add/'+no_trans+'/'+vendor_code);
            }else{
                $.messager.alert('Unseccessfull',check.message,'error',function(){
                    location.reload();
                });
            }
        });
    }
</script>