<!--
Author 		  : Tagor
Last update   : 07/08/2014
Revisi        : Fachri
-->
<?php
		//---------Untuk privellege jika dia ada tombol save----------
			if($group_user->AddPrivillage == 1){
				$cek_autority_add  = "";
			}
			else{
				$cek_autority_add 	= "disabled";
			}
			//-------------end----------------------------
?>

	
<div class="easyui-layout" data-options="fit:true,border:false">
	<div data-options="region:'north',border:false" style="height:30px">
        <div style="padding:2px">
            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="add_row_pop_up();" <?php echo $cek_autority_add;?>>New</a>
            <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-reload'" onClick="$('#grid').datagrid('reload')">Refresh</a>
        </div>
    </div>
	
	 <div data-options="region:'west',split:true,border:true" title="Filter"style="width:190px; background-color:#CCCCFF;">
        <div style="padding:5px">
            <form class="form-filter">
            <table width="100%" cellpadding="0" cellspacing="0" id="tab_transstatus">
            <tr>
                <td style="padding-bottom:8px;">
                    <b>Find</b>
                </td>
            </tr>
            <tr>
                <td>
                    <input id="txt_IDNumber" name="txt_IDNumber"  placeholder="< Tranasction. No. >" style="margin:2px 0px 3px;width:172px;height:22px;border:1px solid #CCC">
                </td>
            </tr>
            <tr>
                <td>
                    <input id="txt_VendorName" name="txt_VendorName"  placeholder="< Vendor Name >" style="margin:2px 0px 3px;width:172px;height:22px;border:1px solid #CCC">
                </td>
            </tr>
            <tr><td><div class="tr-divider"></div></td></tr>
            
            <tr>
            	<td height="38"><div style="float:right;"><a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload'" onClick="location.reload();" >Reset</a> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onClick="searching_data();" >Search</a></div></td>
            </tr>
            
            </table>
            </form>
        </div>
    </div>
	
	<div data-options="region:'center',border:false,iconCls:'icon-ok'">
		<!-- gaya table baru di grid -->
        
		<form id="fm_recur" name="fm_recur" method="post">
		<table id="grid" class="easyui-datagrid"
        	title="" iconCls="icon-edit" 
            singleSelect="true" rowNumbers="true" 
            pageSize="150" 
            fitColumns="true" remoteSort="false" 
            url="<?=base_url($menu_link.'/ajax')?>" 
            style="width:auto;height:560px" 
            toolbar="#tb_dg_recur" 
            data-options = "border:false,view:scrollview,autoRowheight:false"
        > 
            <thead>
            <tr>
                <!--<th width="170" halign="center" align="left" field="SourceNumber">Source No</th>-->
                <th width="150"  halign='center' field="OldNoTransaction" 		data-options="align:'center'" >No Transaction</th>
                <th width="150"  halign='center' field="NoTransaction" 		data-options="align:'center'" >No Receive Item</th>
                <th width="140"  halign='center' field="VendorName" 		data-options="align:'left'"  >Vendor</th>
                <th width="110"  halign='center' field="DateTransaction" 	data-options="align:'center'"  formatter="formatDate">Transaction Date</th>
                <th width="150"  halign='center' field="TotalInvoice" 		data-options="align:'left'" formatter="formatRp">Total Invoice</th>
                <th width="90"  halign='center' field="CurrencyRate" 		data-options="align:'center'" formatter="formatRp">Currency Rate</th>
            </tr>
            </thead>
        </table>
        </form>
	</div>
