<!---- 
Author 	: Herpan / 12-08-2014	
Revisi 	: Ferry / 12-01-2014
-->
<?php
//---------Untuk privellege jika dia ada tombol save----------
	if($group_user->SavePrivillage == 1){
		$cek_autority_save  = "";
	}
	else{
		$cek_autority_save 	= "disabled";
	}
//-------------end----------------------------
?>
<style>
.datagrid-header-row [field='ck'] input{
	display:none;
}
</style>

<div class="easyui-layout" data-options="fit:true,border:false">
    <!-- Top view-->
    <div id="form-header" data-options="region:'north',border:false">
        <div id="form-header-wrapper">
            <table cellpadding="0" cellspacing="0" width="100%">
            <tr>
                <td align="left" valign="middle">
                    <a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="parent.tab_add('New Sales Order', '<?=$menu_link?>', 'icon-add', 'add')">New</a>
                	<a href="#" class="easyui-linkbutton" id="refresh-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload()">Refresh</a>
                </td>							
                <td align="right">								
                    <span class="form-title"><?=$menu_label?></span>
                </td>
            </tr>
            </table>	
        </div>			
    </div>
    <!-- End of top view -->
        
    <!-- center view -->
    <div id="form-body" data-options="region:'center',border:false">
        <div id="form-wrapper" class="easyui-panel" style="padding:5px;" fit="true">
            <form id="fm_sales_order" name="fm_sales_order" method="post">
                <input type="hidden" name="detail" id="detail" />
                <input type="hidden" name="hdn_pph23_pcnt" id="hdn_pph23_pcnt"/>
                
                <!-- Form Header -->
                <table width="100%" height="140" cellpadding="0" cellspacing="0">
                <tr>
                    <td width="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="combo-grid" required="required"
                                    name="cmb_customer" id="cmb_customer" 
                                    style="width:160px;height:20px;" 
                                    data-options="
                                        panelWidth: 370,
                                        idField: 'CustomerCode',
                                        textField: 'CustomerName',
                                        url: '<?=base_url()?>custom/get_data/customer_with_rate',
                                        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_sales();">Select SQ</a>
                                <input type="checkbox" name="chk_taxtable" id="chk_taxtable" onClick="hideppn();" value="1">Taxable								  

                                <span class="disableme" style="display:none;">
                                    <input type="checkbox" name="chk_inclusive" id="chk_inclusive" onClick="calculate_item_intax();" value="1">Inclusive Tax
                                </span>
                            </td>
                        </tr>
                        <tr id="rowRate">
                        	<td><b>Currency Code/Rate</b></td>
                            <td><b>:</b></td>
                            <td colspan="5">
                            	<input type="hidden" name="hdn_currency_code" id="hdn_currency_code" style="width:55px" required readonly />
                                <input type="numberbox" id="txt_rate" name="txt_rate" value="1" class="easyui-numberbox" style="width:90px;text-align:right;" required
                                	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                            	<span id="spn_currency_code"></span> / IDR
                            </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></textarea>
                            </td>
                            <td colspan="3">
                                <textarea name="txa_ship_to" id="txa_ship_to" rows="4" style="width:225px;resize:none;" data-options="required:true" class="easyui-validatebox"></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="hidedp()" value="1" /> Customer needs DP</td>
                            <td width="190"></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">
                                
                            </td>
                            <td width="100" align="center" valign="middle">
                                <input name="txt_so_date" id="txt_so_date" type="text" class="easyui-datebox validBackward" value="<?=$so_date?>" style="width:122px;height:20px" required editable="false" />
                            </td>
                            <td>
                            	<select class="combo-grid" required="required"
                                    name="cmb_fob" id="cmb_fob" 
                                    style="width:122px;height:20px;" 
                                    data-options="
                                        panelWidth: 250,
                                        idField: 'FobID',
                                        textField: 'FobName',
                                        url:'<?=base_url()?>custom/get_data/fob',                                     
                                        method: 'get',
                                        columns: [[
                                            {field:'FobID',title:'FOB ID',width:90,halign:'center'},
                                            {field:'FobName',title:'FOB Name',width:90,halign:'center'}
                                        ]],
                                        fitColumns: true
                                    ">
                                </select>
                            </td>
                        </tr>
                        <tr height="20">
                            <td 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" 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" 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;" 
                                    data-options="
                                        panelWidth: 250,
                                        idField: 'TermspaymentID',
                                        textField: 'TermDesc',
                                        url:'<?=base_url()?>custom/get_data/termspayment',                                        
                                        method: 'get',
                                        columns: [[
                                            {field:'TermspaymentID',title:'Terms payment ID',width:90,halign:'center'},
                                            {field:'TermDesc',title:'Term Desc',width:90,halign:'center'}
                                        ]],
                                        fitColumns: true
                                    ">
                                </select>
                            </td>
                        </tr>
                        <tr height="20">
                            <td style="background:#333399;text-align:center;color:#FFF;">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" 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" value="<?=$so_date?>" style="width:122px;height:20px;" required editable="false"/></td>
                            <td>
                                <select class="combo-grid" required="required"
                                    name="cmb_ship_via" id="cmb_ship_via" 
                                    style="width:122px;height:20px;" 
                                    data-options="
                                        panelWidth: 250,
                                        idField: 'ShipmentID',
                                        textField: 'ShipmentName',
                                        url:'<?=base_url()?>custom/get_data/shipment',                                     
                                        method: 'get',
                                        columns: [[
                                            {field:'ShipmentID',title:'Shipment ID',width:90,halign:'center'},
                                            {field:'ShipmentName',title:'Shipment Name',width:90,halign:'center'}
                                        ]],
                                        fitColumns: true
                                    ">
                                </select>
                            </td>
                        </tr>
                        </table>
                    </td>
                </tr>
                </table>

                <!-- End of form header -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div id="tab_item" title="Items">
                        <table id="dg_item"
                            toolbar="#toolbar" idField="id" 
                            rownumbers="true" fitColumns="true" 
                            singleSelect="true" style="height:250px;" 
                            url="<?=base_url() . $menu_link . "/ajax_item/"?>"
                        >
                            <thead>
                            <tr>
                                <th width="60"  halign='center' field='SQuoNumber' 		data-options="align:'left'" editor="{type:'text'}">SQuo. No.</th>
                                <th width="60"  halign='center' field='SQuoDate' 		data-options="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>SQuotation Desc</th>
                                
                                <th width="40"  halign='center' field="ItemCode" 		data-options="align:'left'" 	editor="{type:'text'}">Item</th>
                                <th width="150" halign='center' field="ItemDesc" 		data-options="align:'left'" 	editor="description">Description</th>
                                <th width="30"  halign='center' field="ItemQty" 		data-options="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" 		data-options="align:'center'" 	editor="unit">Unit</th>
                                <th width="40"  halign='center' field="ItemPrice" 		data-options="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:'center'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true}}" formatter="formatRp">Discount %</th>
                                <th width="40"  halign='center' field="ItemAmount" 		data-options="align:'right'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" formatter="formatRp">Amount</th>	
                                
                                <th width="60"  halign='center' field="EmployeeName" 	data-options="align:'left'" hidden>Salesman</th>	
                                <th width="50"  halign='center' field="SalesmanCode" 	data-options="align:'left'" hidden>Salesman Code</th>
                                <th width="20"  halign='center' field="ItemMax" 		data-options="align:'center'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true, min:0.01}}" formatter="formatRp" hidden>Max</th>
                                <th width="50"  halign='center' field="IntaxStatus" 	data-options="align:'right'" 	editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',required:true,disabled:true}}" hidden>InTax Status</th>                               
                                <th width="50"  halign='center' field="ItemTax" 		data-options="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" 		data-options="align:'center'" hidden>ID</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="30"  halign='center' field="ItemStatus" 			data-options="align:'right'" 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 Hide</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();">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;"></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="0" class="easyui-numberbox" style="text-align:right;"
                                    data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" 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" name="txt_downpayment" id="txt_downpayment" value="0" class="easyui-numberbox dp currency" style="text-align:right;"
                                    	data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                    />
                                </span>
                            </td>
                        </tr>
                        </table>
                    </td>
                    <td width="50%" valign="top">
                        <table width="100%" cellpadding="0" cellspacing="1">
                        <tr>
                            <td rowspan="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="0" style="text-align:right;" readonly
                                    data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" 
                                />
                            </td>
                        </tr>
                       
                        <tr>
                            <td><b><?=$taxes_ppn10->TaxesCode?> (<?=$taxes_ppn10->TaxesRate?>%)</b></td>
                            <td><b>:</b></td>
                            <td>
                                <input type="text" min="0" name="ppn" id="ppn" class="easyui-numberbox" value="0" 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="0" style="text-align:right;" readonly 
                                     data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'"
                                />
                                
                                <input type="hidden" id="total_purchase_hide" name="total_purchase_hide" value="0" class="easyui-numberbox" style="text-align:right;" readonly
                                	data-options="min:0,decimalSeparator:',',groupSeparator:'.',
                                    formatter:function(v){
                                        return v;
                                    },
                                    parser:function(s){
                                        var v = parseFloat(s);
                                        return v;
                                    }
                                    " 
                                />
                            </td>
                        </tr>
                        </table>
                    </td>
               	</tr>
                </table>
            </form>
    	</div>
    </div>
    
    <div id="form-footer" data-options="region:'south',border:false">
    	<table width="100%" cellpadding="0" cellspacing="0">
        <tr>
        	<td>
            	<b>Old SOrd. No. : </b>
                
            </td>
        	<td>
            	<!--<b>Over DueDays :</b> 
				<span id="due_days"></span> Day-->
            	<!--
            	<span><b>Down Payment :: </b></span>
                <span id="total_owning">0</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>
                -->
            </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)" id="save_button" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="insert_data()" <?php echo $cek_autority_save;?>>Save</a>
                <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="parent.tab_close('tt')">Close</a>			
    		</td>
        </tr>
        </table>
    </div>
