
// Define Global namespace
Ext.namespace('Globalis');



Globalis.TreeMenu = Ext.extend(Ext.tree.TreePanel, {

    initComponent: function(){

		Ext.apply(this, {
            border: true,
            width: '100%',
            height: 'auto',
            frame: true,
            singleExpand: true,
            loader: new Ext.tree.TreeLoader(),
            rootVisible: false,
			bodyStyle: 'background-color:transparent;',
			renderTo: "treemenu"
		});

        Globalis.TreeMenu.superclass.initComponent.call(this);
    },

    listeners: {

		beforerender: function(){
            this.setRootNode(new Ext.tree.AsyncTreeNode({
                text: 'Objects',
                children: this.data
            }));
		}

	}
});

Ext.reg('globalistreemenu', Globalis.TreeMenu);



Globalis.StatisticsStore = function(config){
	var defConfig = {
		autoLoad: true,
		dataXML: null,
		dataTable: null,
		year:null,
		years:[]
	};

	Ext.applyIf(this,defConfig);

	Globalis.StatisticsStore.superclass.constructor.call(this,config);

};

Ext.extend(Globalis.StatisticsStore, Ext.data.JsonStore,{

	findYears: function(){
		var today = new Date;
		var fields = this.fields.keys;

		for(i = 0; i < fields.length - 5; i++){
			this.years.push(fields[i]);
			if ( fields[i] < today.getFullYear() ){
				var year=fields[i];
			}
		};
		this.year=year;
	},

	createDataXML: function(year){
		var rs = this.getRange();
		var strXML = "<chart" + Globalis.data.chartParams + ">";
		for ( i = 0; i < rs.length; i++ ){
			var name = rs[i].get('name');
			var value = rs[i].get(year);
			strXML += "<set label='" + shorten( name, 17 ) + "' value='" + value + "' color='E33F30' link='j-myJS-"+rs[i].get('id')+"'/>";
		}
		strXML+="</chart>";
		this.dataXML=strXML;
	},

	createRecordDataXML: function(index){
		var record = this.getAt(index);
		var strXML = "<chart" + Globalis.data.chartParams + ">";
		for(i=0;i<this.years.length;i++){
			var year=this.years[i];
			strXML+="<set label='"+year+"' value='"+record.get(year)+"' color='E33F30'/>";
		};
		strXML+="</chart>";
		return strXML;
	},

	// Create Google Visualization Data Table
	createDataTable: function(year){
		var dataTable = new google.visualization.DataTable();
		var rs = this.getRange();

		dataTable.addRows(rs.length);
		dataTable.addColumn( 'string', 'ISO' );
		dataTable.addColumn( 'number', Globalis.locale.unit );
		dataTable.addColumn( 'string', 'Country' );

		for( i = 0; i < rs.length; i++ ) {
			dataTable.setValue( i, 0, rs[i].get( 'iso' ) );
			dataTable.setValue( i, 1, rs[i].get( year ) );
			dataTable.setValue( i, 2, rs[i].get( 'name') );
		};

	 	var formatter = new google.visualization.NumberFormat({
			decimalSymbol: ',',
			groupingSymbol: ' ',
			fractionDigits: Globalis.data.precision,
			negativeColor: 'red'
		});
	  	formatter.format(dataTable, 1); // Apply formatter to second column

		this.dataTable = dataTable;
	}
});

Ext.reg('statisticsStore',Globalis.StatisticsStore);



Globalis.StatisticsChartPanel = Ext.extend( Ext.Panel,{
    initComponent: function(){

        Ext.apply(this, {chart: null});

        Globalis.StatisticsChartPanel.superclass.initComponent.call(this);
    },
	
	listeners:{
		activate: function(){
			var chartHeight = 80 + this.statStore.getCount() * 15;
			this.chart = new FusionCharts( Globalis.path.chart + "Bar2D.swf", "barchart", this.container.getWidth(), chartHeight, "0", "1");
			//console.log(Globalis.path.chart + "Bar2D.swf");
			this.chart.setDataXML(this.statStore.dataXML);
			this.chart.render(this.body.dom);
		}
	}
});

Ext.reg('statisticschartpanel',Globalis.StatisticsChartPanel);


Globalis.StatisticsGridPanel = Ext.extend(Ext.grid.GridPanel,{
    initComponent:function(){
        Ext.apply(this,{
            border: false,
            width: 635,
            height: 500,
            stripeRows:true,
            autoHeight:false
        });

        Globalis.StatisticsGridPanel.superclass.initComponent.call(this);
    },

    listeners:{
        rowclick: function(grid,index,e){
            var detailPanel = new Globalis.StatisticsDetailPanel({
                statStore: grid.store,
                rowIndex: index
            });
            detailPanel.show();
        }
    }
});

