<!---- 
    Author 	: Ladur
    Tanggal : 12-08-2014	
    Revisi 	: Fachri
-->

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

if($detail->SOrdTaxesStatus == 1) {
	$checked_chk_tax 		= "checked";	
	$style_chk_tax 			= "display:";	
	$style_chk_inclusive 	= "display:";

	if($detail->SOrdInTaxStatus == 1) {
		$checked_chk_inclusive = "checked";	
	}
	else {
		$checked_chk_inclusive = "";	
	}
}
else {
	$checked_chk_tax 		= "";	
	$style_chk_tax 			= "display:none";	
	$style_chk_inclusive 	= "display:none";
}?>

<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="37%">
                	<input type="checkbox" name="chk_suspended" id="chk_suspended" value="3" onClick="suspend(1);" style="margin-top:0px;margin-right:1px;" <?php if($detail->TransStatus == 3){ echo"checked"; } ?> <?=((!in_array($detail->TransStatus,array(0,6,4)))?"disabled":"")?> <?php echo $cek_autority_delete;?>/>
                    <span style="display:inline-block;margin-top:2px;<?=(($detail->TransStatus==3)?'color:gray;':'color:black')?>">Suspend</span>
                    <a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="parent.tab_add('Journal <?=$menu_label?>', '<?=$menu_link?>', 'icon-print', 'to_preview_journal/<?=$detail->DOrdNumber?>');" <?php echo $cek_autority_journal;?>>Journal</a>
                	<a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload()">Refresh</a>
                    <!-- <a href="#" class="easyui-linkbutton" iconCls="icon-currency" plain="true" onclick="to_transaction();" <?=in_array($detail->TransStatus,array(1))?'':'disabled';?>>To Sales Invoice</a> -->
                </td>
                <td align="center" width="33%"><span id="approval_information">
                <?php
				if($detail->TransStatus==4){
					if($this->session->userdata('jobtitle_status')==1){
						echo 'Need Your Approval';
					}
					else{
						echo 'Need Manager Approval';
					}
				}
				else if($detail->TransStatus==1){
					echo 'On Progress';
				}
				?>
                </span></td>
                <td align="right" width="30%">
                    <span class="form-title"><?=$menu_label?></span>							
                </td>
            </tr>
            </table>
        </div>			
    </div>
    <!-- End of top view -->
        
    <!-- center view -->
    <div id="form-body" data-options="region:'center',border:false">
        <div id="form-wrapper" class="easyui-panel" style="padding:5px;" fit="true">
        	<?php if(in_array($detail->TransStatus,array(2,3,9))){?>
        	<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_delivery_order" name="fm_delivery_order" method="post">
				<input type="hidden" name="detail" 		id="detail" />
				<input type="hidden" name="id" 			id="id" value="<?=$detail->DOrdNumber?>"/>	
                <input type="hidden" name="branch_code" id="branch_code" value="<?=$detail->BranchCode?>"/>
                <input type="hidden" name="detail_id" 	id="detail_id">
                <input type="hidden" name="detail_item" id="detail_item">
                <input type="hidden" name="number_unik" id="number_unik" value="<?=$detail->NumberUnik?>"/>
                <input type="hidden" min="0" name="do_total_amount" id="do_total_amount" class="easyui-numberbox" value="<?=$detail->DOrdTotalAmount;?>" 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;
                    }
                    " 
                />	
                <!-- Form Header -->
                <table width="100%" height="140" cellpadding="0" cellspacing="0">
                <tr>
                    <td width="50%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">
                        <tr height="20">
                            <td width="135"><b>Customer</b></td>
                            <td width="10"><b>:</b></td>
                            <td colspan="5">
                                <select class="easyui-combogrid" id="cmb_customer" 
                                    name="cmb_customer" required readonly 
                                    style="width:150px;height:20px;" 
                                    data-options="
                                        value:'<?=$detail->CustomerCode?>',
                                        panelWidth: 329,
                                        idField: 'CustomerCode',
                                        textField: 'CustomerName',
                                        url: '<?=base_url()?>custom/get_data/customer',
                                        method: 'get',
                                        columns: [[
                                            {field:'CustomerCode',title:'Customer Code',width:110,halign:'center'},
                                            {field:'CustomerName',title:'Customer Name',width:190,halign:'center'}
                                        ]],
                                        fitColumns: true
                                    "  
                                >
                                </select> 
                                <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-sales'" onClick="javascript:void(0)" disabled>Select SOrd.</a>
                                <?php
								if($detail->DirectStatus == 1){
								?>
                                	<input type="checkbox" name="chk_direct" id="chk_direct" onClick="" value="1" checked="checked" disabled>DO Direct
                                    <input type="hidden" name="txt_direct" id="txt_direct" value="<?php echo $detail->DirectStatus;?>" readonly>
                                <?php
                                }
								?>
                            </td>
                        </tr>
                        <tr id="rowRate">
                        	<!--<td><b>Currency Code/Rate</b></td>
                            <td><b>:</b></td>-->
                            <td colspan="5">
                            	<input type="hidden" name="txt_currency_code" id="txt_currency_code" value="<?=$detail->CurrencyCode?>" style="width:55px" required readonly />  
                                <input type="hidden" id="txt_rate" name="txt_rate" class="easyui-numberbox" value="<?=$detail->CurrencyRate?>" style="width:80px;text-align:right;" required readonly
                                	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                            	<span id="currency_code"></span>
                            </td>
                        </tr>
                        <tr height="20">
                            <td><b>Billing Address</b></td>
                            <td width="10"><b>:</b></td>
                            <td>&nbsp;</td>
                            <td width="120"><b>Shipping Address</b></td>
                            <td width="10"><b>:</b></td>
                            <td>&nbsp;</td>
                            <td width="114" rowspan="2">&nbsp;</td>
                        </tr>
                        <tr height="20">
                            <td colspan="3">
                                <textarea name="txa_address" id="txa_address" rows="4" style="width:225px;resize:none;" readonly><?=$detail->BillingAddress?></textarea>
                            </td>
                            <td colspan="3">
                                <textarea name="txa_ship_to" id="txa_ship_to" rows="4" style="width:225px;resize:none;" <?=($detail->TransStatus==4)?'':'readonly'?>><?=$detail->ShipAddress?></textarea>
                            </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;">DOrd. No.</td>
                            <td width="122" style="background:#333399;text-align:center;color:#FFF;">DOrd. Date</td>
                            <td width="122" style="background:#333399;text-align:center;color:#FFF;">Ship Via</td>
                        </tr>
                        <tr height="20">
                            <td height="20" width="100" align="center" valign="middle">
                            	<input type="text" name="txt_do_no" id="txt_do_no" class="easyui-validatebox textbox" value="<?=$detail->DOrdNumber?>" style="width:190px;height:18px;text-align:center" required readonly />
                            </td>
                            <td width="100" align="center" valign="middle">
                                <input name="txt_do_date" id="txt_do_date" type="text" class="easyui-datebox validBackward" style="width:170px;height:20px" required readonly editable="false" />
                            </td>
                            <td>
                                <select name="cmb_ship_via" id="cmb_ship_via" 
                                    class="easyui-combobox" editable="false" 
                                    <?=($detail->TransStatus==4)?'':'readonly'?>
                                    data-options="
                                        valueField:'ShipmentID',
                                        textField:'ShipmentName',
                                        url:'<?=base_url()?>custom/get_data/shipment'
                                    " 
                                    style="width:122px;height:20px;" required="true"
                                >
                                </select>
                            </td>
                        </tr>
                        <tr height="20">
                            <!-- <td>&nbsp;</td> -->
                            <td style="background:#333399;text-align:center;color:#FFF;">SOrd No.</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Ship Date</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Driver</td>
                        </tr>
                        <tr height="20">
                            <td><input type="text" name="txt_so_no" id="txt_so_no" class="easyui-validatebox textbox" value="<?=$detail->SOrdNumber?>" style="width:190px;height:18px;text-align:center;" required readonly /></td>
                            <td><input name="txt_ship_date" id="txt_ship_date" type="text" class="easyui-datebox validBackward" style="width:170px;height:20px;" required editable="false" <?=($detail->TransStatus==4)?'':'readonly'?> /></td>
                            <td><input type="text" name="txt_driver" id="txt_driver" class="easyui-validatebox" value="<?=$detail->DriverName?>" style="width:120px;" <?=($detail->TransStatus==4)?'':'readonly'?>  /></td>
                        </tr>
                        <tr height="20">
                            <?php if($detail->DirectStatus == 1):?>
                                <td style="background:#333399;text-align:center;color:#FFF;">Cust. POrd. No.</td>
                            	<td style="background:#333399;text-align:center;color:#FFF;">Company PO. No.</td>
                                <td style="background:#333399;text-align:center;color:#FFF;">License Plate</td>
                            <?php else:?>
                                <td></td>
                                <td style="background:#333399;text-align:center;color:#FFF;">Cust. POrd. No.</td>
                                <td style="background:#333399;text-align:center;color:#FFF;">License Plate</td>
                            <?php endif;?>
                            
                        </tr>
                        <tr height="20">
                            <?php if($detail->DirectStatus == 1):?>
                                <td><input type="text" name="txt_po_no" id="txt_po_no" class="easyui-validatebox textbox" value="<?=$detail->CustPONumber?>" style="width:190px;height:18px;text-align:center;" required readonly /></td>
                                <td>
                                	<select name="cmb_comp_po" id="cmb_comp_po" 
                                        class="easyui-combogrid" editable="false" <?=($detail->TransStatus==4)?'':'readonly'?>
                                        data-options="
                                        	value : '<?php echo $detail->CompPONumber;?>',
                                        	idField: 'POrdNumber',
                                            textField: 'POrdNumber',
                                            url: '<?=base_url()?>list/purchases_order/get_no_po_for_so',
                                            method: 'get',
                                            columns: [[
                                                {field:'POrdNumber',title:'Purchase Order Number Name',width:190,halign:'center'}
                                            ]]
                                        " 
                                        style="width:170px;height:20px;"
                                    >
                                    </select>
                                </td>
                                <td><input type="text" name="txt_car_number" id="txt_car_number" class="easyui-validatebox" value="<?=$detail->LicencePlate?>" style="width:120px;" <?=($detail->TransStatus==4)?'':'readonly'?> /></td>
                            <?php else:?>
                                <td>&nbsp;</td>
                                <td><input type="text" name="txt_po_no" id="txt_po_no" class="easyui-validatebox textbox" value="<?=$detail->CustPONumber?>" style="width:170px;height:18px;text-align:center;" required readonly /></td>
                                <td><input type="text" name="txt_car_number" id="txt_car_number" class="easyui-validatebox" value="<?=$detail->LicencePlate?>" style="width:120px;" <?=($detail->TransStatus==4)?'':'readonly'?> /></td>
                            
                            <?php endif;?>
                        </tr>
                        </table>
                    </td>
                </tr>
                </table>

                <!-- End of form header -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div id="tab_item" title="Items">
                        <table id="dg_item"  
                        	url="<?=base_url() . $menu_link .'/ajax_detail/'. $detail->DOrdNumber .'.'. $detail->BranchCode?>" 
							toolbar="#toolbar" idField="id"
							rownumbers="true" fitColumns="true" 
                            singleSelect="true" style="height:250px;"
                        >
							<thead>
                            <tr>
                                <!--<th field="SOrdNumber" width="40"  data-options="halign:'center',align:'left'">SO. Number</th>-->
                                <th field="DOrdDetailID" width="10" halign="center" align="left" hidden>DOrdDetailID</th>
                                <th field="SOrdDetailID" width="10" halign="center" align="left" hidden>SOrdDetailID</th>
                                <th field="SOrdNumber" 		width="10" halign="center" align="left" hidden>SOrd Number</th>
                                
                                <th field="ItemCategoryID" width="10" halign="center" align="left" hidden>Item Category ID</th>
                                <th field="ItemCode" width="30" halign="center" align="left" >Item</th>
                                <th field="ItemDesc" width="100" halign="center" align="left" >Description</th>
                                <th field="max_item" width="10" halign="center" align="left" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01}}" formatter="formatRp" hidden>Max</th>
                                <th field="ItemQty" width="10" halign="center" align="center" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01,required:true}}" formatter="formatRp">Qty</th>
                                <th field="ItemUnit" width="15" halign="center" align="center" editor="unit">Unit</th>
    
                                <th field="ItemPrice" width="20" halign="center" align="right" editor="{type:'numberbox',options:{decimalSeparator:',',groupSeparator:'.',min:0,required:true,readonly:true,
                                
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                
                                }}" hidden>Item Price</th>
                                <th field="ItemAverage" width="20" halign="center" align="right"
                                editor="{type:'numberbox',options:{decimalSeparator:',',groupSeparator:'.',min:0,required:true,readonly:true,
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                
                                }}" hidden>Item Average</th>
                                <th field="TotalAmount" width="20" data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{decimalSeparator:',',groupSeparator:'.',min:0,required:true,readonly:true,
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                
                                }}" hidden>Total Amount</th>
                                
                                <th field="ItemTax" width="20" data-options="halign:'center',align:'center'" editor="{type:'numberbox',options:{decimalSeparator:',',groupSeparator:'.',min:0,required:true,readonly:true,
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                
                                }}" hidden>Item Tax</th>
                                
                                <th field="ItemQtyDO" width="20" halign="center" align="left" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01}}" formatter="formatRp" hidden>ItemQtyDO</th>
                                <th field="LastQtyDO" width="20" halign="center" align="left" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01}}" formatter="formatRp" hidden>LastQtyDO</th>
                                <th field="RowStatus" width="10" halign="center" align="center" hidden>Row Status</th>
                                <th field="ItemQtySO" width="20" halign="center" align="left" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01}}" formatter="formatRp"hidden>Item Qty SO</th>
                                <th field="ItemQtySpd" width="20" halign="center" align="left" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',min:0.01}}" formatter="formatRp" hidden>Item Qty Spd</th>
                                <th field="ItemStatus"       width="30"  editor="{type:'item_status',options:{readonly:true}}" hidden>Item Status</th>
                                <th field="ItemCategoryCode" width="10" data-options="halign:'center',align:'center'" hidden>Item Category Code</th>
                                <th field="ItemDiscPcnt"   width="40"  data-options="align:'right',halign:'center'"  editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',min:0}}" formatter="formatRp" hidden>Discount %</th>
                            	<th data-options="field:'AmountDisc',width:20,halign:'center',align:'center'" editor="{type:'numberbox',options:{decimalSeparator:',',groupSeparator:'.',min:0,required:true,readonly:true,
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                }}" hidden>Amount Disc</th>
                                <th field="SalesmanCode" width="10" data-options="halign:'center',align:'center'" hidden>Salesman Code</th>
                                <th data-options="field:'Item_pph23',width:20,halign:'center',align:'center'" editor="{type:'numberbox',options:{decimalSeparator:',',groupSeparator:'.',min:0,required:true,readonly:true,
                                formatter:function(v){
                                    return v;
                                },
                                parser:function(s){
                                    var v = parseFloat(s);
                                    return v;
                                }
                                }}" hidden>Tax PPH 23</th>
                            </tr>
							</thead>
						</table>
                        
                        <div id="toolbar">
                            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row()" <?=(in_array($detail->TransStatus,array(0,4)))?'':'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 width="120" valign="top" style="padding-top:4px;"><b>Description</b></td>
                            <td width="10" valign="top" style="padding-top:4px;"><b>:</b></td>
                            <td>
                            	<textarea id="txa_description" name="txa_description" rows="4" style="width:323px;resize:none;" <?=($detail->TransStatus==4)?'':'readonly'?>><?=$detail->DOrdDesc?></textarea>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">
                    	<input type="hidden" name="hdn_taxable" id="hdn_taxable" value="<?=$detail->SOrdTaxesStatus?>" />
                        <input type="hidden" name="hdn_inclusive" id="hdn_inclusive" value="<?=$detail->SOrdInTaxStatus?>" />
                       <input type="text" name="hdn_sub_total" id="hdn_sub_total" class="easyui-numberbox" 
                        data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                        formatter:function(v){
                            return v;
                        },
                        parser:function(s){
                            var v = parseFloat(s);
                            return v;
                        }
                        " 
                        hidden/>
                        <input type="hidden" name="hdn_ppn_pcnt" id="hdn_ppn_pcnt" value="<?=$detail->SOrdTaxPcnt?>" />
                        <input type="text" name="hdn_ppn" id="hdn_ppn" class="easyui-numberbox" 
                        data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                        formatter:function(v){
                            return v;
                        },
                        parser:function(s){
                            var v = parseFloat(s);
                            return v;
                        }
                        " 
                        hidden/>

                        <input type="text" name="hdn_pph23" id="hdn_pph23" class="easyui-numberbox" value="<?=$detail->SOrdPPh23?>"
                        data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                        formatter:function(v){
                            return v;
                        },
                        parser:function(s){
                            var v = parseFloat(s);
                            return v;
                        }
                        " 
                        hidden/>
                       
                       <input type="text" name="hdn_total_amount" id="hdn_total_amount" class="easyui-numberbox" 
                       data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                        formatter:function(v){
                            return v;
                        },
                        parser:function(s){
                            var v = parseFloat(s);
                            return v;
                        }
                        " 
                       hidden/>
                      <input type="text" name="hdn_amont_disc" id="hdn_amont_disc" class="easyui-numberbox" 
                     data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                        formatter:function(v){
                            return v;
                        },
                        parser:function(s){
                            var v = parseFloat(s);
                            return v;
                        }
                        " 
                     hidden/>
                        <input type="hidden" name="branch_code" id="branch_code" value="<?=$detail->BranchCode?>" />
                    </td>
               	</tr>
                </table>
            </form>
    	</div>
    </div>
    
    <div id="form-footer" data-options="region:'south',border:false">
    	<table width="100%" cellpadding="0" cellspacing="0">
        <tr>
        	<td>&nbsp;</td>
            <td align="right">
            	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-document" onclick="show_legend();" plain="true">Legend</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-help" plain="true">Help</a>
                <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-ok" onclick="approval_do()" <?=($detail->TransStatus==4 and $this->session->userdata('jobtitle_status')==1)?'':'disabled'?>>App. Mgr</a>					
                <?php
				if($group_user->ReversePrivillage == 1){
				?>
                	<a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-reload" onclick="app_reverse()" <?=(in_array($detail->TransStatus,array(0,3,5,4,7,9)))?'disabled':''?>>Reverse</a>
                <?php	
				}
				?>
                <a id="save_button" href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="update_data()" <?=(!in_array($detail->TransStatus,array(0,4)))?'disabled':''?> <?php echo $cek_autority_save;?>>Save</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->DOrdNumber?>');" <?=(in_array($detail->TransStatus,array(1,3,2,4,5,6)))?'':'disabled'?>>Preview & Print</a>
                <a href="javascript:void(0)" class="easyui-linkbutton  form-button" iconCls="icon-cancel" onclick="<?=($this->session->userdata('jobtitle_status')==0)?'suspend(2)':'parent.tab_close(\'tt\')'?>" <?=($this->session->userdata('jobtitle_status')==0 && !in_array($detail->TransStatus,array(0,4,7)))?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
    		</td>
        </tr>
        </table>
    </div>
