var const_id_warning_area="id_warningBanner";

loadHomePage();

function loadHomePage()
{
	var cookie_key=getCookie(const_key_cookie_name);
	
    if(cookie_key.length>0)  	
    {
    	document.getElementById("id_requireskeysection").style.display="block";
    	
    	// Send a throw-away member request, just to warm up the app and improve responsiveness
    	var resturl="http://www.sailgeorgina.ca/sga.member?cmd=getAccountDetails&warmup=true&key="+cookie_key;
        var xmlHttpReq = false;
        var self = this;
        // Mozilla/Safari
        if (window.XMLHttpRequest) {
            self.xmlHttpReq = new XMLHttpRequest();
        }
        // IE
        else if (window.ActiveXObject) {
            self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }
        self.xmlHttpReq.open('POST', resturl, true);
        self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        self.xmlHttpReq.onreadystatechange = function() { }
        self.xmlHttpReq.send();
    }

	var cookie_volvo_start=getCookie("volvostart2011");
    if(cookie_volvo_start.length==0)  	
    {
    	document.getElementById("id_volvo_racestart").style.display="block";
    	setCookie("volvostart2011","true",300);
    }

    // retrieve the JSON feed.
    var script = document.createElement('script');
    var resturl="http://www.sailgeorgina.ca/sga.videofeed?channel=volvooceanracevideos&callback=loadvideos";
    	
    script.setAttribute('src', resturl);
    script.setAttribute('id', 'jsonScript');
    script.setAttribute('type', 'text/javascript');
    document.documentElement.firstChild.appendChild(script);
    
	
	var date = new Date();
	var curr_month = date.getMonth();
	
	if(curr_month>=4 && curr_month<=9)
	{
		// From May-Oct (inclusive) get a weather warning
		getWeatherWarning();	
	}	
}

function loadvideos(data)
{
	var video_area=document.getElementById("id_volvo_racevideos");

	if (window.ActiveXObject)
		return;	// hack due to ie bug - do not show videos

	if (typeof(data.status) != "undefined")
	{
		if(data.status=="error")
		{
			return;
		}
		if(data.status=="ok")
		{
	    	document.getElementById("id_volvo_racevideos").style.display="block";
			var i;
			for(i=0; i<data.videos.length; i++)
			{
				var para=document.createElement("p");
				video_area.appendChild(para);
//				var bold=document.createElement("b");
//				bold.appendChild(document.createTextNode(data.videos[i].title));
//				para.appendChild(bold);
//				para.appendChild(document.createElement("br"));
				var published=document.createTextNode(data.videos[i].published)
				para.appendChild(published);
				para.appendChild(document.createElement("br"));
				
				var videourl="http://www.youtube.com/v/"+data.videos[i].id+"?version=3&feature=player_detailpage";
				var object=document.createElement("object");
				object.setAttribute("style","height: 270px; width: 415px");
				para.appendChild(object);
				
				var param1=document.createElement("param");
				param1.setAttribute("name","movie");
				param1.setAttribute("value",videourl);
				object.appendChild(param1);
				
				var param2=document.createElement("param");
				param2.setAttribute("name","allowFullScreen");
				param2.setAttribute("value","true");
				object.appendChild(param2);
				
				var param3=document.createElement("param");
				param3.setAttribute("name","allowScriptAccess");
				param3.setAttribute("value","always");
				object.appendChild(param3);
				
				
				var embed=null;
				if (window.ActiveXObject) 
		        {
		        	// IE doesn't need an embed object
		        	embed=object;
		        }
		        else
					embed=document.createElement("embed");
				
				embed.setAttribute("src",videourl);
				embed.setAttribute("type","application/x-shockwave-flash");
				embed.setAttribute("allowfullscreen","true");
				embed.setAttribute("allowScriptAccess","always"); 
				embed.setAttribute("width","415");
				embed.setAttribute("height","260");
				
				if (!window.ActiveXObject)
					object.appendChild(embed);				
			}			
		}
	}
}

function getWeatherWarning() 
{
	var script = document.createElement('script');
	var resturl=getweatherwarningresturl();
	
	script.setAttribute('src', resturl);
	script.setAttribute('id', 'jsonScript');
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);
}

function getweatherwarningresturl() {
    return "http://www.sailgeorgina.ca/sga.weatherwarning?callback=loadWeatherWarning"
}


function loadWeatherWarning(data)
{	
	var warning_area=document.getElementById(const_id_warning_area);
	removeAllChildren(warning_area);
	
	if (typeof(data.status) != "undefined")
	{
		if(data.status=="error")
		{
			return;
		}
		if(data.status=="ok" && data.warning=="true")
		{
			var warning=document.createElement("a");
			warning.innerHTML="Lake Simcoe Weather Warning in effect, click for details";
			warning.href=data.url;
			warning.target="_blank";
			warning.style.backgroundColor="red";
			warning.style.color="white";
			warning.style.fontWeight="bold";
			warning_area.appendChild(warning);
		}
	}
	
	setTimeout("getWeatherWarning()", 5000*60);  // 5 mins
}

function removeAllChildren(element) 
{
	var i=element.childNodes.length-1;
	while(i>=0)
	{
		element.removeChild(element.childNodes[i--])
	}
}