Ext.reg('statisticsgridpanel',Globalis.StatisticsGridPanel);


Globalis.StatisticsMapPanel = Ext.extend(Ext.Panel,{

    initComponent: function(){

		Ext.apply(this,{
			geoMap: null,
			mapMode: 'regions',
			mapRegion: 'world'
		});

		Globalis.StatisticsMapPanel.superclass.initComponent.call(this);
				
	},
	
	// Draw map
	drawMap: function(){

		//console.log(this.getInnerHeight(), this.container.getHeight());

		// Function from Google Visualization API
		this.geoMap.draw( this.statStore.dataTable,{
			dataMode: this.mapMode,
			region: this.mapRegion,
			showZoomOut: false,
			width: this.container.getWidth(),
			height: this.container.getHeight()
		});
	},
	
	listeners:{

		// Using afterrender to be able to retrieve this.getEl().id
		afterrender: function(){

			this.geoMap = new google.visualization.GeoMap(document.getElementById(this.getEl().id));
			google.visualization.events.addListener( this.geoMap, 'regionClick', this.clickHandler.createDelegate(this));			
			
			this.drawMap();

		},

		// Used when map is shown in resizable window (this.contentEl is undefined)
		resize: function(){

			if (this.geoMap && !this.contentEl) {
				this.drawMap();
			}

		}		
	},
	
	clickHandler: function(obj){
		var index = this.statStore.find( 'iso', obj.region );

        var detailPanel = new Globalis.StatisticsDetailPanel({
            statStore: this.statStore,
            rowIndex: index,
            chartdir: this.chartdir
        });
        detailPanel.show();
    }
});


Globalis.StatisticsEarthPanel = Ext.extend(Ext.Panel,{

    initComponent: function(){

		Ext.apply(this,{
			storeX: null,
			storeZ: null,
			stores: 0,
			dataTable: null,
			motionChart: null
		});

		Globalis.StatisticsEarthPanel.superclass.initComponent.call(this);

	}

});

Ext.reg('statisticsearthpanel',Globalis.StatisticsEarthPanel);	


Globalis.StatisticsMotionPanel = Ext.extend(Ext.Panel,{

    initComponent: function(){

		Ext.apply(this,{
			storeX: null,
			storeZ: null,
			stores: 0,
			dataTable: null,
			motionChart: null
		});

		Globalis.StatisticsMotionPanel.superclass.initComponent.call(this);

		this.motionChart = new google.visualization.MotionChart( document.getElementById('motiondiv'));
	
	},

	listeners:{

		activate: function(){
			
			// Load data if not already loaded
			if (Ext.isEmpty(this.dataTable)) {
				this.loadData();
			}
			else {
				this.drawChart(Globalis.dataStore.year);
			}

		}
	
		
	},

	loadData: function(){

		this.storeX = new Ext.data.JsonStore({
			url: Globalis.path.api + '/indicator',
			baseParams: { id: 182 }, // GDP per capita	
			root: 'records',
			autoLoad: true
		});	
		this.storeX.on('load', function(){ this.storeLoaded() }.createDelegate(this));
		
		this.storeZ = new Ext.data.JsonStore({
			url: Globalis.path.api + '/indicator',
			baseParams: { id: 494 }, // Population	
			root: 'records',
			autoLoad: true
		});		
		this.storeZ.on('load', function(){ this.storeLoaded() }.createDelegate(this));

	},

	storeLoaded: function(){
		this.stores++;
		if (this.stores == 2){
			this.createDataTable();
		}
	},

	// Build MotionChart DataTable
	createDataTable: function (){
	
		this.dataTable = new google.visualization.DataTable();
	
		var id, year, indexX, indexZ; 
	
		var recordsY = this.storeY.getRange();  	
		var recordsX = this.storeX.getRange();  
		var recordsZ = this.storeZ.getRange(); 	
	
		var numCountries = recordsY.length;
		var fields = this.storeY.fields.keys;
		var numYears = fields.length - 3;
			
		//dataTable.addRows(numYears * numCountries);
		this.dataTable.addColumn( 'string', 'Land' );
		this.dataTable.addColumn( 'number', 'År' );
		this.dataTable.addColumn( 'number', 'BNP per innbygger' );
		this.dataTable.addColumn( 'number', 'Spedbarnsdødelighet' );
		this.dataTable.addColumn( 'number', 'Befolkning' );
		this.dataTable.addColumn( 'string', 'Region' );
			
		// Loop through all years		
		for (y = 0; y < numYears; y++) {
	
			year = fields[y];
	
			// If year exist for all indicators
			if (!Ext.isEmpty(this.storeX.fields.map[year]) && !Ext.isEmpty(this.storeZ.fields.map[year])) {
	
				// Loop through all countries
				for( i = 0; i < numCountries; i++ ) {
		
					id = recordsY[i].get('id');  // Country id
	
					// If country id exist for all indicators
					indexX = this.storeX.find('id', id);
					indexZ = this.storeZ.find('id', id);
					if (indexX !== -1 && indexZ !== -1){
	
						this.dataTable.addRow([ 
							recordsY[i].get('name'), 
							parseInt( year ), 
							parseFloat( recordsX[indexX].get(year) ), 
							parseFloat( recordsY[i].get(year) ), 
							parseInt( recordsZ[indexZ].get(year) ),
							recordsY[i].get('region')
						]);
						
					}
				}
			}
		}
		
		this.drawChart(Globalis.dataStore.year);
	
	},


	drawChart: function(year) {

		this.motionChart.draw(this.dataTable, {
			width: this.container.getWidth() - 10, // margins
			height: 450,
			showSidePanel: true,
			showAdvancedPanel: false,
			state: '{"xZoomedIn":false,"iconKeySettings":[],"yZoomedDataMin":2,"xAxisOption":"2","dimensions":{"iconDimensions":["dim0"]},"stateVersion":3,"xLambda":1,"yZoomedIn":false,"xZoomedDataMax":64088,"orderedByX":false,"sizeOption":"4","orderedByY":false,"duration":{"multiplier":1,"timeUnit":"Y"},"yAxisOption":"3","nonSelectedAlpha":0.4,"yLambda":1,"showTrails":true,"xZoomedDataMin":413,"yZoomedDataMax":191,"colorOption":"5","playDuration":15.088888888888889,"time":"' + year + '","iconType":"BUBBLE"}'
		});
	}

	

});

