// Contributors to this code:
// -- Kevin Reed (http://www.tnetweather.com) who was first to decode clientraw.txt in PHP
// -- Pinto (http://www.joske-online.be) who wrote the basic AJAX code for this page
// -- Ken True (Saratoga-Weather.org) for the AJAX flash code
// -- Sam Neely who cleaned up the functions
// -- Bruce Keever (KirklandWeather.com) who made further modiciations
//
// IMPORTANT NOTE: You must comment out any document.getElementById line that is referenced
// here in the script, but NOT used in the body. Failure to do so will break the page.


// This section will flash updated AJAX fields with 
// a color of your choice for the specified duration.

var flashcolor = '#000000'; // color to flash for changed observations
var flashtime = '1000'; // miliseconds to keep flash color on (1000 = 1 second);

var ie4=document.all;
var browser = navigator.appName;

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
  element = document.getElementById(name);
  if (! element) { return; } // don't store if no <span> tag found for this id= 
  lastobs = element.getAttribute("lastobs");
  element.setAttribute("lastobs",value);
  if (value != lastobs) {
    element.style.color=flashcolor;
  }
  element.innerHTML = value;
}
// END AJAX flash section

function convertCtoF(celcius)
// Take temperature value in Metric (Celcius)
// and convert to Fahrenheit
{
	return (1.8 * celcius) + 32.0;
}

