
//
// Canvas code thanks to Mark Crossley May 2010
// http://weather.wilmslowastro.com
//


//**** Change this to your desire update interval in seconds ****
var updateInterval = 10;

var objXML;						//Global XMLHttpRequest object
var cumulus = new Object();		//Will hold the realtime.txt data in a more easily read form
var count = updateInterval;		//Current countdown value
var wd_lastcurr=wd_lastavg=0;	//Hold wind directions from last realtime update
//format string for boxovers
var tds = "font-family: Verdana,Arial,Helvetica; font-size: 9px; color: #000055; "
var mod = 1000;					//Boxover display delay (millisecs)
var sector;
var winddata = [];
var httpError = 0;
var realtime_url = "http://www.wheelocknet.net/cumulus/sc_webtags.txt";


//wind spd animation
var ws_lastcurr = ws_lastavg = ws_lastgust = ws_lastmax = 0;
//wind rose animation
var ws_lastavg2 = ws_lastgust2 = 0;


// new stuff
function dowind(){
	var toadd=2.5, maxspeed=10;
if(cumulus.wgust.indexOf("Calm")>-1) cumulus.wgust=cumulus.wgust.replace("Calm","0");
	if(cumulus.wspeed.indexOf("Calm")>-1) cumulus.wspeed=cumulus.wspeed.replace("Calm","0");

	for(i=0;i<cumulus.wspddata.length-1;i++){
		if(cumulus.wspddata[i]>80){toadd=30;maxspeed=120;}
		else if(cumulus.wspddata[i]>40 && maxspeed<80){toadd=20;maxspeed=80;}
		else if(cumulus.wspddata[i]>20 && maxspeed<40){toadd=10;maxspeed=40;}
		else if(cumulus.wspddata[i]>10 && maxspeed<20){toadd=5;maxspeed=20;}
	}

	var factor=toadd/10;
	var img = document.getElementById('windrose'+maxspeed+'_img');
	var mo=[];
	var now_val;
//	mo[0]="Last:"+cumulus.wlatest+" "+cumulus.windunit+" - "+getord(parseInt(cumulus.bearing));
//	now_val="Last:"+cumulus.wlatest+" "+cumulus.windunit+" - "+getord(parseInt(cumulus.bearing));
	now_val=cumulus.wlatest+" "+cumulus.windunit+" - "+cumulus.bearing+"&deg;";
	avg_val=cumulus.wspeed+" "+cumulus.windunit+" - "+cumulus.avgbearing+"&deg";
	gust_val=cumulus.wgust+" "+cumulus.windunit;
	max_val=cumulus.wgustTM+" "+cumulus.windunit+" - "+cumulus.bearingTM+"&deg;"+" @ "+cumulus.TwgustTM;
	
//	mo[1]="Avg:"+cumulus.wspeed+" "+cumulus.windunit+" - "+getord(parseInt(cumulus.avgbearing));
//	mo[2]="Gust:"+cumulus.wgust+" "+cumulus.windunit;
//	mo[3]="Max:"+cumulus.wgustTM+" "+cumulus.windunit+" - "+getord(parseInt(cumulus.bearingTM))+" at "+cumulus.TwgustTM;

//	document.getElementById("wind").title="header=[Wind ("+cumulus.windunit+")] body=["+getmo(mo)+"] delay=["+mod+"]";
	document.getElementById("wind").hashbox=null;
	scanBO(document.getElementById("wind"));
	var canvas = document.getElementById('wind_can');
	if (canvas.getContext){   
		var ctx = canvas.getContext('2d');
		ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
		ctx.drawImage(img, 0, 0);
		ctx.lineWidth = "3";
		ctx.beginPath();
		ctx.fillStyle = "rgb(153,0,0)";
		ctx.font = "14px verdana";  //set canvas font
	//	ctx.fillText(cumulus.windunit,10,10);
		//ctx.fillStyle = "rgba(50,0,150,0.7)";
		ctx.strokeStyle = "rgba(50,0,150,0.7)";
		for(var i=0;i<cumulus.wspddata.length-1;i++){
			var hist=getpixel(110,110,maxspeed-cumulus.wspddata[i],cumulus.wdirdata[i],factor);
			//draw fat lines rather than rectangles - rectangles render to display immediately,
			//using lines means drawing to memory, then display once at the end
			ctx.moveTo(hist[0],hist[1]-1);  
			ctx.lineTo(hist[0],hist[1]+2);
		}
		ctx.stroke();
	} else {   
		// canvas-unsupported code here   
	}
	aniwind(ws_lastgust2,ws_lastavg2,factor,maxspeed);
	
	document.getElementById("NowVal").innerHTML = now_val;
	document.getElementById("AvgVal").innerHTML = avg_val;
	document.getElementById("GustVal").innerHTML = gust_val;
	document.getElementById("MaxVal").innerHTML = max_val;
	
}