</div>
<div id="dialog-item" class="easyui-dialog" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-buttons" style="width:860px;height:485px;top:27px;background-color:#F8F8F8;padding:5px;">


    <form id="form_import_recur" name="form_import_recur" method="post" novalidate>
    	<input type="hidden" id="txt_terms" name="txt_terms" />
        <input type="hidden" id="txt_vendro_addres" name="txt_vendro_addres" />
        <input type="hidden" id="txt_currencycode" name="txt_currencycode" />
         <input type="hidden" id="detail" name="detail" />
        
    <div id="tab_purchase_req" class="easyui-tabs" style="width:835px;height:435px; background-color:#F8F8F8;" data-options="fit:true,plain:true">
            <div title="Form Receive Item" style="padding:10px">
                <table width="100%" height="116">
                    <tr>
                    	<td width="115" height="76"><b>No Transaction</b></td>
                    	<td width="9"><b>:</b></td>
    
                    	<td width="268">
                       		<input type="text" style="width:250px;height:20px" name="txt_transaction_no" id="txt_transaction_no" class="easyui-validatebox" required/>
                    	</td>
                        <td width="140">
                       		<b>Transaction Date</b>
                    	</td>
                        <td width="5"><b>:</b></td>
                        <td width="250">
                       		<input name="txt_date" id="txt_date" type="text" value="<?php echo $date_now;?>" class="easyui-datebox validBackward" style="width:250px;height:20px"" required editable="false" />
                            
                    	</td>
                	</tr>
                     <tr>
                    	<td width="140" valign="top">
                       		<b>Vendor</b>
                    	</td>
                        <td width="5"  valign="top"><b>:</b></td>
                        <td width="250"  valign="top">
                            <select class="easyui-combogrid" name="cbg_vendor" id="cbg_vendor" style="width:252px;height:22px;" required 
                                data-options="
                                    panelWidth:400,
                                    idField: 'VendorCode',
                                    textField: 'VendorName',
                                    url: '<?=base_url()?>custom/get_data/vendor_new_by_branch_filter',
                                    method: 'get',
                                    columns: [[
                                        {field:'VendorCode',title:'Vendor No',width:100,halign:'center'},
                                        {field:'VendorName',title:'Vendor Name',width:161}
                                    ]],
                                    fitColumns: true
                                ">
                            </select>
                    	</td>
                        <td width="140" valign="top">
                       		<b>Currency Rate</b>
                    	</td>
                        <td width="5" valign="top"><b>:</b></td>
                        <td width="250" valign="top">
                       		<input type="text" style="width:252px;height:20px" name="txt_currencyrate" id="txt_currencyrate" class="easyui-numberbox" data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" value="1" readonly required/>
                            
                    	</td>
                	</tr>
            	</table>
                <br />
              <table toolbar="#tb_dg_item" id="dtg_item" class="easyui-edatagrid" idField="id"
                            rownumbers="true" fitColumns="true" 
                            singleSelect="true" style="height:256px;" 
                            >
<thead>
                    <tr>
                        <!--<th width="170" halign="center" align="left" field="SourceNumber">Source No</th>-->
                        <th width="120"  halign='center' field="ItemCode" 		data-options="align:'center'" editor="{type:'ItemCode',options:{required:true}}">Item Code</th>
                        <th width="160"  halign='center' field="ItemDesc" 		data-options="align:'center'" editor="{type:'text',options:{required:true}}">Item Description</th>
                        <th width="50"  halign='center' field="ItemQty" 		data-options="align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:','}}" formatter="formatRp">Qty</th>
                        <th width="90"  halign='center' field="ItemUnit" 		data-options="align:'center'" editor="{type:'text',options:{required:true}}">Item Unit</th>
    <th width="110"  halign='center' field="Price" 		data-options="align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:','}}" formatter="formatRp">Item Price</th>
    <th width="110"  halign='center' field="Amount" 		data-options="align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',disabled:true}}" formatter="formatRp">Amount</th>
                        <th width="110"  halign='center' field="TotalAmount" 		data-options="align:'center'" editor="{type:'numberbox',options:{precision:2,decimalSeparator:',',disabled:true}}" formatter="formatRp" hidden>Total Amount</th>
                      <th width="110"  halign='center' field="ItemStatus" 		data-options="align:'center'" hidden>Item Status</th>
                      <th width="110"  halign='center' field="ItemType" 			data-options="align:'center'" hidden>Item Type</th>
                        
                      <th width="110"  halign='center' field="ItemCategoryID" 		data-options="align:'center'" hidden>Item Category ID</th>
                      <th width="110"  halign='center' field="ItemCategoryCode" 		data-options="align:'center'" hidden>Item Category Code</th>
