
var i_power_w;//Instantaneous Power (watts) (convert this from kW to watts)
var i_wind_speed;//Instantaneous Wind Speed (m/s)
var i_wind_direction; // Instantaneous Wind Direction (degrees)
var lifetime_cumulative_work; // cumulative lifetime work (kilowatt hours)
var hour = new Array(); // from hour[0] = current hour to hour[23] = current hour - 23 hours
var day = new Array(); // from day[0] = current day to day[30] = current day - 30 days
var month = new Array(); // from month[0] = current month to month[11] = current month - 11 months
var spare = new Array(); // a bunch of spare data (unimportant)
var savings_picture = null;
var hours, days, months;
var generated_power;
var total_kilowatts =0;
var carbon_footprint = 0;
var component = 'all';
var numSites = 2;
var currentSite = 1;
var currentSiteName = "";
var scriptElement = null;
// renders data based on the component needing to be updated
function updateSwiftData() {
	// first call to updateSwiftData, draw each component
	if(component == 'all') {
		drawPicture();
		renderCurrentSite();
		//drawTextualData();
		//drawCharts();	
	}

	else if (component == 'charts_and_text' ) {
		renderCurrentSite();
	}

	// change the chart data
	//else if (component == 'charts') {
	//	drawCharts();
	//}

	// update all the textual display
	//else if (component == 'text' ) {
	//	drawTextualData();
	//}
}

// draws data for the current site (each 20 seconds)
function renderCurrentSite() {
	try {
		// reload the data
	 	parseText();
	 	renderDataHTML();
		hours = new FusionCharts("charts/Charts/Column2D.swf", "hoursChart", 300, 200, 0,0);
		days = new FusionCharts("charts/Charts/Column2D.swf", "daysChart", 300, 200, 0,0);
		months = new FusionCharts("charts/Charts/Column2D.swf", "monthsChart", 300, 200, 0,0);
		renderChartsXML();
		this.currentSite = ((this.currentSite % this.numSites)+1);
	}catch(e) {}
	setTimeout("nextTab()", 20*1000);
	//setTimeout("reloadText('charts_and_text')", 20 * 1000); 
}

function nextTab() {
	var navMenu = document.getElementById("navMenu");
	var links = navMenu.getElementsByTagName("a");
	var nextLink = 0;
	for(var i in links) {
		if(links[i].className == "current") {
			if(i < links.length-1) {
				nextLink = parseInt(i)+1;
			} else {
				nextLink = 0;
			}
			break;
		}
	}
	window.location.replace(links[nextLink]);
}

function drawTextualData() {
	try {
	// request the temperature
	//var b = document.createElement('SCRIPT');
	//b.src='http://www.swiftwindturbine.com/swiftWeather.php';
	//if (scriptElement != null)
	//	document.body.removeChild(scriptElement);
	//document.body.appendChild(b);
	//scriptElement = b;

	// reload the data
 	parseText();
 	renderDataHTML();
	}catch(e) {}
	setTimeout("reloadText('text')", 5 * 1000); // wait 5 seconds and repeat this function
}

function drawCharts() {
	try {
	hours = new FusionCharts("charts/Charts/Column2D.swf", "hoursChart", 300, 200, 0,0);
	days = new FusionCharts("charts/Charts/Column2D.swf", "daysChart", 300, 200, 0,0);
	months = new FusionCharts("charts/Charts/Column2D.swf", "monthsChart", 300, 200, 0,0);
	parseText();
	renderChartsXML();
	}catch(e) {}
	setTimeout("reloadText('charts')", 3600 * 1000); // wait 30 minutes and repeat this function
}

function drawPicture() {
	try {
	document.getElementById("swift_picture").src = "img/picture" + Math.floor( Math.random() * 7) + ".jpg";
	} catch(e) {}
	setTimeout("drawPicture()", 7 * 1000); // wait 7 seconds and repeat this function
}

