// Special thanks to: Kevin Reed http://www.tnetweather.com/
// Kevin was the first to decode the clientraw in PHP
// Special thanks to: Pinto http://www.joske-online.be/
// Pinto wrote the basic AJAX code for this page!
// Cheerfully borrowed from Tom at CarterLake.org and adapted by
// Ken True - Saratoga-weather.org  21-May-2006
// --- added flash-green on data update functions - saratoga-weather.org  24-Nov-2006
// --- adapted for VWS use on data.csv by Ken True - saratoga-weather.org  3-Dec-2006

// -- begin settings
var flashcolor = '#00BB00'; // color to flash for changed observations
var flashtime  = 15000;    // miliseconds to keep flash color on (2000 = 2 seconds);
// -- end of settings

var timer1, timer2; //text, gfx

var ie4=document.all;
var browser = navigator.appName;

function ajaxStart(file, refreshTime) {
	if (document.getElementById("ajaxcounter")) {
		window.setInterval("ajax_countup()", 1000);
	}
	ajaxLoader(file, refreshTime);
}


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; } // V1.04 -- don't set if missing the <span id=name> tag
	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 ) {
// this function will set an ID= to visible or hidden by setting the style="display: "
// from 'inline' or 'none'
	var element = document.getElementById(name);
	if (! element ) { return; }
	if (onoroff) {
		element.style.display=''; //--fallback to default display type
	} else {
		element.style.display='none';
	}
}
// --- end of flash-green functions


// main AJAX routine .. load and format clientraw.txt
function ajaxLoader(url, refreshTime) {
	if (refreshTime == null || refreshTime < 1000) {refreshTime = 5000}

	var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);

	if (x) {
		x.onreadystatechange = function() {
		if (x.readyState == 4 && x.status == 200) {
//============================
	var data = x.responseText.split(',');
	data.unshift('');	//--add dummy so index is base 1

//Temp
	set_ajax_obs("ajaxtemp",data[8]);
	set_ajax_obs("ajaxtemprate",data[36]);

//	templast = (1.8 * x.responseText.split(' ')[90]) + 32.0;
//	document.getElementById("ajaxtemparrow").innerHTML =
//	   genarrow(temp, templast, '',
//		 'Warmer %s&deg;F than last hour.',
//		 'Colder %s&deg;F than last hour.');
//    temprate = temp - templast;
//	document.getElementById("ajaxtemprate").innerHTML = temprate.toFixed(1);
//	set_ajax_obs("ajaxtemprate",temprate.toFixed(1));

// heat index and wind-chill
	var heatidx = data[22];
	if (heatidx >= 60) {
		heatidx = heatidx;
		set_ajax_uom("ajaxheatidxuom",true);
	} else {
		heatidx = '---';
		set_ajax_uom("ajaxheatidxuom",false);
	}
	set_ajax_obs("ajaxheatidx",heatidx);

	var windchill = data[20];
	if (windchill <= 60) {
		windchill = windchill;
		set_ajax_uom("ajaxwindchilluom",true);
	} else {
		windchill = '---';
		set_ajax_uom("ajaxwindchilluom",false);
	}
	set_ajax_obs("ajaxwindchill",windchill);

// FeelsLike
//	temp = x.responseText.split(' ')[4];
//	if (temp <= 16.0 ) {
//		feelslike = x.responseText.split(' ')[44]; //use WindChill
//	} else if (temp >=27.0) {
//		feelslike = x.responseText.split(' ')[45]; //use Humidex
//	} else {
//		feelslike = x.responseText.split(' ')[4];  // use temperature
//	}
//	feelslike  = Math.round((1.8 * feelslike) + 32.0);
//	document.getElementById("ajaxfeelslike").innerHTML = feelslike.toFixed(0);
//	set_ajax_obs("ajaxfeelslike",feelslike.toFixed(0));

	//Pressure...
	pressure =data[9];
	set_ajax_obs("ajaxbaro",pressure);
	pressurerate = data[37];
	set_ajax_obs("ajaxbarotrend",ajax_set_barotrend(pressurerate));
	set_ajax_obs("ajaxbarorate",pressurerate);

	//Windspeed ...
	wind = data[3];
	beaufort = ajax_get_beaufort(wind);
	set_ajax_obs("ajaxbeaufort",beaufort);

	//Wind gust
	gust = data[4];

	//WIND DIRECTION ...
	val = data[2];
// -----


	set_ajax_obs("ajaxwind",wind);
	set_ajax_obs("ajaxgust",gust);
/*
	if (wind >= 0.1) {
		set_ajax_obs("ajaxwind",wind);
		set_ajax_uom("ajaxwinduom",true);
	} else {
		set_ajax_obs("ajaxwind","Calm");
		set_ajax_uom("ajaxwinduom",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);
	}

	if (gust > 0.0 || wind > 0.0) {
		set_ajax_obs("ajaxwindicon","<img src=./images/windicons/" + val + ".gif width=\"12\" height=\"12\" alt=\"Wind from" +
		val + "\" title=\"Wind from " + val + "\" /> ");
		set_ajax_obs("ajaxwinddir",val);
	} else {
		set_ajax_obs("ajaxwindicon","");
		set_ajax_obs("ajaxwinddir","No wind");
	}
*/

// Solar Radiation
	solar = data[19];
	set_ajax_obs("ajaxsolar",solar);

// UV Index
	uv  = data[18];
	set_ajax_obs("ajaxuv",uv) ;
	set_ajax_obs("ajaxuvword",getUVrange(uv));

//Rain
	set_ajax_obs("ajaxrain",data[10]);
	set_ajax_obs("ajaxrainmo",data[61]);
	//set_ajax_obs("ajaxrainyr",rainyr);
	set_ajax_obs("ajaxrainratehr",data[38]);

//Humidity
	set_ajax_obs("ajaxhumidity",data[6]);

//Dewpoint
	set_ajax_obs("ajaxdew",data[23]);

// DateTime
	var ajaxdatetime = data[1];
	ajaxdateformat = ajaxdatetime.split(' ')[0];
	ajaxtimeformat = ajaxdatetime.split(' ')[1];
	set_ajax_obs("ajaxdatetime","<b>" + ajaxdateformat + " " +ajaxtimeformat + "</b>");
	set_ajax_obs("ajaxdate","<b>" + ajaxdateformat + "</b>");
	set_ajax_obs("ajaxtime","<b>" + ajaxtimeformat + "</b>");

	element = document.getElementById("ajaxindicator");
	if (element) { // V1.04 set indicator if <span id="ajaxindicator" class="ajax"> exists
		element.style.color = flashcolor;
	}
	timer1=0;
}} // end update func
//======================

	x.open("GET", url, true);
	x.send(null);

	setTimeout("reset_ajax_color('')",flashtime); // change text back to default color
	var urlnew = url.split('?')[0];	// extract filename
	// get next data, append timestamp to prevent caching
	setTimeout('ajaxLoader("' + urlnew + '" + "?" + new Date(), ' + refreshTime + ')', refreshTime);
} //endif x
} // end ajaxLoader function


