// abweichungsanalyse
// 
// abweichungsanalyse
// 
var abweichungsanalyse =  new fClass({
	
	
	// =============
	// = Variablen =
	// =============
	
	view: 			null,
	container: 		null,
	comboStores: 	null,
	gridComponents: null,
	grid: 			null,
	state: 			{},
	stateRaw: 		{},
	wasStarted: 	false,
	
	
	// ======================
	// = private Funktionen =
	// ======================
	
	changeRelation:function(rel){
		
		if(this.wasStarted){
				
			
			var lastOptions = this.gridComponents.store.lastOptions.params();
			


			
			if(Ext.getCmp('abweichung').getValue() == true){
				// absolut
				lastOptions.abweichung = 'relative';
				
			}else{
				// relativ
				lastOptions.abweichung = 'absolute';				
				
			}
			
			
			lastOptions.callback = function(){
				Ext.Msg.hide();
			}
			
			Ext.Msg.wait('Daten werden geladen...',false,waitDialogConfig)
			
			
			
			
			this.requestOptions.abweichung = lastOptions.abweichung;
			
			
			
			this.gridComponents.store.reload(lastOptions);
			
			
		}
		
		
	},
	
	
	buildView:function(){		
		
		var jahreAnzahl = 2;
		

		var folgeJahreDaten = new Array();
		
		for (var i=0; i < jahreAnzahl + 1; i++) {
			var tmp = new Array();
			tmp.push(i);
			folgeJahreDaten.push(tmp);
		}
		
		
		this.folgeJahre = new Ext.data.SimpleStore({
			fields:['jahr'],
			data:folgeJahreDaten
		});
		
		this.tbar = new Ext.FormPanel({
			border:false,
			head:false,
			id:'maskeAbweichungsanalyse',
			bodyStyle:'padding:4px',
			items:{
	            layout:'column',
				border:false,
				defaults:{
					border:false
				},
	            items:[{
	                columnWidth:.3,
	                layout: 'form',
					
	                items: [
					
					{
	                    xtype:'combo',
	                    fieldLabel: 'Vergleichsinstitut',
						store:rcm.Application.multiStores['bcm_institute_ohne_eigenes'],
						triggerAction:'all',
						mode:'local',						
						editable:false,
						valueField:'id',
						displayField:'name',
	                    name: 'vergleichsinstitut',
	                    anchor:'95%',
						allowBlank:false,
						id:'vergleichsinstitut',
						value:rcm.Application.getIdOfFirstItemInMultiStore(rcm.Application.multiStores['bcm_institute_ohne_eigenes'])
	                },
	
	
					{
	                    xtype:'combo',
	                    fieldLabel: 'Kostenebene',
						store:rcm.Application.multiStores['bcm_kostenebenen_name'],
						triggerAction:'all',
						mode:'local',						
						editable:false,
						valueField:'id',
						displayField:'name',
	                    name: 'kostenebene',
	                    anchor:'95%',
						allowBlank:false,
						id:'kostenebene',
						value:rcm.Application.getIdOfFirstItemInMultiStore(rcm.Application.multiStores['bcm_kostenebenen_name'])
	                },
	
					{
	                    xtype:'combo',
	                    fieldLabel: 'Bezugsgröße',
						store:rcm.Application.multiStores['bcm_bezugsgroessen_name'],
						triggerAction:'all',
						mode:'local',						
						editable:false,
						valueField:'id',
						displayField:'name',
	                    name: 'bezugsgroesse',
	                    anchor:'95%',
						allowBlank:false,
						id:'bezugsgroesse',
						value:rcm.Application.getIdOfFirstItemInMultiStore(rcm.Application.multiStores['bcm_bezugsgroessen_name'])
	                }
	
	
	

			
					]
	            },{
	                columnWidth:.3,
	                layout: 'form',
	                items: [
	
					{
						xtype:'radio',
						hideLabel:true,
						name:'abweichung',
						checked:true,
						id:'abweichung',
						boxLabel:'relative Abweichung',
						scope:this,
						handler:function(){
							this.changeRelation();
						}
						

					},
					
					{
						xtype:'radio',
						hideLabel:true,
						boxLabel:'absolute Abweichung',
						name:'abweichung'
					}
					]
	            },
				{
	                columnWidth:.3,
	                layout: 'form',
					labelWidth:150,
					items:[
						
						
						{
			                xtype:'combo',
			                fieldLabel: 'Startjahr',
							store:rcm.Application.multiStores['bcm_kostendaten_jahre_jahr'],
							triggerAction:'all',
							editable:false,
							mode:'local',
							valueField:'id',
							displayField:'jahr',
			                name: 'startjahr',
			                anchor:'95%',
							allowBlank:false,
							id:'startjahr',
							value:rcm.Application.getIdOfFirstItemInMultiStore(rcm.Application.multiStores['bcm_kostendaten_jahre_jahr'])
			            },
						
						{
		                    xtype:'combo',
		                    fieldLabel: 'Folgejahre',
							store:this.folgeJahre,
							triggerAction:'all',
							mode:'local',
							editable:false,
							valueField:'jahr',
							displayField:'jahr',
		                    name: 'folgejahre',
		                    anchor:'95%',
							allowBlank:false,
							scope:this,
							validator:function(value){
								if(!Ext.getCmp('startjahr').isValid()){
									return "Bitte zuerst das Starjahr auswählen";
								}else{
									var startjahr = Ext.getCmp('startjahr').getValue();
									var letztesJahr = rcm.Application.multiStores['bcm_kostendaten_jahre_jahr'].getAt(rcm.Application.multiStores['bcm_kostendaten_jahre_jahr'].getCount()-1).json[0];

									var startjahr = parseInt(startjahr);
									var letztesJahr = parseInt(letztesJahr);

									if((startjahr + parseInt(value)) > letztesJahr){
										return "Für diese Zeitspanne sind keine Daten vorhanden.";
									}


								}


								return true;
							},
							id:'folgejahre',
							value:0
		                }
					]
	                
	            }]
	        },
			buttonAlign:'left',
			buttons:[
			{
				text:'Start',
				iconCls:'startIcon',
				scope:this,
				handler:function(){
						if(this.tbar.getForm().isValid()){
							// this.stateRaw[field.name] = field.getRawValue();								
							// this.state[field.name] = field.getValue();	
							this.wasStarted = true;
							
							
							var vglInst = Ext.getCmp('vergleichsinstitut').getValue();
							var startJahr = parseInt(Ext.getCmp('startjahr').getValue());
							var folgeJahre = parseInt(Ext.getCmp('folgejahre').getValue());
							var bzgG = Ext.getCmp('bezugsgroesse').getValue();
							Ext.MessageBox.wait('Daten werden geladen...',false,waitDialogConfig);
							Ext.Ajax.request({
							
								scope:this,
								method:'POST',
								url:cfg_backend_url + "abweichungsanalyse/checkBezugsgroessen/" + vglInst + "/" + startJahr + "/" + folgeJahre + "/" + bzgG,
								success:function(response){
									var response = response.responseText;
									
									if(response != '1'){
										var fehler = eval(response);
										var fehlerStr = "";
										
										Ext.each(fehler,function(item){
											fehlerStr = fehlerStr + "<li>"+item+"</li>";
										});
										
										Ext.MessageBox.alert('Fehler',"Die Abfrage konnte nicht gestartet werden da folgende Bezugsgrößendaten fehlen:<br/><br/> <ul>"+fehlerStr + "</ul>");
										
									}else{
										this.buildTable();		
										Ext.getCmp('bt_grafik').enable();
										
									}
									
								}
								
							});
							
													
						}
				}
				
			},
			{
				text:'Grafik',
				iconCls:'startIcon',
				id:'bt_grafik',
				disabled:true,
				scope:this,
				handler:function(){

					var ro = this.requestOptions;
					
					// sortierung?
					var addtionalUrl = "";
					if(rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.sort != null){
						addtionalUrl = "/" + rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.sort + "/" + rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.dir;
					}
					
					
					var graph_url = cfg_backend_url + "abweichungsanalyse/getGraphHtmlView/" +ro.vergleichsinstitut + "/" + ro.bezugsgroesse + "/" + ro.kostenebene + "/" + ro.startjahr + "/" + ro.folgejahre + "/" + ro.abweichung + "/" + ro.pfad_id + addtionalUrl; 
					
					var outputWindow = new Ext.Window({
						modal:true,
						// title:'Abweichung Kosten eigenes Institut - '+ this.requestOptions.vergleichsinstitutRaw + " / "+this.requestOptions.kostenebeneRaw,
						title:' ',
						autoLoad:{
							url:graph_url,
							scripts:true,
							method:'post',
							params:{
								entry_level: ro.entry_level
							}
						},
						width:800,
						height:600,
						tools:[
						{
							id:'print',
							handler:function(){
								var chartToPrint = getChartFromId("bcm_chart");
								chartToPrint.print();
							}
						},{
							id:'save',
							handler:function(){

								var chartToPrint = getChartFromId("bcm_chart");
								chartToPrint.saveAsImage();
							}
						}]
					});
					outputWindow.show();
					outputWindow.center();
					
					
					
					
				}
			}
			]
			
			
			
		});
		

		
		
		this.view = new Ext.Panel({
			title:'Abweichungsanalyse',
			iconCls:'winAbweichungsanalyse',
			layout:'border',
			border:false,
			items:[{
				region:'north',
				items:this.tbar,
				height:120,
				layout:'fit'
			},
			{
				region:'center',
				layout:'fit',
				id:'auswertungContent'
				
			}]
			
			
		});
		
		
		if(rcm.Application.state.eigenes_institut != null){
			// Ext.getCmp('institut').setValue(rcm.Application.state.eigenes_institut);
		}
		

	},

	
	
	buildTable:function(daten){
		
		//request verarbeiten

		
		// eigenschaften sammeln
		this.requestOptions = new Object();
		this.requestOptions.vergleichsinstitut = Ext.getCmp('vergleichsinstitut').getValue();
		this.requestOptions.vergleichsinstitutRaw = Ext.getCmp('vergleichsinstitut').getRawValue();
		
		this.requestOptions.kostenebene = Ext.getCmp('kostenebene').getValue();
		this.requestOptions.entry_level = Ext.getCmp('kostenebene').getValue();
		this.requestOptions.kostenebeneRaw = Ext.getCmp('kostenebene').getRawValue();
		
		this.requestOptions.bezugsgroesse = Ext.getCmp('bezugsgroesse').getValue();
		this.requestOptions.bezugsgroesseRaw = Ext.getCmp('bezugsgroesse').getRawValue();
		
		this.requestOptions.startjahr = parseInt(Ext.getCmp('startjahr').getValue());
		this.requestOptions.folgejahre = parseInt(Ext.getCmp('folgejahre').getValue());
		
		this.requestOptions.pfad_id = false;

		if(Ext.getCmp('abweichung').getValue()){
			this.requestOptions.abweichung = 'relative';
		}else{
			this.requestOptions.abweichung = 'absolute';
		}
		


		
		
		this.gridComponents = new Object();
		this.gridComponents.store = false; //der Datastore
		this.gridComponents.columnModel = false;
		this.gridComponents.proxy = false;
		this.gridComponents.reader = false;
		
		// spalten
		this.gridComponents.readerFields = new Array();


		this.gridComponents.readerFields.push({name:'kostenebene'});
		
		for (var i=0; i < this.requestOptions.folgejahre +1; i++) {
			this.gridComponents.readerFields.push({name:'jahr_'+(this.requestOptions.startjahr+i)});					
		}
		

		

		// col model erstellen
		this.gridComponents.modelFields = new Array();
		
		this.gridComponents.modelFields.push({sortable:true, header:this.requestOptions.kostenebeneRaw, width:275, dataIndex:'kostenebene',renderer:function(value, metadata, record, rowIndex, colIndex, store){
			if(rowIndex == store.getCount()-1){
				metadata.css = 'summenZeile';				
			}

			return value;
		}});
		
		for (var i=0; i < this.requestOptions.folgejahre +1; i++) {
			this.gridComponents.modelFields.push({sortable:true, align:'center', header:(this.requestOptions.startjahr+i), css:'text-align:right !important;', dataIndex:'jahr_'+(this.requestOptions.startjahr+i),renderer:function(value, metadata, record, rowIndex, colIndex, store){
				if(rowIndex == store.getCount()-1){
					metadata.css = 'summenZeile';				
				}

				return value;
			}});
		}
		
		// this.gridComponents.modelFields.push({header:"Jahressumme", dataIndex:'jahressumme'});
		


		
		// proxy erstellen
		this.gridComponents.proxy = new Ext.data.HttpProxy({
			url:cfg_backend_url + 'abweichungsanalyse/json/getGridFrontend',
			method:'POST'
		});
		
		
		// reader erstellen
		this.gridComponents.reader = new Ext.data.JsonReader({
			root:'results',
			totalProperty:'total',
			id:'id'
		},this.gridComponents.readerFields);
		
		// data store erstellen
		this.gridComponents.store =  new Ext.data.Store({
			proxy:this.gridComponents.proxy,
			reader:this.gridComponents.reader,
			remoteSort:true,
			listeners: {
			    load: {
					scope:this,
			        fn: function(){
						Ext.MessageBox.hide();
			            var view = this.grid.getView();
			            for (var i = 0; i < this.gridComponents.store.getCount(); i++) {
			                var cell = Ext.fly(view.getCell(i, 0));
							if(cell.child(".chart_curve")){
								cell.child(".chart_curve").rel = i+1;
				                cell.child(".chart_curve").on('click',function(){
									// Ext.MessageBox.alert(this.rel);

								},this);								
							}
			            }
		
			        }
			    }
			}		
		});
		

		
		// this.gridComponents.columnModel = new Ext.grid.ColumnModel(this.gridComponents.modelFields);
		
		
		this.grid = new Ext.grid.GridPanel({
			store: this.gridComponents.store, 
			columns: this.gridComponents.modelFields, 
			border:false,
			title:'Kostenabweichung zu '+ this.requestOptions.vergleichsinstitutRaw + ", Bezugsgröße "+this.requestOptions.bezugsgroesseRaw,
			disableSelection:true,
			tools:[{id:'print', scope:this, handler:function(){
				if(this.requestOptions!=null){
					
					
					
					var ro = this.requestOptions;

					var abweichung = ro.abweichung;
					

					var url = cfg_backend_url + "abweichungsanalyse/getAbweichungsanalysePrintView/"+ro.vergleichsinstitut + "/" + ro.bezugsgroesse + "/" +  ro.kostenebene + "/" +  ro.startjahr + "/" +  ro.folgejahre + "/" +  abweichung + "/" +  ro.pfad_id + "/false/" + rcm.Application.abweichungsanalyse.requestOptions.entry_level;


					rcm.Application.print(url);
				}
			}},
			
			{id:'save', scope:this, handler:function(){
				if(this.requestOptions!=null){
					
					
					
					var ro = this.requestOptions;

					var abweichung = ro.abweichung;
					

					var url = cfg_backend_url + "abweichungsanalyse/getAbweichungsanalysePrintView/"+ro.vergleichsinstitut + "/" + ro.bezugsgroesse + "/" +  ro.kostenebene + "/" +  ro.startjahr + "/" +  ro.folgejahre + "/" +  abweichung + "/" +  ro.pfad_id + "/true/" + rcm.Application.abweichungsanalyse.requestOptions.entry_level;
					window.location.href = url;

					// rcm.Application.print(url);
				}
			}}
			
			]
			
			
		});
		
		if(!Ext.isEmpty(Ext.getCmp('auswertungContent').items)){
			Ext.getCmp('auswertungContent').remove(Ext.getCmp('auswertungContent').getComponent(0));
		}
		
		Ext.getCmp('auswertungContent').add(this.grid);
		Ext.getCmp('auswertungContent').doLayout();
		
		this.gridComponents.store.load({
					
					params:function(){
						var params = {};
				
						Ext.each(rcm.Application.abweichungsanalyse.tbar.form.items.items, function(field){
							if(!Ext.isEmpty(field.getValue)&&field.name!='abweichung'&&field.name!=null){
								params[field.name] = field.getValue();										
							}
				
						});
						if(Ext.getCmp('abweichung').getValue()){
							params['abweichung'] = 'relative';
						}else{
							params['abweichung'] = 'absolute';
						}
						
						
						
						if(rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.dir != null){
							params['dir'] = rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.dir;
						}
						
						if(rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.sort != null){
							params['sort'] = rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.sort;
						}
						
						params['entry_level'] = rcm.Application.abweichungsanalyse.requestOptions.entry_level;
						
						
						return params;
					}
					
				});
		

		this.grid.on('celldblclick',function(grid, rowIndex, columnIndex){
			if(rowIndex> rcm.Application.abweichungsanalyse.gridComponents.store.getCount()-2){
				return false;
			}


			// überprüfen ob man überhaupt noch tiefer gehen kann
			var ebenenStoreId = rcm.Application.multiStores['bcm_kostenebenen_name'].find('id',rcm.Application.abweichungsanalyse.requestOptions.kostenebene);

			var ebenePlus = rcm.Application.multiStores['bcm_kostenebenen_name'].getAt(ebenenStoreId+1);
			if(ebenePlus){


				rcm.Application.abweichungsanalyse.requestOptions.kostenebene = ebenePlus.data.id;
				rcm.Application.abweichungsanalyse.requestOptions.kostenebeneRaw = ebenePlus.data.name;
				Ext.getCmp('kostenebene').setValue(ebenePlus.data.id);

				rcm.Application.abweichungsanalyse.grid.getColumnModel().setColumnHeader(0,ebenePlus.data.name);

				// pfad im titel
				var record = rcm.Application.abweichungsanalyse.gridComponents.store.getAt(rowIndex);
				var ebenenName = Ext.util.Format.stripTags(record.data.kostenebene);
				
				// console.log(rcm.Application.abweichungsanalyse.grid.header);
				if(!rcm.Application.abweichungsanalyse.requestOptions.pfad_id){
					rcm.Application.abweichungsanalyse.newTitle = rcm.Application.abweichungsanalyse.grid.initialConfig.title + "<br/>";
				}
				
				rcm.Application.abweichungsanalyse.newTitle = rcm.Application.abweichungsanalyse.newTitle + "> "+ebenenName + " ";
				rcm.Application.abweichungsanalyse.grid.setTitle(rcm.Application.abweichungsanalyse.newTitle);

				var spanId = 'span_'+rowIndex;

				var span = Ext.get(spanId).dom.className;		
				rcm.Application.abweichungsanalyse.requestOptions.pfad_id = span;
				
				

				Ext.MessageBox.wait('Daten werden geladen..',false,waitDialogConfig);
				rcm.Application.abweichungsanalyse.gridComponents.store.reload({

					params:function(){
						var params = {};

						Ext.each(rcm.Application.abweichungsanalyse.tbar.form.items.items, function(field){
							if(!Ext.isEmpty(field.getValue) && field.name!='abweichung' && field.name != null){
								params[field.name] = field.getValue();										
							}


						});


						if(Ext.getCmp('abweichung').getValue()){
							params['abweichung'] = 'relative';
						}else{
							params['abweichung'] = 'absolute';
						}


						if(rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.dir != null){
							params['dir'] = rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.dir;
						}

						if(rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.sort != null){
							params['sort'] = rcm.Application.abweichungsanalyse.gridComponents.store.lastOptions.params.sort;
						}
						
						params['entry_level'] = rcm.Application.abweichungsanalyse.requestOptions.entry_level;


						params['kostenebenen_eintrag_parent_id'] = span;

						return params;
					}


				});

			}





		});

		
		
	},
	

	
	// ==========================
	// = öffentliche Funktionen =
	// ==========================
	
	
	init:function(){
		this.buildView();
		// this.buildGrafikChooseWindow();
		
		
		return this;
	}
	
	
	
});
