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

<?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----------------------------

$detail->TransStatus;
$detail->AppLimitStatus;
$detail->SOrdTotalDP;
$detail->SRecTotalDP;
?>

<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(7,6,4)))?"disabled":"")?> <?php echo $cek_autority_delete;?>/>
                    <span style="display:inline-block;margin-top:2px;<?=((in_array($detail->TransStatus,array(0,3)))?'color:gray;':'color:black')?>">Suspend</span>
                    
                    <!--<span class="form-suspend">
                        <input type="checkbox" class="input" name="chk_suspended" id="chk_suspended" value="1" onclick="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->SRecTotalDP==0)?'suspend(1)':'return false;'?>" style="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->SRecTotalDP==0)?'':'opacity:0.5;'?>" <?php echo $cek_autority_delete;?>/>
                        <span class="text" style="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->SRecTotalDP==0)?'':'color:gray;'?>"><?=(($detail->TransStatus!=3)?"Suspend":"Un-Suspend")?> </span>
                    </span>-->
                    
                    <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 Delivery Order</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==7){
					if($this->session->userdata('jobtitle_status')==0 && $this->session->userdata('jobtitle')==$app_over_limit_by){
						echo 'Need Your Approval';
					}
					elseif($this->session->userdata('jobtitle_status')==1 && $this->session->userdata('jobtitle')==$app_over_limit_by){
						echo 'Need Your Approval';
					}
					else{
						if($app_over_limit_by=='DIR'){
							echo 'Need Director Approval';
						}
						elseif($app_over_limit_by=='MGR'){
							echo 'Need Manager Approval';
						}
						elseif($app_over_limit_by=='BM'){
							echo 'Need Branch Manager Approval';
						}
						elseif($app_over_limit_by=='SPV'){
							echo 'Need Supervisor Approval';
						}
						elseif($app_over_limit_by=='RM'){
							echo 'Need Regional Manager Approval';
						}
						elseif($app_over_limit_by=='GM'){
							echo 'Need General Manager Approval';
						}
						elseif($app_over_limit_by=='CEO'){
							echo 'Need CEO Approval';
						}
						elseif($app_over_limit_by=='SPV'){
							echo 'Need Supervisor Approval';
						}
						else{
							echo 'Preferences Approval Limit Not Complete';
						}
					}
				}
				else if($detail->TransStatus==0){
					echo 'Waiting For Down Payment';
				}
				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,8))){ ?>
        	<div class="blanket"></div>
            <div class="status-box"><b><?php if($detail->TransStatus==2){ echo 'Finished'; }elseif($detail->TransStatus==3){ echo 'Suspended'; }elseif($detail->TransStatus==9){ echo 'Canceled by Dir.'; }elseif($detail->TransStatus==8){ echo 'Suspended Item'; }else{ echo 'Unknown'; } ?></b></div>
            <?php } ?>
            
        	
            <form id="frm_sales_order" name="frm_sales_order" method="post">
                <input type="hidden" name="detail" id="detail" />
                <input type="hidden" name="txt_dp_status_hidden" id="txt_dp_status_hidden" value="<?=$detail->SOrdDPStatus?>"/>
                <input type="hidden" name="detail_id" id="detail_id">
                <input type="hidden" name="detail_qty" id="detail_qty">
                <input type="hidden" name="hdn_pph23_pcnt" id="hdn_pph23_pcnt" value="<?php echo $detail->SOrdPPh23Pcnt;?>" />
                <!-- 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:155px;height:20px;" 
                                    data-options="
                                    	value:'<?=$detail->CustomerCode?>',
                                        panelWidth: 320,
                                        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="select_sq()" disabled>Select SQ</a> 
                                
                                <input type="checkbox" name="chk_taxtable" id="chk_taxtable" onClick="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'hideppn()':'return false;'?>" value="1" style="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'opacity:0.5;'?>" <?= in_array($detail->TransStatus,array(0,1,2,3,9)) ? 'disabled' : '' ?>> Taxable
                                <span class="disableme" style="display:none;">
                                    <input type="checkbox" name="chk_inclusive" id="chk_inclusive" onClick="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'calculate_item_intax()':'return false;'?>" value="1" style="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'opacity:0.5;'?>" <?= in_array($detail->TransStatus,array(0,1,2,3,9)) ? 'disabled' : '' ?>> Inclusive Tax
                                </span>
                            </td>
                        </tr>
                        <tr id="rowRate">
                        	<td><b>Currency Rate</b></td>
                            <td><b>:</b></td>
                            <td colspan="5">
                            	<input type="hidden" id="hdn_currency_code" name="hdn_currency_code" value="<?=$detail->CurrencyCode?>" />
                                <input type="numberbox" id="txt_rate" name="txt_rate" class="easyui-numberbox" value="<?=$detail->CurrencyRate?>" style="width:90px;text-align:right;" required
                                	<?php 
									if($detail->CurrencyCode == 'IDR'){
										echo 'readonly';
									}
									else{
										echo (in_array($detail->TransStatus,array(0,4,7)) and ($detail->AppLimitStatus==0) and ($detail->SRecTotalDP==0))?'':'readonly';
									}
									?>
                                    data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                            	<span id="spn_currency"><span id="spn_cust_curr"><?=$detail->CurrencyCode?></span> / IDR</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;" <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'readonly'?>><?=$detail->ShippingAddress?></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"><input type="checkbox" id="chk_payment_dp" name="chk_payment_dp" onclick="<?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'hidedp()':'return false;'?>" value="1" style="<?=(in_array($detail->TransStatus,array(0,4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'opacity:0.5;'?>" <?= in_array($detail->TransStatus,array(0,1,2,3,9)) ? 'disabled' : '' ?>/> Customer needs DP</td>
                            <td width="190" style="background:#333399;text-align:center;color:#FFF;">SOrd. No.</td>
                            <td width="122" style="background:#333399;text-align:center;color:#FFF;">SOrd. Date</td>
                            <td width="122" style="background:#333399;text-align:center;color:#FFF;">FOB</td>
                        </tr>
                        <tr height="20">
                            <td height="20" width="100" align="center" valign="middle">
                                <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 width="100" align="center" valign="middle">
                                <input name="txt_so_date" id="txt_so_date" type="text" class="easyui-datebox validBackward" style="width:122px;height:20px" required editable="false" readonly  />
                            </td>
                            <td>
                            	<select class="easyui-combogrid" required="required"
                                    name="cmb_fob" id="cmb_fob" 
                                    style="width:122px;height:20px;" 
                                    <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'disabled'?>
                                    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;">SQuo. No.</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">SQuo. Date</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Terms</td>
                        </tr>
                        <tr height="20">
                            <td><input name="txt_sq_no" id="txt_sq_no" type="text" class="textbox" value="<?php echo $detail->SQuoNumber; ?>" style="width:190px;height:18px;text-align:center;" required readonly /></td>
                            <td><input name="txt_sq_date" id="txt_sq_date" type="text" class="textbox" value="<?=$detail->SQuoDate?>" style="width:120px;height:18px" required readonly /></td>
                            <td>
                                <select class="combo-grid" required="required"
                                    name="cmb_terms" id="cmb_terms" 
                                    style="width:122px;height:20px;" 
                                    <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'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;">Cust. POrd. No.</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Ship Date</td>
                            <td style="background:#333399;text-align:center;color:#FFF;">Ship Via</td>
                        </tr>
                        <tr height="20">
                            <td><input name="txt_po_no" id="txt_po_no" type="text" class="textbox" value="<?php echo $detail->CustPONumber; ?>" 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:122px;height:20px;" required editable="false" <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'readonly'?> /></td>
                            <td>
                                <select class="combo-grid" required="required"
                                    name="cmb_ship_via" id="cmb_ship_via" 
                                    style="width:122px;height:20px;" 
                                    <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'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>
