Ext.namespace('CC');
Ext.namespace('CC.help');

CC.help.grid = function(){
	return{
	
		init : function(){},
		
		setGridStore: function(urlParam, colsParam, urlBaseParam, primary_field ){	
			return new Ext.data.Store({
								proxy: new Ext.data.HttpProxy({
									url: urlParam + urlBaseParam, 
									method: 'POST'
								}),
								//baseParams:{task: baseParam}, 
								//sortInfo:{field: primary_field, direction: "ASC"},
								reader: new Ext.data.JsonReader({
									id : primary_field,
									root: 'results',
									totalProperty: 'total'
								},
								colsParam
								)
							});
		},
		
		setColModel: function(cmParam, extraCols){
			var colModelTemp = [];
			var temp2 = {};
			
			//ovverride user settings
			if (typeof extraCols != 'undefined'){
				var tempSplit = extraCols[0].dataIndex.split('>');
				var actModul = tempSplit[0];
				var gridName = tempSplit[1];
				if (typeof CC.b.mod[actModul].config.userCols!= 'undefined'){
					if (typeof CC.b.mod[actModul].config.userCols.config != 'undefined'){
						if (CC.b.mod[actModul].config.userCols.config.length>0 && CC.b.mod[actModul].config.userCols.gridName == gridName){
							var userCols = Ext.decode(CC.b.mod[actModul].config.userCols.config);				
							var temp = [];
							for (i in userCols){
								var colExist = false;
								for (j in cmParam){
									//na itt a hiba mert, annyi col lesz ahány el van tárolva, ha a configban nincs benne akkor ne vegyük fel
									if (cmParam[j].dataIndex ==userCols[i].dataIndex){							
										userCols[i] = Ext.applyIf(userCols[i],cmParam[j] );
										temp.push(userCols[i]);
										colExist = true;
									}
								}
								
								if(colExist==false){
									
								}
							}	
							cmParam = temp;
						}
					}
				}
			}

			for(i in cmParam){
				if (typeof cmParam[i] != 'undefined'){
					if (typeof cmParam[i] == 'object'){
						//creating editor object
						if(typeof cmParam[i].ownEditor != 'undefined'){	
							var editorTemp = {};
							switch(cmParam[i].ownEditor.xtype){
								case 'textfield':
									editorTemp = new Ext.form.TextField(
										cmParam[i].ownEditor
									);
									break;	
									
								case 'checkbox':
									editorTemp = new Ext.form.Checkbox(
										cmParam[i].ownEditor
									);
									break;	
									
								case 'datefield':
									editorTemp = new Ext.form.DateField(
										cmParam[i].ownEditor
									);
									break;	
									
								case 'numberfield':
									editorTemp = new Ext.form.NumberField(
										cmParam[i].ownEditor
									);		
									break;
									
								case 'fileuploadfield':
									editorTemp = new Ext.form.FileUploadField(
									//	cmParam[i].ownEditor
									);		
									break;
									
								case 'combobox':
									//TODO ezt majd meg tesztelni kene, ha majd szukseg lesz ra
									
									cmParam[i].ownEditor.ownIsGridEditor = true;
									
									editorTemp = CC.help.form.createCombo(
											cmParam[i].ownEditor, 
											cmParam[i].ownEditor.modulName, 
											null,
											cmParam[i].ownEditor
									);
									break;																
							}
							//configb�l hozott onChange esem�ny hozz�f�z�se az elemhez
							if (typeof cmParam[i].ownEditor.onChange != 'undefined'){
								editorTemp.on('blur', CC.f.mod[cmParam[i].ownEditor.modulName][cmParam[i].ownEditor.onChange]);
							}
							cmParam[i].editor = editorTemp;		
						}
						//editors create end		
						//change values
						if(typeof cmParam[i].changeValues != 'undefined'){
							switch(cmParam[i].changeValues){
								case 'bool':
									cmParam[i].renderer = function(value, cell, record, row, col, store){
										var content = '';
										if (value == 'Y' || value =='y' || value==1){
											content += '<img src="'+CC_webroot+'/images/icons/yes.gif" />';
										}else if (value == 'N' || value =='n' || value==0){
											content += '<img src="'+CC_webroot+'/images/icons/no.gif" />';
										}else{
											content = value;
										}
										return content;
									};
									
								break;
								
								
								case 'mail':
									cmParam[i].renderer = function(value, cell, record, row, col, store){
										var content = '';										
										content += '<a href="mailto:'+value+'">'+value+'</a> ';									
										return content;
									};
								break;
								default :
									if ( cmParam[i].changeValues != '' ) {
										cmParam[i].renderer = eval( cmParam[i].changeValues );
									}
								break;
							}
						}	
						//change end
							
						colModelTemp[i] = cmParam[i];
					}
				}
			}
			var cmParamMax = objCount(cmParam);
			
			for(j=0; j<objCount(extraCols); j++){
				if (typeof extraCols[j] == 'object'){
					var where = cmParamMax+j;
					colModelTemp[where] = extraCols[j];
					colModelTemp[where].renderer = function(value, cell, record, row, col, store){
					//	die_r('value', record);
					
						var content = '';
						
						var temp = this.name.split('>');
						for (i in CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons){
							if(typeof CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons[i] == 'object'){
								if (CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons[i].col == temp[2]){
									var icon = CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons[i].icon;
									var kep = CC.b.enter.config.images+CC.b.enter.config.icons+'/'+icon;
									var modul = CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons[i].modulName;
									var func = CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons[i].doFunction;
									var gridObject =CC.b.mod[ temp[0] ].config.grids[ temp[1] ].gridExtraIcons[i].gridObject;
									//ha van gridObject akkor adjuk �t param�terk�nt
									
									var tempFunction = '';
									if ( gridObject != ''){
									//	tempFunction = 'CC.f.mod.'+modul+'.'+func+'(gridObject, '+record.id+');';
										tempFunction = 'CC.f.mod.'+modul+'.'+func+'(\''+record.id+'\');';
									}else{
										tempFunction = 'CC.f.mod.'+modul+'.'+func+'();';
									}
									//TODO param�teresen h�vni az adott f�ggv�nyt a kattintott sor id-ja alapj�n
									content += '<img src="'+kep+'" onclick="'+tempFunction+'" class="actionIcon" />';
								}
							}		
						}
					
						return	content;
					};
				}
			}	
			/*for (i in colModelTemp){
				if (typeof colModelTemp[i] != 'function' && typeof colModelTemp[i] == 'object'){
					var temp = {};
					temp = Ext.apply(colModelTemp[i], userCols);
					colModelTemp[i]
				}
			}*/
			return new Ext.grid.ColumnModel(
						    colModelTemp
						);						    
		},


		setGrid : function(idParam, dataStore, coloumnModel, modulNameParam, pTbarConfig, orderBar) {
			if(typeof orderBar == 'undefined') {
				var bbarTemp = [
				    {
        				xtype : 'pagingtoolbar',
	        			id : modulNameParam + 'Pagingtoolbar',
	                	pageSize : 15,
	                	width : 300,
	                	//border:false,
	                	//bodyBorder: false,
	                	store : dataStore,
	                	displayInfo : true,
	                	//mode: 'slider',
	                	autoLoad : false
            		},
					{
            			xtype : 'tbfill'
            		},
            		{
			  	    	xtype : 'orderbar',
			   	    	config : {
			        		gridId : idParam
			        	}
			        }
            	];

			} else if(!orderBar){
				var bbarTemp = [{
        			xtype : 'pagingtoolbar',
	        		id : modulNameParam + 'Pagingtoolbar',
	                pageSize: 15,
	                //autoWidth:true,
	                width : 300,
	                //border:false,
	                //bodyBorder: false,
	                store : dataStore,
	                displayInfo : true,
	                //mode: 'slider',
	                autoLoad : true
            	}];
			}

			return new Ext.grid.EditorGridPanel(
				{
					id : idParam,
					ds : dataStore,
					cm : coloumnModel,
					stripeRows : true,
					enableColLock : false,
					loadMask : true,
					clicksToEdit : 1,
					width : '100%',
					//autoHeight:true,
					tbar : pTbarConfig ,
					bbar : bbarTemp,

					/*[
        			{
        				xtype : 'pagingtoolbar',
	        			id : modulNameParam+'Pagingtoolbar',
	                	pageSize: 15,
	                	width : 250,
	                	//border:false,
	                	//bodyBorder: false,
	                	store: dataStore,
	                	displayInfo: true,
	                	//mode: 'slider',
	                	autoLoad: true
            		},
					{xtype: 'tbfill'},
            		{
			  	    	xtype:'orderbar',
			   	    	config:{
			        		gridId : idParam
			        	}
			        }

	            	],*/
					selModel : new Ext.grid.RowSelectionModel(
						{
							singleSelect:false
						}
					)
				}
			);
		
	    },


	    initGrid : function(modulNameParam, configObject, tbarConfig, orderBar) {
	    	if(typeof configObject.dataIndex == 'undefined' ||
	    			typeof configObject.ajaxUrl == 'undefined' ||
                    typeof configObject.primaryField == 'undefined') {
				die_r( configObject, 'gridhelp.initGrid nem megfelelően konfigurált. configObject' );
				return false;
			}

	    	var gridName = configObject.dataIndex;
	    	var ajaxUrl = configObject.ajaxUrl;
	    	var primaryField = configObject.primaryField;

	    	if(typeof configObject.height == 'undefined'){
	    		configObject.height = 300;
	    	}

	    	var f_module = CC.f.mod[modulNameParam];
			f_module.grids[gridName] = {
				gridStore : null,
				colModel : null,
				grid : null
			}
			var f_gridObjs = f_module.grids[gridName];
			var b_conf = CC.b.mod[modulNameParam].config.grids[gridName];

			f_gridObjs.gridStore = this.setGridStore(f_module.ajaxUrl + ajaxUrl, b_conf.colsParam, 'listing', primaryField);
			f_gridObjs.colModel = this.setColModel(b_conf.cmParam, b_conf.gridExtraCols);

			if(typeof orderBar == 'undefined'){
				f_gridObjs.grid = this.setGrid(modulNameParam + gridName + 'Grid', f_gridObjs.gridStore, f_gridObjs.colModel, modulNameParam, tbarConfig);
				f_gridObjs.grid.height = configObject.height;
			} else if(orderBar == false){
				f_gridObjs.grid = this.setGrid(modulNameParam + gridName + 'Grid', f_gridObjs.gridStore, f_gridObjs.colModel, modulNameParam, tbarConfig, false);
				f_gridObjs.grid.height = configObject.height;
				f_gridObjs.grid.on('render',
					function() {
						setTimeout(
							function() {
								f_gridObjs.grid.setHeight(f_gridObjs.grid.height);
						    }, 300);
					}
				);
			}
			
			if(typeof b_conf.ownEvents != 'undefined') {
				var eventName = '';
				for(eventName in b_conf.ownEvents) {
					f_gridObjs.grid.on(eventName, eval(b_conf.ownEvents[eventName]));
				}
			}
			
			f_gridObjs.grid.isResizing = false;
			f_gridObjs.grid.isRefreshingData = false;
			f_gridObjs.grid.nextHeight = null;
			f_gridObjs.grid.parentResizeInited = false;
			
			
	    	if(configObject.disableAutoSize == null || configObject.disableAutoSize == false) {
				f_gridObjs.grid.afterResizeMe = function() {
					/**
					 * @magic a grid.tbar + a grid fejl�c + a l�bl�c 78px (tbar n�lk�l 52px) egy sor pedig 24 a borderrel egy�tt
					 * TODO kezelni, ha nincs tbar
					 * parseInt lehet, hogy jobb
					 */
					var limitParam = Math.ceil(Math.floor((this.nextHeight - 78) / 24));
					//die_r(Ext.getCmp(this.bottomToolbar.items.keys[0]));
					if(Ext.getCmp(this.bottomToolbar.items.keys[0]).getPageSize() != limitParam) {
						//if(this.store.getTotalCount() > limitParam) {
							this.nextHeight = null;
							if(limitParam < 1) {
								limitParam = 1;
							}
							var startParam = Ext.getCmp(this.bottomToolbar.items.keys[0]).getActivePage() *
									Ext.getCmp(this.bottomToolbar.items.keys[0]).getPageSize();
							
							this.store.reload({
								params: {
									start: startParam,
									limit: limitParam
								}
							});
						//}
						Ext.getCmp(this.bottomToolbar.items.keys[0]).setPageSize(limitParam);
					}
					this.isRefreshingData = false;
					this.isResizing = false;
				}
	
				f_gridObjs.grid.resizeMe = function(t, adjWidth, adjHeight, rawWidth, rawHeight) {
					if(this.isResizing) return;
	
					this.isResizing = true;
					if(t.id != CC.main.layout.center.id) {
						var oCt = t.ownerCt.ownerCt.ownerCt.ownerCt;
						var rawHeight = (oCt.closable == null ? oCt.ownerCt.getSize().height : oCt.getSize().height) - 139;
						if(rawHeight < 25) rawHeight = 25;
					}
					if(this.getSize().height != rawHeight) {
						this.setHeight(rawHeight);
						this.nextHeight = rawHeight;
						if(!this.isRefreshingData) {
							this.isRefreshingData = true;
							setTimeout('var c = Ext.getCmp(\''+ this.id +'\'); if(c != null) c.afterResizeMe();', 500);
						}
					}
					this.isResizing = false;
				}
	
				f_gridObjs.grid.setResizeEvent = function(t) {
					if(!this.parentResizeInited) {
						this.parentResizeInited = true;
						var t = this;
						this.ownerCt.on('resize', 
							function(modulNameParam, gridName, ajaxUrl, primaryField, tbarConfig) {
								t.resizeMe(modulNameParam, gridName, ajaxUrl, primaryField, tbarConfig);
							}
						);
						this.resizeMe(this.ownerCt, null, null, this.ownerCt.getSize().width, this.ownerCt.getSize().height);
					}
				}
				f_gridObjs.grid.on( 'bodyresize', f_gridObjs.grid.setResizeEvent );	
	    	}
			
			//excel gomb
	    	if(configObject.hideExcel == null || configObject.hideExcel == false) {
				f_gridObjs.grid.getBottomToolbar().push({
	        		text : 'Excel',
	        		cls : 'x-btn-text-icon',
	        		icon : CC_webroot+'/images/icons/excel.gif', 
	      			handler : function() {
	      				f_gridObjs.grid.showExcelWindow();
	      			}
		    	});
		    	
				f_gridObjs.grid.showExcelWindow = function() {
					/*for(i in f_gridObjs.grid.colModel.config){
						if(typeof f_gridObjs.grid.colModel.config[i] == 'object') {
						}
					}*/
					//kellenek a letez� nem hidden oszlopok				
					f_gridObjs.grid.excel = {};
					f_gridObjs.grid.excel.params = {};
					f_gridObjs.grid.excel.params['printExcel'] = true;
					var printCols = [];
					var comboTemp = null;
					for(j = 0; j < f_gridObjs.grid.initialConfig.cm.config.length; j++) {
						if(typeof f_gridObjs.grid.initialConfig.cm.config[j] == 'object') {
							if(f_gridObjs.grid.initialConfig.cm.config[j].hidden != true) {
								comboTemp  = {
									boxLabel : f_gridObjs.grid.initialConfig.cm.config[j].header,
									id : f_gridObjs.grid.initialConfig.cm.config[j].dataIndex,
									checked : false
								};
								printCols.push(comboTemp);
							}
						}
					}
					
	            	f_gridObjs.grid.excel.window = new Ext.Window({
		                layout : 'form',
		                width : 650,
		                height : 300,
		                autoScroll : true, 
		                title : CC.b.enter.config.print,
		                items : [
		                	{
		                		xtype : 'checkbox',
		                		fieldLabel : CC.b.enter.config.allcol,
		                		id : f_gridObjs.id + 'excelAll',
		                		checked : true
		                	},
		                	{
		                		xtype : 'checkboxbar',
		                		items : printCols,
		                		hidden : true,
		                		id : f_gridObjs.id + 'selectedCols',
		                		autoWidth : true,
		                		layout : 'form',
		                		hidden: true,
		                		fieldLabel : CC.b.enter.config.col,
								columns : 3
		                	},
		                	{
		                		xtype : 'radiobar',
		                		fieldLabel : CC.b.enter.config.pages,
		                		items : [
		                			{
			                			inputValue : 'all',
			                			id : f_gridObjs.id + 'excelCurrPage',
			                			boxLabel : CC.b.enter.config.currpage,
			                			checked : true,
			                			name : 'page'
		                			},
		                			{
			                			inputValue : 'current',
			                			id : f_gridObjs.id + 'excelAllPage',
			                			boxLabel : CC.b.enter.config.allpage,
			                			checked : false,
			                			name : 'page'
		                			}
		                		]
		                	}      		                	
		                ],
		
		                buttons: [
			                {
			                    text : CC.b.enter.config.buttonok,
			                    handler : function() {
			                        if(grExcelAll.getValue()){
			                        	f_gridObjs.grid.excel.params.cols = 'all';
			                        } else {
			                        	var selectedColsTemp = grSelectedCols.getValue();
			                        	f_gridObjs.grid.excel.params.cols = selectedColsTemp.join(',');
			                        }
			                        f_gridObjs.grid.excel.params.gridID = gridName;
			                       	f_gridObjs.grid.excel.doPrint(f_gridObjs.grid.excel.params); 
			                	}
			                },
			                {
			                    text : CC.b.enter.config.buttoncancel,
			                    handler : function() {
			                        f_gridObjs.grid.excel.window.close();
			                	}
			                }
		                ]
		            });
	            	
	            	var grSelectedCols = Ext.getCmp(f_gridObjs.id + 'selectedCols');
	            	var grExcelAll = Ext.getCmp(f_gridObjs.id + 'excelAll');
	         	
	            	grExcelAll.on('check', function(){
		            	if(this.checked) {
		            		grSelectedCols.hide();						
		            	} else {
		            		grSelectedCols.show();
		            	}
		           	});
	
					f_gridObjs.grid.excel.doPrint = function(printParams){					
						var data = Ext.apply(f_gridObjs.grid.getStore().lastOptions.params,printParams);
						if(Ext.getCmp(f_gridObjs.id+'excelAllPage').getValue()){
							data.limit = -1;
						}
										
						var param ={
							url: f_gridObjs.grid.getStore().proxy.conn.url,
							params:	data,
	
							success: function(result){
								if ( result.success ) {
									window.open(f_gridObjs.grid.getStore().proxy.conn.url+'?file='+result.file+'');
								} else {
									Ext.MessageBox.alert( CC.b.enter.config.msgError, result.message );
								}
								
							}
						};	
						CC.help.ajax.doAjax(param);
					
					};
					f_gridObjs.grid.excel.window.show();
				};
	    	}
			//excel vege
	    }      
	}
}();