</tr>
                  </thead>
              </table>
<div id="tb_dg_item">
                    <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="add_row();">New</a>	
                    <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="delete_row();">Delete</a>								
                </div>
               <table width="100%" height="32">
                    <tr>
                    	<td height="26">&nbsp;</td>
                    	<td width="140">
                       		<b>Total Receive Item</b>
                    	</td>
                        <td width="5"><b>:</b></td>
                        <td width="250">
                       		<input type="text" style="width:252px;height:20px;text-align:right;" name="txt_total_invoice" id="txt_total_invoice" class="easyui-numberbox" data-options="min:0,precision:2,decimalSeparator:',',groupSeparator:'.'" value="0" readonly required/>
                            
                    	</td>
                	</tr>
            	</table>
                         
  <div style="border:none; margin-top:10px; float:right;">
                    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_recur();">&nbsp; Save &nbsp; &nbsp;</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-item');">Cancel</a>
                </div>
          </div>
        </div>

    </form>
</div>

<!-- Dialog Production Amount-->
<div id="dialog-production-amount" class="easyui-dialog" style="width:850px;height:523px;top:27px;background-color:#F8F8F8;padding:0px" closed="true" data-options="modal:true, iconCls:'icon-save'" buttons="#dialog-productions-amount">
    <form id="form_account" method="post" novalidate>
        <table width="100%" align="left" border="0">
            <tr>
                <td width="308" align="left" valign="middle"><b>Item Category</b></td>
                <td width="10"><b>:</b></td>

                <td colspan="2">
                    <select name="cmb_ItemCategoryID" id="cmb_ItemCategoryID" class="easyui-combobox" style="width:502px;" editable="false" 
                        data-options = "
                            valueField:'ItemCategoryID',
                            textField:'ItemCategoryName',
                            url:'<?php echo base_url(); ?>custom/get_data/itemcategory',
                            onSelect: function(rec){
                                var id = rec.ItemCategoryID;
                                search_production_amount();	
                            }
                        ">
                    </select>
                </td>
            </tr>
            <tr>
                <td width="50" align="left" valign="middle"><b>Item Code</b></td>
                <td><b>:</b></td>

                <td colspan="2">
                    <input type="text" style="width:500px;height:20px" name="txt_ItemCode" id="txt_ItemCode" class="easyui-validatebox" placeholder="< Item Code >" onkeyup="search_production_amount();" />
                </td>
            </tr>

            <tr>
                <td width="50" align="left" valign="middle"><b>Description</b></td>
                <td><b>:</b></td>

                <td colspan="2">
                    <input type="text" style="width:500px;height:20px" name="txt_ItemDesc" id="txt_ItemDesc" class="easyui-validatebox" placeholder="< Item Name >" onkeyup="search_production_amount();" />
                </td>
            </tr>

            <tr>
                <td colspan="3">
                    <table id="tt_choose_production_amount" class="easyui-datagrid" rownumbers="true"
                        url="<?Php echo base_url()?>list/daily_production_amount/search_production_not_in" 
                        singleSelect="true" fitColumns="true" 
                        pageSize="150" 
                        style="width:828px;height:360px"
                        data-options = "border:true,view:scrollview,autoRowheight:false"
                    >
                        <thead>
                            <tr>
                                <th field="ItemCode" width="150" sortable="true">Item Code</th>
                                <th field="ItemDesc" width="200" sortable="true">Name</th>
                                <th field="ItemCategoryName" width="200" sortable="true">Item Category Name</th>
                            </tr>
                        </thead>
                    </table>
                </td>
            </tr>
        </table>
    </form>
</div>

<div id="dialog-productions-amount" style="border:none;">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="choose_initial_amount();">OK</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-production-amount');">Cancel</a>
</div>

<script type="text/javascript">
var LoopIndexGrid   = 0;