</div>

<div id="dialog-sq" class="easyui-dialog" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-buttons-sq" style="width:860px;height:532px;top:27px;background-color:#F8F8F8;padding:5px;"> 
        <div id="tab_purchase_req" class="easyui-tabs" style="width:835px;height:485px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
            <div title="Select Sales Quotation" style="padding:10px" >
            <table id="tt_choose" class="easyui-datagrid" 
                url="<?=base_url()?>list/sales_order/get_data_sq" 
                remoteSort="false"
                pageSize="150"
                fitColumns="true" 
                rowNumbers="true"
                style="width:812px;height:400px"
                data-options = "border:true,view:scrollview,autoRowheight:false"
            >
                <thead>
                    <tr>
                        <th field="ck" checkbox="true" width="20">All</th>
                        <th field="SQuoNumber" width="150" halign="center" align="left" sortable="true">SQuo. Number</th>
                        <th field="SQuoDate" width="80" halign="center" align="center" formatter="formatDate" sortable="true">SQuo. Date</th>
                        <th field="SQuoDesc" width="300" halign="center" align="left">Description</th>
                    </tr>
                </thead>
            </table>
    
             
            <!-- Dialog Button for Dialog Item-->
            <div style="border:none; margin-top:10px; float:right;">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_item_sq();">&nbsp; OK &nbsp; &nbsp;</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-sq');">Cancel</a>
            </div>
            <!-- End of Dialog Button for Dialog Item-->
            </div>
         </div>
