/* 
AJAX weather updater
Adapted from VWS and AJAX script by Ken True at Saratoga Weather: 
http://saratoga-weather.org/scripts-VWS-AJAX.php
Also by: 
Kevin Reed: http://www.tnetweather.com/
Pinto: http://www.joske-online.be/
CarterLake.org
*/
var flashcolor = '#009900';
var flashtime = 2000;
var ie4 = document.all;
var browser = navigator.appName;
var counterSecs = 0;
var lastajaxtimeformat = 'unknown';
function get_ajax_tags() {
	// search all the span tags and return the list with class="ajax" in it
	if (ie4 && browser != "Opera") {
		var elem = document.body.getElementsByTagName('span');
		var lookfor = 'className';
	} else {
		var elem = document.getElementsByTagName('span');
		var lookfor = 'class';
	}
	var arr = new Array();
	for(i = 0,iarr = 0; i < elem.length; i++) {
		att = elem[i].getAttribute(lookfor);
		if(att == 'ajax') {
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}
function reset_ajax_color(usecolor) {
// reset all the <span class="ajax"...> styles to have no color override
      var elements = get_ajax_tags();
	  var numelements = elements.length;
	  for (var index=0;index!=numelements;index++) {
         var element = elements[index];
	     element.style.color=usecolor;
 
      }
}
function set_ajax_obs(name, value) {
// store away the current value in both the doc and the span as lastobs="value"
// change color if value != lastobs
	var element = document.getElementById(name);
	if (! element) { return; }
	var lastobs = element.getAttribute("lastobs");
	element.setAttribute("lastobs",value);
	if (value != lastobs) {
		element.style.color=flashcolor;
	}
	element.innerHTML =  value;
}
function set_ajax_uom(name, onoroff) {
	var element = document.getElementById(name);
	if (! element ) { return; } 
	if (onoroff) {
		element.style.display='inline';
	} else {
		element.style.display='none';
	}
}
function windDir($winddir)
// Take wind direction value, return the text label based upon 16 point compass
// function by beeker425, http://www.weather-watch.com/smf/index.php/topic,20097.0.html
{
	$windlabel = new Array("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW");
	return $windlabel[Math.floor(((parseInt($winddir) + 11) / 22.5) % 16 )];
}
function ajaxLoader(url) {
	// Main AJAX function
	if (document.getElementById) {
		var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
	}
  if (x) {
  	var thedate = new Date();
	var timestamp = parseInt(thedate.getTime() / 1000);
	
    x.onreadystatechange = function() {
      if (x.readyState == 4 && x.status == 200) {
// Temp
	var temperature = parseFloat(x.responseText.split(',')[13]);
	set_ajax_obs("ajaxtemp",temperature.toFixed(1));
	
	var temprate = parseFloat(x.responseText.split(',')[33]);
	set_ajax_obs("ajaxtemprate",temprate.toFixed(1));	
// heat index and wind chill
        var heatidx = parseFloat(x.responseText.split(',')[30]);
        var windchill = parseFloat(x.responseText.split(',')[28]);
        
	if (temperature >= 60.0) {
	   tempfeel = heatidx;
	   tempfeel_title = "Heat index";
	} else {
	   tempfeel = windchill;
	   tempfeel_title = "Wind chill";
	}
	set_ajax_obs("ajaxwindindex", tempfeel.toFixed(1));
	set_ajax_obs("ajaxwindindex_title", tempfeel_title);
//Pressure
	pressure = x.responseText.split(',')[14];
	set_ajax_obs("ajaxbaro",pressure);
	pressurerate = x.responseText.split(',')[35];
	set_ajax_obs("ajaxbarotrend",ajax_set_barotrend(pressurerate));
	set_ajax_obs("ajaxbarorate",pressurerate);
//Wind gust
	gust = x.responseText.split(',')[8];
//Windspeed
	wind = x.responseText.split(',')[7];	
// Wind direction
	val = windDir(x.responseText.split(',')[9]);
	if (wind >= 0.1) {
		set_ajax_obs("ajaxwind",wind);
		set_ajax_uom("ajaxwindunits",true);
		set_ajax_obs("ajaxwinddir",val);
		set_ajax_uom("ajaxwindat", true);
	} else {
		set_ajax_obs("ajaxwind","Calm");
		set_ajax_uom("ajaxwindunits",false);
		set_ajax_obs("ajaxwinddir","");
		set_ajax_uom("ajaxwindat", false);
	}
	if (gust > 0.0) {
		set_ajax_obs("ajaxgust",gust);
		set_ajax_uom("ajaxgustuom",true);
	} else {
		set_ajax_obs("ajaxgust","None");
		set_ajax_uom("ajaxgustuom",false);
	}
// Rain
	rain = x.responseText.split(',')[16];
	set_ajax_obs("ajaxrain",rain);
	rainmo = x.responseText.split(',')[39];
	set_ajax_obs("ajaxrainmo",rainmo);
	rainyr = x.responseText.split(',')[15];
	set_ajax_obs("ajaxrainyr",rainyr);
	rainrate = parseFloat(x.responseText.split(',')[32]);
	set_ajax_obs("ajaxrainrate",rainrate.toFixed(2));
// Humidity
	humidity = x.responseText.split(',')[11];
	set_ajax_obs("ajaxhumidity",humidity);
// Dewpoint
	dewpoint = parseFloat(x.responseText.split(',')[31]);
	set_ajax_obs("ajaxdew", dewpoint.toFixed(1));

	ajaxtimeformat = ajax_format_time(x.responseText.split(',')[4], x.responseText.split(',')[5], thedate.getSeconds());
	ajaxdateformat = x.responseText.split(',')[2] + '/' + x.responseText.split(',')[3] + '/' + x.responseText.split(',')[1];
	set_ajax_obs("ajaxdatetime","<b>" + ajaxdateformat + " " +ajaxtimeformat + "</b>");
	set_ajax_obs("ajaxdate","<b>" + ajaxdateformat + "</b>");
	set_ajax_obs("ajaxtime","<b>" + ajaxtimeformat + "</b>");
	
	if (lastajaxtimeformat != ajaxtimeformat) {
		counterSecs = 0;
		lastajaxtimeformat = ajaxtimeformat;
	}
	
	element = document.getElementById("ajaxindicator");
	if (element) {
		element.style.color = flashcolor;
	}
      }
    }
	x.open("GET", url + '?' + timestamp, true);
	x.send(null);
	setTimeout("reset_ajax_color('')", flashtime);
	setTimeout("ajaxLoader('" + url + "')", 10000);
  }
}
function ajax_set_barotrend(btrnd) {
	// Barometric Trend
	if ((btrnd >= -0.02) && (btrnd <= 0.02)) { return("Steady"); }
	if ((btrnd > 0.02) && (btrnd < 0.06)) { return("Rising Slowly"); }
	if (btrnd >= 0.06) { return("Rising Rapidly"); }
	if ((btrnd < -0.02) && (btrnd > -0.06)) { return("Falling Slowly"); }
	if (btrnd <= -0.06) { return("Falling Rapidly"); }
	return(btrnd);
}
function ajax_format_time(hours,minutes,seconds) {
	// convert 24hr time to 12hr time
	var amOrPm = "am";
	if (hours > 11) amOrPm = "pm";
	if (hours > 12) hours = hours - 12;
	if (hours == 0) hours = 12;
	if (minutes <= 9) minutes = "0" + minutes;
	if (seconds <= 9) seconds = "0" + seconds;
	return(hours + ":" + minutes + ":" + seconds + amOrPm);
}
function ajax_countup() {
	element = document.getElementById("lastupdated");
	if (! element) return;
	if(counterSecs == 1)
	{
		element.innerHTML = counterSecs + ' second';
	}
	else
	{
		element.innerHTML = counterSecs + ' seconds';
	}
	counterSecs++;
}