$(document).ready(function(){
	/*$('#grid').datagrid({
            onDblClickRow:function(rowIndex, rowData){
				parent.tab_edit('Edit Purchase Invoice', 'list/purchases_invoice', 'icon-edit', 'edit', rowData.NoTransaction);
			}
	});*/
	
	$('#dtg_item').edatagrid({
		onBeginEdit:function(rowIndex){
			editors = $('#dtg_item').edatagrid('getEditors',rowIndex);
			
			ItemCode		= $(editors[0].target);
			ItemDesc		= $(editors[1].target);
			ItemQty			= $(editors[2].target);
			ItemUnit		= $(editors[3].target);
		
			ItemPrice			= $(editors[4].target);
			Amount			= $(editors[5].target);
			TotalAmount		= $(editors[6].target);
			
			/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
			//save_button_begendedit(SavePrivillage);
			/*=================================end============================================================*/
			ItemDesc.prop('readonly', true);
			ItemUnit.prop('readonly', true);
			/*
				Check apalah dia Inventory apa expense
			*/
			$(ItemCode).click(function(){
				open_modal_item(rowIndex);
			}).mouseover(function(){
				$(this).css('cursor','pointer');
			});
			
			ItemQty.numberbox({
				onChange:function(){
					qty 	 = $(ItemQty).numberbox('getValue');
					price 	 = $(ItemPrice).numberbox('getValue');
				
					total_amount = parseFloat(price) * parseFloat(qty);
					
					$(Amount).numberbox('setValue',total_amount);
					$(TotalAmount).numberbox('setValue',total_amount);
				}
			});
			ItemPrice.numberbox({
				onChange:function(){
					qty 	 = $(ItemQty).numberbox('getValue');
					price 	 = $(ItemPrice).numberbox('getValue');
				
					total_amount = parseFloat(price) * parseFloat(qty);
					$(Amount).numberbox('setValue',total_amount);
					$(TotalAmount).numberbox('setValue',total_amount);
				}
			});	
			
		},
		onEndEdit:function(rowIndex, rowData, changes){
			var item        = $('#dtg_item').datagrid('getRows');
			var sub_total   = 0;
			
			
			$.each(item, function( index, value ) {
				if(value.Amount != undefined){
					sub_total += (value.Price * value.ItemQty);
				}				
			});

			$('#txt_total_invoice').numberbox('setValue',sub_total);
		}
	});
	
	$('#form_import_recur').click(function(){
		$('#dtg_item').edatagrid('saveRow');
	});
		
	$('#cbg_vendor').combogrid({
		onSelect:function(rowIndex, rowData){
			$('#txt_currencyrate').numberbox('setValue', rowData.ExchangeRate);
			$('#txt_currencycode').val(rowData.Vnd_CurrencyCode);
			$('#txt_vendro_addres').val(rowData.VendorAddress);
			$('#txt_terms').val(rowData.TermsPaymentID);
			
			
			if(rowData.Vnd_CurrencyCode == 'IDR' ){
				$('#txt_currencyrate').prop('readonly', true);
			}
			else{
				$('#txt_currencyrate').prop('readonly', false);
			}
		}
	});	
	grid_navigation('Import_Recur','<?php echo $menu_link; ?>'); 
});

function add_row_pop_up(){
	modal_open('Receive Item','dialog-item');
}

function open_modal_item(indexRow){
	LoopIndexGrid = indexRow;
   modal_open('Item Master','dialog-production-amount');
}

function add_row(){
	if($('#txt_transaction_no').val() == ""){
		$.messager.alert('Unseccessfull','Silahkan isikan No transaksi terlebih dahulu','info',function(){	
		});
	}
	else{
		var row 				= $('#dtg_item').datagrid('getRows');
		$('#dtg_item').datagrid('endEdit', (row.length - 1));
		
		$('#dtg_item').edatagrid('addRow',{
			//index: 1,
			row: {
				Amount     : 0,
				ItemQty     : 0,
				TotalAmount : 0,
				Price : 0
			}
		});
		$('#dtg_item').datagrid('beginEdit', (row.length - 1));
	}
}