function showWindSpeed()
{
	  // Create and populate the data table.
	  var data = new google.visualization.DataTable();
	  data.addColumn('string', 'Label');
	  data.addColumn('number', 'Value');
	  data.addRows(3);
	  data.setValue(0, 0, 'Wind Speed');
	  data.setValue(0, 1, 2);
	  data.setValue(1, 0, 'Direction');
	  data.setValue(1, 1, 10);
	  data.setValue(2, 0, 'Temp');
	  data.setValue(2, 1, 55);
	  
	   var options = {width: 400, height: 120, 
	                  yellowFrom: 0, yellowTo: 5,
	                  greenFrom: 5, greenTo: 20,
	                  redFrom: 20, redTo: 40,
	                  minorTicks: 5, majorTicks: 10, 
	                  min: 0, max: 25
	                 };

	  // Create and draw the visualization.
	  new google.visualization.Gauge(document.getElementById('visualization')).
	      draw(data, options);
	  
	  //
	  var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
	  chart.draw(data, options);
}


function showWindDir()
{
	/*	Javascript Wind Rose, using Google's AJAX Feed and Chart, v.0.1
	Carlos Labs Pty, 2008
	PID: 200803B, http://www.carloslabs.com
	
	This code is released under a Creative Commons license. 
	http://creativecommons.org/licenses/by/3.0/legalcode

	You may use this code in any software project, provided you
	do not remove or modify this header and you credit us as the
	original authors of the code.
	
	 */

	//* Globals
	var Wx = 220, Wy = 220;		// width pixels coordinate X,Y	
	var chU1 = "<img src=\"http://chart.apis.google.com/chart?cht=r&";
	var chU2 = "chs=" + Wx + "x" + Wy + "&amp;chd=t:";
	var chU3 = "&chls=2.0,2.0,1.0&chco=AA6666&chm=h,999999,0,1.0,1.0|B,FF000080,0,1.0,5.0&chxt=x&chxl=0:|N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW&chxr=0,0.0,360.0\">";
	var chS = "<img src='whitedot.gif' height='" + Wx + "' width='" + Wy + "'>";
	var chT = "<img src='cleardot.gif' height='" + Wx + "' width='1'>";
	var url_r = "http://rss.weather.com.au/";
	var url_f = "";
	var n = "";
	var st = "";
	var combo = 0;

	var FEED_ERROR_MSG = "<div class='Error'>Network error; no data feed available.</div>";
	var DATA_ERROR_MSG = "<div class='Error'>No data available for this location</div>";
	var INDICATOR = "X";
	var MINIMUM = "12";
	var MAXIMUM = "100";
	var CURRENT_ENTRY = 0;
	var CURRENT_ATTRIBUTE = 0;
	var TEST_ONE = "Wind Direction:";
	var TEST_TWO = "Wind Speed:";

	aM = new Array("none","nsw/sydney","vic/melbourne","qld/brisbane","sa/adelaide","wa/perth","act/canberra","tas/hobart","nt/darwin");
	cM = new Array("N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW");

	google.load("feeds", "1");
}

function renderChart()
{
	if (combo < 1)
		return 0;
			
	var gUrl = 	chU1 + chU2 + st + chU3;
	document.getElementById("tableDiv").innerHTML = chT + gUrl;
	
	return 1;
}

function initializeWindDir() {
	var feed = new google.feeds.Feed(url_f);
	feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
	var item = "";
	var oLink = "";
	st = "";
	var found = 0;
	document.getElementById('status').innerHTML = "";
	feed.load(function(result) {
		var container = document.getElementById("feed");
		if (!result.error) {
			oLink = result.xmlDocument.getElementsByTagName("link");
			linkback = oLink[0].childNodes[0].nodeValue.toString();
		    var items = result.xmlDocument.getElementsByTagName("description");
		    var thisElement = items[1].childNodes[0].nodeValue.toString();
		    var xArray = thisElement.split("<br />");
		    for (var k = 0; k < (xArray.length - 1); k++) {
		    	var yArray = xArray[k].split("</b>");
		    	var key = yArray[0].replace("<b>","");
		    	key = key.replace(" ","");
		    	var value = yArray[1].toString();
		    	value = value.replace(" ","");		    	
				if (key == TEST_ONE)	{
					// alert(value);
					for (var m = 0; m < cM.length; m++)	{
						//alert(cM[m]);
						if (value == cM[m]){
							st = st + ',' + MAXIMUM;
							found = 1;
						}
						else	{
							st = st + ',' + MINIMUM; 
						}
					}
					// close the gap when the value is "N"					
					if (value == "N")	{ 
						st = st + ',' + MAXIMUM;
					}
					else	{
						st = st + ',' + MINIMUM;
					}					
					st = st.substring(1,(st.length));
				}
				if (key == TEST_TWO)	{
					document.getElementById('status').innerHTML = key + ' ' + value;
				}				
			}
			document.getElementById('link').innerHTML = "<a href=\"" + linkback + "\">" + linkback + "</a>";
		}
		else	{
			document.getElementById('status').innerHTML = FEED_ERROR_MSG;
			document.getElementById('link').innerHTML = " ";
		}
		if (found != 1)	{
			document.getElementById('status').innerHTML = DATA_ERROR_MSG;
			document.getElementById('link').innerHTML = " ";
		}
		else	{
			var foo = renderChart();
		}		
	});
	return 1;
}
    
function loadFeed(form)	{
	combo = form.selector.value;
	if (combo < 1)
		return 0;
	
	url_f = url_r + aM[combo];
	var run = initialize();
	return 1;
}		    
function buildArea()
{
	document.getElementById("tableDiv").innerHTML = chS;
	document.forms.places.selector.value = 0;
	return 1;
}
	

