Ext.namespace('CC');
Ext.namespace('CC.help');

CC.help.form =  function(){
	return{
		
		allowedFormItemXtypes : 'default,gridselector,grid,textarea,combo,checkbox,checkboxgroup,textfield,datefield,checkboxbar,hidden,radiogroup,radio,radiobar,button,htmleditor,fileupload,panel,button,numberfield,datetimefield',
		
		fieldtypes_default : {
		
			numberfield:{
				style : 'text-align:right;'
			},
			fileupload:{
			},
			radiogroup:{
			},
			
			htmleditor:{
			},
			
			radiobar:{
			},
			
			hidden:{
			},
			
			gridselector : {
			},
			
			grid : {
				
			},
			
			textarea : {
				width : '45%',
				height: 80
				 
			},
			combo : {
				xtype : 'combo',
				triggerAction : 'all',
				allowCreate : false,
				minChars : 2
			},
			checkbox : {},
			checkboxgroup : {},
			textfield : {
				xtype : 'textfield',
				fieldLabel : 'Text input',
				allowBlank : true
			},			
			datefield : {
				xtype : 'datefield',
				format : 'Y-m-d H:i:s',
				fieldLabel: 'Date',
				allowBlank: true
			},
			datetimefield:{
				format : 'Y-m-d H:i:s'
			}
		},
		
		//create Index array from gridConfig cmParamIndex
		createCmParamIndex : function( gridConfig ) {
			if ( gridConfig != null && !isEmpty( gridConfig ) ) {
				create = false;
				
				try {
					if ( typeof gridConfig.cmParamIndex == 'array' ) {
						create = gridConfig.cmParamIndex.length() == 0;
					} else {
						create = true;
					}
				} catch( e ) {
					create = true;
				}
				
				if ( create ) {
					gridConfig.cmParamIndex = [];
					for (i in gridConfig.cmParam ){
						if ( typeof gridConfig.cmParam[i] == 'object' ) {
							gridConfig.cmParamIndex[ gridConfig.cmParam[i].dataIndex ] = i;
						}
					}
				}
			}
		},
		
		createCombo : function(itemParam, modulNameParam, gridConfig, gridItemParam){
			var allowBlankUrlParam = '';
			if (
				(typeof gridItemParam.allowBlank != 'undefined' && gridItemParam.allowBlank) ||
				(typeof itemParam.allowBlank != 'undefined' && itemParam.allowBlank)				
			) {
				allowBlankUrlParam = '?allow_blank=1';
			}
			if(gridItemParam.mode == 'remote'){
			 	var tempStore = new Ext.data.JsonStore({
					autoLoad: false,
					url: CC.f.mod[modulNameParam].ajaxUrl + gridItemParam.store.url + allowBlankUrlParam,
					root: 'result',
					fields: gridItemParam.store.fields
				});
			}else if (gridItemParam.mode == 'local'){
				var tempStore = new Ext.data.SimpleStore({
					fields: gridItemParam.store.fields,
					data : gridItemParam.store.data
				});

			}
					
			var tempCombo = new Ext.form.ComboBox({});
			Ext.apply( tempCombo, gridItemParam, CC.help.form.fieldtypes_default[ gridItemParam.xtype ] );
			tempCombo.store = tempStore;
		
			var tempFunc = function(){
				
				if ( allowBlankUrlParam != '' ) {
					var emptyRecord = {};
					emptyRecord[ this.valueField ] = '';
					emptyRecord[ this.displayField ] = '';
					this.store.add( new Ext.data.Record( emptyRecord ) );
				}
				
				if ( typeof this.ownIsGridEditor != 'undefined') {
					
					if ( typeof this.ownOwnerGrid != 'undefined') {
						if ( typeof this.ownValueGridCol != 'undefined' || typeof this.ownDisplayGridCol != 'undefined' ) {
							
							var tempInitDefaultValue = function( pCombo, record ) {
								var id = this.getValue();
								if ( id != '' ) {
									var grid = eval( pCombo.ownOwnerGrid );
									var sm = grid.getSelectionModel().getSelected();
									var tmp_value = sm.get( this.ownValueGridCol );
									
									//alert( 'InitDefaultValue id: '+ id +' '+ this.ownValueGridCol +': '+ tmp_value +' '+ this.ownDisplayGridCol +': '+ sm.get( this.ownDisplayGridCol ) );
									//die_r(pCombo.store);
									if (pCombo.store.find('value', tmp_value) == -1){
										pCombo.store.add( 
											new Ext.data.Record(
												{
													value : tmp_value,
													text : sm.get( this.ownDisplayGridCol )
												}
											)
										);
									}
									pCombo.setValue( tmp_value );
								}
							};
							this.on( 'beforeshow', tempInitDefaultValue );							
							
							var tempModifyValuField = function( pCombo, record ) {
								pCombo.fromselect = true;
								var grid = eval( pCombo.ownOwnerGrid );
								var sm = grid.getSelectionModel().getSelected();
								
								sm.set( pCombo.ownDisplayGridCol, record.data[ pCombo.displayField ] );
							};
							this.on( 'select', tempModifyValuField );	
							
											
							if (this.forceSelection == false){
								var tempModifyValuField2 = function( pCombo) {
									var grid = eval( pCombo.ownOwnerGrid );
									this.gridRow.set( pCombo.ownDisplayGridCol, pCombo.getRawValue() );
									this.gridRow.set( pCombo.ownValueGridCol, pCombo.getRawValue() );
									//grid.store.modified.push(this.gridRow.data);	
									//die_r(this.gridRow);														
									if(typeof grid.store.dirty == 'undefined' && pCombo.fromselect == false && (typeof this.gridRow.data.id == undefined)){	
										grid.fireEvent('afteredit', grid);									
									}
									pCombo.fromselect = false;
								};
								this.on( 'blur', tempModifyValuField2 );	
							}
							
							this.on( 'focus', function(pCombo){
								var grid = eval( pCombo.ownOwnerGrid );
								var sm = grid.getSelectionModel().getSelected();
								this.gridRow = 	sm;
								pCombo.fromselect = false;	
							});
							
							
							
						} else {
							alert( 'A "'+ this.dataIndex +'" grid editor combo-nak a konfigjából hiányzik a ownValueGridCol vagy a ownDisplayGridCol paraméter.');
						}
					} else {
						alert( 'A "'+ this.dataIndex +'" grid editor combo-nak a konfigjából hiányzik a ownOwnerGrid paraméter.');
					}
				} else {
					if(typeof this.ownValue != 'undefined'){
						if ( typeof this.ownValue.value != 'undefined' ) {
							this.store.add( new Ext.data.Record(this.ownValue) );
							this.setValue( this.ownValue.value);
						}
					}
				}
				if(typeof this.ownOnSelect != 'undefined'){
					this.on( 'select', eval(this.ownOnSelect) );
				}
				if(typeof this.ownEvents != 'undefined'){
					for ( event_name in this.ownEvents ) {
						this.on( event_name, eval(this.ownEvents[ event_name ]) );
					}
				}
				/*var combo = this;
				var tempLoadFunc = function(store, record, opt){
					if(typeof combo.store != null){
						combo.setValue( combo.value );
						combo.validate();
					}
				}
				this.store.on('load', tempLoadFunc );
				this.store.load();*/
			};
			
			//show/render esemenyre ki kene valasztani a valunek visszadott erteket.
			tempCombo.on('render', tempFunc);	
			return tempCombo;	
		},
		
		createOneFromCm : function( itemParam, modulNameParam, gridConfig ){
			if(typeof gridConfig == 'undefined'){
				die_r(itemParam,'Ehhez az itemhez nincs gridconfig');
			}
			var ret_field = {};
			try {
				var gridItemParam = gridConfig.cmParam[ gridConfig.cmParamIndex[ itemParam.dataIndex ] ];
				if(typeof gridItemParam != 'object'){
					alert('Cannot connect cmParam to Object');
					die_r(itemParam);
				}
				
				//lekell kezelni ha combo, erre nincs �tadhat� xtype, js oldalon kell l�trehozni
				if (gridItemParam.xtype == 'combo'){
					ret_field = CC.help.form.createCombo(itemParam, modulNameParam, gridConfig, gridItemParam);
				}
				else{
					var defaults = CC.help.form.fieldtypes_default[ gridItemParam.xtype ];
					var temp_ret = {};
					Ext.apply( temp_ret, gridItemParam, CC.help.form.fieldtypes_default[ gridItemParam.xtype ] );
					Ext.apply( ret_field, temp_ret,defaults );
				}
				
				
				
				ret_field.hidden = false;
				ret_field.fieldLabel = ret_field.header;
				
				for ( f in itemParam ) {
					if ( f != 'id' && f != 'xtype' && f != 'dataIndex' ) {
						ret_field[f] = itemParam[f];
					}
				}
				
				//ret_field.id = modulNameParam + gridItemParam.dataIndex;
				
			} catch(e) {
				CCdebug( 'modulNameParam: '+ modulNameParam +' Error: '+ e.message +' itemParam', itemParam );
			}
			return ret_field;	
		},
		
		recursiveCreate : function(item, modulNameParam, formItemParam, gridConfig){
			switch (item.xtype){
				case 'default':
					if(typeof item.dataIndex == 'undefined'){
						alert('Add meg a form elemek dataIndexet');
					}	
					var temp = CC.help.form.createOneFromCm( item, modulNameParam, gridConfig );
					/*if(typeof temp.dataGroup == 'undefined'){
						temp.dataGroup = 'default';
						temp.id = temp.dataIndex;
					}else{
						var tempId = temp.dataGroup+'$'+temp.dataIndex;
						temp.id = tempId;
					}*/
					retItem = temp;
				break;
				
				case 'button':
					item.handler = eval(item.ownHandler);
					retItem = item;
				break;
				
				case 'grid':
					var tbarConfig = null;
			    	if(item.hideAdd == null || item.hideAdd == false) {
						tbarConfig = [ 
							{
								text : CC.b.enter.config.gridNewRecord,
								handler : eval('CC.f.mod.' + modulNameParam + '.showAdd' + item.dataIndex + 'Form'),
					            cls: 'x-btn-text-icon add'
							}
						];
			    	}  
					CC.help.grid.initGrid(modulNameParam, item, tbarConfig, false);
					retItem = CC.f.mod[modulNameParam].grids[item.dataIndex].grid;
				break;
				
				case 'fileupload':
				retItem = new Ext.Panel({
					html:'<div id="upform"></div>'
				});
				new Ext.ux.UploadForm('upform', {
					autoCreate: true,
					url: 'upload.php',
					method: 'post',
					maxFileSize: 1048570,
					baseParams: {
						cmd:'upload',
						path: 'root'
					}
				});
				break;
				
				
				
				case 'gridselector':
					CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridL.dsL.urlBase = CC.f.mod[ modulNameParam ].ajaxUrl;
					CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridR.dsR.urlBase = CC.f.mod[ modulNameParam ].ajaxUrl;
					CCdebug( 'CC.b.mod['+ modulNameParam +'].config.grids['+ item.dataIndex +'].gridL.dsL', CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridL.dsL );
					
					var def = {
						dsL : CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridL.dsL,
						cmL : CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridL.cmL,
						dsR : CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridR.dsR,
						cmR : CC.b.mod[ modulNameParam ].config.grids[ item.dataIndex ].gridR.cmR,
						resultAjaxUrl : CC.f.mod[ modulNameParam ].ajaxUrl + item.dataIndex +'Save'
						
					};
					var temp = {};
					
					Ext.apply(temp, item, def);
					/*if(typeof temp.dataGroup == 'undefined'){
						temp.dataGroup = 'default';
					}*/
					retItem = new Ext.GridSelector(
						temp
					);
				break;
				
				
				case 'combo':
					if(typeof item.dataIndex == 'undefined'){
						alert('Add meg a form elemek dataIndexet');
					}	
					var temp = CC.help.form.createCombo(item, modulNameParam, gridConfig, item);
					retItem = temp;
				break;

				
				default:		
					if(typeof item.dataIndex == 'undefined'){
						alert('Add meg a form elemek dataIndexet');
					}						
					var temp = {};
					Ext.apply(temp, item, CC.help.form.fieldtypes_default[ item.xtype ]);
					/*
					if(typeof temp.dataGroup == 'undefined'){
						temp.dataGroup = 'default';
						temp.id = temp.dataIndex;
					}else{
						var tempId = temp.dataGroup+'$'+temp.dataIndex;
						temp.id = tempId;
					}
					*/
					retItem = temp;
				break;
			}
			if(retItem.xtype != 'grid'){				
				if(typeof retItem.dataGroup == 'undefined'){
					retItem.dataGroup = 'default';
					retItem.id = retItem.dataIndex;
				}else{					
					var tempId = retItem.dataGroup+'$'+retItem.dataIndex;
					retItem.id = tempId;
				}
				var id2 = retItem.id;
				if (typeof gridConfig == 'object') {
					retItem.id = id2 + '$' + gridConfig.dataIndex;
				}
				CC.f.mod[ modulNameParam ].formItems[formItemParam].push(retItem);
			}
			if (typeof retItem.ownEvent != 'undefined'){
				retItem.on(retItem.ownEvent.type, eval(retItem.ownEvent.doFunction));
			}
			return retItem;
		},
		
		//fix and merge items's config, and put indexes to formItems
		recursiveSearch : function(rootObject, modulNameParam, formItemParam, gridConfig){
			for (i in rootObject){
				var item = rootObject[i];
				//if fieldset and has not have title set border to false
				
				if(item.xtype == 'fieldset'){
					if(item.title == ''){rootObject[i].border=false;}
				}
				
				//if columnpanel and has not have title than set border to false
				if(typeof item.columnWidth != 'undefined'){
					if(item.title == ''){rootObject[i].border=false;}
				}
				
				//if the current item is object check if it is in the allowed items if not and has item
				//then call recursion on it, else call create item
				if (typeof item == 'object'){
					if(CC.help.form.allowedFormItemXtypes.indexOf(item.xtype) < 0 ){
						if(typeof item.items == 'object'){
							CC.help.form.recursiveSearch(item.items, modulNameParam, formItemParam, gridConfig);
						}
					}else{
						rootObject[i] = CC.help.form.recursiveCreate(item, modulNameParam, formItemParam, gridConfig);
					}				
				}
			}
		},
		
		makeItems : function(configParam, modulNameParam, formItemParam, gridConfig){
			//el�sz�r �ritj�k a hely�t
			CC.f.mod[ modulNameParam ].formItems[formItemParam] = [];
			//indexek kiszed�se a cmParamb�l
			if (typeof gridConfig == 'object'){
				CC.help.form.createCmParamIndex( gridConfig );
			}
			//ha �res akkor elkezdj�k belepakolni az adatokat
			if ( CC.f.mod[ modulNameParam ].formItems[formItemParam].length == 0 ) {
				CC.help.form.recursiveSearch(configParam, modulNameParam, formItemParam, gridConfig);
			}
			
		},
		
		showWindow : function(itemParam, modulNameParam, windowField, saveParam, windowParam, saveObj){
			if(typeof windowParam == 'undefined'){
				alert('Nincs ablak config');
			}
			
			CC.f.mod[ modulNameParam ].windows[ windowField ] = {};
			var tempPanel = {};
			tempPanel = new Ext.Panel( {
				//labelAlign: 'top',
				//bodyStyle:'padding:3px',
				border : false, 
				bodyBorder : false,
				autoScroll : true,	   
				items :  {
					xtype : 'tabpanel',
					deferredRender : false,
					activeTab : 0,
					defaults : {
						autoHeight : true,
						autoWidth : true,
						//bodyStyle : 'padding:5px;',
						hidden : false
					}, 
					items: itemParam
				},		
				buttons: [
					{
						text: 'Mentés és bezárás', //'Save and Close',
						handler : function(){
				  			if (typeof saveObj == 'undefined'){
				  				if (eval( 'CC.f.mod.'+ modulNameParam +'.'+ saveParam +'()')){
					  				CC.f.mod[ modulNameParam ].windows[ windowField ].items.clear();
					  				CC.f.mod[ modulNameParam ].windows[ windowField ].destroy();  
					  				CC.f.mod[ modulNameParam ].windows[ windowField ] = {};					
				  				}
				  			}else if (typeof saveObj == 'object'){
				  				if (eval( 'CC.f.mod.'+ modulNameParam +'.'+ saveParam +'("'+saveObj.id+'")')){
					  				CC.f.mod[ modulNameParam ].windows[ windowField ].items.clear();
					  				CC.f.mod[ modulNameParam ].windows[ windowField ].destroy();  
					  				CC.f.mod[ modulNameParam ].windows[ windowField ] = {};					
				  				}
				  			}
	
				  			
				  		}
					},
					{
				  		text: 'Mégsem', //'Cancel',
				  		handler: function(){
				  			CC.f.mod[ modulNameParam ].windows[ windowField ].items.clear();
				  			CC.f.mod[ modulNameParam ].windows[ windowField ].destroy();
				  			CC.f.mod[ modulNameParam ].windows[ windowField ] = {};   
				  		}
					}
				]
			} );

			var newWindow = {};
			var windowDefault={
				closable:true,
				width: 600,
				height: 400,
				constrainHeader : true,
				layout: 'fit'
			};
			var windowConfig = Ext.apply(newWindow, windowParam, windowDefault);
			CC.f.mod[ modulNameParam ].windows[ windowField ] = new Ext.Window({
				id: modulNameParam+windowField,
				items: tempPanel
			});	
			Ext.apply(CC.f.mod[ modulNameParam ].windows[ windowField ], windowConfig);
			
			//hat�rozzuk meg mi az aktiv ablak, ezt a lastZIndex �rt�k�vel lehet kinyerni
			//de ha m�g nemvolt nyitott ablak akkor ez undefinied lesz �s akkor a 200,50 default helyre nyitjuk meg
			var activeModul = CC.main.layout.history.pop();
			CC.main.layout.history.push(activeModul);
			var activeWindow = {};
			activeWindow.z = 0;
			activeWindow.id = '';
			for(i in CC.f.mod[activeModul].windows){
				if(typeof CC.f.mod[activeModul].windows[i] == 'object'){
					if(typeof CC.f.mod[activeModul].windows[i].lastZIndex == 'undefined' && activeWindow.id == ''){
						activeWindow.z = 0;
						activeWindow.id = i;
						activeWindow.x = 50;
						activeWindow.y = 25;
					}else if (CC.f.mod[activeModul].windows[i].lastZIndex > activeWindow.z){
						activeWindow.z = CC.f.mod[activeModul].windows[i].lastZIndex;
						activeWindow.id = i;
						activeWindow.x = CC.f.mod[activeModul].windows[i].x +25;
						activeWindow.y = CC.f.mod[activeModul].windows[i].y +25;
					}	
				}
			}
			CC.f.mod[ modulNameParam ].windows[ windowField ].setPosition(activeWindow.x, activeWindow.y);
			CC.f.mod[ modulNameParam ].windows[ windowField ].show();
			for (i in tempPanel.items.items[0].items.items){
				if(typeof tempPanel.items.items[0].items.items[i] == 'object'){
					if(tempPanel.items.items[0].items.items[i].ownDisplay == false){
						tempPanel.items.items[0].hideTabStripItem(tempPanel.items.items[0].items.items[i].id);
					}
				}
			}
			CC.f.mod[ modulNameParam ].windows[ windowField ].on('close', function(){
				CC.f.mod[ modulNameParam ].windows[ windowField ] = {};  
			});
			
		},
		
		getFormData : function(formItemsParam, allowedItems) {
			var data = {};
			data['default'] = {};
			var item = {};
			for (i in formItemsParam ) {
				if(typeof formItemsParam[i] != 'function'){
					if ((typeof allowedItems == 'undefined') || (typeof allowedItems[formItemsParam[i].dataGroup] != 'undefined') ){	
						if(typeof formItemsParam[i].getXType == 'function'){
							item = formItemsParam[i];
							item.xtype = item.getXType();
						}else{
							item = Ext.getCmp(formItemsParam[i].id);
						}
						if (item.xtype=='combo'){
							if(item.allowCreate == true){
								var temp2 = item.dataIndex;
								if(typeof data[item.dataGroup] == 'undefined'){
									data[item.dataGroup] = {};
								}
								if (item.dataIndex.indexOf('$') != -1){
									var temp3 = item.id.split('$');
									temp2 = temp3[1];
								}
								data[item.dataGroup][ temp2 ] = null;
								data[item.dataGroup][ temp2+'_text' ] = item.getRawValue();
								
							}else{
								var temp2 = item.dataIndex;
								if(typeof data[item.dataGroup] == 'undefined'){
									data[item.dataGroup] = {};
								}
								if (item.dataIndex.indexOf('$') != -1){
									var temp3 = item.dataIndex.split('$');
									temp2 = temp3[0];
								}				
								data[item.dataGroup][ temp2 ] = item.getValue();
							}
						}else {	
							try {
								var temp2 = item.dataIndex;
								if(typeof data[item.dataGroup] == 'undefined'){
									data[item.dataGroup] = {};
								}
								if (item.id.indexOf('$') != -1){
									var temp3 = item.id.split('$');
									if (item.dataGroup == 'default'){
										temp2 = temp3[0];
									}else{
										temp2 = temp3[1];
									}
								}
								
								data[item.dataGroup][ temp2 ] = item.getValue();
							} catch (e) {
								// Van olyan, hogy nem kérhető le az adat.
							}
						}		
					}
				}
			}	
			return data;
		},


		validateForm : function(formItemsParam, validateObject) {
			var ok = true;
			var item = {};
			for(i in formItemsParam) {
				if(typeof formItemsParam[i] == 'function' ||		
						validateObject != null && validateObject[formItemsParam[i].dataGroup] == null) continue;

				if(typeof formItemsParam[i].getXType == 'function') {
					item = formItemsParam[i];
					item.xtype = item.getXType();
				} else {
					item = Ext.getCmp(formItemsParam[i].id);
				}
	
				if(item.xtype == 'combo') {
					if(typeof item.store.reader.jsonData == 'object') {
						//ha levan tiltva hogy ujat vigyen fel,de mehgvan engedve hogy bele�rhat, vagyha alpb�l nincs megdva jogk�rnek semmi
						//teh�t alap�rtelmezettben m�gha bele is �rhat akkor sem hozhat l�tre �jat
						var allowCreate = item.allowCreate;
						if(allowCreate == false) item.validate();
						var value = item.getRawValue();
						var van = !item.valueField;
						if(!van) {
							Ext.each(item.store.reader.jsonData.result,
								function(itemParam) {
									if(itemParam.text == value) van = true;
								}
							);
						}
						if(allowCreate) {
							if(van) die_r(item.items);
						} else {
							if(!van) {
								ok = false;
								item.markInvalid();
							}
						}
					} else {
						var value = item.getRawValue();
						if(!item.allowBlank && value == '') {
							item.markInvalid();
							ok = false;
						}
					}
				} else {
					try {
						if(!item.validate()) ok = false;
					} catch(e) {
						// Van olyan, ogy nincs validációja
					}
				}
			}

			return ok;
		},


		setComboDefaultValue : function( comboObjId, key, text ) {
			var  comboObj = Ext.getCmp( comboObjId );
			comboObj.store.add( 
				new Ext.data.Record(
					{
						value : key,
						text : text
					}
				)
			);
			comboObj.setValue( key );
			return comboObj;
		}
	};
}();