
window.onload = PageLoaded;

var descrs = { "Solar Radiation": "1000W/m2 equates to full sunlight. Vermilion\nRecieves 3.28 hours of full intensity sun per day.", "PV": "\nDepending on demand, voltage may\nreach 80V.  The batteries require 54V."};

var picc;
var txt;
var expandWindow;
var nwin;
var owin = "";
var openWin = false;
///////////////////////////// CLICK THE QUESTION MARK ///////////////////////////////////
var WhatsThis = function (opwin) {
	if (openWin == false && opwin != "Solar Radiation" && opwin != "PV") {
	//if (navigator.appName == "Microsoft Internet Explorer") clearInterval(bladeTimer);
	openWin = true;
	owin = opwin;
	nwin = new canvas.TFObject("rectangle", "awindow", [["fillcolour", "white"], ["width", "3"]]);
	nwin.SetParameter("layer", "window");
	nwin.AddPoints([[20,20], [695,20]]);
	canvas.RefreshCanvas();
	if (navigator.appName != "Microsoft Internet Explorer") expandWindow = setInterval(expWin, 20);
	else expandWindow = setInterval(expWin, 40);
	}
}

///////////////////////////// OPEN NEW PAGE ///////////////////////////////////
function opage (gname) {
	//if (gname == "heatimg") window.open("solarcollectordiagram/");
}

var closeWin;

var msi;
///////////////////////////// CREATE THE WINDOW ///////////////////////////////////
function expWin () {
	var cpp = nwin.GetPoints()[1];
	if (navigator.appName != "Microsoft Internet Explorer") nwin.SetPoint(1, [cpp[0], cpp[1]+8]);
	else nwin.SetPoint(1, [cpp[0], cpp[1]+16]);
	if (cpp[1] > 411) {
		nwin.SetPoint(1, [cpp[0], 411]);
		clearInterval(expandWindow);
		closeWin = new canvas.TFObject("circle", "CloseButton");
		closeWin.Translate([695, 20]);
		closeWin.SetParameters([["radius", 10], ["fillcolour", "red"]]);
		closeWin.SetParameter("layer", "window");
		// for collision detection... although circles should really be implimented....
		closeWin.AddPoints([[-10,-10], [10,-10], [10,10], [-10,10]]);
		closeWin.MakeButton(ClosingIt);
		
		if (owin == "Underground Tank") {
			picc = new canvas.TFObject("image", "tankimg", [["image", "animationimages/undergroundtank.png"]]);
			txt = new canvas.TFObject("text", "dscr", [["text", "You can’t stop the Sun from shining.  When\nsolar hot water heat is not needed for the\nbuilding the glycol solution is diverted to a copper\ncoil heat exchanger in the 4500L buried water\ntank.  The tank is insulated with 30 cm of\nStyrofoam insulation."]]);
		} else if (owin == "Solar Heating") {
			picc = new canvas.TFObject("image", "heatimg", [["image", "animationimages/solarwater.png"]]);
			txt = new canvas.TFObject("text", "dscr", [["text", "The Energy Cabin uses solar energy to heat the\ninterior space. The solar heat from 60 evacuated\ntube collectors supplies the buildings heat for\nmost of the year.  Propane is used in the coldest\nmonths to meet the heating demand.\n\nEach 20 tube solar collector covers 1.7 m2 of\nroof and is rated at 586 watts for a total of 1750\nwatts for the installed system.  The system is\npressurized and a glycol solution is circulated by\na small 24VDC PV powered pump.\n\nThe in-floor hot water heating system needs\nwater above 45°C to operate.  Water circulated\nto the collectors usually gains about 8-10°C.\nTwo hot water tanks store the heat between day\nand night.  In the summer when building heat is\nnot needed hot water is circulated to a 4500L\nunderground storage tank."]]);
		} else if (owin == "Photo Voltaic Panels") {
			picc = new canvas.TFObject("image", "pvimg", [["image", "animationimages/solarpanel.png"]]);
			txt = new canvas.TFObject("text", "dscr", [["text", "The Energy Cabin operates completely off-grid\nusing ten 175 watt solar panels for a system\ncapacity of 1.75 kW.  The system operates at a\nnominal 48V.  A charge controller manages the\nstate of the battery bank supplying electricity to\nthe load and changing the batteries when\nneeded.  The system generates about 3-12kW-hr\nof electricity per day saving about $40 per month\nin electricity charges and about 1.5 tonne of CO2\nannually.  The 48VDC is converted to regular\n120VAC current by a 3.5 kW inverter for use within\nthe building.  Power is used for lighting, activities\nin meeting room , water heat circulation pumps\nand the computer serving this web site 24 hours\na day."]]);
		} else if (owin == "Wind Turbine") {
			picc = new canvas.TFObject("image", "turbineimg", [["image", "animationimages/windturbine.png"]]);
			txt = new canvas.TFObject("text", "dscr", [["text", "Wind is a good complement to the solar PV\nsystem.  Often the wind turbine provides power\nwhen days are cloudy or at night.  The Energy\nCabin has a turbine rated at 3.0 kW at 39km/hour\nwinds and mounted at a height of 18.3 meters\n(60 feet).  The rotors are 15 feet in diameter and\nstart producing power at 12 km/hour (3.4m/sec).\nThe current wind speed is XXX km/hour. If power\nis not needed, electricity generated by the wind\nturbine is diverted to heat water for use in the\nheating system."]]);
		} else if (owin == "Hot Air Solar Wall") {
			picc = new canvas.TFObject("image", "wallimg", [["image", "animationimages/solarair.png"]]);
			txt = new canvas.TFObject("text", "dscr", [["text", "Air from the inside of the building is circulated\nthrough this collector and returned to building.\nThis collector is very efficient but only runs on\nthe coldest day to supplement building heat. The\nsystem has no capacity to store heat making\ntemperature regulation difficult."]]);
		}
		picc.SetParameter("layer", "window");
		picc.AddPoints([[0,0], [0,391], [391,391], [390,0]]);
		picc.MakeButton(opage);
		picc.Translate([20,20]);
		txt.SetParameter("layer", "window");
		txt.Translate([421,30]);
		txt.SetParameter("font", "1em arial");
		
		if (!exdone) msi = setInterval(ri, 100);
	}
	canvas.RefreshCanvas();
}