<!--class="easyui-<?=(in_array($detail->TransStatus,array(0,4,7,1)) and ($detail->SRecTotalDP==0))?'edatagrid':'datagrid'?>" -->
                <!-- End of form header -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div id="tab_item" title="Items">
                        <table id="dtg_item" 
                        	toolbar="#toolbar" idField="id" 
                        	rownumbers="true" fitColumns="true" 
                        	singleSelect="true" style="height:250px;" 
                        	url="<?=base_url() . $menu_link . "/ajax_item_for_edit/" . $detail->SOrdNumber?>" 
                        >
                            <thead>
                            <tr>
                                <th width="60"  halign="center" field="SQuoNumber" 		align="left" editor="{type:'text'}">SQuo. No.</th>
                                <th width="60"  halign="center" field="SQuoDate" 		align="left" hidden>SQuo. Date.</th>
                                <th width="60"  halign='center' field='CustPONumber' 	data-options="align:'left'" hidden>Vendor No.</th>
                                <th width="60"  halign='center' field='SQuoDesc' 		data-options="align:'left'" hidden>SQuo Desc.</th>
                                
                                <th width="40"  halign="center" field="ItemCode" 		align="left" 	editor="{type:'item',options:{required:true,readonly:true}}">Item Code</th>
                                <th width="130" halign="center" field="ItemDesc" 		align="left" 	editor="description">Description</th>
                                <th width="30"  halign="center" field="ItemQty" 		align="center" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, min:0.01}}" formatter="formatRp">Qty</th>
                                
                                <th width="30"  halign="center" field="ItemUnit" 		align="center" 	editor="unit">Unit</th>
                                <th width="40"  halign="center" field="ItemPrice" 		align="right" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Item Price</th>
                                <th width="40"  halign='center' field="ItemDisc" 		data-options="align:'right'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp" >Discount %</th>
                                <th width="40"  halign="center" field="ItemAmount" 		align="right" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Amount</th>	
                                <th width="30"  halign="center" field="ItemQtyDO" 		align="center" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, disabled:true}}" formatter="formatRp" >Qty DO</th>
                                <th width="35"  halign="center" field="Status"  		align="center" 	editor="{type:'checkbox',options:{on:'Yes',off:'No'}}">Close</th>
                                
                                <th width="50"  halign="center" field="ItemQtySpd" 		align="center" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',disabled:true}}" formatter="formatRp" >Qty Suspend</th>
                                
                                <th width="60"  halign="center" field="EmployeeName" 	align="left" 	hidden="true">Salesman</th>
                                
                                <th width="50"  halign="center" field="SalesmanCode" 	align="left" 	hidden>Salesman Code</th>
                                <th width="20"  halign="center" field="ItemMax" 		align="center" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, disabled:true}}" formatter="formatRp" hidden>Item Max</th>
                                <th width="30"  halign="center" field="IntaxStatus" 	align="center" 	editor="{type:'numberbox',options:{min:0}}" hidden>InTax</th>
                                <th width="50"  halign="center" field="ItemTax" 		align="right" 
                                editor="{type:'numberbox',options:{decimalSeparator:',',
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                }}"
                                hidden>Item Tax</th>
                                
                                
                                <th width="10"  halign="center" field="SQuoDetailID" 	align="left" 	hidden>SQ ID</th>
                                <th width="10"  halign="center" field="SOrdDetailID" 	align="left" 	hidden>SO ID</th>
                                <th width="30"  halign="center" field="TempQty" 		align="center" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, disabled:true}}" formatter="formatRp" hidden>Temp Qty</th>
                                <th width="30"  halign="center" field="ItemQtySQ" 		align="center" 	formatter="formatRp" hidden>ItemQtySQ</th>
                                <th width="50"  halign="center" field="RowStatus" 		align="center" editor="{type:'numberbox'}" hidden>Status</th>
                                <th width="40"  halign='center' field="ItemCategoryID" 	data-options="align:'right'" editor="{type:'numberbox',options:{required:true,disabled:true}}" hidden>Item Category ID</th>
                                <th width="40"  halign='center' field="ItemCategoryCode" data-options="align:'right'" editor="{type:'text',options:{required:true,disabled:true}}" hidden>Item Category Code</th>
                                <th width="40"  halign="center" field="ItemAmountKoma" 	align="right" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" hidden >Amount Koma</th>
                                <th width="50"  halign="center" field="ItemTaxKoma" 	align="right" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:','}}" hidden>Item Tax Koma</th>
                                <th width="30"  halign="center" field="ItemStatus" 		editor="{type:'item_status',options:{readonly:true}}" hidden>Item Status</th>	
								
                                <!--
                                	Item Price hide loss tidak ada koma
                                    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="ItemPrice_Hide"  	editor="{type:'numberbox',options:{decimalSeparator:',',
                                formatter:function(v){
                                	return v;
                                },
                                parser:function(s){
                                	var v = parseFloat(s);
                                    return v;
                                }
                                }}" hidden>Item Price</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</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>
                                
                                <!---------------------------end------------------------------------>
                            </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(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'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 name="txa_description" id="txa_description" rows="4" style="width:323px;resize:none;" <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'readonly'?>><?=$detail->SOrdDesc?></textarea>
                            </td>
                        </tr>
                        <!-- <tr>
                            <td width="120" valign="top" style="padding-top:4px;"><b>Over Limit</b></td>
                            <td width="10" valign="top" style="padding-top:4px;"><b>:</b></td>
                            <td>
                                <input type="numberbox" name="txt_limit" id="txt_limit" value="" class="easyui-numberbox" 
                                    data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" style="text-align:right;" readonly
                                    
                                />
                            </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" value="0" class="easyui-numberbox dp currency" 
                                    	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" style="text-align:right;" 
                                    	<?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'readonly'?>
                                    />
                                </span>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">
                        <tr>
                            <td rowspan="6">&nbsp;</td>
                            <td width="120"><b>Sub Total</b></td>
                            <td width="10"><b>:</b></td>
                                <td width="171">
                                <input type="numberbox" id="sub_total" name="sub_total" value="0" class="easyui-numberbox" style="text-align:right;" readonly
                                	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                                
                                <input type="hidden" id="sub_total_hide" name="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="<?=$detail->SOrdDiscount?>" style="text-align:right;" 
                                    data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                    
                                    readonly
                                />
                            </td>
                        </tr>
                        
                        <tr>
                            <td><b>PPN (<?=$detail->SOrdTaxPcnt?>%)</b></td>
                            <td><b>:</b></td>
                            <td>
                                <input type="text" min="0" name="ppn" id="ppn" class="easyui-numberbox" value="<?=$detail->SOrdTaxes?>" style="text-align:right;" readonly 
                                    data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"
                                />
                                
                                <input type="hidden" min="0" name="ppn_hide" id="ppn_hide" class="easyui-numberbox" value="0" 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;
                                    }
                                    " 
                                />
                                
                                <input type="hidden" name="txt_ppn_rate" value="<?=$taxes_ppn10->TaxesRate?>" />
                            </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>Total Sales</b></td>
                            <td><b>:</b></td>
                            <td>
                                <input type="text" name="total_purchase" id="total_purchase" class="easyui-numberbox" value="<?=$detail->SOrdTotalAmount?>" style="text-align:right;" readonly 
                                     data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"
                                />
                                
                                <input type="hidden" min="0" name="total_purchase_hide" id="total_purchase_hide" class="easyui-numberbox" value="0" 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>
            	<b>Old SOrd. No. : </b>
                <?=$detail->OldSOrdNumber?>
            </td>
            
        	<td align="center">
            		<!--<b>Over DueDays :</b> -->
				<?php 
					echo ' ';
				?>
            	<!--
            	<span><b>Down Payment :: </b></span>
                <span id="total_owning">1.000.000.000,00</span>
                <span><b>DP Used :: </b></span>
                <span id="dp_used">0</span>
                <span><b>Available DP :: </b></span>
                <span id="available_dp">0</span>
                -->
                <input type="hidden" id="txt_ppay_total_dp" value="<?=$detail->PPayTotalDP?>" />
            </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>
				<?php
				if($detail->TransStatus==7){
				?>
            	<!-- <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" id="btn_app_limit" iconCls="icon-ok" onclick="approval()" <?=(($app_over_limit==true))?'':'disabled'?>>App. Limit</a> -->
                <?php
				}
				if($this->session->userdata("jobtitle_status")==0){
				?>
                	<a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-ok" onclick="approval_bypass_dp(1)" <?=($detail->TransStatus==0)?'':'disabled'?> >ByPass DP.</a>
                <?php
				}
				?>
                <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-ok" onclick="approval_so(1)" <?=($this->session->userdata("jobtitle_status")==1 and $detail->TransStatus==4)?'':'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" id="save_button" iconCls="icon-save" style="" onclick="update_data()" <?=(in_array($detail->TransStatus,array(4,7)) and $detail->AppLimitStatus==0 and $detail->SRecTotalDP==0)?'':'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->SOrdNumber?>');" <?=(in_array($detail->TransStatus,array(0,1,2,3,9,8,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>