function aniwind(gust,avg,factor,maxspeed){
	var repeat=false;
	var targ_gust = shortestDist(gust,parseInt(cumulus.bearing));
	var targ_avg  = shortestDist(avg,parseInt(cumulus.avgbearing));
	var step=3;
	
	if(gust != targ_gust){ // need to keep looping
		if(Math.abs(gust-targ_gust)<=step)
			gust=targ_gust;
		else
			(gust < targ_gust ? gust+=step : gust-=step);
		repeat=true;
	}
	if(avg != targ_avg){ // need to keep looping
		if(Math.abs(avg-targ_avg)<=step)
			avg=targ_avg;
		else
			(avg < targ_avg ? avg+=step : avg-=step);
		repeat=true;
	}
	if(!repeat){
		ws_lastavg2=avg;
		ws_lastgust2=gust;
		return;
	}

	var canvas = document.getElementById('wind_can2');
	if (canvas.getContext){
		var pnt,left,right,from,to;
		
		var avg = parseInt(avg);
		var wspeed = parseFloat(cumulus.wspeed);
		
		var gust = parseInt(gust);
		var wlatest = parseFloat(cumulus.wlatest);
		
		var ctx = canvas.getContext('2d');
		ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
		ctx.lineWidth = "4"; //make the arrows fatter, and semi-transparent so 'dots' show thorough
		ctx.strokeStyle = "rgba(0,153,0,0.6)";  //"rgba(0,220,0,0.6)";
		ctx.fillStyle = "rgba(0,153,0,0.6)";    "rgba(0,220,0,0.6)";

		//is there enough room for the arrow shaft?
		if ( wspeed > 9*factor ){
			from=getpixel(110,110,maxspeed,avg,factor);
			to=getpixel(110,110,maxspeed-wspeed+9*factor,avg,factor);
			ctx.beginPath();
			ctx.moveTo(from[0],from[1]);
			ctx.lineTo(to[0],to[1]);
			ctx.stroke();
		}
		
		//add pointer arrow
		pnt=getpixel(110,110,maxspeed-wspeed,avg,factor);
		left=getpixel(110,110,maxspeed-wspeed+10*factor,avg-5,factor);
		right=getpixel(110,110,maxspeed-wspeed+10*factor,avg+5,factor);
		ctx.beginPath();  
		ctx.moveTo(pnt[0],pnt[1]);  
		ctx.lineTo(left[0],left[1]);  
		ctx.lineTo(right[0],right[1]);  
		ctx.fill();

		
		ctx.strokeStyle = "rgba(220,0,0,0.6)";
		ctx.fillStyle = "rgba(220,0,0,0.6)";
		//is there enough room for the arrow shaft?
		if ( wlatest > 7*factor  ){
			from=getpixel(110,110,maxspeed,gust,factor);
			to=getpixel(110,110,maxspeed-wlatest+7*factor,gust,factor);
			ctx.beginPath();
			ctx.moveTo(from[0],from[1]);
			ctx.lineTo(to[0],to[1]);
			ctx.stroke();
		}
		//add pointer arrow
		pnt=getpixel(110,110,maxspeed-wlatest,gust,factor);
		left=getpixel(110,110,maxspeed-wlatest+8*factor,gust-5,factor);
		right=getpixel(110,110,maxspeed-wlatest+8*factor,gust+5,factor);
		ctx.beginPath();  
		ctx.moveTo(pnt[0],pnt[1]);  
		ctx.lineTo(left[0],left[1]);  
		ctx.lineTo(right[0],right[1]);  
		ctx.fill();

		window.setTimeout("aniwind("+gust+","+avg+","+factor+","+maxspeed+");", 50);
	
	} else {   
		// canvas-unsupported code here   
	}

}

function getord(d){
	//convert to range 0-360
	if(d>=360) d-=360;
	var deg = Math.ceil((d+11.25)/22.5);
	ords = ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
	return(ords[deg-1]);
}
function dowindspd(){
	var mo=[];
	// default to 20 range scale
	var offset = 10;
	var scale = 13.5;

	if(parseFloat(cumulus.wgustTM)>80){ //use 0-120
		offset = 60;
		scale = 2.25;
	}else if (parseFloat(cumulus.wgustTM)>40){ //use 0-80
		offset = 40;
		scale = 3.375;
	}else if (parseFloat(cumulus.wgustTM)>20){ // use 0-40
		offset = 20;
		scale = 6.75;
	}

	mo[0]="Now: "+cumulus.wlatest+" "+cumulus.windunit;
	mo[1]="Gust: "+cumulus.wgust+" "+cumulus.windunit;
	mo[2]="Average: "+cumulus.wspeed+" "+cumulus.windunit;
	mo[3]="Max gust: "+cumulus.wgustTM+" "+cumulus.windunit+", "+getord(+cumulus.bearingTM)+" at "+cumulus.TwgustTM;
	
	aniwindspd(ws_lastcurr,ws_lastavg,ws_lastgust,ws_lastmax,offset,scale);
	
	document.getElementById("windspd").title="header=[Wind Speed ("+cumulus.windunit+")] body=["+getmo(mo)+"] delay=["+mod+"]";
	document.getElementById("windspd").hasbox=null;
	scanBO(document.getElementById("windspd"));
}

