// Load Google Visualization API
google.load('visualization', '1', {'packages': ['geomap', 'motionchart']});

// Encapsulate all variables and methods in one global object
Ext.namespace('Globalis');

Ext.onReady(function(){

	// Creates markup required for history management (globalis.js)
	Globalis.initialiseHistory();

	// Create data store for main indicator
	Globalis.dataStore = new Globalis.StatisticsStore({
		url: Globalis.path.api + '/indicator',
		baseParams: { 
			id: Globalis.data.indicatorId,
			fields: 'name,iso,path,region'  
		},
		root: 'records'
	});

	Globalis.dataStore.on('load', function() {

		// Find all years in data store
		Globalis.dataStore.findYears();
		
		// Filter on default year (most recent)
		Globalis.dataStore.filter( this.year, new RegExp("\\d+") );

		// Default sorting		
		Globalis.dataStore.sort( this.year, Globalis.data.sorting );

		// Create FusionCharts XML
		Globalis.dataStore.createDataXML( this.year );

		// Create Google Visualization data table
		Globalis.dataStore.createDataTable( this.year );

		// simple array store
		Globalis.yearStore = new Ext.data.SimpleStore({
			fields: ['year'],
			data: Globalis.dataStore.years,
			expandData: true
		});
	
		// Create year drop-down for toolbar
		Globalis.yearBox = new Ext.form.ComboBox({
			name: 'year',
			mode: 'local',
			store: Globalis.yearStore,
			displayField: 'year',
			valueField: 'year',
			editable: false,
			forceSelection: true,
			triggerAction: 'all',
			value: Globalis.dataStore.year, // Most recent year
			width: 55,
			listeners: {
				select: function(combo, record, index){
	
					Globalis.dataStore.year = record.data.year;
	
					Globalis.dataStore.clearFilter();
					Globalis.dataStore.filter(record.data.year, new RegExp("\\d+"));
	
					Globalis.table.getColumnModel().setConfig([
						{id:'name', dataIndex:'name', header:'Land', width: 150, sortable: true},
						{id:'value', dataIndex: record.data.year, header: record.data.year, sortable: true, align: 'right', renderer: formatValue}
					]);
	
					// Default sorting
					Globalis.dataStore.sort(record.data.year, Globalis.data.sorting);
	
					// Recreate FusionCharts XML
					Globalis.dataStore.createDataXML(record.data.year);

					// Recreate Google Visualization data table
					Globalis.dataStore.createDataTable(record.data.year);
	
					// Index of active tab
					switch(Globalis.tabs.items.indexOf(Globalis.tabs.getActiveTab())){
						case 0:
							Globalis.barChart.fireEvent('activate');
							break;
						case 2:
							Globalis.map.drawMap();
							break;
						case 3:
							Globalis.motionChart.drawChart(record.data.year);
							break;
					};
				}
			}
		});

        // Create bar chart panel
    	Globalis.barChart = new Globalis.StatisticsChartPanel({
			id: 'barstab',
			tabId: 'bars',
    		title: Globalis.locale.barChart,
    	    contentEl: 'chartdiv',
    		statStore: Globalis.dataStore,
    		tbar: Globalis.toolbar
    	});
	
	    // Create table (grid) panel
	    Globalis.table = new Globalis.StatisticsGridPanel({
			id: 'tabletab',
			tabId: 'table',
	    	title: Globalis.locale.table,
	    	contentEl: 'tablediv',
	        store: Globalis.dataStore,
	        columns: [
	        	{id:'name', dataIndex:'name', header: Globalis.locale.country, width: 150, sortable: true},
	        	{id:'value', dataIndex: Globalis.dataStore.year, header: Globalis.dataStore.year, sortable: true, align: 'right', renderer: formatValue}
	        ]
	    });
	
		// Create map panel
	    Globalis.map = new Globalis.StatisticsMapPanel({
			id: 'maptab',
			tabId: 'map',
	    	title: Globalis.locale.map,
	    	contentEl: 'mapdiv',
	    	statStore: Globalis.dataStore // Object binding
	    });

		
		Globalis.bigMapButton = new Ext.Button({
			iconCls: 'arrow_out',
			id: 'bigMapButton',
			handler: function(btn){

				// Create new map panel (possible to reuse existing map panel?)
			    var bigMapPanel = new Globalis.StatisticsMapPanel({
					width: 1000,
					height: 580,	
			    	statStore: Globalis.dataStore 
			    });
				
				// Create resizeable window containing big map panel
	            var bigMapWindow = new Ext.Window({
	                title: Globalis.locale.indicatorName + ' ' + Globalis.dataStore.year,
					maximizable: true,
		            shadow: true,
		            constrain: true,
		            modal: true,
					items: bigMapPanel,
					layout: 'fit'					
	            });
	            bigMapWindow.show();
			}
		});


        // Create toolbar
        Globalis.toolbar = new Ext.Toolbar({
            items: [Globalis.locale.selectYear + ': ', Globalis.yearBox, '->', Globalis.bigMapButton]
    	});

        // Draw tab panel
        Globalis.tabs = new Ext.TabPanel({
            renderTo: 'tabs',
            width: 724,
            border: true,
            plain: true,
            activeTab: 0,
            defaults: {autoHeight: true},
            items:[
                Globalis.barChart,
                Globalis.table,
                Globalis.map
            ],
    		tbar: Globalis.toolbar,
			
			listeners:{

				tabchange: function(tabPanel, tab){
					
					//console.log(tabPanel, tab);
					Ext.History.add(tab.tabId);
		
					// Show/hide map specific button
					if (tab.contentEl === 'mapdiv'){
						Globalis.bigMapButton.show();
					}
					else{
						Globalis.bigMapButton.hide();						
					}
		
				}		
			}
	
        });

		var hash = document.location.hash.replace("#", "");  
		//console.log(hash);
		if (hash){
			Globalis.tabs.setActiveTab(hash + 'tab');			
			//console.log(hash + 'tab');
		}

	    // Handle this change event in order to restore the UI to the appropriate history state
	    Ext.History.on('change', function(tabId){
	        if(tabId){
	            Globalis.tabs.setActiveTab(tabId + 'tab');
	        }else{
	            // This is the initial default state.  Necessary if you navigate starting from the
	            // page without any existing history token params and go back to the start state.
	            
				Globalis.tabs.setActiveTab(0);
	        }
	    });



		// Add motion chart tab if checked
		if (Globalis.data.motionChart){

			// Create motion chart panel
			/*
		    Globalis.globe = new Globalis.StatisticsEarthPanel({
		    	title: Globalis.locale.globe,
		    	contentEl: 'earthdiv',
				bodyStyle: 'margin: 5px 5px 10px 5px',
		    	storeY: Globalis.dataStore // Object binding
		    });
			
			Globalis.tabs.add(Globalis.globe);
			*/

			// Create motion chart panel
		    Globalis.motionChart = new Globalis.StatisticsMotionPanel({
		    	title: Globalis.locale.motionChart,
		    	contentEl: 'motiondiv',
				bodyStyle: 'margin: 5px 5px 10px 5px',
		    	storeY: Globalis.dataStore // Object binding
		    });
			
			Globalis.tabs.add(Globalis.motionChart);
		}
		
	});
});