<!-- Dialog Button -->
<div id="dialog-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_item_sq()">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-sq')">Cancel</a>
</div>

<div id="dialog-confirm-cancel-dp" class="easyui-dialog" 
	style="background-color:#F8F8F8;padding:0px;" closed="true" 
    data-options="modal:true, iconCls:'icon-edit'" button="#dialog-buttons"
>
	<table width="100%" cellpadding="0" cellspacing="0">
    <tr>
    	<td width="120"><b>Jumlah DP</b></td>
        <td width="10"><b>:</b></td>
        <td>
        	<input type="text" name="txt_ppay_total_dp" value="<?=$detail->PPayTotalDP?>" style="width:250px;height:20px;" readonly />
        </td>
     </tr>
     <tr>
    	<td width="120"><b>Bank Account</b></td>
        <td width="10"><b>:</b></td>
        <td>
        	<select class="easyui-combogrid" name="cmb_bank" id="cmb_bank" style="width:250px;height:22px;" required editable="false"
                data-options="
                    panelWidth:250,
                    idField: 'AccountNumber',
                    textField: 'AccountName',
                    url: '<?=base_url()?>list/purchases_payment/ajax_bank_account',
                    method: 'post',
                    columns: [[
                    	{field:'AccountName',title:'Bank Name',width:100, halign:'center'}						
                    ]],
                    fitColumns: true
                ">
            </select>
        </td>
     </tr>
    </table>