var ri = function () {
	if (exdone) {
		clearInterval(msi);
		canvas.RefreshCanvas();
	}
}

///////////////////////////// DELETE THE WINDOW ELEMENTS ///////////////////////////////////
var ClosingIt = function () {
	if (navigator.appName != "Microsoft Internet Explorer") expandWindow = setInterval(unWin, 20);
	else expandWindow = setInterval(unWin, 40);
	closeWin.DeleteObject();
	txt.DeleteObject();
	picc.DeleteObject();
}

var unWin = function () {
	var cpp = nwin.GetPoints()[1];
	if (navigator.appName != "Microsoft Internet Explorer") nwin.SetPoint(1, [cpp[0]-13, cpp[1]]);
	else nwin.SetPoint(1, [cpp[0]-26, cpp[1]]);
	if (cpp[0]-8 <= 20) {
		openWin = false;
		clearInterval(expandWindow);
		nwin.DeleteObject();
		//if (navigator.appName == "Microsoft Internet Explorer") bladeTimer = setInterval( turbineInt, lspeed );
	}
	canvas.RefreshCanvas();
}

var clc;
///////////////////////////// OVER THE QUESTION MARK ///////////////////////////////////
var MOver = function (tname, poss) {
	if (openWin == false) {
		if (tname != "Solar Radiation" && tname != "PV") {
			clc = new canvas.TFObject("text", "clickplease", [["text", tname + " - Click to Learn More"]]);
			clc.SetParameters([["x", poss[0]-100], ["y", poss[1]-20], ["fillcolour", "white"], ["font", "bold 1em arial"]]);
		} else {
			clc = new canvas.TFObject("text", "clickplease", [["text", descrs[tname]]]);
			clc.SetParameters([["x", poss[0]], ["y", poss[1]+20], ["fillcolour", "white"], ["font", "bold 1em arial"]]);
		}
	}
	canvas.RefreshCanvas("");
}

///////////////////////////// EXIT THE QUESTION MARK ///////////////////////////////////
var MOut = function (poss) {
	if (typeof(clc) != "undefined") clc.DeleteObject();
	canvas.RefreshCanvas("");
}