</div>
<?php $this->load->view('v_custom_pop_up');?>
<script type="text/javascript">
	var dbl_ppn10 		= '<?= $taxes_ppn10->TaxesRate ?>';
	var SavePrivillage 	= '<?php echo $group_user->SavePrivillage;?>';

    $('#hdn_pph23_pcnt').val(2);
	
    $(document).ready(function(){ 
        $('#cmb_customer').combogrid({
            onSelect:function(rowIndex, rowData){
                customer_status       = rowData.CustomerStatus;
                customer_taxnumber    = rowData.TaxesNumber;
                customer_currcode     = rowData.CurrencyCode;

				$('#dg_item').datagrid('load',{
                    sq_no: ''
                });
                
                $('#tt_choose').datagrid('load',{
                    cust_code : rowData.CustomerCode
                });		
				
                var Address = rowData.CustomerAddress + ', ' + rowData.CustomerCityName + ', ' + rowData.CustomerStateName + ', ' + rowData.CustomerCountryName;
				get_so_limit(rowData.CustomerCode, 0, '');
				get_so_over_due_days(rowData.CustomerCode);
				
                $('#txa_address').val( Address );
                $('#txa_ship_to').val( Address );
				$('#spn_currency_code').text(rowData.CurrencyCode);
				$('#hdn_currency_code').val(rowData.CurrencyCode);
				$('#txt_rate').numberbox('setValue',rowData.CurrencyRate);
                $('#txt_pph23').numberbox('setValue', 0);
				
                if(rowData.TaxIncludedStatus == 1){
                    $('#chk_taxtable').prop('checked',true);
                }
                else{
                    $('#chk_taxtable').prop('checked',false);
                }
				
				if(rowData.CurrencyCode!='IDR'){
					$('#txt_rate').attr('readonly',false);
					$('#txt_rate').numberbox('setValue',rowData.CurrencyRate);
				}
				else{
					$('#txt_rate').attr('readonly',true);
					$('#txt_rate').numberbox('setValue',rowData.CurrencyRate);
				}

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

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

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

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

            }
        });	
	
//	$('#tt_choose').datagrid({
//            onDblClickRow:function(){		
//                var sq      = $('#tt_choose').datagrid('getSelected').SQuoNumber;
//                var po      = $('#tt_choose').datagrid('getSelected').CustPONumber;
//                var sales   = $('#tt_choose').datagrid('getSelected').SalesmanCode;
//                var total   = $('#tt_choose').datagrid('getSelected').SQuoSubTotal;
//
//                $('#dg_item').datagrid('load',{
//                    sq_no: sq
//                });
//
//                $('#sub_total').numberbox('setValue',total);
//                $('#txt_sq_no').val(sq);
//                $('#txt_po_no').val(po);
//                $('#cmb_salesman').combobox('select',sales);
//
//                modal_close('dialog-sq');
//                //$('#disc_persent').removeAttr('disabled');
//            }
//	});
	
        $('#dg_item').edatagrid({
            onLoadSuccess: function(){
                dg          = $('#dg_item').datagrid('getRows');
                sub_total   	= 0;
				total_sales   	= 0;

                $.each(dg, function(index, value){
					
					if(value.ItemAmount == null){
						item_amount = 0;
					}
					else{
						item_amount = value.ItemAmount_Hide;
					}
                    sub_total 	= parseFloat(sub_total) + parseFloat(item_amount);
					total_sales += parseFloat(item_amount);
					 
					//sub_semua = value.ItemAmount;
                });
                $('#sub_total').numberbox('setValue', sub_total);
				$('#total_purchase').numberbox('setValue', total_sales);
                
				hideppn();
            },
			
            onBeginEdit:function(rowIndex,rowDatax){
                var editors     = $('#dg_item').datagrid('getEditors', rowIndex);
                var sq		    = $(editors[0].target); //Item Qty
                var item_code   = $(editors[1].target); //Item Qty
				var n1		    = $(editors[3].target); //Item Qty
                var n2		    = $(editors[5].target); //Item Price
                var n7		    = $(editors[6].target); //Item Disc
				var n3		    = $(editors[7].target); //Item Amount
                var n4		    = $(editors[8].target); //Item Qty Max
                var n5		    = $(editors[9].target); //Item Min Price
                var n6		    = $(editors[10].target); //Item Temp Price
				
				var n8		= $(editors[14].target); //Item Amount Disc
				var n9		= $(editors[15].target); //Item ItemPrice_Hide 
				var n10		= $(editors[16].target); //Item ItemHome_Hide
				var n11		= $(editors[11].target); //Item Category
				var n12		= $(editors[13].target); //Item Type

                

                var qty 			= n1.numberbox('getValue');
                var price 			= n2.numberbox('getValue');
				var ItemCategory 	= n11.numberbox('getValue');
				var ItemType 		= n12.val();
                

				
				n2.numberbox('enable');
				/*if(ItemType == 2){
					n2.numberbox('enable');
				}
				else{
					n2.numberbox('disable');
				}*/
				$(sq).prop('readonly', true);
                $(sq).click(function(){
                    var TransNo             = rowDatax.SQuoNumber;
                    parent.tab_edit('Edit Sales Quotation','list/sales_quotation', 'icon-edit', 'edit',TransNo);
                });

                $(item_code).prop('readonly', true);
                $(item_code).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);
                });

				save_button_begendedit(SavePrivillage);
				
                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(){	
								$('#dg_item').datagrid('reload');
                            });
							
                        }
                        else {
							var disc_pcnt 		= n7.numberbox('getValue');
							var qty 			= n1.numberbox('getValue');
							var price 			= n2.numberbox('getValue');
                            $('#dg_item').edatagrid('saveRow');
                            calculate_item(rowIndex, disc_pcnt, qty, price, ItemType);
                        }
                    }
                });
                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(){	
                                $('#dg_item').datagrid('reload');
                            });
                        }
                        else {
                           	var disc_pcnt 		= n7.numberbox('getValue');
							var qty 			= n1.numberbox('getValue');
							var price 			= n2.numberbox('getValue');
                            $('#dg_item').edatagrid('saveRow');
                            calculate_item(rowIndex, disc_pcnt, qty, price, ItemType);
                        }
                    }
                });
				n7.numberbox({
                    onChange:function(){
						if(n7.numberbox('getValue') > 100){
							$.messager.alert('Maaf','Discount per item tidak boleh lebih dari 100%, silahkan cek kembali transaksi anda','warning',function(){		
								$('#dg_item').datagrid('reload');
							});
						}
					
                        var disc_pcnt 		= n7.numberbox('getValue');
						var qty 			= n1.numberbox('getValue');
						var price 			= n2.numberbox('getValue');
						$('#dg_item').edatagrid('saveRow');
						calculate_item(rowIndex, disc_pcnt, qty, price, ItemType);
                    }
                });
            },

            onEndEdit:function(rowIndex, rowData, changes){
                var item 			= $('#dg_item').datagrid('getRows');
                var sub_total 		= 0;
				var sub_total_hide 	= 0;
				var total_disc 		= 0;
				var amount_disc 	= 0;
				
				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);		
           }
        });
		
		$('#fm_sales_order').click(function(){
			$('#dg_item').edatagrid('saveRow');
		});     
		
		datagrid_item_type_status("dg_item");//untuk warna grid  
    });

    function choose_item_sq() {
		var rows 	 	= $('#tt_choose').datagrid('getChecked');
		var po 		 	= new Array();
		var sq 		 	= new Array();
		var sd     	 	= new Array();
		var so_desc     = new Array();
		
		var sd_split = "";
		
		$.each(rows, function(index, value) {
            
            if(value.SQuoNumber != undefined){
                sq.push(value.SQuoNumber);
				
				sd_split = value.SQuoDate.split('-');
				sd_split = sd_split[2] +'-'+ sd_split[1] +'-'+ sd_split[0];
				
                sd.push(sd_split);
				po.push(value.CustPONumber);
				so_desc.push(value.SQuoDesc);
				
				$('#txa_description').val(so_desc);	
            }
        });
		
		
		
		$('#dg_item').datagrid('load',{
			sq_no: sq,
			currency_code: $('#hdn_currency_code').val()
		});
		
		$('#txt_sq_no').val(sq.array_unique());
        $('#txt_sq_date').val(sd.array_unique());
		$('#txt_po_no').val(po.array_unique());	
		
		
		$('#sub_total').numberbox('setValue', 0);
		
		modal_close('dialog-sq');
    }

    function select_sales() {
		var Customer			= $('#cmb_customer').combogrid('grid');	// get datagrid object
		var SelectedCustomer	= Customer.datagrid('getSelected'); // get the selected row
	
		if(SelectedCustomer == null ){
			$.messager.alert('Maaf','Silahkan pilih customer terlebih dahulu','warning',function(){});
		}
		else{
			modal_open('Sales Quotation','dialog-sq');
		}		
    }
	