function aniwindspd(curr,avg,gust,max,offset,scale) {
	
	var canvas = document.getElementById('windspd_can');
	if (canvas.getContext){   
		var ctx = canvas.getContext('2d');

		var repeat=false;
		var targ_curr = parseFloat(cumulus.wlatest);
		var targ_avg  = parseFloat(cumulus.wspeed);
		var targ_gust = parseFloat(cumulus.wgust);
		var targ_max  = parseFloat(cumulus.wgustTM);
		var step=offset/30;
		if(curr != targ_curr){ // need to keep looping
			if(Math.abs(curr-targ_curr)<=step)
				curr=targ_curr;
			else
				(curr < targ_curr ? curr+=step : curr-=step);
			repeat=true;
		}
		if(avg != targ_avg){ // need to keep looping
			if(Math.abs(avg-targ_avg)<step)
				avg=targ_avg;
			else
				(avg < targ_avg ? avg+=step : avg-=step);
			repeat=true;
		}
		if(gust != targ_gust){ // need to keep looping
			if(Math.abs(gust-targ_gust)<step)
				gust=targ_gust;
			else
				(gust < targ_gust ? gust+=step : gust-=step);
			repeat=true;
		}
		if(max != targ_max){ // need to keep looping
			if(Math.abs(max-targ_max)<step)
				max=targ_max;
			else
				(max < targ_max ? max+=step : max-=step);
			repeat=true;
		}

		var val_gust,val_avg,val_now,val_max,val_now;
		//array data = [0-gust, 1-bearing, 2-avg, 3-bearing, 4-latest, 5-maxGust, 6-maxGust_string]

		val_now=scale*(curr-offset);
		
		val_gust=scale*(gust-offset);

		val_avg=scale*(avg-offset);

		val_max=scale*(max-offset);
		
		var img = document.getElementById("windspd"+(offset*2)+"_img");

		ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
		ctx.drawImage(img, 0, 0);
		ctx.font = "12 verdana";  //set canvas font
		ctx.textAlign = "center";
		ctx.lineWidth = "2";
		ctx.beginPath();
		var to=getpixel(110,110,65,val_gust,2);
		ctx.strokeStyle = "rgba(0,0,153,0.7)";
		ctx.moveTo(110,110);
		ctx.lineTo(to[0],to[1]); //draw gust needle
		ctx.fillStyle = "rgb(0,0,153)";
	//	ctx.fillText("Gust: "+cumulus.wgust+" "+cumulus.windunit,110,180);
		ctx.stroke();
		ctx.beginPath();
		to=getpixel(110,110,65,val_avg,2);
		ctx.strokeStyle = "rgba(0,153,0,0.7)";
		ctx.moveTo(110,110);
		ctx.lineTo(to[0],to[1]); //draw avg needle
		ctx.fillStyle = "rgb(0,153,0)";
	//	ctx.fillText("Average: "+cumulus.wspeed+" "+cumulus.windunit,110,192);
		ctx.stroke();
		ctx.beginPath();
		to=getpixel(110,110,65,val_max,2);
		ctx.strokeStyle = "rgba(255,0,255,0.7)";
		ctx.moveTo(110,110);
		ctx.lineTo(to[0],to[1]); //draw max gust needle
		ctx.fillStyle = "rgb(255,0,255)";
	//	ctx.fillText("Max today: "+cumulus.wgustTM+" "+cumulus.windunit,110,204);
		ctx.stroke();
		ctx.beginPath();
		to=getpixel(110,110,90,val_now,2);
		ctx.strokeStyle = "rgba(255,0,0,0.7)";  //"rgba(153,0,0,0.7)";
		ctx.moveTo(110,110);
		ctx.lineTo(to[0],to[1]); //draw now needle
		ctx.fillStyle = "rgb(255,0,0)";  //"rgba(153,0,0,0.7)";
	//	ctx.fillText("Now: "+cumulus.wlatest+" "+cumulus.windunit,110,168);
		ctx.stroke();
		ctx.beginPath();
		ctx.arc(110,110,7,0,Math.PI*2,true); //needle ring
		ctx.stroke();
		ctx.beginPath();
		ctx.strokeStyle = "rgb(153,153,153)";
		ctx.fillStyle = "rgb(153,153,153)";
		ctx.arc(110,110,5,0,Math.PI*2,true); //filled centre
		ctx.fill();
		ctx.stroke();

		if(!repeat){
			ws_lastcurr=curr;
			ws_lastavg=avg;
			ws_lastgust=gust;
			ws_lastmax=max;
		} else {
			window.setTimeout("aniwindspd("+curr+","+avg+","+gust+","+max+","+offset+","+scale+");", 50);
		}

		
	} else {   
		// canvas-unsupported code here   
	}
}