var bladeTimer;
var blades = new Array();
var panelone;
var paneltwo;
var panelthree;
var whats = new Array();
var nums = new Array();
var nightScene;
var sun;
var tsun;
var sky;
var ground;

var exdone = false;
var tef = function () { exdone = true; }

var DisplayLoading = function () {
	var dimensions = canvas.Dimensions();
	loadingObj = new canvas.TFObject("image", "loadingObj", [["image", "loadingImg"], ["x", (dimensions.width/2)-192], ["y", (dimensions.height/2)-72]]);
	canvas.RefreshCanvas();
	canvas.Preload(Initialize, [["animationimages/iesun.gif"], ["animationimages/sun.png"], ["animationimages/ecabmain.png"], ["animationimages/bladespin0000.png"], ["animationimages/bladespin0001.png"], ["animationimages/bladespin0002.png"], ["animationimages/bladespin0003.png"], ["animationimages/bladespin0004.png"], ["animationimages/bladespin0005.png"], ["animationimages/bladespin0006.png"], ["animationimages/bladespin0007.png"], ["animationimages/panel1.png"], ["animationimages/panel2.png"], ["animationimages/panel3.png"], ["animationimages/ecabinnight.png"], ["animationimages/what.png"]], 2);
}
function PageLoaded () {
	canvas = new TFApplication("maingraphic");
	canvas.CreateLayer("newone", "textcan");
	canvas.CreateLayer("window", "winlay");
	canvas.Preload(DisplayLoading, [["loadingImg", "animationimages/Loading-Black.gif"]]);
}
///////////////////////////// SETUP EVERYTHING ///////////////////////////////////
var Initialize = function () {
	canvas.Preload(tef, [["animationimages/undergroundtank.png"], ["animationimages/solarwater.png"], ["animationimages/solarpanel.png"], ["animationimages/windturbine.png"], ["animationimages/solarair.png"]]);
	
	// only sky, in gradient form
	sky = new canvas.TFObject("rectangle", "sky");
	sky.AddPoints([[0,0], [715,431]]);
	sky.SetParameters([["fillcolour", new canvas.LinearGradient([0,0], [0,431], [[0, "rgb(0,160,255)"], [.6, "rgb(160,200,255)"]])], ["linecolour", "none"]]);
	//var sky = new canvas.TFObject("image", "sky", "dullsky.png");
	
	// sun
	sun = new canvas.TFObject("line", "thesun", [["x", 350], ["y", 350]]);
	tsun = new canvas.TFObject("image", "thesun", [], sun);
	tsun.Translate([350,600]);
	if (navigator.appName == "Microsoft Internet Explorer") tsun.SetParameters([["image", "animationimages/iesun.gif"]]);
	else tsun.SetParameters([["image", "animationimages/sun.png"]]);
	
	// ground, cabin etc
	ground = new canvas.TFObject("image", "mainscene", [["image", "animationimages/ecabmain.png"]]);
	
	// blades
	blades.push(new canvas.TFObject("image", "blade1", [["image", "animationimages/bladespin0000.png"]]));
	blades.push(new canvas.TFObject("image", "blade2", [["image", "animationimages/bladespin0001.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	blades.push(new canvas.TFObject("image", "blade3", [["image", "animationimages/bladespin0002.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	blades.push(new canvas.TFObject("image", "blade4", [["image", "animationimages/bladespin0003.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	blades.push(new canvas.TFObject("image", "blade5", [["image", "animationimages/bladespin0004.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	blades.push(new canvas.TFObject("image", "blade6", [["image", "animationimages/bladespin0005.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	blades.push(new canvas.TFObject("image", "blade7", [["image", "animationimages/bladespin0006.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	blades.push(new canvas.TFObject("image", "blade8", [["image", "animationimages/bladespin0007.png"]]));
	blades[blades.length-1].SetParameter("visible", false);
	
	var i = 0;
	while (i < blades.length) {
		//if (navigator.appName != "Microsoft Internet Explorer") 
		blades[i].SetParameter("layer", "newone");
		i++;
	}
	///////////////////// CREATE PANEL OBJS HERE ///////////////////////
	panelone = new canvas.TFObject("image", "panel1", [["image", "animationimages/panel1.png"], ["visible", false]])
	paneltwo = new canvas.TFObject("image", "panel2", [["image", "animationimages/panel2.png"]])
	panelthree = new canvas.TFObject("image", "panel3", [["image", "animationimages/panel3.png"], ["visible", false]])
	
	nightScene = new canvas.TFObject("image", "nightscene", [["image", "animationimages/ecabinnight.png"]]);
	nightScene.SetParameter("visible", false);
	
	whats.push(new canvas.TFObject("image", "Underground Tank", [["image", "animationimages/what.png"]]));
	whats[0].Translate([250,340]);
	whats[0].MakeButton(WhatsThis, MOver, MOut);
	whats[0].AddPoints([[17,0],[17,32],[0,32],[0,0]]);
	
	whats.push(new canvas.TFObject("image", "Solar Heating", [["image", "animationimages/what.png"]]));
	whats[1].Translate([560,200]);
	whats[1].MakeButton(WhatsThis, MOver, MOut);
	whats[1].AddPoints([[17,0],[17,32],[0,32],[0,0]]);
	
	whats.push(new canvas.TFObject("image", "Photo Voltaic Panels", [["image", "animationimages/what.png"]]));
	whats[2].Translate([100,130]);
	whats[2].MakeButton(WhatsThis, MOver, MOut);
	whats[2].AddPoints([[17,0],[17,32],[0,32],[0,0]]);
	
	whats.push(new canvas.TFObject("image", "Wind Turbine", [["image", "animationimages/what.png"]]));
	whats[3].Translate([350,50]);
	whats[3].MakeButton(WhatsThis, MOver, MOut);
	whats[3].AddPoints([[17,0],[17,32],[0,32],[0,0]]);
	
	whats.push(new canvas.TFObject("image", "Hot Air Solar Wall", [["image", "animationimages/what.png"]]));
	whats[4].Translate([500,320]);
	whats[4].MakeButton(WhatsThis, MOver, MOut);
	whats[4].AddPoints([[17,0],[17,32],[0,32],[0,0]]);
	
	nums.push(new canvas.TFObject("text", "Solar Radiation", [["text", "Solar Radiation: W/m2"]]));
	nums[0].Translate([440,100]);
	nums[0].SetParameters([["fillcolour", "white"], ["font", "bold 1em arial"]]);
	nums[0].MakeButton(WhatsThis,MOver, MOut);
	nums[0].AddPoints([[150,-10],[150,60],[-10,60],[-10,-10]]);
	
	nums.push(new canvas.TFObject("text", "PV", [["text", "PV Voltage: V\nPV Current: A"]]));
	nums[1].Translate([190,240]);
	nums[1].SetParameters([["fillcolour", "white"], ["font", "bold 1em arial"]]);
	nums[1].MakeButton(WhatsThis,MOver, MOut);
	nums[1].AddPoints([[150,-10],[150,60],[-10,60],[-10,-10]]);
	
	canvas.RefreshCanvas();
	bladeTimer = setInterval( turbineInt, 100 );
	setInterval(getTime, 1000*300);
	getTime();
	GrabData();
	
	mid = setInterval(id, 100);
}

var mid;
var id = function () {
	if (tsun.GetImage().complete && ground.GetImage().complete && whats[0].GetImage().complete && whats[1].GetImage().complete && whats[2].GetImage().complete && whats[3].GetImage().complete && whats[4].GetImage().complete) {
		clearInterval(mid);
		canvas.RefreshCanvas();
	}
}

var cBlade = 0;
///////////////////////////// DISPLAY NEW BLADE ///////////////////////////////////
var turbineInt = function () {
	blades[cBlade].SetParameter("visible", false);
	cBlade--;
	if (cBlade == -1) cBlade = blades.length-1; 
	blades[cBlade].SetParameter("visible", true);
	
	canvas.RefreshCanvas("newone");
}

///////////////////////////// CHECK FOR AND APPLY CHANGES ///////////////////////////////////
var getTime = function () {
	var d = new Date();
	var hour = d.getHours();
	
	var mins = d.getMinutes();
	mins = mins/60;
	var hfrac = hour+mins;
	
	sun.SetParameter("rotation", -(3.14/12)*hfrac);
	
	
	var amountTo = (Math.abs(hfrac-14)/6);
	if (amountTo < .5) {
		amountTo = 0;
	} else {
		amountTo = amountTo/2;
	}
	var ra = parseInt((amountTo*0)+(Math.abs(1-amountTo)*0));
	var ga = parseInt((amountTo*75)+(Math.abs(1-amountTo)*160));
	var ba = parseInt((amountTo*120)+(Math.abs(1-amountTo)*255));
	var rb = parseInt((amountTo*255)+(Math.abs(1-amountTo)*160));
	var gb = parseInt((amountTo*150)+(Math.abs(1-amountTo)*200));
	var bb = parseInt((amountTo*0)+(Math.abs(1-amountTo)*255));
	
	
	sky.SetParameter("fillcolour", new canvas.LinearGradient([0,0], [0,431], [[0, "rgb(" + ra + "," + ga + "," + ba + ")"], [.6, "rgb(" + rb + "," + gb + "," + bb + ")"]]) );
	
	if (hour < 11) {
		paneltwo.SetParameter("visible", false);
		panelthree.SetParameter("visible", false);
		panelone.SetParameter("visible", true);
	} else if (hour >= 17) {
		paneltwo.SetParameter("visible", false);
		panelthree.SetParameter("visible", true);
		panelone.SetParameter("visible", false);
	} else {
		paneltwo.SetParameter("visible", true);
		panelthree.SetParameter("visible", false);
		panelone.SetParameter("visible", false);
	}
	
	if (hour > 20 || hour < 8) {
		nightScene.SetParameter("visible", true);
		nightScene.SetParameter("visible", false);
	} else {
		nightScene.SetParameter("visible", false);
	}
	canvas.RefreshCanvas();
}

var lspeed = 50;
function GrabData() {
	// check wind speed
	var getting; 
	if (window.XMLHttpRequest) { 
		getting = new XMLHttpRequest(); 
	} else { 
		getting = new ActiveXObject("Microsoft.XMLHTTP"); 
	}  
	getting.open("GET", "../processors/GetParameter.php?param=Wind_Speed", false);
	getting.send(""); 	
	var wspeed = getting.responseText;
	if (ANumber(wspeed)) {
		if (typeof(bladeTimer) != "undefined") clearInterval(bladeTimer);
		if (parseFloat(wspeed) > 0) {
			lspeed = Math.round(1000/parseFloat(wspeed));
			bladeTimer = setInterval( turbineInt, lspeed );
		}
	}
	
	var solarrad; 
	if (window.XMLHttpRequest) { 
		solarrad = new XMLHttpRequest(); 
	} else { 
		solarrad = new ActiveXObject("Microsoft.XMLHTTP"); 
	}  
	solarrad.open("GET", "../processors/GetParameter.php?param=Solar_Radiation", false);   
	solarrad.send("");   
	var sradia = solarrad.responseText; 
	nums[0].SetParameter("text", "Solar Radiation: " + sradia + "W/m2");
	canvas.RefreshCanvas();
	
	
	var pvp; 
	if (window.XMLHttpRequest) { 
		pvp = new XMLHttpRequest(); 
	} else { 
		pvp = new ActiveXObject("Microsoft.XMLHTTP"); 
	}  
	pvp.open("GET", "../processors/GetParameter.php?param=PV_Voltage", false);   
	pvp.send("");   
	var pvt = pvp.responseText;
	var pva; 
	if (window.XMLHttpRequest) { 
		pva = new XMLHttpRequest(); 
	} else { 
		pva = new ActiveXObject("Microsoft.XMLHTTP"); 
	}  
	pva.open("GET", "../processors/GetParameter.php?param=PV_Current", false);   
	pva.send("");   
	var pat = pva.responseText; 
	nums[1].SetParameter("text", "PV Voltage: " + pvt + "V\nPV Current: " + pat + "A");
	canvas.RefreshCanvas();
}

function ANumber (sText) {
	for (i = 0; i < sText.length; i++) {
		var Char = sText.charAt(i);
		if ("0123456789.-".indexOf(Char) == -1) return false;
	}
	return true;
}

