﻿/*******************************************************************************
Globals 
*******************************************************************************/

var everySlash = /\//g;



/*******************************************************************************
DOM loaded
*******************************************************************************/

jq(function() {

	// Edit page if li#contentview-view exists, do nothing
	if(jq('li#contentview-view').length > 0) {
		return;
	}

	// If Flash 6 is available
	if(swfobject.getFlashPlayerVersion().major >= 6) {
	
		var tables = jq('div#content>div.inner');
		var electricityChart = tables.find('table.electricity-generation-data:first');
		var primaryChart = tables.find('table.primary-emissions-data:first');
		var secondaryChart = tables.find('table.secondary-emissions-data:first');
		var licenceChart = tables.find('table.licence-limits:first');
		var chart, chartHeading, chartControls;
		var abscissa = [];
		electricityData = [];
		var durations = [7, 30, 60, 90]; // Days to show in one chart
		selectedDurationIndex = 3;
		var genralSettings = 
			'<general_settings bg_color="ffffff" showAnchor="0" showArea="0" type_animation="1">' +
				'<header text="" size="1" />' +
				'<subheader text="" size="1" />' +
				'<legend font="Arial" color="000000" font_size="13" />' +
				'<legend_popup font="Arial" bgcolor="FFFFE3" font_size="13" />' +
				'<Xheaders rotate="90" color="000000" size="10" title="" title_color="333333" />' +
				'<Yheaders color="000000" size="10" title="" title_rotate="90" title_color="333333" />' +
				'<grid showX="1" showY="1" persent_stepY_from_stepX="400" grid_width="510" grid_height="380" grid_color="cccccc" grid_alpha="100" grid_thickness="1" bg_color="8f6b2f" bg_alpha="0" alternate_bg_color="FFA600" border_color="cccccc" border_thickness="1" />' +
			'</general_settings>';
		
		/* EMBED CHART */
		
		var embedFlashChart = function(includeEmissions) {
			// 554
			// /++resource++sita.theme.swf/fcp-line-chart.swf
			tables.prepend('<div id="flash-chart-wrapper"><fieldset id="chart-controls"></fieldset><br/><h2 id="chart-heading"></h2><div id="flash-chart"></div></div><br/>');
			// Move body text before
			tables.prepend(tables.find('div#parent-fieldname-text'));
			swfobject.embedSWF(
				'/++resource++sita.theme.swf/fcp-line-chart.swf',
				'flash-chart', 
				'554', 
				'500', 
				'6', 
				null, //xiSwfUrlStr
				null, //flashvarsObj
				null, //parObj
				null, //attObj
				null //callbackFn
			)
			chartHeading = tables.parent().find('h2#chart-heading');
			chartControls = tables.parent().find('fieldset#chart-controls')
			chartControls.css({border:'none', padding:0});
			
			// Chart controls
			
			var fieldset = chartControls[0];
			
			if(includeEmissions) {
				var emissionLabel = document.createElement("label");
				emissionLabel.appendChild(document.createTextNode("Emission: "));
				fieldset.appendChild(emissionLabel);
			
				var emissionSelect = document.createElement("select");
				emissionSelect.setAttribute("id", "emissions-select");
				fieldset.appendChild(emissionSelect);
				emissionSelect.setAttribute("disabled", "disabled");
			}
			
			var dateLabel = document.createElement("label");
			dateLabel.appendChild(document.createTextNode(" Show the last: "));
			fieldset.appendChild(dateLabel);
			
			var dateSelect = document.createElement("select");
			dateSelect.setAttribute("disabled", "disabled");
			dateSelect.setAttribute("id", "date-select");
			fieldset.appendChild(dateSelect);
			
			// Wrap tables below toggle link
			jq('div#content>div.inner>*').not(jq('div#flash-chart-wrapper, div#parent-fieldname-text'))
			.wrapAll('<div id="data-tables"></div>').parent().hide()
			.before('<a id="show-data" href="#">Show detailed data</a>').prev('a#show-data')
			.click(function() {
				var dataTables = jq(this).next('div#data-tables');
				dataTables.toggle();
				jq(this).text(dataTables.is(':visible') ? 'Hide detailed data' : 'Show detailed data');
				return false;
			});
		}
		
		
		/* POPULATE CHART CONTROLS */
		var populateChartControls = function(updateMethod) {
	
			// Populate emissions select
			var emissionsSelect = jq("#emissions-select")[0];
			
			if(emissionsSelect) {
				// For each emission
				for(var i = 0 ; emissions[i] ; i++) {
					var option = document.createElement("option");
					option.appendChild(document.createTextNode(emissions[i].title));
					emissionsSelect.appendChild(option);
				}
				// Onchange handler
				emissionsSelect.onchange = function() {
					selectedEmissionIndex = this.selectedIndex;
					updateMethod();
				}
				// Enable widget
				emissionsSelect.removeAttribute("disabled");
			}
			
			// Populate date select
			var dateSelect = jq("#date-select")[0];
			
			// For each duration
			for(var i = 0 ; durations[i] ; i++) {
				var option = document.createElement("option");
				if(i == selectedDurationIndex) {
					option.setAttribute("selected", "selected");
				}
				option.appendChild(document.createTextNode(durations[i] + " days"));
				dateSelect.appendChild(option);
			}
			// Onchange handler
			dateSelect.onchange = function() {
				selectedDurationIndex = this.selectedIndex;
				updateMethod();
			}
			// Enable widget
			dateSelect.removeAttribute("disabled");
			updateMethod();
			
		}
		
		/* POPULATE ARRAYS FROM HOME */
		function populateArrayFromRows(arr, sourceRows, cellIndex) {
			    
			for(var i = sourceRows.length-1 ; i>0  ; i--) {
			    //console.log(i)
				// get a reference to the cells in this row
				cells = sourceRows[i].getElementsByTagName("td");
				// Append the value of the appropriate cell to the array
				arr.push(cells[cellIndex].innerHTML);
			}
		}

		
		/* GENERATE XML FOR CHART */
		var generateGraphXmlString = function(type, attributes, data) {
		
			// Remove duration from data
			var duration = durations[selectedDurationIndex];
			var durationData = data.slice(data.length - duration, data.length);
		
			// If the data contains only null values;
			if(durationData.join("").length == 0) {
				// Return an empty string to prevent graph crashing
				return "";
			}
			// Open root start element
			var xmlString = "<" + type + "_data";
			
			// If this is a series, add series name attribute
			if(attributes) {
				for(attribute in attributes) {
					xmlString += " " + attribute + '="' + attributes[attribute] + '"';
				}
			}
			xmlString += ">";
			var axis = type == "abscissa" ? "x" : "y";
			// For each data member
			for(var i = 0 ; i < durationData.length ; i++) {
				var value = durationData[i];
				
				if(axis === 'y') {
					//value = Math.round(value);
					//console.log(value);
				}
				
				// If this is the abscissa data
				if(type == "abscissa") {
				
					// If the number of columns excedes 30, blank all but every 3rd
					if(durationData.length > 30 && (i+1) % 3 != 0 && i != 0) {
						value = "";
						// Otherwise reformat
					} else {
						// Convert "d/m/y" to "d-mon"
						var dMY = value.split("/");
						var month = parseInt(dMY[1], 10)-1;
						value = dMY[0] + " " + ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][month];
					}
				}
				xmlString += '<' + axis + ' value="' + value + '" />';
			}
			// Close root element
			xmlString += "</" + type + "_data>";
			return xmlString;
		}
		
		
		
		
		/* ELECTRICITY PAGE */
		if(electricityChart.length === 1) {
		
			chartRows = electricityChart[0].getElementsByTagName("tr");
			populateArrayFromRows(abscissa, chartRows, 0);
			populateArrayFromRows(electricityData, chartRows, 1);
		
			// Embed and populate chart
			embedFlashChart();
			var closure = function() {
				populateChartControls(updateElectricityChart);	
			}
			setTimeout(closure, 500);
			
			
			function updateElectricityChart() {
				
				chartHeading.html('Electricity generation (MWh)');
				
				// Build up the XML string for the graph
			
				var abscissaXml = generateGraphXmlString("abscissa", null, abscissa);
				var electricityXxml = generateGraphXmlString("ordinal", {seriesName:"Electricity generation", color:"FFA600", size:"3"}, electricityData);
				
				var xmlString = "<graph>" + genralSettings + abscissaXml + electricityXxml + "</graph>";
				
				// Pass the XML to the chart
				var FCObject = jq('#flash-chart')[0];
				FCObject.SetVariable('_root.xml_string', xmlString);
				
			}	
			
		}
		
		
		
		
		
		
		/* EMISSIONS PAGE */
		else if(primaryChart.length + secondaryChart.length + licenceChart.length === 3) {
		
			// Embed and populate chart
			embedFlashChart(true);
			var closure = function() {
				populateChartControls(updateEmissionsChart);	
			}
			setTimeout(closure, 500);
		
			/* CLASS AND FUNCTIONS FOR EMISSIONS PAGE */
			
			// An emission object represents a type of emission, for example VOCs.
			function Emission(name, title) {
				this.name = name;
				this.title = title;
				this.legalLimit; // Populated later when charts are parsed
				
				// Minimum and maximum values, default to zero, updated as values are added
				this.minValue = 0; // Populated later when charts are parsed
				this.maxValue = 0; // Populated later when charts are parsed
				this.initialise();
				
				// Add quick look-up for this emission to static variable
				Emission[this.name] = this;
			}
			// Set the legal limit for the emission
			Emission.prototype.setLegalLimit = function(limit) {
				this.legalLimit = parseFloat(limit);
			}
			// Get the legal limit for the emission
			Emission.prototype.getLegalLimit = function() {
				return this.legalLimit;
			}
			// Create instance properties for reference types
			Emission.prototype.initialise = function() {
				// Arrays representing ordinate series for primary and secondary generators
				this.primaryData = new Array(); // Populated later when charts are parsed
				this.secondaryData = new Array(); // Populated later when charts are parsed
			}
			// Add a new value to the ordinate series for a generator
			Emission.prototype.appendValue = function(generator, value) {
				// If generator correctly identifies a ordinate series
				if(generator == "primary" || generator == "secondary") {
					// If the value is not a number, set it to null
					value = isNaN(value) ? null : value;
					// Add the value to the series
					this[generator + "Data"].push(value);
					// Update min and max values for emission
					this.minValue = Math.min(this.minValue, value);
					this.maxValue = Math.max(this.maxValue, value);
				}
			}
			Emission.prototype.getValue = function(generator, index) {
				return this[generator + "Data"][index];
			}
			Emission.prototype.getData = function(generator) {
				return this[generator + "Data"];
			}
		
			var emissions = new Array();
			var selectedEmissionIndex = 0;
			
			// Get a reference to the rows of each chart
			var primaryChartRows = primaryChart[0].getElementsByTagName("tr");
			var secondaryChartRows = secondaryChart[0].getElementsByTagName("tr");
			var licenceChartRows = licenceChart[0].getElementsByTagName("tr");
			
			// Populate x axis with dates from primary emissions table
			populateArrayFromRows(abscissa, primaryChartRows, 0);
			
			// Using primary chart create an emission object for each type of emission.
			// The type title is taken from the first row. the thead, of that chart
			var cells = primaryChartRows[0].getElementsByTagName("td");
			for(var i = 1 ; cells[i] ; i++) {
				// The human readable title
				var title = cells[i].innerHTML.toString();
				// Safe variable name from title - strip non word characters
				var name = title.toLowerCase().replace(/\W+/g, '');
				var emission = new Emission(name, title);
				emissions[emissions.length] = emission;
			}
			
			var populateEmissionsData = function(generator, rows) {
	
				// For each row in the chart, after the thead
				for(var i = rows.length-1 ; i>0 ; i--) {
				
					// Get a refence to the table cells in tis row
					var tds = rows[i].getElementsByTagName("td");
					
					// For each td in that row, beyond the first one (date)
					for(var j = 1 ; tds[j] ; j++) {
						// Add the value to the appropriat emission - note that the
						// index shifts by -1 because the date column is not an emission
						emissions[j - 1].appendValue(generator, tds[j].innerHTML);
					}
				}
			}
			
			// Populate emissions objects with data from each chart
			populateEmissionsData("primary", primaryChartRows);
			populateEmissionsData("secondary", secondaryChartRows);
			
			// Get a reference to legal limit row 2 tds
			var tds = licenceChartRows[1].getElementsByTagName("td");
			// Populate legal limits
			for(var i = 0 ; tds[i] ; i++) {
				emissions[i].setLegalLimit(tds[i].innerHTML);
			}
				
			function updateEmissionsChart() {
				
				chartHeading.html(emissions[selectedEmissionIndex].title);
				
				// Retrieve data for generators
				var primaryData = emissions[selectedEmissionIndex].getData("primary");
				var secondaryData = emissions[selectedEmissionIndex].getData("secondary");
				
				
				// Generate data for the legal limit, a flat line
				var licenceLimit = emissions[selectedEmissionIndex].getLegalLimit();
				var licenceLimitData = new Array();
				for(var i = 0 ; i < primaryData.length ; i++) {
					licenceLimitData[i] = licenceLimit;
				}
			
				var abscissaXml = generateGraphXmlString("abscissa", null, abscissa);
				var primaryXxml = generateGraphXmlString("ordinal", {seriesName:"Primary incinerator", color:"8bc53e", size:"3"}, primaryData);
				var secondaryXxml = generateGraphXmlString("ordinal", {seriesName:"Secondary incinerator", color:"ffc11f", size:"3"}, secondaryData);
				var licenceXml = generateGraphXmlString("ordinal", {seriesName:"Licence limit", color:"00998f", size:"3"}, licenceLimitData);
				
				var xmlString = "<graph>" + genralSettings + abscissaXml + primaryXxml + secondaryXxml + licenceXml + "</graph>";
				//alert(xmlString);
				
				// Pass the XML to the chart
				var FCObject = jq('#flash-chart')[0];
				FCObject.SetVariable('_root.xml_string', xmlString);
				
			}
		}
	
	}
	
});