</div>

<div id="dialog-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="confirm_dp_ok()">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-confirm-cancel-dp')">Cancel</a>
</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':[]};
/*==============================end=========================================*/
var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';

$(document).ready(function(){
	
	$('#txt_so_date').datebox('setValue','<?=convert_to_dmy($detail->SOrdDate)?>');
	$('#txt_ship_date').datebox('setValue','<?=convert_to_dmy($detail->ShipingDate)?>');

	tax_status      = '<?=$detail->SOrdTaxesStatus?>';
	intax_status    = '<?=$detail->SOrdInTaxStatus?>';
	dp_status       = '<?=$detail->SOrdDPStatus?>';
	trans_status    = '<?=$detail->TransStatus?>';
	currency_code 	= '<?=$detail->CurrencyCode?>'; 
	AppLimitCode 	= '<?=$detail->AppLimitCode?>'; 
	App_Over_limit 	= '<?=$app_over_limit;?>';
    dbl_pph23       = '<?= $detail->SOrdPPh23Pcnt ?>';

    $('#lbl_pph23').text('PPh23 (' + dbl_pph23 + '%)');
	
	
	/*
		Cek App limit & Over due
	*/
	
	/*if((AppLimitCode == "")){
		if((App_Over_limit)){
			$.messager.alert('Warning', 'Customer ini sudah melewati limit silahkan klik tombol Save untuk melihat perubahan', 'info', function(){
			
			});
		}
		else{
			
		}
	}*/
	/*============================End==============================*/
	
	
	
	if(tax_status == 1){
		$('.disableme').css('display','');                
		$('#chk_taxtable').prop('checked',true);
	
		if(intax_status == 1){
			$('.disableme1').css('display','');                
			$('#chk_inclusive').prop('checked',true);
		}
		else {
			$('#chk_inclusive').prop('checked',false);
			$('.disableme1').css('display','none');                
		}	
	}
	else {
		$('.disableme').css('display','none');                
		$('#chk_taxtable').prop('checked',false);
		$('#chk_inclusive').prop('checked',false);
	}

	if(dp_status == 1){
		$('#chk_payment_dp').prop('checked',true);
		$('.dp_line').css('display','');			
		$('.dp').css('display','');	
		
		$('#txt_downpayment').numberbox('setValue', '<?=$detail->SOrdTotalDP?>');
	}

	$('#frm_sales_order').click(function(){
		$('#dtg_item').edatagrid('saveRow');
	});

	$('#dtg_item').edatagrid({
		onLoadSuccess: function(){
			dg          = $('#dtg_item').datagrid('getRows');
			var sub_total   		= 0;
			var total_disc 			= 0;
			var amount_disc 		= 0;
			var total_amount_disc 	= 0;
			var sub_total_hide 		= 0;
			
			$.each(dg, function(index, value){
				sub_total 			= sub_total + parseFloat(value.ItemAmount);
				total_disc			= parseFloat(value.ItemDisc);
				total_amount_disc 	= ((parseFloat(value.ItemQty) * parseFloat(value.ItemPrice)) * parseFloat(value.ItemDisc)) / 100;
				amount_disc			= parseFloat(total_amount_disc);
				sub_total_hide 		= sub_total_hide + parseFloat(value.ItemAmount_Hide);
				
				$('#dtg_item').datagrid('updateRow',{
                index:index, 
                row:{AmountDisc       : total_amount_disc}
             	});
			 
			});



			$('#sub_total').numberbox('setValue', sub_total);
			$('#sub_total_hide').numberbox('setValue', sub_total_hide);
			$('#txt_discount').numberbox('setValue', amount_disc);	
			calculate_total();
		},
		onBeginEdit:function(rowIndex,rowDatax){
			var editors = $('#dtg_item').datagrid('getEditors', rowIndex);
            var sq      = $(editors[0].target); //SQuoNumber 
            var ic      = $(editors[1].target); //Item Code 
			var n1	= $(editors[3].target); //Item Qty
			var n2	= $(editors[5].target); //Item Price
			var n3	= $(editors[7].target); //Item Amount
			var n4	= $(editors[11].target); //Item tax
			var n5	= $(editors[12].target); //Intax Price
			//var n6	= $(editors[4].target); //Suspend Item
			//var n1	= $(editors[2].target); //Item Qty
			var n6	= $(editors[9].target); //Suspend Item
			var n10	= $(editors[8].target); //Item Qty DO
			var n11	= $(editors[10].target); //Item Qty Spd
			var n13	= $(editors[15].target); //Row Status
			var n14	= $(editors[6].target); //Item Disc
			var n15	= $(editors[21].target); //Amount Disc
			var n16	= $(editors[22].target); //Item ItemPrice_Hide 
			var n17	= $(editors[23].target); //Item Amount_Hide
			var n18	= $(editors[16].target); //Item Category
			var n19	= $(editors[20].target); //Item Status
			
			var qty 			= n1.numberbox('getValue');
			var price 			= n2.numberbox('getValue');
			var disc 			= n14.numberbox('getValue');
			
			var ItemCategory 	= n18.numberbox('getValue');
			var ItemStatus 		= n19.val();
			n2.numberbox('enable');
			/*if(ItemStatus == 2){
				n2.numberbox('enable');
			}
			else{
				n2.numberbox('disable');
			}*/
				
			if((trans_status == 7) || (AppLimitCode == 1)){
				save_button_begendedit(SavePrivillage);
			}
			
			if((trans_status != 1)){
				n6.prop('disabled',true);//Suspend Item
				
				if((trans_status == 4) && (AppLimitCode != "")){
					n1.prop('readonly',true);//Item Qty
					n2.prop('readonly',true);//Item Price
					n14.prop('readonly',true);//Item Disc
				}
			}
			else{
				n6.prop('disabled',false);//Suspend Item
				n1.prop('readonly',true);//Item Qty
				n2.prop('readonly',true);//Item Price
				n14.prop('readonly',true);//Item Disc
			}

            $(sq).prop('readonly', true);
            $(sq).click(function(){
                var TransNo             = rowDatax.SQuoNumber;
                parent.tab_edit('Edit Sales Quotation','list/sales_quotation', 'icon-edit', 'edit',TransNo);
            });

            $(ic).prop('readonly', true);
            $(ic).click(function(){
                var ItemCode             = rowDatax.ItemCode;
                var cmb_customer         = $('#cmb_customer').combogrid('getValue');
                parent.tab_add('List Price Item','list/sales_order','icon-add','view_list_price'+'/'+ItemCode+'/'+cmb_customer);
            });

			
			n1.numberbox({
				onChange:function(){
					if(parseFloat(n1.numberbox('getValue')) > parseFloat(n4.numberbox('getValue'))) {
						$.messager.alert('Error','Qty tidak boleh lebih dari (' + n4.numberbox('getValue') + ')','error',function(){	
							n1.numberbox('setValue', qty);
						});
					}
					else {
						var qty_editor 	= n1.numberbox('getValue');
						var price_editr = n2.numberbox('getValue');
						var disc_editor = n14.numberbox('getValue');
			
						$('#dtg_item').edatagrid('saveRow');
					
						calculate_item(rowIndex, qty_editor, price_editr, disc_editor,ItemStatus);
					}
				}
			}),
			
			$(n6).click(function(){
				if($(this).is(':checked')){
					var itemqty     = n1.numberbox('getValue');
					var itemqtydo   = n10.numberbox('getValue');
											
					var suspend_qty = parseFloat(itemqty) - parseFloat(itemqtydo);
					
					n11.numberbox('setValue', suspend_qty);
					n13.numberbox('setValue', 2);
					suspend_item(1);                         
				}
				else{
					n11.numberbox('setValue', 0);
					n13.numberbox('setValue', 2);
					suspend_item(1);
				}
			});
			
			n2.numberbox({
				onChange:function(){
					if(parseFloat(n2.numberbox('getValue')) < parseFloat(n5.numberbox('getValue'))) {
						$.messager.alert('Error','Harga tidak boleh kurang dari (' + n5.numberbox('getValue') + ')','error',function(){	
							n2.numberbox('setValue',price);
						});
					}
					else {
						var qty_editor 	= n1.numberbox('getValue');
						var price_editr = n2.numberbox('getValue');
						var disc_editor = n14.numberbox('getValue');
						
						$('#dtg_item').edatagrid('saveRow');
						calculate_item(rowIndex, qty_editor, price_editr, disc_editor,ItemStatus);
					}
				}
			});
			
			n14.numberbox({
				onChange:function(){
					if(n14.numberbox('getValue') > 100){
						$.messager.alert('Maaf','Discount per item tidak boleh lebih dari 100%, silahkan cek kembali transaksi anda','warning',function(){		
							$('#dtg_item').datagrid('reload');
						});
					}
					
					var qty_editor 	= n1.numberbox('getValue');
					var price_editr = n2.numberbox('getValue');
					var disc_editor = n14.numberbox('getValue');
						
					$('#dtg_item').edatagrid('saveRow');
					calculate_item(rowIndex, qty_editor, price_editr, disc_editor);
				}
			});
		},

		onEndEdit:function(rowIndex, rowData, changes){
			var item 		= $('#dtg_item').datagrid('getRows');
			var sub_total 	= 0;
			var total_disc 	= 0;
			var amount_disc = 0;
			var sub_total_hide 	= 0;
			
			if((trans_status == 7) || (AppLimitCode == 1)){
				save_button_endedit(SavePrivillage);
			}
			
			$.each(item, function( index, value ) {
				sub_total		+= parseFloat(value.ItemAmount);
				total_disc		+= parseFloat(value.ItemDisc);
				amount_disc		+= parseFloat(value.AmountDisc);
				sub_total_hide	+= parseFloat(value.ItemAmount_Hide);				
			});
				
			$('#sub_total').numberbox('setValue', sub_total);
			$('#txt_discount').numberbox('setValue', amount_disc);	
			$('#sub_total_hide').numberbox('setValue', sub_total_hide);
	   }
	});
	
	datagrid_item_type_status("dtg_item");//untuk warna grid  
});