// reloads the textual data for the swift tool
function reloadText(component) {
	//document.getElementById('textFile').onLoad = "updateSwiftData('" + component + "')";

	this.component = component;
	window.frames[0].location.reload(false); // this will trigger the onload of the iframe containing the data
	window.frames[1].location.reload(false); // this will trigger the onload of the iframe containing the data
}

function gotWeatherXml(xml) {

 try {
 xmlDoc = toXmlObj(xml);
   var temp_f; //added for no web access
   var temp_c; //added for no web access
 //var temp_f = xmlDoc.getElementsByTagName('temp_f')[0].childNodes[0].nodeValue;
 //var temp_c = xmlDoc.getElementsByTagName('temp_c')[0].childNodes[0].nodeValue;
 
//document.getElementById("temperature_f").innerHTML =   roundNumber(temp_f,1) + " F";
//document.getElementById("temperature_c").innerHTML =   roundNumber(temp_c,1) + " C";
} catch(e) {
}
}
function toXmlObj(stringXML) {
	try //Internet Explorer
	  {
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.loadXML(stringXML);
	  }
	catch(e)
	  {
	  try //Firefox, Mozilla, Opera, etc.
	    {
		var domParser = new DOMParser();
		var xmlDoc = domParser.parseFromString(stringXML, 'application/xml');
	    }
	  catch(e) {alert(e.message)}
	  }
	try 
	  {
	  return(xmlDoc);
	  }
	catch(e) {alert(e.message)}
	return(null);
}

//parse file, set global data to file data
function parseText(){
	dstring = window.frames[this.currentSite-1].document.body.innerHTML.replace(/\<[^\>]+\>/gm, "");
	a = dstring.split(",");
	this.currentSiteName = a[119];
	hourCount = 0;
	dayCount = 0;
	monthCount = 0;
	spareCount = 0;
	for (i=0; i<a.length; i++) {
				
		if (i <= 23) {//hours
			hour[hourCount] = a[i] * 1000;
			hourCount++;
		} else if (i <= 54) {//days
			day[dayCount] = a[i] * 1000;
			dayCount++;
		} else if (i <= 66) {//months
			month[monthCount] = a[i] * 1000;
			monthCount++;
		} else if (i == 100) {
			i_power_w = a[i];
		} else if (i == 101) {
			i_wind_speed = a[i];
		} else if (i == 102) {
			i_wind_direction = a[i];
		} else if (i == 103) {
			lifetime_cumulative_work = a[i];
		} else if (i == 104) {
			temp_c = a[i];
			temp_f = ((temp_c * 9) / 5) + 32;
		} else {
			spare[spareCount] = a[i];
			spareCount++;
		}		
	}
}

// puts the HTML-based data on the page
function renderDataHTML() {
	// set current power, wind speed, and wind direction
	document.getElementById("site_name").innerHTML =  "<h2 style='margin-top:10px;margin-bottom:8px;'>Location:&nbsp;&nbsp;" + this.currentSiteName + "</h2>";
	document.getElementById("current_power").innerHTML =  "<h1>" + ((i_power_w >= 1.0)?roundNumber(i_power_w,0):"<1") + "</h1>" + "<h2>WATTS</h2>";
	document.getElementById("wind_speed_mph").innerHTML =  roundNumber((i_wind_speed * 2.23693629),1) + " MPH";
	document.getElementById("wind_speed_mps").innerHTML =  roundNumber(i_wind_speed,1) + " m/s";
	document.getElementById("wind_direction").innerHTML =  degreesToDirection(i_wind_direction);
	//
	document.getElementById("lifetime_cumulative_work").innerHTML = roundNumber(lifetime_cumulative_work * 1000,1);
	document.getElementById("temperature_f").innerHTML =   roundNumber(temp_f,1) + " F";
	document.getElementById("temperature_c").innerHTML =   roundNumber(temp_c,1) + " C";
	document.getElementById("turbine_powered").innerHTML = getPowerSavingsMessage(lifetime_cumulative_work);
	document.getElementById("carbon_footprint").innerHTML = "<span class='text'>CARBON DIOXIDE AVOIDED FROM<br/> TURBINE GENERATION</span><p style='line-height:5px'>&nbsp;</p><h1>" + ((getCarbonFootprint() >= 1.0)?roundNumber(getCarbonFootprint(),0):"<1") + "</h1>" + "<h2>POUNDS</h2>";
	document.getElementById("energy_savings_picture").src=getPowerSavingsPicture(lifetime_cumulative_work);
}