function windDir ($winddir)
// Take wind direction value, return the
// text label based upon 16 point compass
{
	$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) {
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  }


  if (x) {
    x.open("GET", url, true);
    x.onreadystatechange = function() {
      if (x.readyState == 4 && x.status == 200) {
//alert(x.responseText)


	//TEMPERATURE
	temp = convertCtoF(x.responseText.split(' ')[4]);

	//Provide temperature with no decimal place
//	document.getElementById("ajaxtempnodp").innerHTML = temp.toFixed(0) + "&deg";

	//Provide temperature with one decimal place for header
//	set_ajax_obs("ajaxtempheader",temp.toFixed(1) + "&deg;F");	

	//Provide temperature with one decimal place for body
	set_ajax_obs("ajaxtemp",temp.toFixed(1) + "&deg;");

	//Provide temperature trend
	temptrend = convertCtoF(x.responseText.split(' ')[4]) - convertCtoF(x.responseText.split(' ')[90]);
	if (temptrend > 0) {
		temptrend = "+" + temptrend.toFixed(1);
		document.getElementById("ajaxtemptrendgraphic").innerHTML = '&nbsp;<img src="images/greenup.gif" height="15" width="15" alt="Temperature Rising" title="Temperature Rising" />';
	} else if (temptrend < 0) {
		temptrend = temptrend.toFixed(1);
		document.getElementById("ajaxtemptrendgraphic").innerHTML = '&nbsp;<img src="images/reddown.gif" height="15" width="15" alt="Temperature Falling" title="Temperature Falling" />';
	} else {
		temptrend = "+" + temptrend.toFixed(1);
		document.getElementById("ajaxtemptrendgraphic").innerHTML = '';
	}
//	set_ajax_obs("ajaxtemptrend",temptrend + " &deg;F /hr");

	//Provide teperature high/low for day
	tempdayhigh = convertCtoF(x.responseText.split(' ')[46]);
	document.getElementById("ajaxtempdayhigh").innerHTML =  tempdayhigh.toFixed(0) + "&deg";

	tempdaylow = convertCtoF(x.responseText.split(' ')[47]);
	document.getElementById("ajaxtempdaylow").innerHTML =  tempdaylow.toFixed(0) + "&deg";
		
	

	// HUMIDITY ...
	// Provide Humidity
	set_ajax_obs("ajaxhum",x.responseText.split(' ')[5] + "%");

	// Provide humidity trend
	humtrend = x.responseText.split(' ')[144];
	if (humtrend > 0) {
		document.getElementById("ajaxhumtrendgraphic").innerHTML = '&nbsp;<img src="images/greenup.gif" height="15" width="15" alt="Humidity Rising" title="Humidity Rising" />';
	} else if (temptrend < 0) {
		document.getElementById("ajaxhumtrendgraphic").innerHTML = '&nbsp;<img src="images/reddown.gif" height="15" width="15" alt="Humidity Falling" title="Humidity Falling" />';
	} else {
		document.getElementById("ajaxhumtrendgraphic").innerHTML = '';
	}
//	set_ajax_obs("ajaxhumtrend",humtrend + "% /hr");


	//BAROMETER ...
	press = x.responseText.split(' ')[6] / 33.86388158;
	set_ajax_obs("ajaxbaro",press.toFixed(2));

	presstrend = x.responseText.split(' ')[50] / 33.86388158;
	if (presstrend > 0) {
		presstrend = "+" + presstrend.toFixed(3);
		document.getElementById("ajaxpresstrendgraphic").innerHTML = '&nbsp;<img src="images/greenup.gif" height="15" width="15" alt="Pressure Rising" title="Pressure Rising" />';
	} else if (presstrend < 0) {
		presstrend = presstrend.toFixed(3);
		document.getElementById("ajaxpresstrendgraphic").innerHTML = '&nbsp;<img src="images/reddown.gif" height="15" width="15" alt="Pressure Falling" title="Pressure Falling" />';
	} else {
		presstrend = "+" + presstrend.toFixed(3);
		document.getElementById("ajaxpresstrendgraphic").innerHTML = '';
	}
//	document.getElementById("ajaxpresstrend").innerHTML = presstrend + " in. /hr";


	//WINDSPEED ...
	wind = x.responseText.split(' ')[2]* 1.1507794;
	set_ajax_obs("ajaxwind",wind.toFixed(1) + " mph");

	gusthour = x.responseText.split(' ')[133]* 1.1507794;
	set_ajax_obs("ajaxgusthour",gusthour.toFixed(1) + " mph at ");

	gusthourtime = x.responseText.split(' ')[134];
	gusthourtime = gusthourtime.replace( "_" , " ");
	set_ajax_obs("ajaxgusthourtime",gusthourtime.toLowerCase());

	gusttoday = x.responseText.split(' ')[71]* 1.1507794;
	set_ajax_obs("ajaxgusttoday",gusttoday.toFixed(1) + " mph at ");

	gustdaytime = x.responseText.split(' ')[135];
	gustdaytime = gustdaytime.replace( "_" , " ");
	set_ajax_obs("ajaxgusttodaytime",gustdaytime.toLowerCase());
						

	//WIND DIRECTION ...
	// Direction arrow .gifs available at http://carterlake.org/weatherphp.php

	val = windDir(x.responseText.split(' ')[3]);

	set_ajax_obs("ajaxwinddir","&nbsp;" + val);
	document.getElementById("ajaxwindicon").innerHTML = '&nbsp;<img src="images/winddir/' + val + '.gif" width="14" height="14" alt="Wind from ' + val + '" title="Wind from ' + val + '" />';


	//RAIN ...
	rain = x.responseText.split(' ')[7]* .0393700787;
	set_ajax_obs("ajaxrain",rain.toFixed(2));

	raintoday = x.responseText.split(' ')[7]* .0393700787;
	set_ajax_obs("ajaxraintoday",raintoday.toFixed(2));

	rainmonth = x.responseText.split(' ')[8]* .0393700787;
	set_ajax_obs("ajaxrainmonth",rainmonth.toFixed(2));

	rainyear = x.responseText.split(' ')[9]* .0393700787;
	set_ajax_obs("ajaxrainyear",rainyear.toFixed(2));

	rainyesterday = x.responseText.split(' ')[19]* .0393700787;
	set_ajax_obs("ajaxrainyesterday",rainyesterday.toFixed(2));

	if (rain > 0) {
//		document.getElementById("ajaxraindays").innerHTML = "0";
	} else {
//		document.getElementById("ajaxraindays").innerHTML = "3";
	}


	//DEWPOINT ...
	dew = convertCtoF(x.responseText.split(' ')[72]);
//	document.getElementById("ajaxdew").innerHTML = dew.toFixed(1) + " &deg;F";


	// TIME
	ajaxdatetimeformat = x.responseText.split(' ')[32];
	ajaxdatetimeformat = ajaxdatetimeformat.replace( "KirklandWeather.com_____________Kirkland,_Washington-" , "");
	ajaxdatetimeformat = ajaxdatetimeformat.replace( "-" , "");
	ajaxdatetimeformat = ajaxdatetimeformat.replace( "_" , " ");
	set_ajax_obs("ajaxdatetime",ajaxdatetimeformat + ' PDT');

   }
    }

    x.send(null);

// Perform the AJAX check and update
// Edit the location of your clientraw.txt twice (here and in the body onload)

	setTimeout("reset_ajax_color('')",1000); // change text back to default color after 1 sec
	setTimeout("ajaxLoader('clientraw.txt?'+new Date())", 5000); // check for updates every 5 seconds
  }
}