function suspend_item(status) {        
	$('#dtg_item').edatagrid('saveRow');
	url = base_url +'list/sales_order/suspend_item';

	message_text    = '';
	so_number     = $("#txt_so_no").val();
	detail          = JSON.stringify($('#dtg_item').datagrid('getRows'));

	if(status == 0) {
    	message_text = 'Anda yakin, ingin melakukan UnSuspend item?';
	}
	else{
    	message_text = 'Anda yakin, ingin melakukan Suspend item?';            
	}

	$.messager.confirm('Warning :', message_text,  
		function(r){
			if (r){
				$.post(url, {so_number:so_number, detail:detail}, function(result){
					if (result.status == true){
						$.messager.alert('Success',result.message,'info',function(){
							location.reload();
							//$('#dtg_item').datagrid('reload');						                    
						});				
					} 
					else {
						$.messager.alert('Error',result.message,'error',function(){
							location.reload();
							//$('#dtg_item').datagrid('reload');						                    
						});				
					}
				},'json');
			}
			else {
				//location.reload();
				$('#dtg_item').datagrid('reload');						                    
			}
		}
	);
}


function update_data(){
	var amount  = true;
	var item    = $('#dtg_item').datagrid('getRows');
	
	var url             	= '<?= base_url();?>custom/custom/checking_update';
	var no_transaksi    	= $('#txt_so_no').val();
	var trans_status 		= '<?=$detail->TransStatus?>';
	var validate 				= true;
	
	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');?>';
	
	$.each(item, function( index, value ) {
		if(value.ItemPrice == undefined || value.ItemPrice == 0 ){
			amount = false;
		}				
	});

	if(amount == false){
	   $.messager.alert('Unseccessfull','Masih ada price yang kosong','error',function(){});
	}
	
	if($('#txt_downpayment').numberbox('getValue') == 0 && $('#txt_dp_status_hidden').val() == 1){
		$.messager.alert('Unseccessfull','Cust. Payment DP telah Anda checklist, silahkan isi nominal Downpayment','error',function(){		
			$('#txt_downpayment').numberbox().focus();
		});
		
		validate = false;
	}
	
	if(parseFloat($('#txt_downpayment').numberbox('getValue')) > parseFloat($('#sub_total').numberbox('getValue'))){
		$.messager.alert('Unseccessfull','Downpayment tidak boleh lebih besar dari pada Sub Total','error',function(){		
			$('#txt_downpayment').numberbox().focus();
		});
		
		validate = false;
	}
	
	if((validate == true) && (check_qty()) && (amount == true)){
		var i       = $('#dtg_item').datagrid('getRows');
		var detail  = JSON.stringify(i);

		$("#detail").val(detail);
		edit_transaction_check('<?=$menu_link?>','#frm_sales_order', no_transaksi, url, trans_status,created_by, login_as, job_title);	
	}
}