//Wind direction main function
function doWindDir(){	
	//set the boxover display text array
	var mo=[];
	mo[0]="Last: "+cumulus.wlatest+" "+cumulus.windunit+" - "+getord(parseInt(cumulus.bearing));
	mo[1]="Avg 10m: "+cumulus.wspeed+" "+cumulus.windunit+" - "+getord(parseInt(cumulus.avgbearing));
	mo[2]="Max gust: "+cumulus.wgustTM+" "+cumulus.windunit+" at "+cumulus.TwgustTM;

	//set the boxover, by putting params into winddir.title
	document.getElementById("winddir").title="header=[Wind ("+cumulus.windunit+")] body=["+getmo(mo)+"] delay=["+mod+"]";
	//if boxover has already parsed this <div>, then remove it's flag
	document.getElementById("winddir").hashbox=null;
	//force boxover to reparse the <div>
	scanBO(document.getElementById("winddir"));
	
	//now call the animation function to draw the gauage
	aniWindDir(wd_lastcurr,wd_lastavg);
}

//Animation function for the wind direction
function aniWindDir(curr, avg){
	var repeat = false;		//do we need to repeat the animation?
	//convert the current readings into target values, to avoid going the
	//long way round the circle
	var targ_curr = shortestDist(curr,parseInt(cumulus.bearing));
	var targ_avg  = shortestDist(avg,parseInt(cumulus.avgbearing));
	var step;
	
	if (curr != targ_curr){ //not there yet, need to keep looping
		(Math.abs(curr-targ_curr)>10 ? step=3 : step=1); //big steps if far away
		(curr < targ_curr ? curr+=step : curr-=step);
		repeat=true;
	}
	if (avg != targ_avg){ //not there yet, need to keep looping
		(Math.abs(avg-targ_avg)>10 ? step=3 : step=1);
		(avg < targ_avg ? avg+=step : avg-=step);
		repeat=true;
	}
	if (!repeat){ //we are done, save current values as last vals, then exit
		wd_lastcurr = curr;
		wd_lastavg = avg;
		return;
	}

	//get a reference to the hidden compass image
	var img = document.getElementById('compass_img');

	//Draw on the canvas
	var canvas = document.getElementById('winddir_can');
	if (canvas.getContext){   
		var ctx = canvas.getContext('2d');
		ctx.clearRect(0, 0, canvas.width, canvas.height); 	//clear the canvas
		ctx.font = "16pt verdana";  							//set canvas font
		// ctx.drawImage(img,0,0);								//background image

		//draw the Average wind direction
		ctx.strokeStyle = "rgba(0,153,0,1)";				//line colour, 100% opacity for avg arrow    "rgba(0,0,255,1)";
		ctx.fillStyle = "rgba(0,153,0,1)";					//fill colour, 100% opacity	for avg arrow    "rgba(0,0,255,1)";
		//draw arrow head	
		var pnt = getpixel(224,250,120,avg,2);				//get inner point of avg arrow (Blue)
		var left = getpixel(224,250,145,avg-3,2);			//shift round -12 degrees and out 25 pixels to find left triangle point
		var right = getpixel(224,250,145,avg+3,2);			//shift round +12 degrees and out 25 pixels to find right triangle point
		ctx.lineWidth = "1";								//narrow lines for arrow head
		ctx.beginPath();									//start a new path
		ctx.moveTo(pnt[0],pnt[1]);							//move to point of arrow
		ctx.lineTo(left[0],left[1]);						//draw to left corner
		ctx.lineTo(right[0],right[1]);						//draw to right corner
		ctx.lineTo(pnt[0],pnt[1]);							//draw back to point
		ctx.fill();											//shade the pointer
		//draw arrow shaft
		var to = getpixel(224,250,140,avg,2);				//get outer end of avg arrow shaft
		var from = getpixel(224,250,226,avg,2);				//get inner end of avg arrow shaft
		ctx.lineWidth = "4";								//arrow shaft width
		ctx.beginPath();									//start a new canvas path
		ctx.moveTo(from[0],from[1]);						//move to beginning of shaft
		ctx.lineTo(to[0],to[1]);							//draw to end of shaft
		ctx.stroke();										//write to the canvas
	//	ctx.textAlign = "left";
	//	ctx.fillText("Avg: "+cumulus.avgbearing+" deg.",0,470);	//add some text
		
		//draw the Gust wind direction
		ctx.lineWidth = "8";								//arrow shaft width (Red)
		ctx.strokeStyle = "rgba(255,0,0,0.7)";				//line colour, 70% opacity
		ctx.fillStyle = "rgba(255,0,0,0.7)";				//fill colour, 70% opacity
		//draw arrow head	
		pnt = getpixel(224,250,140,curr,2);					//get inner point of avg arrow
		left = getpixel(224,250,162,curr-3,2);				//shift round -12 degrees and out 25 pixels to find left triangle point
		right = getpixel(224,250,162,curr+3,2);				//shift round +12 degrees and out 25 pixels to find right triangle point
		ctx.lineWidth = "1";								//narrow lines for arrow head
		ctx.beginPath();									//start a new path
		ctx.moveTo(pnt[0],pnt[1]);							//move to point of arrow
		ctx.lineTo(left[0],left[1]);						//draw to left corner
		ctx.lineTo(right[0],right[1]);						//draw to right corner
		ctx.lineTo(pnt[0],pnt[1]);							//draw back to point
		ctx.fill();											//shade the pointer
		//draw arrow shaft
		to = getpixel(224,250,160,curr,2);					//get outer end of avg arrow shaft
		from = getpixel(224,250,226,curr,2);					//get inner end of avg arrow shaft
		ctx.lineWidth = "4";								//arrow shaft width
		ctx.beginPath();									//start a new canvas path
		ctx.moveTo(from[0],from[1]);						//move to beginning of shaft
		ctx.lineTo(to[0],to[1]);							//draw to end of shaft
		ctx.stroke();										//write to the canvas
	//	ctx.textAlign = "right";
		//ctx.fillText("Last: "+cumulus.bearing+" deg.",480,470);	//add some text
		
		//do all this again in 50 millisecs
		window.setTimeout("aniWindDir("+curr+","+avg+");", 50);
	
	} else {   
		// canvas-unsupported code here   
	}
	
}