</div>
<?php $this->load->view('v_custom_pop_up');?>
<script type="text/javascript">
/*========================deklar variabel array for remove===================*/
var array_item 			= [];
var new_array_item 		= {'a':[],'b':[],'c':[],'d':[],'e':[]};
/*==============================end=========================================*/
var SavePrivillage 		= '<?php echo $group_user->SavePrivillage;?>';
var TransStatus 		= '<?php echo $detail->TransStatus;?>';

$(document).ready(function(){
	$('#cmb_ship_via').combobox('select','<?=$detail->ShipmentID?>');
	$('#txt_do_date').datebox('setValue','<?=convert_to_dmy($detail->DOrdDate)?>');
	$('#txt_ship_date').datebox('setValue','<?=convert_to_dmy($detail->ShipDate)?>');
	
	$('#fm_delivery_order').click(function(){
		$('#dg_item').edatagrid('saveRow');
	});
	
	$('#dg_item').edatagrid({
		rowStyler:function(index,value){
			if(value.RowStatus==3){
				return 'background:#DADADA;';
			}
		},
		onLoadSuccess:function(){
			dtg_item = $('#dg_item').datagrid('getRows');
			AmountDisc 		= 0;
			
			$.each(dtg_item,function(index,value){
				AmountDisc 		= (parseFloat(value.ItemQty * value.ItemPrice) * (parseFloat(value.ItemDiscPcnt / 100)));
				
				$('#dg_item').datagrid('updateRow',{
					index: index, 
					row:{
						AmountDisc: AmountDisc
					}
				});
			});
			calculate_sub();
		},
		onBeginEdit:function(rowIndex){
			var editors	= $('#dg_item').datagrid('getEditors', rowIndex);
			var n1 		= $(editors[1].target); // Item Qty
			var n2 		= $(editors[0].target); // Max Item
			var n3 		= $(editors[3].target); // Item Price
			var n4 		= $(editors[5].target); // Total Amount
			var n5		= $(editors[6].target); // Tax Amount
			var n6		= $(editors[12].target); // Item Disc
			var n7		= $(editors[13].target); // Amount Disc
			
			save_button_begendedit(SavePrivillage);
			
			if((TransStatus == 1) || (TransStatus == 2)){
				n1.prop('readonly',true);
			}
			else{
				n1.prop('readonly',false);
			}
			
			n1.numberbox({
				onChange:function(){
					var price 	= n3.numberbox('getValue');
					var qty 	= n1.numberbox('getValue');
					var disc    = n6.numberbox('getValue');
					
					if(parseFloat(n1.numberbox('getValue')) > parseFloat(n2.numberbox('getValue'))) {
						$.messager.alert('Unseccessfull','Qty tidak boleh lebih dari (' + n2.numberbox('getValue') + ')','error',function(){
							location.reload();
						});
					}else {
						ppn_pcnt = parseFloat($('#hdn_ppn_pcnt').val());
						
						/*
							Harga dikurangi discount
						*/
						var total_disc 		= parseFloat((qty * price) * (disc / 100));
						var total_price 	= (parseFloat(price) - (parseFloat(price) * disc / 100)); 
						/*====================End===============================*/
						
						/*
							Jika dia inclusive
						*/
						if($('#hdn_taxable').val() == 1){
							 if($('#hdn_inclusive').val() == 1){
								total_price 	= parseFloat((100 / (100 + ppn_pcnt) * total_price)); 
							}
						}
						/*===============END=======================*/
						
						var amount          = parseFloat(qty) * parseFloat(total_price);
                        var ppn             = 0;
						
						if($('#hdn_taxable').val()==1){
							ppn = parseFloat(amount) * (ppn_pcnt / 100);
						}
						
						n4.numberbox('setValue', amount);
						n5.numberbox('setValue', ppn);
						n7.numberbox('setValue', total_disc);
						
						$('#dg_item').edatagrid('saveRow');
						calculate_sub();
					}
				}
			});
		},
		onEndEdit:function(rowIndex, rowData, changes){
			var item 			= $('#dg_item').datagrid('getRows');
			var do_total_amount = 0;
			var item_tax 		= 0;
			
			$.each(item, function( index, value ) {
				do_total_amount		+= parseFloat(value.TotalAmount);	
				item_tax			+= parseFloat(value.ItemTax);			
			});
			
			$('#do_total_amount').numberbox('setValue', (do_total_amount + item_tax));
			
			if((TransStatus == 4)){
				save_button_endedit(SavePrivillage);
			}
		}
	});

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

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

function approval(no_transaksi){
	var item = $('#dg_item').datagrid('getRows');

	if(item){
		var direc_status_do 	= '<?php echo $detail->DirectStatus;?>'; 
		var id					= $('#id').val();
		var txt_currency_code	= $('#txt_currency_code').val();
		var txt_rate			= $('#txt_rate').numberbox('getValue');
		var hdn_sub_total		= $('#hdn_sub_total').numberbox('getValue');
		var hdn_ppn_pcnt 		= $('#hdn_ppn_pcnt').val();
		var hdn_ppn				= $('#hdn_ppn').numberbox('getValue');
        var hdn_pph23             = $('#hdn_pph23').numberbox('getValue');

		var hdn_total_amount 	= $('#hdn_total_amount').numberbox('getValue'); 
		var txt_so_no 			= $('#txt_so_no').val(); 
		var branch_code 		= $('#branch_code').val(); 
		var txt_direct			= $('#txt_direct').val();
		var number_unik			= $('#number_unik').val();
		
		if(direc_status_do == 1){
			var cmb_comp_po 	= $('#cmb_comp_po').combogrid('getValue'); 
		}
		
		var txt_do_date 		= $('#txt_do_date').datebox('getValue');
		var txt_ship_date 		= $('#txt_ship_date').datebox('getValue');
		 
		var txa_description 	= $('#txa_description').val();
		var hdn_amont_disc 		= $('#hdn_amont_disc').numberbox('getValue'); 
		detail 					= JSON.stringify($('#dg_item').datagrid('getRows'));
		var url     			= base_url + 'list/delivery_order/approval';
		
		$.post(url, {txt_ship_date:txt_ship_date, id:id, txt_currency_code:txt_currency_code, txt_rate:txt_rate, hdn_sub_total:hdn_sub_total, hdn_ppn_pcnt:hdn_ppn_pcnt, hdn_ppn:hdn_ppn, hdn_total_amount:hdn_total_amount, txt_so_no:txt_so_no, branch_code:branch_code, txt_direct:txt_direct, cmb_comp_po:cmb_comp_po, txt_do_date:txt_do_date, txa_description:txa_description, hdn_amont_disc:hdn_amont_disc, detail:detail, number_unik:number_unik,hdn_pph23:hdn_pph23}, function(result){
			if (result.status == true){
				$.messager.alert('Success',result.message,'info',function(){
                    $.messager.confirm('Confirm', 'Apakah anda ingin membuat variant ?', function (r) {
                        if (r){
                            parent.tab_add('New Variant','<?=$menu_link?>', 'icon-add', 'to_variant/'+no_transaksi);     	
                        }else{
                            location.reload();
                        }
                    });
                });				
			} 
			else {
				$.messager.alert('Error',result.message,'error',function(){
					location.reload();						                    
				});				
			}
		},'json');
	}
}

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

function update_data() {
	//$('#dg_item').edatagrid('saveRow');	
	var url             	= '<?= base_url();?>custom/custom/checking_update';
	var no_transaksi    	= $('#txt_do_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');?>';
		
	var i		= $('#dg_item').datagrid('getRows');
	var detail	= JSON.stringify(i);
	
	$("#detail").val(detail);
	edit_transaction_check('<?=$menu_link?>','#fm_delivery_order', no_transaksi, url, trans_status,created_by, login_as, job_title);
}

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_do_no').val(), 'Delivery Orders', url, created_by, login_as, job_title);
}

function calculate_sub(){
	$('#dg_item').edatagrid('saveRow');

	var item        = $('#dg_item').datagrid('getRows');
	var sub_total   = 0;
	var toal_disc   = 0;
	
	$.each(item, function(index, value) {
		if(value.TotalAmount != undefined){
			sub_total+= parseFloat(value.TotalAmount);
			toal_disc+= parseFloat(value.AmountDisc);
		}				
	});
	
	$('#hdn_sub_total').numberbox('setValue', sub_total);
	$('#hdn_amont_disc').numberbox('setValue',toal_disc);
	
	calculate();
}

//calculating
function calculate(){
	$('#dg_item').edatagrid('saveRow');
	
	var SInvSubTotal 	= $('#hdn_sub_total').numberbox('getValue');
	var SInvTotalAmount = 0;
	var SInvTaxes 		= 0;
	var SInvTaxPcnt 	= parseFloat($('#hdn_ppn_pcnt').val());
	
	if($('#hdn_taxable').val()==1){
		SInvTaxes = parseFloat(SInvSubTotal) * (SInvTaxPcnt / 100);
	}
	SInvTotalAmount = parseFloat(SInvSubTotal) + parseFloat(SInvTaxes);
	
	$('#hdn_ppn').numberbox('setValue', SInvTaxes);
	$('#hdn_total_amount').numberbox('setValue', SInvTotalAmount);
}

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

	if(item <= 1){
		$.messager.alert('Warning','Anda tidak dapat menghapus list item, minimum list item adalah satu (1)','error');
	}
	else {
		var selectedrow     = $('#dg_item').datagrid('getSelected');
		var row_index       = $('#dg_item').datagrid('getRowIndex', selectedrow);

		$.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.ItemCode + '"',  
			function(r){
				if (r){
					array_item.push(selectedrow.DOrdDetailID);
					
					new_array_item.a.push(selectedrow.SOrdDetailID);
                   	new_array_item.b.push(selectedrow.ItemQtyDO);
					new_array_item.c.push(selectedrow.LastQtyDO);
					new_array_item.d.push(selectedrow.ItemQty);
					new_array_item.e.push(selectedrow.ItemCode);
					
                   	$("#detail_id").val(JSON.stringify(array_item));
					$("#detail_item").val(JSON.stringify(new_array_item));
                   	$('#dg_item').datagrid('deleteRow', row_index);	
					
					save_button_endedit(SavePrivillage);
					
					/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
					$('.app-button').linkbutton('disable');
					/*=================================end============================================================*/
				}
			}
		);        
					
	}            
}

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

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

function to_sales_invoice(){
	
	if(TransStatus == 1){
		$.messager.alert('Warning','Transaksi sudah di approve silahkan lihat list Sales Invoice dengan No Delivery Order : '+$('#txt_do_no').val()+'','info');
	}
	else{
		$.messager.alert('Warning','Silahkan Approve transaksi, Invoice terbentuk setelah di approve','info');
	}
}

</script>