// given the degrees in standard compass notation, return the direction (E, NE, etc.)
function degreesToDirection(deg) {
	deg = (deg / 1) % 360; // standard integer from 0 to 359
	var delta = 45.0 / 2; // maximum tolerable distance from a true direction
	var dir = new Object;
	dir['N'] = 0;
	dir['NE'] = 45;
	dir['E'] = 90;
	dir['SE'] = 135;
	dir['S'] = 180;
	dir['SW'] = 225;
	dir['W'] = 270;
	dir['NW'] = 315;
	if( deg >= dir['NW'] + delta || deg <= dir['NE'] - delta) {
		return 'N';
	} else if ( deg >= dir['NE'] - delta && deg <= dir['NE'] + delta ) {
		return 'NE';
	} else if ( deg >= dir['E'] - delta && deg <= dir['E'] + delta ) {
		return 'E';
	} else if ( deg >= dir['SE'] - delta && deg <= dir['SE'] + delta ) {
		return 'SE';
	} else if ( deg >= dir['S'] - delta && deg <= dir['S'] + delta ) {
		return 'S';
	} else if ( deg >= dir['SW'] - delta && deg <= dir['SW'] + delta ) {
		return 'SW';
	} else if ( deg >= dir['W'] - delta && deg <= dir['W'] + delta ) {
		return 'W';
	} else if ( deg >= dir['NW'] - delta && deg <= dir['NW'] + delta ) {
		return 'NW';
	} 
}

// returns a message based on the total watts saved
function getPowerSavingsMessage(kwh) {
	var savings_message = "";
	var wh = kwh * 1000;
	if(wh >= 0 && wh < 500001) {
		savings_message ="The Swift has generated enough energy to make " + roundNumber(wh / 5.83, 0) + " cups of coffee.";
	}
	else if (wh >= 500001 && wh < 1000001) {
		savings_message = "The Swift has generated enough energy to power the lights on in " + roundNumber(wh / 115, 0) + " homes for an hour.";
	}
	else if (wh >= 1000001 && wh < 2000001) {
		savings_message = "The Swift has generated enough energy to power "+ roundNumber(wh / 100, 0)+" hours of TV.";
	}
	else if (wh >= 2000001) {
		savings_message = "The Swift has offset the carbon dioxide generated by a passenger car for "+roundNumber(wh * 0.001418 / .607, 0)+" hours.";
	}
	return savings_message;
}

// returns a picture-file based on watt-hour usage
function getPowerSavingsPicture(kwh) {
	// determine image...
	var file;
	var wh = kwh * 1000;
	if(wh >= 0 && wh < 500001) {
		file = "img/coffeecup_1.jpg";
	}
	else if (wh >= 500001 && wh < 1000001) {
		file = "img/homeexteriorlights_1.jpg";
	}
	else if (wh >= 1000001 && wh < 2000001) {
		file = "img/flatscreentv_1.jpg";
	}
	else if (wh >= 2000001) {
		file = "img/caronroad_1.jpg";
	}
	return file;
}

// returns pounds of carbon saved
function getCarbonFootprint() {
	return (lifetime_cumulative_work * 1.418)	
}