//Set the error message
function setError(str){
	document.getElementById("error").innerHTML = str;
}

//Set the status message
function setStatus(str){
	document.getElementById("status").innerHTML = str;
}


//Loops through all the <spans> on a webpage and if their
//id matches a Cumulus webtage name, set their value
function updateSpans(){
	//get all the spans on the page
	var spans = document.getElementsByTagName("span");
	//loop through the spans to update them
	for(var i=0; i<spans.length; i++){
		var id = spans[i].id;
		if(id.length){									//does the <span> have an id?
			eval("var val=cumulus."+id+";");			//get the cumulus value
			if(val != null) spans[i].innerHTML = val;	//if it exists in cumulus object set the value
		}
	}
	}



//Provide a countdown on the webpage between updates
// new from astro
function countDown(){
	cumulus.sensorcontactlost = 0;
	count--;
	if(count==0){
	
		getRealtime();
		//setTimeout("getRealtime()",2000);
		count=10;
	}else{
		setTimeout("countDown()",1000);
		if(httpError==0){
			if(cumulus.sensorcontactlost==0)
			
					
				if(lang_opt=="gb"){
					setStatus("Next Update in "+count+" secs");
				}
				else if(lang_opt=="fr"){
					setStatus("Prochaine mise &agrave; jour dans "+count+" secondes");
				}
				
				else if(lang_opt=="nl"){
					setStatus("Volgende update in "+count+" seconden");
				}
				
				else if(lang_opt=="de"){
					setStatus("N&auml;chstes Update in "+count+" Sekunden");
				}
				else if(lang_opt=="ct"){
					setStatus("Propera actualitzaci&oacute; de "+count+" segons");
				}
				else {
					setStatus("Pr&oacute;xima actualizaci&oacute;n de "+count+" segundos");
				}
				
				
			//	else{
				
			//	setStatus(" "+count+" secs");
	//	}
			else
				setError("Remote sensor contact lost!, next update in "+count+" secs");
				
		}else{
			setError("HTTP request failed, error:"+httpError+" Retry:"+count+"s");
		}
	}
}


//convert a 0-360 bearing into compass direction
function getord(d){
	//convert to range 0-360
	while(d>=360) d -= 360;
	while(d<0) d += 360;
	var deg = Math.ceil((d+11.25)/22.5);
	ords = ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
	return(ords[deg-1]);
}

// Set start/end of yaw move to shortest distance
// Avoids rotating round the 'long' way
function shortestDist(oldAngle, newAngle){
	var distanceNormal = Math.abs(oldAngle - newAngle);
	var distanceForward = Math.abs(oldAngle - (newAngle + 360));
	var distanceBackward = Math.abs(oldAngle - (newAngle - 360));
	if (Math.min(distanceNormal, Math.min(distanceForward, distanceBackward)) == distanceForward) {
		newAngle += 360;
	} else if (Math.min(distanceNormal, Math.min(distanceForward, distanceBackward)) == distanceBackward) {
		newAngle -= 360;
	} else {
		// use current newAngle
	}
	return newAngle;
}

