Ext.namespace('CC');
Ext.namespace('CC.b');
Ext.namespace('CC.b.mod');

CC.b.mod.inventory = function(){

	return{
	
		config : {},
	
		init : function(){
			CC.f.mod.inventory.init();
		}
	}

}();

Ext.namespace('CC.f');
Ext.namespace('CC.f.mod');

CC.f.mod.inventory = function(){
	
	return{
		
		ajaxUrl : CC_baseURL +'inventory/',
		
		grids : {},
		formItems : [],
		windows: [],
		
		warehouse_changed : false,
		last_movement_id : null,
		last_invoice_group_id : null,
				
		init : function(){
			eval( 'this.'+ CC.b.mod.inventory.config.start_event +'();' );
		},
		
		list : function () {
			
			this.last_invoice_group_id = null;
			var tbarConfig = [ 
	        		{
	        			text : CC.b.enter.config.gridNewRecord,
	        			handler : CC.f.mod.inventory.displayBillForm
	        		},
	        		{ xtype : 'tbfill' },
					{
						xtype : 'label',
						text : CC.b.mod.inventory.config.textWarehouse,
						style : 'padding:0 2px;'
					},
	        		{
	        			xtype : 'combo',
	        			id : 'WAREHOUSE_ID',
	        			dataIndex : 'WAREHOUSE_ID',
	        			displayField : 'text',
	            		valueField : 'value',
	        			mode : 'remote',
	        			triggerAction : 'all',
	        			store : new Ext.data.JsonStore(
	        				{
	        					autoLoad: true,
		        				url : this.ajaxUrl + 'extComboListFilterWarehouse',
		              			fields : ['value', 'text'],
		              			root: 'result'
		        			}
	        			),
	               		autoLoad : true,
	               		typeAhead : true,
	               		forceSelection : true,
	        			allowBlank : false
	        		}
        		];
        	
        	//modulNameParam, gridName, ajaxUrl, primaryField, tbarConfig
			CC.help.grid.initGrid(
				'inventory', 
				{
					dataIndex : 'bill_base',
					ajaxUrl : 'extBase',
					primaryField : 'ID'
				}, 
				tbarConfig
			);
			
			CC.main.layout.center.add(this.grids.bill_base.grid);
			
			CC.f.mod.inventory.grids.bill_base.gridStore.baseParams = {
				invoice_group_id : this.last_invoice_group_id
			};
			
			CC.main.layout.center.doLayout();
			this.grids.bill_base.grid.on('rowdblclick', this.displayEditorWindowByDblClick );
			
			// Warehouse alapérték beállítás
			ware_combo = CC.help.form.setComboDefaultValue( 
				'WAREHOUSE_ID',
				CC.b.mod.inventory.config.defaultWarehouse.ID,
				CC.b.mod.inventory.config.defaultWarehouse.NAME
			);
			ware_combo.on('select', CC.f.mod.inventory.ware_filter_change );
		},
		
		listBills : function () {
			var tbarConfig = [ 
        		{
        			text : CC.b.enter.config.gridNewRecord,
        			//handler : CC.f.mod.inventory.displayBillForm
        			handler : CC.f.mod.inventory.open_antecedent_selector_window_for_bills
        		},
        		{
        			xtype : 'combo',
        			id : 'MOVEMENT_TYPE_ID_BILL',
        			dataIndex : 'MOVEMENT_TYPE_ID_BILL',
        			displayField : 'text',
            		valueField : 'value',
        			mode : 'remote',
        			triggerAction : 'all',
        			store : new Ext.data.JsonStore(
        				{
        					autoLoad: true,
	        				url : this.ajaxUrl + 'extComboListFilterMovementTypeBills',
	              			fields : ['value', 'text'],
	              			root: 'result'
	        			}
        			),
               		autoLoad : true,
               		editable : false,
               		forceSelection : true,
        			allowBlank : false
        		},
        		{ xtype : 'tbfill' },
        		{
        			text : CC.b.mod.inventory.config.textInvoiceGroup,
        			border : false
        		},
        		{
        			xtype : 'combo',
        			id : 'INVOICE_GROUP_ID',
        			dataIndex : 'INVOICE_GROUP_ID',
        			displayField : 'text',
            		valueField : 'value',
        			mode : 'remote',
        			triggerAction : 'all',
        			store : new Ext.data.JsonStore(
        				{
        					autoLoad: true,
	        				url : this.ajaxUrl + 'extComboListFilterInvoiceGroupId',
	              			fields : ['value', 'text'],
	              			root: 'result'
	        			}
        			),
               		autoLoad : true,
               		typeAhead : true,
               		forceSelection : true,
        			allowBlank : false
        		}
    		];
	    	
	    	//						modulNameParam, gridName, ajaxUrl, primaryField, tbarConfig
			CC.help.grid.initGrid(
				'inventory', 
				{
					dataIndex : 'bill_base',
					ajaxUrl : 'extBill',
					primaryField : 'ID'
				}, 
				tbarConfig
			);
			CC.main.layout.center.add(this.grids.bill_base.grid);

			CC.f.mod.inventory.grids.bill_base.gridStore.baseParams = {
				invoice_group_id : CC.b.mod.inventory.config.defaultInvoiceGroup.ID
			};
			
			CC.main.layout.center.doLayout();
			this.grids.bill_base.grid.on('rowdblclick', this.displayEditorWindowByDblClick );
			
			invoice_group_combo = CC.help.form.setComboDefaultValue( 
				'INVOICE_GROUP_ID',
				CC.b.mod.inventory.config.defaultInvoiceGroup.ID,
				CC.b.mod.inventory.config.defaultInvoiceGroup.NAME
			);
			invoice_group_combo.on('select', CC.f.mod.inventory.invoice_group_filter_change );
			
			bill_move_type_combo = CC.help.form.setComboDefaultValue( 
				'MOVEMENT_TYPE_ID_BILL',
				CC.b.mod.inventory.config.billMoveTypeId,
				CC.b.mod.inventory.config.billMoveTypeName
			);		
			ware_combo.on('select', CC.f.mod.inventory.ware_filter_change );
		},
		
		
		
		
		displayEditorWindow : function( dbId, srcBillIds, movement_type_id, duplicate ){
			
			var request_params = null;
			request_params = {};
			if ( dbId != null ) {
				request_params.ID = dbId;
			}
			request_params.duplicate = duplicate;
			if ( srcBillIds != null ) {
				request_params.antecedent_bill_ids = Ext.encode( srcBillIds );
			}
			if ( movement_type_id != null && movement_type_id > 0 ) {
				request_params.movement_type_id = movement_type_id;
			}
			
			
			var param ={
				singleInstance : true,
				url: CC.f.mod.inventory.ajaxUrl +'extBaseform',
				params: request_params,
				success: function(result){
					if ( typeof result.success != 'undefined' && result.success == false ) {
						if ( typeof result.message != 'undefined' ) {
							Ext.MessageBox.show(
								{
									title: CC.b.enter.config.msgError,
									msg: result.message,
									buttons: Ext.MessageBox.OK,
									icon: Ext.MessageBox.ERROR
								}
							);

						}
					} else {	
						CC.b.mod.inventory.config.formData.editForm = result;
						if (result.finalized == 'N' || duplicate || typeof duplicate=='undefined'){
							//makeitems(formleíró adatok, modul neve, formon belüli index, gridconfig helye helye)
							CC.help.form.makeItems( CC.b.mod.inventory.config.formData.editForm.items, 'inventory', 'edit', CC.b.mod.inventory.config.grids.bill_base);
							CC.help.form.showWindow( CC.b.mod.inventory.config.formData.editForm.items, 'inventory', 'edit', 'doSaveRecord', CC.b.mod.inventory.config.formData.editForm.window.edit);
							CC.f.mod.inventory.windows.edit.dbId = dbId;
							CC.f.mod.inventory.windows.edit.duplicate = duplicate;
							
							
							// FIXME ez nem megy mac alatt!!!
							/*try{
							Ext.getCmp('ISSUE_DATE$bill_base').on('change',function(obj){
								var payType = Ext.getCmp('PAYMENT_METHOD$bill_base').getValue();
								
								if(payType == 'cache' || payType == 'online_card'){
									var time = Ext.getCmp('ISSUE_DATE$bill_base').getValue();
									Ext.getCmp('TRADE_DATE$bill_base').setValue(time);
									Ext.getCmp('TRADE_DATE$bill_base').setDisabled(true);
									Ext.getCmp('PAYMENT_DATE$bill_base').setValue(time);
									Ext.getCmp('PAYMENT_DATE$bill_base').setDisabled(true);
								}else{
									Ext.getCmp('TRADE_DATE$bill_base').reset();
									Ext.getCmp('TRADE_DATE$bill_base').setDisabled(false);
									Ext.getCmp('PAYMENT_DATE$bill_base').reset();
									Ext.getCmp('PAYMENT_DATE$bill_base').setDisabled(false);
								}
							});
							}catch(e){}
												
							/*var selector = Ext.getCmp('PAYMENT_METHOD$bill_base');
							for(var i=0; i<selector.items.length;i++){
								if(typeof selector.items.items[i] == 'object'){
									//die_r(Ext.getCmp(selector.items.items[i].id));
									Ext.getCmp(selector.items.items[i].id).on('check', function(obj){
										Ext.getCmp('ISSUE_DATE$bill_base').fireEvent('change');
									});
								}
							}*/					
						}else{
							CC.help.form.makeItems( CC.b.mod.inventory.config.formData.editForm.items, 'inventory', 'edit', CC.b.mod.inventory.config.grids.bill_base);
							CC.help.form.showWindow( CC.b.mod.inventory.config.formData.editForm.items, 'inventory', 'edit', 'cantEdit', CC.b.mod.inventory.config.formData.editForm.window.edit);
							CC.f.mod.inventory.windows.edit.dbId = dbId;
							
						}
					}
				}
			};	
			CC.help.ajax.doAjax(param);
		},
		
		cantEdit : function(){
		
			Ext.MessageBox.show(
			{
				title: CC.b.enter.config.msgError,
				msg: 'Finalized',
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.ERROR
			});
		},
		
		displayEditorWindowByDblClick : function( gridObject, rowIndex ){
			var key = null;
			var gridObject = CC.f.mod.inventory.grids.bill_base.grid;
			if ( typeof gridObject.selModel.selections.keys == 'object' ) {
				key = gridObject.selModel.selections.keys[0];
			} else {
				key = gridObject.selModel.selections.keys;
			}
			CC.f.mod.inventory.displayEditorWindow( key, null, null, false );
		},

		displayBillForm : function(){
			CC.f.mod.inventory.displayEditorWindow( null, null, CC.b.mod.inventory.config.billMoveTypeId, false );
		},
		

		ware_filter_change : function() {
			if ( this.isValid() ) {
				var temp = {warehouse_id : this.getValue() };		
				CC.f.mod.inventory.warehouse_changed = true;
				CC.f.mod.inventory.reload_grid(temp);
			}
		},

		invoice_group_filter_change : function() {
			if ( this.isValid() ) {
				CC.f.mod.inventory.last_invoice_group_id = this.getValue();
				CC.f.mod.inventory.reload_grid();
			}
		},
		
		reload_grid : function(param) {
			CC.f.mod.inventory.grids.bill_base.gridStore.baseParams = param;
			CC.f.mod.inventory.grids.bill_base.gridStore.reload();
		},
		
		changePartnerHandData : function( combo_obj ) {
			var id_prefix = combo_obj.id.split('_');
			id_prefix = id_prefix[0] +'_';
			var id_suffix = '$bill_base';
			var url_params = {};
			url_params.ID = combo_obj.getValue();
			
			var param ={
				url: CC.f.mod.inventory.ajaxUrl +'extGetPartner',	
				params : url_params,
				success: function(result){
					if ( result.success ) {
						Ext.getCmp( id_prefix + 'NAME' + id_suffix ).setValue( result.partner.NAME );
						Ext.getCmp( id_prefix + 'ZIP' + id_suffix ).setValue( result.partner.ZIP );
						Ext.getCmp( id_prefix + 'CITY' + id_suffix ).setValue( result.partner.CITY );
						Ext.getCmp( id_prefix + 'ADDRESS' + id_suffix ).setValue( result.partner.ADDRESS );
						Ext.getCmp( id_prefix + 'TAX_NUMBER' + id_suffix ).setValue( result.partner.TAX_NUMBER );
						Ext.getCmp( id_prefix + 'BANK_ACCOUNT' + id_suffix ).setValue( result.partner.BANK_ACCOUNT );
					}
				}
			};	
			CC.help.ajax.doAjax(param);
		},

		open_antecedent_selector_window_for_bills : function(){
			var request_params = {
				movement_type_id : Ext.getCmp('MOVEMENT_TYPE_ID_BILL').getValue()	
			};
			var param ={
				singleInstance : true,
				url: CC.f.mod.inventory.ajaxUrl +'extAntecedentSelectorForm',
				params: request_params,
				success: function(result){
					if ( typeof result.noAntecedents == 'undefined' ) {
						CC.b.mod.inventory.config.formData.antecedentSelectorForm = result;
						//makeitems(formleíró adatok, modul neve, formon belüli index, gridconfig helye helye)
						CC.help.form.makeItems( CC.b.mod.inventory.config.formData.antecedentSelectorForm.items, 'inventory', 'antecedentSelector', CC.b.mod.inventory.config.grids.open_bills);
						CC.help.form.showWindow( CC.b.mod.inventory.config.formData.antecedentSelectorForm.items, 'inventory', 'antecedentSelector', 'doSelectAntecedentsBills', CC.b.mod.inventory.config.formData.antecedentSelectorForm.window.antecedentSelector);
						CC.f.mod.inventory.windows.antecedentSelector.movement_type_id = request_params.movement_type_id;
					} else {
						CC.f.mod.inventory.displayEditorWindow( null, null, Ext.getCmp('MOVEMENT_TYPE_ID_BILL').getValue(), false );
					}
				}
			};	
			CC.help.ajax.doAjax(param);
		},





		open_antecedent_selector_window : function(){
			var request_params = {
				warehouse_id : Ext.getCmp('WAREHOUSE_ID').getValue(),
				movement_type_id : Ext.getCmp('MOVEMENT_TYPE_ID').getValue()	
			};
			var param ={
				singleInstance : true,
				url: CC.f.mod.inventory.ajaxUrl +'extAntecedentSelectorForm',
				params: request_params,
				success: function(result){
					if ( typeof result.noAntecedents == 'undefined' ) {
						CC.b.mod.inventory.config.formData.antecedentSelectorForm = result;
						//makeitems(formleíró adatok, modul neve, formon belüli index, gridconfig helye helye)
						CC.help.form.makeItems( CC.b.mod.inventory.config.formData.antecedentSelectorForm.items, 'inventory', 'antecedentSelector', CC.b.mod.inventory.config.grids.open_bills);
						CC.help.form.showWindow( CC.b.mod.inventory.config.formData.antecedentSelectorForm.items, 'inventory', 'antecedentSelector', 'doSelectAntecedents', CC.b.mod.inventory.config.formData.antecedentSelectorForm.window.antecedentSelector);
						CC.f.mod.inventory.windows.antecedentSelector.warehouse_id = request_params.warehouse_id;
						CC.f.mod.inventory.windows.antecedentSelector.movement_type_id = request_params.movement_type_id;
					} else {
						CC.f.mod.inventory.displayEditorWindow( null, null, Ext.getCmp('MOVEMENT_TYPE_ID').getValue(), false );
					}
				}
			};	
			CC.help.ajax.doAjax(param);
		},
		
		doSelectAntecedents : function(){
			var data = CC.help.form.getFormData( CC.f.mod.inventory.formItems.antecedentSelector );
			CC.f.mod.inventory.displayEditorWindow( null, data['default'].open_bills, Ext.getCmp('MOVEMENT_TYPE_ID').getValue(),false );
			return true;
		},
		
		doSelectAntecedentsBills : function(){
			var data = CC.help.form.getFormData( CC.f.mod.inventory.formItems.antecedentSelector );
			CC.f.mod.inventory.displayEditorWindow( null, data['default'].open_bills, Ext.getCmp('MOVEMENT_TYPE_ID_BILL').getValue(), false );
			return true;
		},
		
		doSaveRecord : function(){
			var ok = CC.help.form.validateForm(CC.f.mod.inventory.formItems.edit);
			if ( ok ) {
				var data = CC.help.form.getFormData(CC.f.mod.inventory.formItems.edit);
				if (!CC.f.mod.inventory.windows.edit.duplicate){
					data['default']['ID'] = CC.f.mod.inventory.windows.edit.dbId;
				}else{
					if (data['default']['FINALIZED'] == true){
						data['default']['FINALIZED'] = false;
					}
				}		
				data['default']['VENDOR_ID'] = Ext.getCmp('WAREHOUSE_ID').getValue();
				var param ={
					url: CC.f.mod.inventory.ajaxUrl +'extBasesave',
					params: {
						formdata: Ext.encode( data )
					},
					success: function(result){
						if ( result.success ) {
							//CC.f.mod.inventory.windows.edit.close();
						} else {
							Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
						}
						CC.f.mod.inventory.grids.bill_base.gridStore.reload();
					}
				};	
				CC.help.ajax.doAjax(param);
			} else {
				Ext.MessageBox.alert( CC.b.enter.config.msgError, CC.b.enter.config.msgCheckField );
			}
			
			return ok;
		},
		
		doDelete : function( key ) {
			Ext.MessageBox.confirm('', 
				CC.b.mod.inventory.config.deleteQuestion, 
				function( btn )
				{
					if (btn == 'yes')
					{
						CC.f.mod.inventory.deleteFromDatabase( key, false );
					}
				}
			);
		},
		
		deleteFromDatabase : function( pDbId, confirmed ) {
			var url_params = {
				ID: pDbId
			};
			if ( confirmed ) {
				url_params['confirmed'] = true;
			}
			
			var param ={
				url: CC.f.mod.inventory.ajaxUrl +'extBasedelete',
				params: url_params,
				success: function(result){
					if ( result.success ) {
						CC.f.mod.inventory.grids.bill_base.gridStore.reload();
					} else {
						if ( result.confirm ) {
							Ext.MessageBox.confirm('', 
								result.message, 
								function( btn )
								{
									if (btn == 'yes')
									{
										CC.f.mod.inventory.deleteFromDatabase( pDbId, true );
									}
								}
							);
						} else {
							Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
						}
					}
				}
			};	
			CC.help.ajax.doAjax(param);
		},
		

		doPrint : function( pDbId ){
			var param ={
				url: CC.f.mod.inventory.ajaxUrl +'extIsPrintable',
				params: {
					ID: pDbId
				},
				success: function(result){
					if ( !result.success ) {
						Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
					} else {
						window.open(CC.f.mod.inventory.ajaxUrl +'PrintDeliveryNotes/ID/'+ pDbId );
					}
				}
			};	
			CC.help.ajax.doAjax(param);
		},
		
		
		before_query_delivery_address : function( obj ) {
			
			var combo_obj = obj.combo;
			var id_suffix = '$bill_base';
			var customer_id_obj = CCgetCmp( CC.f.mod.inventory.formItems.edit ,'CUSTOMER_ID'+ id_suffix );
			if ( customer_id_obj != null ) {
				var last_customer_id = customer_id_obj.getValue();
				combo_obj.store.baseParams = {
					customer_id : last_customer_id
				}
			}
			return true;
		},
		
		
		// ------ v v v ---- Tételek kezelése ---- v v v -------------------------------
		/**
		 * bill_base - bill_item
		 * editForm	 - itemEditForm
		 * edit		 - itemEdit
		 */
		
		/*
		display_bill_item_EditorWindow : function( dbId ){
			var request_params = null;
			if ( dbId != null ) {
				request_params = { 'ID': dbId };
			} else {
				request_params = {};
			}
			
			var param ={
				singleInstance : true,
				url: CC.f.mod.inventory.ajaxUrl +'extItemform',
				params: request_params,
				success: function(result){
					CC.b.mod.inventory.config.formData.bill_item_EditForm = result;
					//makeitems(formleíró adatok, modul neve, formon belüli index, gridconfig helye helye)
					CC.help.form.makeItems( CC.b.mod.inventory.config.formData.bill_item_EditForm.items, 'inventory', 'bill_item_Edit', CC.b.mod.inventory.config.grids.bill_item);
					CC.help.form.showWindow( CC.b.mod.inventory.config.formData.bill_item_EditForm.items, 'inventory', 'bill_item_Edit', 'doSave_bill_item_Record', CC.b.mod.inventory.config.formData.bill_item_EditForm.window.edit);
					CC.f.mod.inventory.windows.bill_item_Edit.dbId = dbId;
					
					var postfix = '$bill_item';
					Ext.getCmp( 'AMOUNT'+ postfix ).on( 'change', CC.f.mod.inventory.bill_item_num_change );
					Ext.getCmp( 'NET_UNIT_PRICE'+ postfix ).on( 'change', CC.f.mod.inventory.bill_item_num_change );
					Ext.getCmp( 'DISCOUNT'+ postfix ).on( 'change', CC.f.mod.inventory.bill_item_discount_change );
					Ext.getCmp( 'DISCOUNTED_NET_UNIT_PRICE'+ postfix ).on( 'change', CC.f.mod.inventory.bill_item_num_change );
				}
			};	
			CC.help.ajax.doAjax(param);
		},
		*/
		
		showAddbill_itemForm : function() {
			//CC.f.mod.inventory.display_bill_item_EditorWindow( null );
			CC.f.mod.inventory.grids.bill_item.grid.store.add( new Ext.data.Record(
					{
						id : -1,
						AMOUNT : 1
					}
				)
			);
		},
		

		/*
		doSave_bill_item_Record : function(){
			var ok = CC.help.form.validateForm(CC.f.mod.inventory.formItems.bill_item_Edit);
			if ( ok ) {
				var data = CC.help.form.getFormData(CC.f.mod.inventory.formItems.bill_item_Edit);
				data['default']['ID'] = CC.f.mod.inventory.windows.bill_item_Edit.dbId;
				
				//CCdebug( 'data', data );
				
				var param ={
					url: CC.f.mod.inventory.ajaxUrl +'extItemsave',
					params: {
						formdata: Ext.encode( data )
					},
					success: function(result){
						if ( result.success ) {
							
							CC.f.mod.inventory.changeSumPrice( result.sumPrice );
							
							//CC.f.mod.inventory.windows.edit.close();
						} else {
							Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
						}
						CC.f.mod.inventory.grids.bill_item.gridStore.reload();
					}
				};	
				CC.help.ajax.doAjax(param);
			} else {
				Ext.MessageBox.alert( CC.b.enter.config.msgError, CC.b.enter.config.msgCheckField );
			}
			
			return ok;
		},
		*/
		
		doDelete_bill_item : function( key ) {
			var record = CC.f.mod.inventory.grids.bill_item.grid.store.getById( key );
			if ( typeof record.data.ID == 'undefined' ) {
				CC.f.mod.inventory.grids.bill_item.grid.store.remove( record );
			} else {
				Ext.MessageBox.confirm('', 
					CC.b.mod.inventory.config.deleteItemQuestion, 
					function( btn )
					{
						if (btn == 'yes')
						{
							CC.f.mod.inventory.delete_bill_item_FromDatabase( key );
						}
					}
				);
			}
		},
		
		delete_bill_item_FromDatabase : function( pDbId ) {
			var param ={
				url: CC.f.mod.inventory.ajaxUrl +'extItemdelete',
				params: {
					ID: pDbId
				},
				success: function(result){
					if ( result.success ) {
						if ( typeof result.sumPrice != 'undefined' ) {
							CC.f.mod.inventory.changeSumPrice( result.sumPrice );
						}
						CC.f.mod.inventory.grids.bill_item.gridStore.reload();
					} else {
						Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
					}
					
				}
			};
			CC.help.ajax.doAjax(param);
		},
		

		changeSumPrice : function( price ) {
			/*postfix = '$bill_base';
			Ext.getCmp( 'NET'+ postfix ).setValue( price.SUM_NET );
			Ext.getCmp( 'GROSS'+ postfix ).setValue( price.SUM_GROSS );*/
		},
		

		// FIXME Ezt a gridhelp -nek kellene megoldania
		bill_item_renderer_packing_name : function( value, metadata, record, colIndex, rowIndex, store ) {
			return record.data.PRODUCT_NAME;
		},
		
		bill_item_autosave : function( event ) {
			/**
			 * The edit event object has the following properties 
		    * grid - This grid
		    * record - The record being edited
		    * field - The field name being edited
		    * value - The value being set
		    * originalValue - The original value for the field, before the edit.
		    * row - The grid row index
		    * column - The grid column index
		    */
			if ( typeof event.record != 'undefined' ) {
				switch ( event.field ) {
					
					case 'PACKING_ID':
						CC.f.mod.inventory.bill_item_change_packing( event.record )
						break;
					
					case 'AMOUNT':
						CC.f.mod.inventory.bill_item_save( event.record );
						break;
					case 'NET_UNIT_PRICE':
					case 'DISCOUNTED_NET_UNIT_PRICE':
					case 'DISCOUNT_AMOUNT':
						CC.f.mod.inventory.bill_item_amount_change( event.record )
						break;
						
					case 'DISCOUNT':
						CC.f.mod.inventory.bill_item_discount_percent_change( event.record )
						break;
						
					default:
						die_r( event.record, 'bill_item_autosave: '+ event.field);
						break;
				}
				
				
				
			}
		},
		
		bill_item_save : function( record ) {
			if(typeof record.modified != 'undefined'){
		    	if(typeof record.modified.PACKING_ID != 'undefined'){
		    		record.data.PACKING_ID = record.modified.PACKING_ID;
		    	} 
		    }	
			
			if ( 
				typeof record.data.PACKING_ID != 'undefined' &&
				typeof record.data.AMOUNT != 'undefined'
			) {
			
				var formdata = {};
				formdata['default'] = record.data;
				var param ={
					url: CC.f.mod.inventory.ajaxUrl +'extItemsave',
					params: {
						formdata: Ext.encode( formdata )
					},
					success: function(result){
						if ( result.success ) {
							CC.f.mod.inventory.changeSumPrice( result.sumPrice );
							if ( typeof result.newId != 'undefined' ) {
								record.set('ID', result.newId );
								record.id = result.newId;
							}
						} else {
							Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
						}
					}
				};
				CC.help.ajax.doAjax(param);
				
			}
		},
		
		bill_item_change_packing : function( record ) {
			var customer_id = null;
			
			// FIXME ezt nem találja meg az Ext!!!
			//var customer_id_combo_obj = Ext.getCmp( "CUSTOMER_ID$bill_base" );
			var customer_id_combo_obj = null;
			var idx = 0;
			for ( idx = 0; (idx < CC.f.mod.inventory.formItems.edit.length) && customer_id_combo_obj == null; idx++ ) {
				if ( CC.f.mod.inventory.formItems.edit[ idx ].dataIndex == 'CUSTOMER_ID' ) {
					customer_id_combo_obj = CC.f.mod.inventory.formItems.edit[ idx ];
				}
			}
			try {
				customer_id = customer_id_combo_obj.getValue()
			} catch(e){
				die_r( customer_id_combo_obj ,'furcs ollyektum' );
			}
			
			var param ={
				url: CC.f.mod.inventory.ajaxUrl +'extPackingData',
				params: {
					ID: record.get( 'PACKING_ID' ),
					CUSTOMER_ID : customer_id
				},
				success: function(result){
					if ( result.success ) {
						
						//die_r( result, 'result' );
						
						if ( record.get('UNIT_TYPE_NAME') != result.data.UNIT_TYPE_NAME ) {
							record.set( 'UNIT_TYPE_NAME', result.data.UNIT_TYPE_NAME );
						}
						
						if ( record.get('VAT_KEY') != result.data.VAT_KEY ) {
							record.set( 'VAT_KEY', result.data.VAT_KEY );
						}
						if ( record.get('NET_UNIT_PRICE') != result.data.NET_UNIT_PRICE ) {
							record.set( 'NET_UNIT_PRICE', result.data.NET_UNIT_PRICE );
						}
						if ( record.get('DISCOUNT') != result.data.DISCOUNT ) {
							record.set( 'DISCOUNT', result.data.DISCOUNT );
						}
						
						CC.f.mod.inventory.bill_item_amount_change( record );
					} else {
						Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
					}
				}
			};
			CC.help.ajax.doAjax(param);
			
		},
		
		bill_item_amount_change : function( record ) {
			var tmp_price = record.get('NET_UNIT_PRICE');
			var tmp_discount = 0;
			if ( record.get('DISCOUNTED_NET_UNIT_PRICE') > 0 ) {
				tmp_price = record.get('DISCOUNTED_NET_UNIT_PRICE');
				tmp_discount = round_fixed( 100 * (1 - ( record.get('DISCOUNTED_NET_UNIT_PRICE') / record.get('NET_UNIT_PRICE') )) , 4);
			} else {
				tmp_discount = '';
				record.set('DISCOUNTED_NET_UNIT_PRICE', '' );
			}
			
			if ( record.get( 'DISCOUNT' ) != tmp_discount ) {
				record.set( 'DISCOUNT', tmp_discount );
			}
			
			var tmp_price = record.get('AMOUNT') * tmp_price;
			//var tmp_net = round_fixed( tmp_price, 2 );
			//record.set( 'NET', round_fixed( tmp_price, 2 ) );
			if ( record.get('NET') != tmp_price ) {
				record.set( 'NET', tmp_price );
			}
			
			//var tmp_gross = round_fixed( tmp_price * (1+( record.get('VAT_KEY')/100 )), 2);
			var tmp_gross = tmp_price * (1+( record.get('VAT_KEY')/100 ));
			if ( record.get('GROSS') != tmp_gross ) {
				record.set( 'GROSS', tmp_gross );
			}
			
			this.bill_item_save( record );
		},

		bill_item_discount_percent_change : function( record ) {
			
			tmp_price = record.get('NET_UNIT_PRICE');
			discount_percent = record.get('DISCOUNT');
			if ( discount_percent > 0 && discount_percent < 100 ) {
				tmp_price = round_fixed( tmp_price * (1 -(discount_percent/100) ), 4 );
				record.set( 'DISCOUNTED_NET_UNIT_PRICE', tmp_price );
			} else {
				record.set( 'DISCOUNT', null );
				record.set( 'DISCOUNTED_NET_UNIT_PRICE', null );
			}
			
			tmp_price = record.get('AMOUNT') * tmp_price;
			//record.set( 'NET', round_fixed( tmp_price, 2) );
			record.set( 'NET', tmp_price );
			//record.set( 'GROSS', round_fixed( tmp_price * (1+( record.get('VAT_KEY')/100 )), 2) );
			record.set( 'GROSS', tmp_price * (1+( record.get('VAT_KEY')/100 )) );

			this.bill_item_save( record );
		},

		
		duplicate : function(id){
			CC.f.mod.inventory.displayEditorWindow( id, null, null, true );
		}
		
		/**
		 * Formos bizonylat tétel kezelés
		 */
		
		/*
		bill_item_num_change : function() {
			
			postfix = '$bill_item';
			
			amount_OBJ = Ext.getCmp('AMOUNT' + postfix );
			net_unit_price_OBJ = Ext.getCmp('NET_UNIT_PRICE' + postfix );
			discount_OBJ = Ext.getCmp('DISCOUNT' + postfix );
			discounted_net_unit_price_OBJ = Ext.getCmp('DISCOUNTED_NET_UNIT_PRICE' + postfix );
			
			net_OBJ = Ext.getCmp('NET' + postfix );
			vat_key_OBJ = Ext.getCmp('VAT_KEY' + postfix );
			gross_OBJ = Ext.getCmp('GROSS' + postfix );
			
			tmp_price = net_unit_price_OBJ.getValue();
			if ( discounted_net_unit_price_OBJ.getValue() > 0 ) {
				tmp_price = discounted_net_unit_price_OBJ.getValue();
				discount_OBJ.setValue( round_fixed( 100 * (1 - (discounted_net_unit_price_OBJ.getValue()/net_unit_price_OBJ.getValue())) , 4) );
			} else {
				discount_OBJ.setValue( null );
				discounted_net_unit_price_OBJ.setValue( null );
			}
			
			
			tmp_price = amount_OBJ.getValue() * tmp_price;
			net_OBJ.setValue( round_fixed( tmp_price, 2 ) );
			gross_OBJ.setValue( round_fixed( tmp_price * (1+(vat_key_OBJ.getValue()/100)), 2) );
			
		},
		
		bill_item_discount_change : function() {

			postfix = '$bill_item';
			
			amount_OBJ = Ext.getCmp('AMOUNT' + postfix );
			net_unit_price_OBJ = Ext.getCmp('NET_UNIT_PRICE' + postfix );
			discount_OBJ = Ext.getCmp('DISCOUNT' + postfix );
			discounted_net_unit_price_OBJ = Ext.getCmp('DISCOUNTED_NET_UNIT_PRICE' + postfix );
			
			net_OBJ = Ext.getCmp('NET' + postfix );
			vat_key_OBJ = Ext.getCmp('VAT_KEY' + postfix );
			gross_OBJ = Ext.getCmp('GROSS' + postfix );
			
			tmp_price = net_unit_price_OBJ.getValue();
			discount_percent = discount_OBJ.getValue();
			if ( discount_percent > 0 && discount_percent < 100 ) {
				tmp_price = round_fixed( tmp_price * (1 -(discount_OBJ.getValue()/100) ), 4 );
				discounted_net_unit_price_OBJ.setValue( tmp_price );
			} else {
				discount_OBJ.setValue( null );
				discounted_net_unit_price_OBJ.setValue( null );
			}
			
			
			tmp_price = amount_OBJ.getValue() * tmp_price;
			net_OBJ.setValue( round_fixed( tmp_price, 2) );
			gross_OBJ.setValue( round_fixed( tmp_price * (1+(vat_key_OBJ.getValue()/100)), 2) );
			
		},
		
		changePacking : function( product_id_combo_obj ) {
			var field_suffix = '$bill_item';
			var customer_id = null;
			
			// FIXME ezt nem találja meg az Ext!!!
			//var customer_id_combo_obj = Ext.getCmp( "CUSTOMER_ID$bill_base" );
			var customer_id_combo_obj = null;
			var idx = 0;
			for ( idx = 0; (idx < CC.f.mod.inventory.formItems.edit.length) && customer_id_combo_obj == null; idx++ ) {
				if ( CC.f.mod.inventory.formItems.edit[ idx ].dataIndex == 'CUSTOMER_ID' ) {
					customer_id_combo_obj = CC.f.mod.inventory.formItems.edit[ idx ];
				}
			}
			try {
				customer_id = customer_id_combo_obj.getValue()
			} catch(e){
				die_r( customer_id_combo_obj ,'furcs ollyektum' );
			}
			
			var param ={
				url: CC.f.mod.inventory.ajaxUrl +'extPackingData',
				params: {
					ID: product_id_combo_obj.getValue(),
					CUSTOMER_ID : customer_id
				},
				success: function(result){
					if ( result.success ) {
						
						//die_r( result, 'result' );
						
						Ext.getCmp( 'VAT_KEY'+ field_suffix ).setValue( result.data.VAT_KEY );
						Ext.getCmp( 'NET_UNIT_PRICE'+ field_suffix ).setValue( result.data.NET_UNIT_PRICE );
						Ext.getCmp( 'DISCOUNT'+ field_suffix ).setValue( result.data.DISCOUNT );
						
						CC.f.mod.inventory.bill_item_num_change();
					} else {
						Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
					}
				}
			};
			CC.help.ajax.doAjax(param);
			
		}
		*/
		
		/**
		 * IDÁIG Formos bizonylat tétel kezelés
		 */
		
	}
	
}();