function renderChartsXML(/*isFirstTime*/) {
/*
	if(isFirstTime) {
		hours.setDataXML("<chart></chart>");
		hours.render("hoursdiv");
		days.setDataXML("<chart></chart>");
		days.render("daysdiv");
		months.setDataXML("<chart></chart>");
		months.render("ytddiv");
	}
	else {	
		updateChart("hoursChart");
		updateChart("daysChart");
		updateChart("monthsChart");
	}
*/		hours.setDataXML(generateXML('hours'));
		hours.render("hoursdiv");
		days.setDataXML(generateXML('days'));
		days.render("daysdiv");
		months.setDataXML(generateXML('months'));
		months.render("ytddiv");

	
}
function generateXML(chartType) {
	var curDate = new Date;
	if (chartType == 'hours') {return getHoursXML(curDate);}
	else if (chartType == 'days') {return getDaysXML(curDate);}
	else if (chartType == 'months') {return getMonthsXML(curDate);}
}
function getHoursXML(curDate) {	
	var hoursXML = "<chart animation='0' bgColor='FFFFFF' showBorder='0' capFontSize='12' caption='ENERGY PRODUCED LAST 24 HOURS' xAxisName='Hours, Most Recent --->' yAxisName='Watt Hours' showLabels='0' showValues='0' rotateNames='1'>";
	var curHour = curDate.getHours();
	var tempXMLText = "";
	for (i=0; i<hour.length; i++) {
		if (curHour == 0) {
			curHour = 24;
			curHour--;
		} else {
			curHour--;
		}
		if (curHour > 9) {
			hourStr = curHour +":00";
		} else {
			hourStr = "0" + curHour +":00";
		}
		tempXMLText = getSetTag(hourStr, hour[i]) + tempXMLText;
	}
	hoursXML += tempXMLText + "</chart>";
	return hoursXML;
}

function getDaysXML(curDate) {
	var daysXML = "<chart animation='0' bgColor='FFFFFF' showBorder='0' caption='ENERGY PRODUCED LAST 31 DAYS' xAxisName='Days, Most Recent --->' yAxisName='Watt Hours' showLabels='0' showValues='0' rotateNames='1'>";
	var curDay = curDate.getDate();
	var curMonth = curDate.getMonth();
	var curYear = curDate.getFullYear();
	var tempXMLText = "";
	for (i=0; i<day.length; i++) {
		curDay--;
		if ((curDay) == 0) {
			curDay = daysInMonth(curDate.getMonth() -1, curDate.getFullYear());
			curMonth--;
			if(curMonth==0) {
				curMonth = 12;
				curYear--;
			}   
		}
		tempXMLText =  getSetTag( ((curMonth + 1) + "/" + curDay + "/" + curYear), day[i]) + tempXMLText;	
	}
	daysXML += tempXMLText + "</chart>";
	return daysXML;
}

function getMonthsXML(curDate) {
	var monthsXML = "<chart animation='0' bgColor='FFFFFF' showBorder='0' caption='ENERGY PRODUCED YEAR TO DATE' xAxisName='Months, Most Recent --->' yAxisName='Watt Hours' showLabels='0' showValues='0' rotateNames='1'>";
	var curMonth = curDate.getMonth() + 1;
	var curYear = curDate.getFullYear();
	var tempXMLText = "";
	for (i=0; i<month.length; i++) {
		curMonth--;
		if (curMonth == 0) {
			curMonth = 12;
			curYear--;			
		}
		tempXMLText = getSetTag( (curMonth + "/" + curYear), month[i] ) + tempXMLText;
	}
	monthsXML += tempXMLText + "</chart>";
	return monthsXML;
}

function getSetTag(labelStr, value) {
	var str = "<set color='98261f' label='" + labelStr + "' value='" + roundNumber(value, 1) + "' />";
	return str;
}


function daysInMonth(iMonth, iYear) {
	return 32 - new Date(iYear, iMonth, 32).getDate();
}

function roundNumber(num, dec) {
	return Math.round(num*Math.pow(10,dec)) / Math.pow(10,dec);
}