// Format boxover information table
function getmo(mot){ 
	var st = '';
	st += '<table cellpadding=3 cellspacing=0 border=0 style=\"'+tds+'\">';
	for (var j=0;j<mot.length;j++){
		st += '<tr>\n<td align=right style=\"'+tds+'">';
		st += mot[j].substring(0,mot[j].indexOf(":")+1);
		st += '</td>\n<td align=left style=\"'+tds+'\">';
		st += mot[j].substring(mot[j].indexOf(":")+1);
		st += '</td>\n</tr>\n';
	}
	st += '</table>\n';
	return st;
}

// Helper function to find the x,y pixel corresponding to
// a rotation angle
function getpixel(midx,midy,speed,degrees,factor){
	var ret=[];
	var x=midx;
	var y=midy;
	var dia=(parseFloat(speed)/factor)*2;
	var point=parseInt(degrees);
	var angle=((90-point)*(2*Math.PI))/360;
	var xx=parseInt(Math.round(Math.cos(angle)*dia));
	ret[0]=x+xx;
	var yy=parseInt(Math.round(Math.sin(angle)*dia));
	ret[1]=y-yy;
	return(ret);
}

// ---- Wheelos Catalan wind names ----------------------------------


function calc_cat_wind(){  
 
// var wind_k_ave = cumulus.wspeed;
// val_org_ave= cumulus.avgbearing;


 if(val_org_ave >= 0 && val_org_ave <= 29) { // Sector 1 - Provences
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Provences" ;
		sector = "1a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Provenccotes" ;
		sector = "1b";
		}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Provences" ;
		sector = "1c"
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Provencada" ;
		sector = "1d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Provences" ;
		sector = "1e";
	}
 } // END sector 1


if(val_org_ave >= 30 && val_org_ave <= 64) { // Sector 2 - Gregal
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Gregal" ;
		sector = "2a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Gregalet" ;
		sector = "2b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Gregal" ;
		sector = "2c";
		}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Gregalada" ;
		sector = "2d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Gregal" ;
		sector = "2e";
		}
 } // END sector 2


if(val_org_ave >= 65 && val_org_ave <= 99) { // Sector 3 - Llevant
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Ventet de Bon Temps" ;
		sector = "3a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Ventot de Llevant" ;
		sector = "3b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Llevant" ;
		sector = "3c";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Llevantada" ;
		sector = "3d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Llevant" ;
		sector = "3e";
	}
 } // END sector 3


if(val_org_ave >= 100 && val_org_ave <= 144) { // Sector  4 - Xaloc
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Foranell" ;
		sector = "4a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Xaloquet" ;
		sector = "4b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Xaloc" ;
		sector = "4c";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Xalocada" ;
		sector = "4d"
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Xaloc" ;
		sector = "4e";
		}
 } // END sector 4


if(val_org_ave >= 145 && val_org_ave <= 167) { // Sector 5A - Garbi
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector ="0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Garbi" ;
		sector = "5a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Garbinet Llarg" ;
		sector = "5b1";
		}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Garbi Llarg" ;
		sector = "5c1";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Garbinada" ;
		sector = "5d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Garbi" ;
		sector = "5e";
	}
 } // END sector 5A


if(val_org_ave >= 168 && val_org_ave <= 191) { // Sector 5B - Garbi
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Garbi" ;
		sector = "5a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Ventot de Garbi Rodo" ;
		sector = "5b2";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Garbi Rodo" ;
		sector = "5c2";
		}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Garbinada" ;
		sector = "5d";
		}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Garbi" ;
		sector = "5e";
	}
 } // END sector 5B


if(val_org_ave >= 192 && val_org_ave <= 214) { // Sector 5c - Garbi
    if(wind_k_ave== 0) {

		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Garbi" ;
		sector = "5a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Ventot de Garbi Terrer" ;
		sector = "5b3";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Garbi Terrer" ;
		sector = "5c3";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Garbinada" ;
		sector = "5d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Garbi" ;
		sector = "5e";
	}
 } // END sector 5c


if(val_org_ave >= 215 && val_org_ave <= 249) { // Sector 6 - Llebeig
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Oratge Terral" ;
		sector = "6a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Ventot de Llebeig" ;
		sector = "6b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Llebeig" ;
		sector = "6c";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Llebetjada" ;
		sector = "6d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Llebig" ;
		sector = "6e";
	}
 } // END sector 6


if(val_org_ave >= 250 && val_org_ave <= 294) { // Sector 7 - Ponent
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Oratge Terral" ;
		sector = "6a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Ponentot" ;
		sector = "7b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Ponent" ;
		sector = "7c";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Ponentada" ;
		sector = "7d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Ponent" ;
		sector = "7e";
	}
 } // END sector 7


if(val_org_ave >= 295 && val_org_ave <= 329) { // Sector 8 - Mestral
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Mestral" ;
		sector = "8a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Mestralo" ;
		sector = "8b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Mestral" ;
		sector = "8c";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Mestralada" ;
		sector = "8d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Mestral" ;
		sector = "8e";
	}
 } // END sector 8