function getUVrange ( uv ) {
   uvword = "Unspec.";
   if (uv <= 0) {
       uvword = "None";
   }
   if (uv > 0 && uv < 3) {
       uvword = "<span style=\"border: solid 1px; background-color: #A4CE6a;\">&nbsp;Low&nbsp;</span>";
   }
   if (uv >= 3 && uv < 6) {
       uvword = "<span style=\"border: solid 1px; background-color: #FBEE09;\">&nbsp;Medium&nbsp;</span>";
   }
   if (uv >=6 && uv < 8) {
       uvword =  "<span style=\"border: solid 1px; background-color: #FD9125;\">&nbsp;High&nbsp;</span>";
   }
   if (uv >=8 && uv < 11) {
       uvword =  "<span style=\"border: solid 1px; color: #FFFFFF; background-color: #F63F37;\">&nbsp;Very&nbsp;High&nbsp;</span>";
   }
   if (uv >= 11) {
       uvword =  "<span style=\"border: solid 1px; color: #FFFF00; background-color: #807780;\">&nbsp;Extreme&nbsp;</span>";
   }
   return uvword;
} // end getUVrange function

function windDir ($winddir) {
// Take wind direction value, return the
// text label based upon 16 point compass -- function by beeker425
//  see 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 ajax_get_beaufort ( wind ) { // return a phrase for the beaufort scale based on wind MPH
  if (wind < 1 ) {return("0-Calm"); }
  if (wind < 4 ) {return("1-Light air"); }
  if (wind < 8 ) {return("2-Light breeze"); }
  if (wind < 13 ) {return("3-Gentle breeze"); }
  if (wind < 19 ) {return("4-Moderate breeze"); }
  if (wind < 25 ) {return("5-Fresh breeze"); }
  if (wind < 32 ) {return("6-Strong breeze"); }
  if (wind < 39 ) {return("7-Near gale"); }
  if (wind < 47 ) {return("8-Gale"); }
  if (wind < 55 ) {return("9-Strong gale"); }
  if (wind < 64 ) {return("10-Storm"); }
  if (wind < 75 ) {return("11-Violent storm"); }
  if (wind >= 75 ) {return("12-Hurricane"); }
  return("?-unknown" + wind);
}

function ajax_set_barotrend(btrnd) {
// routine from Anole's wxsticker PHP (adapted to JS by Ken True)
// Barometric Trend

// Change Rates
// Rapidly: =.06 inHg; 1.5 mm Hg; 2 hPa; 2 mb
// Slowly: =.02 inHg; 0.5 mm Hg; 0.7 hPa; 0.7 mb

// 5 conditions

// Page 52 of the PDF Manual
// http://www.davisnet.com/product_documents/weather/manuals/07395.234-VP2_Manual.pdf
// figure out a text value for barometric pressure 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_countup() {
 element = document.getElementById("ajaxcounter");
 if (element) {
  element.innerHTML = timer1;
  timer1++;
 }
}
function ajax_countup2() {
 element = document.getElementById("ajaxcounter2");
 if (element) {
  element.innerHTML = timer2;
  timer2++;
 }
}