function insert_data(){
	var validate 	= true;
	var amount  	= true;
	var item    	= $('#dg_item').datagrid('getRows');

	$.each(item, function( index, value ) {
		if(value.ItemPrice == undefined || value.ItemPrice == 0 ){
			amount = false;
		}				
	});

	if(amount == false){
	   $.messager.alert('Maaf','Masih ada price yang kosong','error',function(){});
	   validate = false;
	}
	
	/*if($('#sub_total').numberbox('getValue') == 0){
	   $.messager.alert('Maaf','Sub Total Tidak Boleh Kosong','error',function(){});
	   validate = false;
	}*/
	
	if($('#txt_downpayment').numberbox('getValue') == 0 && $('#chk_payment_dp').is(':checked')){
		$.messager.alert('Maaf','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 Sub Total','error',function(){		
			$('#txt_downpayment').numberbox().focus();
		});
		validate = false;
	}
	
	if((validate == true) && (check_qty())){
		$('#dg_item').edatagrid('saveRow');		

		var i=$('#dg_item').datagrid('getRows');
		var detail = JSON.stringify(i);
		
		$("#detail").val(detail);
		save_transaction('<?=$menu_link?>','#fm_sales_order');
	}
}

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

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

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

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

function  calculate_item_intax(){
	var item = $('#dg_item').datagrid('getRows');
	flag = true;
	$.each(item, function(index, value){
		if(value.ItemPrice == 0){
			flag = false;
		}
	});
	
	if(flag != false){
		var item = $('#dg_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(){
	$('#dg_item').edatagrid('saveRow');
	item = $('#dg_item').datagrid('getRows');
	
	var itemprice   = 0;
	var itemamount  = 0;
	var intax       = 0;
	var itemtax     = 0;
	var itemppn     = 0;
	var itemdisc    = 0;
	var disc 		= 0;
    var item_pph23  = 0;
	
	var itemamount_hide  = 0;

	$.each(item, function(index, value) {
		intax       		= 0;
		itemtax     		= 0;
		itemprice   		= value.ItemPrice;
		itemprice_Hide   	= value.ItemPrice_Hide;
		itemdisc    		= value.ItemDisc;
		item_qty   			= value.ItemQty;
		dbl_ppn10 			= parseFloat(dbl_ppn10);
		
		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).toFixed(9)); 
					intax = 1;
				}
				else{
					/*if(value.IntaxStatus == 1){
						total_price   = parseFloat(total_price) + (parseFloat(total_price) * (dbl_ppn10 / 100));
						
						//itemprice_Hide   = parseFloat(itemprice_Hide) + (parseFloat(itemprice_Hide) * (10 / 100));
					}*/

					intax       = 0;
				}
				itemamount  = (parseFloat(total_price) * parseFloat(value.ItemQty));
				itemtax     = parseFloat((itemamount) * (dbl_ppn10 / 100).toFixed(9));
			}
			else{
				if(value.IntaxStatus == 1){
					//itemprice   = parseFloat(itemprice) + (parseFloat(itemprice) * (10 / 100));
					
					//itemprice_Hide   = parseFloat(itemprice_Hide) + (parseFloat(itemprice_Hide) * (10 / 100));
					intax       = 0;
				}
				itemamount  = (parseFloat(value.ItemQty) * parseFloat(total_price));
				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;
            }
			
			$('#dg_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_item(rowIndex, disc_pcnt, qty, price, itemtype){
	$('#dg_item').edatagrid('saveRow');
	item = $('#dg_item').datagrid('getRows');
	
	var itemprice   		= 0;
	var item_amount  		= 0;
	var intax       		= 0;
	var itemtax     		= 0;
	var item_ppn10     		= 0;
    var item_pph23          = 0;
	var itemdisc    		= 0;
	var disc 				= 0;
	var itemamount_hide  	= 0;
	var dbl_ppn10 			= parseFloat('<?=$taxes_ppn10->TaxesRate?>');
	total_price 			= parseFloat(price - ((price * disc_pcnt) / 100));
	item_amount 			= parseFloat(qty * total_price);
	total_disc 				= parseFloat((qty * price) * (disc_pcnt / 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 ((itemtype == 2)){
        dbl_pph23   = $('#hdn_pph23_pcnt').val();
        item_pph23  = parseFloat((item_amount * (dbl_pph23 / 100)).toFixed(9));
    }
    else{
        item_pph23  = 0;
    }

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

function calculate_total(){
	$('#dg_item').edatagrid('saveRow');
	
	var item        = $('#dg_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, '');
}

function remove_row(){
	var selectedrow     = $('#dg_item').datagrid('getSelected');
	var row_index       = $('#dg_item').datagrid('getRowIndex', selectedrow);
	var item_row        = $('#dg_item').datagrid('getRows');
	
	var sq_no       	= new Array();
   	var sq_date 		= new Array();
	var vendor_no 		= new Array();
	var sq_desc 		= new Array();
	
		
	$.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.ItemCode + '"?',  
		function(r){
			if (r){
				var item = $('#dg_item').datagrid('getData').total;
				
				if(item == 0){
					$("#chk_inclusive").prop("checked",false);
				}
				
				$('#dg_item').datagrid('deleteRow', row_index);
				
				save_button_endedit(SavePrivillage);
				
				calculate_total();
				
				$.each(item_row, function(index, value) {
					if(value.SQuoNumber != undefined){
						sq_no.push(value.SQuoNumber);
						sq_date.push(value.SQuoDate);
						vendor_no.push(value.CustPONumber);
						sq_desc.push(value.SQuoDesc);
					}
				});
				
				$('#txt_sq_no').val(sq_no.array_unique());
				$('#txt_sq_date').val(sq_date.array_unique());
				$('#txt_po_no').val(vendor_no.array_unique());
				$('#txa_description').val(sq_desc.array_unique());
			}
		}
	);
}

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 get_so_over_due_days(customer_code){
	url	= base_url + 'list/sales_order/sales_order_over_due'; 
	$.post(url, {customer_code:customer_code}, function(result){
		$('#due_days').text(result.over_due_customer);
		
	},'json');
}
</script>