if(val_org_ave >= 320 && val_org_ave <= 360) { // Sector 9 - Mestral
    if(wind_k_ave== 0) {
		cat_wind = "Bafa perduda" ;
		sector = "0";
	}
	if(wind_k_ave > 0 && wind_k_ave < 8) {
		cat_wind = "Aire de Tramuntana" ;
		sector = "9a";
	}
    if(wind_k_ave > 8 && wind_k_ave < 16) {
		cat_wind = "Tramuntaneta" ;
		sector = "9b";
	}
    if(wind_k_ave >= 16 && wind_k_ave < 31) {
		cat_wind = "Tramutana" ;
		sector = "9c";
	}
    if(wind_k_ave >= 31 && wind_k_ave < 61) {
		cat_wind = "Tramuntanada" ;
		sector = "9d";
	}
    if(wind_k_ave >= 61) {
		cat_wind = "Gropada de vent de Tramuntana" ;
		sector = "9e";
	}
 } // END sector 9
 
 // Start Sectors
//setError("Calc_wind");
  document.getElementById("Catalan_Wind_Sector").innerHTML = "<img src=\"http://www.wheelocknet.net/betel/EXTRAS/Rosa_vents_" + sector + ".gif\">"; 

document.getElementById("Catalan_Wind").innerHTML = cat_wind; 



 return;

}
	
	
// Fetches the realtime.txt file from your website
// Set your URL in the variable at the top of this script
function getRealtime(){
	//Tell the user what we are doing
	setError("Downloading...");
if (objXML==null){						//If we haven't already created an XMLHttpRequest, do it now
		if (window.XMLHttpRequest){     	//Object of the current window, just check it is supported
			objXML = new XMLHttpRequest();	//Firefox, Safari, IE7,8...
		} else if (window.ActiveXObject){   //ActiveX version - Internet Explorer 5,6
			 try {
				objXML = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					objXML = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (E) {
						objXML = false;		//Give up! Can't create an XMLHttpRequest :(
						setError("Failed to create XMLHttp object");
					}
			}
		}
		//Set the function to be called when we get a response from the website
		if (objXML) objXML.onreadystatechange = checkRtResp;
	}
	if (objXML) { //Creation of XMLHttpRequest was OK
		// append a random number to the URL to defeat the local browser cache
		//objXML.open('GET', realtime_url+'?'+Math.random(), true);     
		 objXML.open('GET', realtime_url+ '?' + new Date().getTime(),true);  
		// ajaxLoader(currdatFile + '?' + new Date().getTime());            
		objXML.send(null); 
	//	objXML.overrideMimeType('text/xml');

	//	objXML.xmlHttp.overrideMimeType('text/xml');// Go get it
		//	var currdat = x.responseText.replace(/\r\n/g, "");	// this gets rid of any line ending
	}
}

//Called whenever we get a response from the website
function checkRtResp(){
	
	if (objXML.readyState  == 4){
		if (objXML.status  == 200){
			setError("Line 973");
		//	setTimeout("parseRealtime()",200);
		try {
			parseRealtime();
		}
			catch(e2){
				setTimeout("parseRealtime()",500);
					setStatus("parseRealtime again");
				}
					//Stuff the data into the cumulus object
		//	setTimeout("doUpdate()",500);
		try {
			doUpdate();
			}
			catch(e5){
				setTimeout("doUpdate()",500);
					setError("doUpdate");
				}
		//	cat_wind();				//update the webpage
		} else if (objXML.status > 200){
			setError("HTTP request failed, error: "+objXML.status);
		}
	}
}