//needs to ovveride the grid, cause in ext2.2 after ajaxing in grig changes, editors will loose focus
Ext.grid.GridView.override({
    
    syncFocus : false,
    
    removeRow : function(row){
        Ext.removeNode(this.getRow(row));
        this.syncFocusEl(row);
    },
    removeRows : function(firstRow, lastRow){
        var bd = this.mainBody.dom;
        for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
            Ext.removeNode(bd.childNodes[firstRow]);
        }
        this.syncFocusEl(firstRow);
    },
    insertRows : function(dm, firstRow, lastRow, isUpdate){
        if(!isUpdate && firstRow === 0 && lastRow == dm.getCount()-1){
            this.refresh();
        }else{
            if(!isUpdate){
                this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
            }
            var html = this.renderRows(firstRow, lastRow);
            var before = this.getRow(firstRow);
            if(before){
                Ext.DomHelper.insertHtml('beforeBegin', before, html);
            }else{
                Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html);
            }
            if(!isUpdate){
                this.fireEvent("rowsinserted", this, firstRow, lastRow);
                this.processRows(firstRow);
            }
        }
        this.syncFocusEl(firstRow);
    },
    onDataChange : function(){
        this.refresh();
        this.updateHeaderSortState();
        this.syncFocusEl(0);
    },
    onClear : function(){
        this.refresh();
        this.syncFocusEl(0);
    },
    focusCell : function(row, col, hscroll){
        this.syncFocusEl(row, col, hscroll, true)
        if(Ext.isGecko){
            this.focusEl.focus();
        }else{
            this.focusEl.focus.defer(1, this.focusEl);
        }
    },
    syncFocusEl : function(row, col, hscroll, /*private*/ force){
        if(force || this.syncFocus){
            row = Math.min(row, Math.max(0, this.getRows().length-1));
            var xy = this.ensureVisible(row, col, hscroll);
            this.focusEl.setXY(xy||this.scroller.getXY());
        }
    }
});