function app_reverse(){
	var no_transaksi    = $('#txt_so_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?>','#frm_sales_order');
		}else{
		   $.messager.alert('Unseccessfull',check.message,'error',function(){
				location.reload();
			});
		}
	});
}

function check_qty(){		
	var item            = $('#dtg_item').datagrid('getRows');
	var check_status    = true;

	$.each(item, function(index, value) {		   
		if(parseFloat(value.ItemQty) > parseFloat(value.ItemMax)){
			$.messager.alert('Informasi','Item ' + value.ItemDesc +' tidak boleh lebih dari ' + value.ItemMax,'warning', function(){});            
			check_status=false;
		}
	});
	
	return check_status;
}

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

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

	intax_ppn();
}

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{
			intax_ppn();
		}
	}
	else{
		$.messager.alert('Warning', "Maaf silahkan isi terlebih dahulu item price di Sales Order", 'error');
		$("#chk_inclusive").prop("checked",false);
	}
}

function intax_ppn(){
	$('#dtg_item').edatagrid('saveRow');
	item = $('#dtg_item').datagrid('getRows');

	var itemprice   	 = 0;
	var itemamount  	 = 0;
	var intax       	 = 0;
	var itemtax     	 = 0;
	var itemppn     	 = 0;
	var disc 			 = 0;
	
	var itemprice_Hide   = 0;
	var itemamount_Hide  = 0;
	
	$.each(item, function(index, value) {
		intax       	= 0;
		itemtax     	= 0;
		itemprice   	= value.ItemPrice;
		itemdisc    	= value.ItemDisc;
		item_qty   		= value.ItemQty;
		dbl_ppn10 		= parseFloat('<?=$detail->SOrdTaxPcnt?>');
		
		itemprice_Hide  = value.ItemPrice_Hide;
		total_price 	= parseFloat(itemprice - (itemprice * itemdisc) / 100);
		total_disc 		= parseFloat((item_qty * itemprice) * (itemdisc / 100));
		
		
		if(itemprice >= 0 || itemprice !== null){
			if($('#chk_taxtable').is(':checked')){
				if($('#chk_inclusive').is(':checked')){
					total_price = parseFloat((100 / (100 + dbl_ppn10) * total_price)); 
					
					intax 		= 1;
					itemamount  = parseFloat(total_price) * parseFloat(value.ItemQty);
					itemtax     = parseFloat(itemamount) * dbl_ppn10 / 100;
				}
				else{
					intax   	= 0;
					itemamount  = parseFloat(total_price) * parseFloat(value.ItemQty);
					itemtax     = parseFloat(itemamount) * dbl_ppn10 / 100;
				}                
			}
			else{
				if(value.IntaxStatus == 1){
					intax       = 0;
				}
				itemamount  	 = parseFloat(total_price) * parseFloat(value.ItemQty);
				itemtax     	 = 0;                 
			}

            if ((value.ItemStatus == 2)){
                dbl_pph23   = $('#hdn_pph23_pcnt').val();
                item_pph23  = parseFloat((itemamount * (dbl_pph23 / 100)).toFixed(9));
            }
            else{
                item_pph23  = 0;
            }

			$('#dtg_item').datagrid('updateRow',{
				index:index,
					row: {
						ItemAmount      : itemamount,
						IntaxStatus     : intax,
						ItemTax         : itemtax,
						AmountDisc 		: total_disc,
						ItemAmount_Hide : itemamount,
                        Item_PPh23 : item_pph23
					}
			});
		}
	});

	calculate_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.ItemTax);
		sub_disc  += parseFloat(value.AmountDisc);

        sub_pph23  += parseFloat(value.Item_PPh23);
	});
	
	$('#sub_total').numberbox('setValue', sub_total );
	$('#sub_total_hide').numberbox('setValue', sub_total );
	
	$('#ppn').numberbox('setValue', sub_ppn10);
	$('#ppn_hide').numberbox('setValue', sub_ppn10);

    $('#txt_pph23').numberbox('setValue', sub_pph23);
    $('#txt_pph23_hide').numberbox('setValue', sub_pph23);
	
	$('#txt_discount').numberbox('setValue', sub_disc);
	
	total =  parseFloat(sub_total) + parseFloat(sub_ppn10) - parseFloat(sub_pph23);
	total = isNaN(total) ? 0 : parseFloat(total);
	
	$('#total_purchase').numberbox('setValue', total);
	$('#total_purchase_hide').numberbox('setValue', total);
	
	get_so_limit($('#cmb_customer').combogrid('getValue'), total, $('#txt_so_no').val());
}