function choose_initial_amount() {
	var selected_data=$('#tt_choose_production_amount').datagrid('getSelected');	

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

	$.each(item, function(index,value){
		if(selected_data.ItemCode == value.ItemCode){
			$.messager.alert('Unseccessfull','Item sudah tersedia.','error',function(){	
				$('#tt_choose_production_amount').datagrid('reload'); 	
			});
			
			flag = false;
		}
	});
	
	if(flag != false){
		if(selected_data.ItemTypeID == 1){
			ItemStatus = 1;
		}
		else{
			ItemStatus = 0;
		}
		
		var row 				= $('#dtg_item').datagrid('getRows');
		//$('#dg_job').datagrid('endEdit', (row.length - 1));
		
		$('#dtg_item').edatagrid('saveRow');
		
		$('#dtg_item').datagrid('updateRow',{
			index: LoopIndexGrid,
			row: {
				ItemCode       : selected_data.ItemCode,
				ItemDesc       : selected_data.ItemDesc,
				ItemUnit : selected_data.ItemUnit,
				ItemStatus : ItemStatus,
				ItemType : 0,
				ItemCategoryID : selected_data.ItemCategoryID,
				ItemCategoryCode : selected_data.ItemCategoryName
				//Amount_item : 0
			}
		});
		
		$('#dtg_item').datagrid('beginEdit', LoopIndexGrid);
		
		
		modal_close('dialog-production-amount');
	}
}

function choose_recur(){
	$.messager.confirm('Confirm', 'Pastikan semua data sudah benar, jika sudah di import, transaksi tidak bisa dirubah kembali',
        function (r) {
            if (r) {
				if($('#txt_total_invoice').numberbox('getValue') == 0){
					$.messager.alert('Info','Transaksi gagal di import Total Invoice tidak boleh kosong','info',function(){					
						//location.reload();							
					});
				}
				else if($('#txt_currencyrate').numberbox('getValue') == 0){
					$.messager.alert('Info','Transaksi gagal di import Currency Rate tidak boleh kosong(0) silahkan isi dengan angka 1','info',function(){					
						//location.reload();							
					});
				}
				else{
					$('#dtg_item').edatagrid('saveRow');

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

        			$("#detail").val(detail);
		
					save_transaction('<?php echo $menu_link?>','#form_import_recur');
				}   
        }
    });
}

function searching_data(){
		var txt_no 		= $('#txt_IDNumber').val();
		var txt_vendor 	= $('#txt_VendorName').val();
		
		
		
		$('#grid').datagrid('load',{
			NoTransaction 	: txt_no,
			VendorName 	: txt_vendor
		});	
}
$.extend($.fn.datagrid.defaults.editors, {
	
	ItemCode: {
        init: function(container, options){
            var input = $('<input type="text" class="ItemCode" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function(target){
            $(target).remove();
        },
        getValue: function(target){
            return $(target).val();
        },
        setValue: function(target, value){
            $(target).val(value);
        },
        resize: function(target, width){
            $(target)._outerWidth(width);
        }
    }
});

function search_production_amount(){
	
	searchParameter = {};
		
	searchParameter['cmb_ItemCategoryID'] 	= $('#cmb_ItemCategoryID').combobox('getValue');
	searchParameter['txt_ItemCode'] 		= $('#txt_ItemCode').val();
	searchParameter['txt_ItemDesc'] 		= $('#txt_ItemDesc').val();
	
	
	$('#tt_choose_production_amount').datagrid('load',{
		param: searchParameter
	});
}

function delete_row(){
	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){
				var item = $('#dtg_item').datagrid('getData').total;

				$('#dtg_item').datagrid('deleteRow', row_index);
				//calculate_total();
				/*====================on beg in edit saat grid di klik maka tombol save disable===================*/
				$('.save-button').linkbutton('enable');
				/*=================================end============================================================*/
				
				var item        = $('#dtg_item').datagrid('getRows');
				var sub_total   = 0;
				
				
				$.each(item, function( index, value ) {
					if(value.Amount != undefined){
						sub_total += (value.Price * value.ItemQty);
					}				
				});
	
				$('#txt_total_invoice').numberbox('setValue',sub_total);
			
			}
		}
	);
}
</script>