Ext.reg('statisticsmotionpanel',Globalis.StatisticsMotionPanel);


Globalis.StatisticsDetailPanel = Ext.extend(Ext.Window,{
    initComponent: function(){
        Ext.apply(this,{
            title:' ',
            width:500,
            height:330,
            shadow:true,
            constrain:true,
            modal:true,
            dataXML:null,
            columnChart:null
        });

        Globalis.StatisticsDetailPanel.superclass.initComponent.call(this);
    },

    listeners: { 
		render: function(){
			this.setTitle( this.statStore.getAt(this.rowIndex).data['name'] );
			this.dataXML = this.statStore.createRecordDataXML(this.rowIndex);
		},
		resize: function(){
			this.columnChart = new FusionCharts( Globalis.path.chart + "Column2D.swf", "columnchart", this.getInnerWidth(), this.getInnerHeight(), "0", "1");
			this.columnChart.setDataXML( this.dataXML );
			this.columnChart.render( this.body.dom );
		}
	}
});

Ext.reg('statisticsdetailpanel',Globalis.StatisticsDetailPanel);



/**
* Creates the necessary DOM elements required for Ext.History to manage state
* Sets up a listener on Ext.History's change event to fire this.handleHistoryChange
* Code from: http://edspencer.net/2009/01/using-exthistory.html
*/
Globalis.initialiseHistory = function () {
	Globalis.historyForm = Ext.getBody().createChild({  
    	tag:    'form',  
    	action: '#',  
    	cls:    'x-hidden',  
    	id:     'history-form',  
    	children: [  
      		{  
        		tag: 'div',  
        		children: [  
          			{  
            			tag:  'input',  
            			id:   Ext.History.fieldId,  
            			type: 'hidden'  
          			},  
          			{  
            			tag:  'iframe',  
            			id:   Ext.History.iframeId  
          			}  
        		]  
      		}  
   		]  
  	});  
  
  	//initialize History management  
  	Ext.History.init();  



}





/**
 *
 * @access public
 * @return void
 **/
function myJS(myVar){

	// Find row index
	var index = Globalis.dataStore.find('id', myVar);

	// Create panel
	var detailPanel = new Globalis.StatisticsDetailPanel({
		statStore: Globalis.dataStore,
		rowIndex: index,
		chartdir: '{$chartdir}'
	});

    detailPanel.show();

};



shorten = function(str,n){
	if(str.length>n){
		return str.substr(0,n)+'...';
	}
	else return str;
};

function formatValue(value){
	return parseFloat(value).toFixed(Globalis.data.precision);
};



/*
Ext.onReady(function(){
	console.log(Ext.select('div.frame').getCount()); 

	// Create Ext.Panel from div
	Ext.select('div.frame').each( function(el){
		console.log(el, el.dom, el.dom.id, el.dom.title);

		new Ext.Panel({
			applyTo: el,
			frame: true
		});	
	});
});
*/