function calculate_item(rowIndex, qty, price, disc,ItemStatus){
	$('#dtg_item').edatagrid('saveRow');
	item = $('#dtg_item').datagrid('getRows');
	
	var item_amount  		= 0;
	var intax       		= 0;
	var itemtax     		= 0;
	var item_ppn10     		= 0;
	var itemamount_hide  	= 0;
	var dbl_ppn10 			= parseFloat('<?=$detail->SOrdTaxPcnt?>');
	total_price 			= parseFloat(price - ((price * disc) / 100));
	item_amount 			= parseFloat(qty * total_price);
	total_disc 				= parseFloat((qty * price) * (disc / 100));
	
	if($('#chk_taxtable').is(':checked')){
		if($('#chk_inclusive').is(':checked')){
			total_price 	= parseFloat(total_price * (100 / (100 + dbl_ppn10)).toFixed(9)); 
			intax       = 1;
			item_amount = parseFloat(qty) * parseFloat(total_price);
			item_ppn10  = parseFloat((item_amount) * (dbl_ppn10 / 100).toFixed(9));
		}
		else{
			intax       = 0;
			item_amount = parseFloat(qty) * parseFloat(total_price);
			item_ppn10  = parseFloat((item_amount) * (dbl_ppn10 / 100).toFixed(9));
		}
	}
	else{
		/*if(value.IntaxStatus == 1){
			intax       = 0;
		}*/
		item_amount = parseFloat(qty) * parseFloat(total_price);
		item_ppn10  = 0;
	}

    if ((ItemStatus == 2)){
        dbl_pph23   = $('#hdn_pph23_pcnt').val();
        item_pph23  = parseFloat((item_amount * (dbl_pph23 / 100)).toFixed(9));
    }
    else{
        item_pph23  = 0;
    }

    

	$('#dtg_item').datagrid('updateRow',{
		index:rowIndex,
		row: {
				ItemAmount      : item_amount,
				IntaxStatus     : intax,
				ItemTax         : item_ppn10,
				AmountDisc 		: total_disc,
				ItemAmount_Hide : item_amount,
				ItemPrice_Hide 	: price,
                Item_PPh23 : item_pph23
			}
	});
	
	calculate_total();
}


function approval_so(status) {
	var url_check           = '<?= base_url();?>custom/custom/checking_approval';
	var no_transaksi    	= $('#txt_so_no').val();
	
	checking_approval(no_transaksi,function(check){
		if(check.status == false){
			approval(status);
		}else{
			$.messager.alert('Unseccessfull',check.message,'error',function(){
				location.reload();
			});
		}
	});
}
	    