//Take the realtime.txt file, which is a space separated list of variables
//and store the data in the global cumulus object for use elsewhere
function parseRealtime(){
//	setStatus("Line 988");
	//var realtime = x.responseText.replace(/\r\n/g, "");	// this gets rid of any line ending
	//Split the realtime.txt file on spaces and store ina an array
	//var realtime = x.responseText.replace(/\r\n/g, "");	// this gets rid of any line ending
	
	var realtime = objXML.responseText.split(" ");
		
	//We will make the cumulus object property names the same as the Cumulus
	//webtag names - keeps things consistent
	try {
		
		cumulus.date = realtime[0];
		cumulus.time = realtime[1]; //actually #hour:#minute
		cumulus.temp = realtime[2];
		cumulus.hum = realtime[3];
		cumulus.dew = realtime[4];
		cumulus.wspeed = realtime[5];//*0.621371).toFixed(1);//*0.621371.toFixed(0);
		cumulus.wlatest = realtime[6];
		cumulus.bearing = realtime[7];
		cumulus.rrate = realtime[8];
		cumulus.rfall = realtime[9];
		cumulus.press = realtime[10];
		cumulus.currentwdir = realtime[11];
		cumulus.beaufort = realtime[12];
		cumulus.windunit = realtime[13];
		cumulus.tempunit = realtime[14].replace("&deg;","°");
		cumulus.pressunit = realtime[15];
		cumulus.rainunit = realtime[16];
		cumulus.windrun = realtime[17];
		cumulus.presstrendval = realtime[18];
		cumulus.rmonth = realtime[19];
		cumulus.ryear = realtime[20];
		cumulus.rfallY = realtime[21];
		cumulus.intemp = realtime[22];
		cumulus.inhum = realtime[23];
		cumulus.wchill = realtime[24];
		cumulus.temptrend = realtime[25];
		cumulus.tempTH = realtime[26];
		cumulus.tTempTH = realtime[27];
		cumulus.tempTL = realtime[28];
		cumulus.TtempTL = realtime[29];
		cumulus.windTM = realtime[30];
		cumulus.TwindTM = realtime[31];
		cumulus.wgustTM = realtime[32];
		cumulus.TwgustTM = realtime[33];
		cumulus.pressTH = realtime[34];
		cumulus.pressTL =realtime[35];
		cumulus.TpressTL - realtime[36];
		cumulus.version = realtime[37];
		cumulus.build = realtime[38];
		cumulus.wgust = realtime[39];//*0.621371).toFixed(1);
		cumulus.heatindex = realtime[40];
		cumulus.humidex = realtime[41];
		cumulus.UV = realtime[42];
		cumulus.ET = realtime[43];
		cumulus.SolarRad = realtime[44];
		cumulus.avgbearing = realtime[45];
		cumulus.rhour = realtime[46];
		cumulus.forecastnumber = realtime[47];
		cumulus.isdaylight = realtime[48];
		cumulus.SensorContactLost = realtime[49];
		cumulus.wdir = realtime[50];				//new 1.9.0
		cumulus.cloudbase = realtime[51];			//new 1.9.0, note: normal #cloudbase tag = 'cloudbase cloudbasunit'
		cumulus.cloudbaseunit = realtime[52];
		cumulus.xxx = realtime[53];
        cumulus.wdirdata = realtime[54];		
		cumulus.wspddata = realtime[55]//*0.621371).toFixed(1);			
		cumulus.bearingTM = realtime[56];
		cumulus.bearingYM = realtime[57];
		cumulus.windrununit = realtime[58];
		cumulus.hour = realtime[59];
		cumulus.minute = realtime[60];
	//	setStatus("Line 1058");
	//	var wind_k_ave = cumulus.wspeed;
// val_org_ave= cumulus.avgbearing;
		
	} catch(e) 
		{
			setTimeout("parseRealtime()",1000);
			}
	//setStatus("Line 1063");
}



//Update the webpage
function doUpdate(){
//	cumulus.wdirdata = new Array();
//	cumulus.wspddata = new Array();
	try{
//	cumulus.wdirdata = cumulus.wdirdata.split(",",350);
	cumulus.wdirdata = cumulus.wdirdata.split(",");
	} catch(e1){
//	setTimeout("cumulus.wdirdata = cumulus.wdirdata.split(",",350)",500);
	setTimeout("cumulus.wdirdata = cumulus.wdirdata.split(",")",500);
		setError("not 100 wdirdata");
	}
	
	try{			
//	cumulus.wspddata = cumulus.wspddata.split(",",350)//.toFixed(1);
	cumulus.wspddata = cumulus.wspddata.split(",")//.toFixed(1);
		} catch(e1){
//	setTimeout("cumulus.wspddata = cumulus.wspddata.split(",",350)",500);
	setTimeout("cumulus.wspddata = cumulus.wspddata.split(",")",500);
		setError("not 100 wspddata # 2");
		}
	
	wind_k_ave = cumulus.wspeed;
	  val_org_ave= cumulus.avgbearing;	
	setError("Updating...");
	//update the variable text
	
	try{
	updateSpans();
	} catch(e3)
		{
		setTimeout("updateSpans()",500);
		}
//		setError("Line 1104");
	//update wind direction gauge
	try{
	doWindDir();
	}catch(e4)
		{
		setTimeout("dowindDir()",500);	
		}
	//	setError("Line 1112");
	//calls to updates of other gauges woud go here
	 //   	document.getElementById("Catalan_Wind_Sector").innerHTML = "<img src=\"http://www.wheelocknet.net/betel/EXTRAS/Rosa_vents_" + sector + ".gif\">"; 
	 
	 setTimeout("dowindspd()",500);
//	 setError("Line 1117");
	// if(document.getElementById("windspd")) dowindspd();
	setTimeout("dowind()",500);
	//if(document.getElementById("wind")) dowind();
//	setError("Line 1121");
	//start coundown timer
	
	calc_cat_wind();
	countDown();
}

var objXML;