function approval(status){
	var item = $('#dtg_item').datagrid('getRows');
	var SOrdNumber  	= $("#txt_so_no").val();
	var SQuoNumber  	= $("#txt_sq_no").val();
	var TotalSales  	= $("#total_purchase").numberbox('getValue');
	var SubTotal  		= $("#sub_total").numberbox('getValue');
	var CustomerCode  	= $('#cmb_customer').combogrid('getValue');
	var DownPayment  	= $('#txt_downpayment').numberbox('getValue');
	var SOrdDate        = $('#txt_so_date').datebox('getValue');
	
	var CurrencyCode 	= $("#hdn_currency_code").val();
	var CurrencyRate 	= $("#txt_rate").numberbox('getValue');
	var SOrdDPStatus	= $('#chk_payment_dp').val();
	
	if(status == 1){
		var url     = base_url + 'list/sales_order/approval';                
	}
	else{
		var url     = base_url + 'list/sales_order/approval_limit';                                
	}
	
	detail = JSON.stringify($('#dtg_item').datagrid('getRows'));
	
	$.post(url, {SOrdNumber:SOrdNumber, SQuoNumber:SQuoNumber, detail_so:detail, TotalSales:TotalSales, CustomerCode:CustomerCode, SubTotal:SubTotal, DownPayment:DownPayment, SOrdDate:SOrdDate, CurrencyCode:CurrencyCode, CurrencyRate:CurrencyRate, SOrdDPStatus:SOrdDPStatus}, function(result){
		if (result.status == true){
			$.messager.alert('Success',result.message,'info',function(){
				location.reload();						                    
			});				
		} 
		else {
			$.messager.alert('Error',result.message,'error',function(){
				location.reload();						                    
			});				
		}
	},'json');
}

function approval_bypass_dp(){
	var item 			= $('#dtg_item').datagrid('getRows');
	var SOrdNumber  	= $("#txt_so_no").val();
	var SQuoNumber  	= $("#txt_sq_no").val();
	var TotalSales  	= $("#total_purchase_hide").numberbox('getValue');
	var SubTotal  		= $("#sub_total_hide").numberbox('getValue');
	var CustomerCode  	= $('#cmb_customer').combogrid('getValue');
	var DownPayment  	= $('#txt_downpayment').numberbox('getValue');
	var SOrdDate        = $('#txt_so_date').datebox('getValue');
	
	var CurrencyCode 	= $("#hdn_currency_code").val();
	var CurrencyRate 	= $("#txt_rate").numberbox('getValue');
	var SOrdDPStatus	= $('#chk_payment_dp').val();
	detail 				= JSON.stringify($('#dtg_item').datagrid('getRows'));
	var url     		= base_url + 'list/sales_order/bye_pass_dp';
	
	$.post(url, {SOrdNumber:SOrdNumber, SQuoNumber:SQuoNumber, detail_so:detail, TotalSales:TotalSales, CustomerCode:CustomerCode, SubTotal:SubTotal, DownPayment:DownPayment, SOrdDate:SOrdDate, CurrencyCode:CurrencyCode, CurrencyRate:CurrencyRate, SOrdDPStatus:SOrdDPStatus}, function(result){
		if (result.status == true){
			$.messager.alert('Success',result.message,'info',function(){
				location.reload();						                    
			});				
		} 
		else {
			$.messager.alert('Error',result.message,'error',function(){
				location.reload();						                    
			});				
		}
	},'json');
}

function remove_row(){
	var item 		= $('#dtg_item').datagrid('getData').total;
	var item_row    = $('#dtg_item').datagrid('getRows');
	
	var sq_no      	= new Array();
   	var sq_date 	= new Array();
	var cus_po 		= new Array();
	var so_desc 	= new Array();
		
	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.SOrdDetailID);
					
					new_array_item.a.push(selectedrow.SQuoDetailID);
                   	new_array_item.b.push(selectedrow.ItemQty);
					
                   	$("#detail_id").val(JSON.stringify(array_item));
					$("#detail_qty").val(JSON.stringify(new_array_item));
                   	$('#dtg_item').datagrid('deleteRow', row_index);
					calculate_total();
					
					save_button_endedit(SavePrivillage);
					
					/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
					$('.app-button').linkbutton('disable');
					/*=================================end============================================================*/
						
					$.each(item_row, function(index, value) {
						if(value.SQuoNumber != undefined){
							sq_no.push(value.SQuoNumber);
							sq_date.push(value.SQuoDate);
							cus_po.push(value.CustPONumber);
							so_desc.push(value.SQuoDesc);
						}
					});
					
					$('#txt_sq_no').val(sq_no.array_unique());
					$('#txt_sq_date').val(sq_date.array_unique());	
					$('#txt_po_no').val(cus_po.array_unique());	
					$('#txa_description').val(so_desc.array_unique());	
				}
			}
		);        
					
	}            
}

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_so_no').val(), 'Sales Order', url, created_by, login_as, job_title);
}

function confirm_dp_ok(){
	suspend_data_new('F', type, '<?=$menu_link?>', $('#txt_so_no').val(), 'Sales Order');
}

function get_so_limit(customer_code, total_purchase, SOrdNumber){
	url	= base_url + 'list/sales_order/get_sales_limit'; 
	$.post(url, {customer_code:customer_code, total_purchase:total_purchase, SOrdNumber:SOrdNumber}, function(result){
		$('#txt_limit').numberbox('setValue', result.limit_customer);
	},'json');
}

function to_transaction(){
    var appfinished         = '<?=$detail->TransStatus;?>';
    var no_transaksi        = $('#txt_so_no').val();
    var customer_code       = $('#cmb_customer').combogrid('getValue');
    var no_trans            = no_transaksi.replace(/\//g,"__");
    var customer_code       = customer_code.replace(/\//g,"__");


    if(appfinished == 1){
        parent.tab_add('New Delivery Order','list/delivery_order','icon-add','add/'+no_trans+'/'+customer_code);
    }else{
        $.messager.alert('Unseccessfull','TransStatus Finished. Transaksi selesai.','error',function(){
            //location.reload();
        });
    }
    
}
</script>