// <![CDATA[

// 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
// -- begin settings
var flashcolor = '#FF0000'; // color to flash for changed observations
var flashtime  = '3000';    // miliseconds to keep flash color on (2000 = 2 seconds);
var ie4=document.all;
var browser = navigator.appName;
var imagedir = './images';  // place for wind arrows, rising/falling arrows, etc.
var counterSecs = 0;  // for MCHALLIS counter script from weather-watch.com (adapted by K. True)
var lastajaxtimeformat = 'unknown'; //used to reset the counter when a real update is done
// -- end of settings

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

		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;
}
// --- end of flash-green functions

// Mike Challis' counter function (adapted by Ken True)
//
function ajax_countup() {
 element = document.getElementById("ajaxcounter");
 if (element) {
  element.innerHTML = counterSecs;
  counterSecs++;
 }
}

// BOF updated x sec ago counter by Mike Challis

var counter=0;
function countup() {
 element = document.getElementById("counter");
 if (element) {
  element.innerHTML = counter;
  counter= counter+1;
 }
}
window.setInterval("countup()", 1000);

// EOF updated x sec ago counter 

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 )];
}



// main AJAX routine .. load and format clientraw.txt
function ajaxLoader(url) {
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
  }
  if (x) {
    x.onreadystatechange = function() {
      if (x.readyState == 4 && x.status == 200) {
//alert(x.responseText)

		//Temp
		temp = (1.8 * x.responseText.split(' ')[4]) + 32.0;
			set_ajax_obs("ajaxtempnp",temp.toFixed(0) + " &deg;F");
			set_ajax_obs("ajaxtemp",temp.toFixed(1) + " &deg;F");

//	    temptrend = ((1.8 * x.responseText.split(' ')[4]) + 32.0) - ((1.8 * x.responseText.split(' ')[90]) + 32.0);
//		set_ajax_obs("ajaxtemptrend",temptrend.toFixed(1) + " &deg;F");

temptrend = ((1.8 * x.responseText.split(' ')[4]) + 32.0) - ((1.8 * x.responseText.split(' ')[90]) + 32.0);
			if (temptrend > 0) {
			document.getElementById("ajaxtemptrendgraphic").innerHTML = '&nbsp;<img src="./images/greenup.gif" height="15" width="15" alt="Temperature Rising" title="Temperature Rising">';
		} else if (temptrend < 0) {
			document.getElementById("ajaxtemptrendgraphic").innerHTML = '&nbsp;<img src="./images/reddown.gif" height="15" width="15" alt="Temperature Falling" title="Temperature Falling">';
		} else {
			
			document.getElementById("ajaxtemptrendgraphic").innerHTML = '';
		}		
		set_ajax_obs("ajaxtemptrend",temptrend.toFixed(1) + " &deg;F /hr");	
		set_ajax_obs("ajaxtemptrends",temptrend.toFixed(1) + " &deg;F /hr");

// 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  = ((1.8 * feelslike) + 32.0);
	      set_ajax_obs("ajaxfeelslike",feelslike.toFixed(1) + " &deg;F");

//Apparent Temp
	apptemp = (1.8 * x.responseText.split(' ')[130]) + 32.0;		
	set_ajax_obs("APPTEMP",apptemp.toFixed(1) + " &deg;F");

	maxapptemp = (1.8 * x.responseText.split(' ')[136]) + 32.0;
	set_ajax_obs("MAXAPPTEMP",maxapptemp.toFixed(1) + " &deg;F");
	
	minapptemp = (1.8 * x.responseText.split(' ')[137]) + 32.0;		
	set_ajax_obs("MINAPPTEMP",minapptemp.toFixed(1) + " &deg;F");

	maxtemp = (1.8 * x.responseText.split(' ')[46]) + 32.0;		
	set_ajax_obs("MAXTEMP",maxtemp.toFixed(1) + " &deg;F");
	mintemp = (1.8 * x.responseText.split(' ')[47]) + 32.0;		
	set_ajax_obs("MINTEMP",mintemp.toFixed(1) + " &deg;F");
	
	
	windtemp = (1.8 * x.responseText.split(' ')[44]) + 32.0;		
	set_ajax_obs("WINDTEMP",windtemp.toFixed(1) + " &deg;F");

	minwindtemp = (1.8 * x.responseText.split(' ')[78]) + 32.0;		
	set_ajax_obs("MINWINDTEMP",minwindtemp.toFixed(1) + " &deg;F");

		//Pressure...
		pressure = x.responseText.split(' ')[6] / 33.86388158;
		set_ajax_obs("ajaxbaro",pressure.toFixed(2) + " in.");
		set_ajax_obs("ajaxbaron",pressure.toFixed(2) + " in.");

		pressure = x.responseText.split(' ')[50] / 33.86388158;
		set_ajax_obs("ajaxbarotrend",pressure.toFixed(2) + " in.");

		press = x.responseText.split(' ')[131] / 33.86388158;
		set_ajax_obs("MAXPRESSURE",press.toFixed(2) + " in.");

		press = x.responseText.split(' ')[132] / 33.86388158;
		set_ajax_obs("MINPRESSURE",press.toFixed(2) + " in.");


			press = x.responseText.split(' ')[50];
								if (press >= -.6 && press <= .6) 
								press = "Steady"
								if (press > .6 && press <= 2) 
								press = "Rising"	
            							if (press > 2 ) 
								press = "Rising Rapidly"
      								if (press < -.6 && press >= -2) 
								press = "Falling"
     								if (press < -2 ) 
								press = "Falling Rapidly"
     			set_ajax_obs("presstrendt",press);
		
		press = x.responseText.split(' ')[50];
								if (press >= -.6 && press <= .6) 
								press = "Steady"
								if (press > .6 && press <= 2) 
								press = "Rising"	
            							if (press > 2 ) 
								press = "Rising Rapidly"
      								if (press < -.6 && press >= -2) 
								press = "Falling"
     								if (press < -2 ) 
								press = "Falling Rapidly"
     				set_ajax_obs("presstrend",press);

        //Wind gust
		gust = x.responseText.split(' ')[140]* 1.1507794;
		set_ajax_obs("ajaxgust",gust.toFixed(1) + " mph");

		//Windspeed ...
		wind = x.responseText.split(' ')[1]* 1.1507794;
		set_ajax_obs("ajaxavg",wind.toFixed(1) + " mph");
		wind = x.responseText.split(' ')[2]* 1.1507794;
		set_ajax_obs("ajaxwindy",wind.toFixed(1) + " mph");
		wind = x.responseText.split(' ')[140]* 1.1507794;
		set_ajax_obs("ajaxgust",wind.toFixed(1) + " mph");
//Max Windspeed
		wind = x.responseText.split(' ')[71]* 1.1507794;
		set_ajax_obs("MAXSPEED",wind.toFixed(1) + " mph");
		time = x.responseText.split(' ')[135];
       	set_ajax_obs("WINDTIME",time);
		//Max Avg Wind Speed
		wind = x.responseText.split(' ')[113]* 1.1507794;
		set_ajax_obs("MAXAVSPEED",wind.toFixed(1) + " mph");
		
		wind = x.responseText.split(' ')[2]* 1.1507794;
	 		set_ajax_obs("AVWSPEED",wind.toFixed(1) + " mph");
		wind = x.responseText.split(' ')[133]* 1.1507794;
	 		set_ajax_obs("maxwindlsthr",wind.toFixed(1) + " mph");

//Windspeed ...
		cwind = x.responseText.split(' ')[140]* 1.1507794;
		              						if (cwind >= 0 && cwind < 1) 
								beaf = "Calm"
								if (cwind >= 1 && cwind < 3) 
								beaf = "Light Air"
								if (cwind >=3  && cwind < 7) 
								beaf = "Light Breeze"	
								if (cwind >=7 && cwind < 12 )
								beaf = "Gentle Breeze"
								if (cwind >=12 && cwind < 18) 
								beaf = "Moderate Breeze"
								if (cwind >= 18 && cwind < 24) 
								beaf = "Fresh Breeze"
								if (cwind >= 24 && cwind < 31) 
								beaf = "Strong Breeze"
								if (cwind >= 31 && cwind < 38) 
								beaf = "Near Gale"
								if (cwind >= 38 && cwind < 46) 
								beaf = "Gale"
								if (cwind >= 46 && cwind < 54) 
								beaf = "Strong Gale"
								if (cwind >= 54 && cwind < 63) 
								beaf = "Storm"
								if (cwind >= 63 && cwind < 72)
								beaf = "Violent Storm" 
								if (cwind >= 72 && cwind < 100) 
 								beaf = "Hurricane"
							set_ajax_obs("BEAUFORT",beaf);

 //WIND DIRECTION ...
        val = windDir(x.responseText.split(' ')[117]);
// -----
       if (wind >= 0.1) {
 		set_ajax_obs("ajaxwindicon","<img src=./images/" + val + ".gif width=\"14\" height=\"14\" alt=\"Wind from" + 
		val + "\" title=\"Wind from " + val + "\" /> ");
		set_ajax_obs("ajaxwind",wind.toFixed(1) + " mph");
		set_ajax_obs("ajaxwinddir",val);
	   } else {
 		set_ajax_obs("ajaxwindicon","<img src=./images/" + val + ".gif width=\"14\" height=\"14\" alt=\"Wind from" + val + "\" title=\"Wind from " + val + "\" />");
		set_ajax_obs("ajaxwind","0.0 mph");
		set_ajax_obs("ajaxwinddir",val);
	   }

//WIND DIRECTION ...
        val = windDir(x.responseText.split(' ')[3]);
	set_ajax_obs("ajaxwinddirn",val);




		//Rain ...
		rain = x.responseText.split(' ')[7]* .0393700787;
		set_ajax_obs("ajaxrain",rain.toFixed(2) + " in. ");
		set_ajax_obs("ajaxraing",rain.toFixed(2) + " in. ");

		rainydy = x.responseText.split(' ')[19]* .0393700787;
		set_ajax_obs("ajaxrainydy",rainydy.toFixed(2) + " in. ");

		rainmo = x.responseText.split(' ')[8]* .0393700787;
		set_ajax_obs("ajaxrainmo",rainmo.toFixed(2) + " in. ");

		rainyr = x.responseText.split(' ')[9]* .0393700787;
		set_ajax_obs("ajaxrainyr",rainyr.toFixed(2) + " in. ");

		rainratehr = x.responseText.split(' ')[10]* .0393700787 * 60;
		set_ajax_obs("ajaxrainratehr",rainratehr.toFixed(2) + " in./hour ");

		rain = x.responseText.split(' ')[11]* .0393700787 * 60;
		set_ajax_obs("MAXRAINRATE",rain.toFixed(2) + " in./hour ");

rain = x.responseText.split(' ')[10]* 60;
								if (rain <= 0 && rain <= 0) 
								rain = "Dry"						
								if (rain > 0 && rain <= .3) 
								rain = "Light Drizzle"
								if (rain > .3 && rain <= .5) 
								rain = "Moderate Drizzle"
								if (rain > .5 && rain <= .8) 
								rain = "Heavy Drizzle"
      								if (rain > .8 && rain <= 2.5) 
								rain = "Light Rain"
      								if (rain > 2.5 && rain <= 7.5) 
								rain = "Moderate Rain"
      								if (rain > 7.5 && rain <= 16) 
								rain = "Heavy Rain"
      								if (rain > 16 && rain <= 35) 
								rain = "Intense Rain"
      								if (rain > 35 && rain <= 100) 
								rain = "Deluge Rain"
								if (rain > 100) 
								rain = "Flood Rains"
			set_ajax_obs("RATERAINW",rain);
//Icon
					
					icon = x.responseText.split(' ')[48];
               	
								if (icon >= 0 && icon < 1) 
								iconname = "Sunny"
								if (icon >= 1 && icon < 2) 
								iconname = "Clear Night"	
								if (icon >= 2 && icon < 3) 
								iconname = "Cloudy"
								if (icon >= 3 && icon < 4) 
								iconname = "Cloudy"
								if (icon >= 4 && icon < 5) 
								iconname = "Cloudy Night"
								if (icon >= 5 && icon < 6) 
								iconname = "Clear"
								if (icon >= 6 && icon < 7) 
								iconname = "Fog"
								if (icon >= 7 && icon < 8) 
								iconname = "Haze"
								if (icon >= 8 && icon < 9) 
								iconname = "Heavy Rain"
								if (icon >= 9 && icon < 10) 
								iconname = "Partly Sunny"
								if (icon >= 10 && icon < 11) 
								iconname = "Mist"
								if (icon >= 11 && icon < 12) 
								iconname = "Night Fog"	
								if (icon >= 12 && icon < 13) 
								iconname = "Night Heavy Rain"
								if (icon >= 13 && icon < 14) 
								iconname = "Night Overcast"
								if (icon >= 14 && icon < 15) 
								iconname = "Night Rain"
								if (icon >= 15 && icon < 16) 
								iconname = "Night Showers"
								if (icon >= 16 && icon < 17) 
								iconname = "Night Snow"
								if (icon >= 17 && icon < 18) 
								iconname = "Night Thunder"
								if (icon >= 18 && icon < 19) 
								iconname = "Overcast"
								if (icon >= 19 && icon < 20) 
								iconname = "Partly Cloudy"
								if (icon >= 20 && icon < 21) 
								iconname = "Rain"
								if (icon >= 21 && icon < 22) 
								iconname = "Rain"	
								if (icon >= 22 && icon < 23) 
								iconname = "Showers"
								if (icon >= 23 && icon < 24) 
								iconname = "Sleet"
								if (icon >= 24 && icon < 25) 
								iconename = "Sleet Showers"
								if (icon >= 25 && icon < 26) 
								iconname = "Snow"
								if (icon >= 26 && icon < 27) 
								iconname = "Snow Melt"
								if (icon >= 27 && icon < 28) 
								iconname = "Snow Showers"
								if (icon >= 28 && icon < 29) 
								iconname = "Sunny"
								if (icon >= 29 && icon < 30) 
								iconname = "Thunder Showers"
								if (icon >= 30 && icon < 31) 
								iconname = "Thunder Showers"
								if (icon >= 31 && icon < 32) 
								iconname = "Thunder Storms"	
								if (icon >= 32 && icon < 33) 
								iconname = "Tornado"
								if (icon >= 33 && icon < 34) 
								iconname = "Windy"
								if (icon >= 34 && icon < 35) 
								iconname = "Stopped Raining"
				set_ajax_obs("WEATHERD",iconname);

		//Humidity ...
		humidity = x.responseText.split(' ')[5] + " %";
		set_ajax_obs("ajaxhumidity",humidity);
		set_ajax_obs("ajaxhumidityg",humidity);

		//	document.getElementById("ajaxwebcam").src = "autosnap.jpg"+"?"+new Date();
		//	document.getElementById("ajaxradar").src = "/crop.php"+"?"+new Date();
   		//	document.getElementById("ajaxlite").src = "tracgraphicexample.php"+"?"+new Date();	
	
	
	
		//Dewpoint ...
		dew = (1.8 * x.responseText.split(' ')[72]) + 32.0;
		set_ajax_obs("ajaxdew",dew.toFixed(1) + " &deg;F");
		set_ajax_obs("ajaxdewg",dew.toFixed(1) + " &deg;F");
		
		dew = (1.8 * x.responseText.split(' ')[138]) + 32.0;
		set_ajax_obs("maxdew",dew.toFixed(1) + " &deg;F");
		
		dew = (1.8 * x.responseText.split(' ')[139]) + 32.0;
		set_ajax_obs("mindew",dew.toFixed(1) + " &deg;F");

		
		// current date and time of observation in clientraw.txt
		ajaxtimeformat = x.responseText.split(' ')[32];
		ajaxdateformat = x.responseText.split(' ')[74];
		ajaxtimeformat = ajaxtimeformat.split('-')[1];
		ajaxtimeformat = ajaxtimeformat.replace( "_" , "");
		ajaxtimeformat = ajaxtimeformat.toLowerCase();

		set_ajax_obs("ajaxdatetime",ajaxdateformat + " " +ajaxtimeformat);
		set_ajax_obs("ajaxdate",ajaxdateformat);
		set_ajax_obs("ajaxtime",ajaxtimeformat);
		
		if (lastajaxtimeformat != ajaxtimeformat) {
			counterSecs = 0;                      // reset timer
			lastajaxtimeformat = ajaxtimeformat; // remember this time
		}

	
        document.getElementById("ajaxindicator").style.color = flashcolor;
	counter=0; // reset updated x sec ago counter 

   }
    }
    x.open("GET", url, true);
    x.send(null);

//get all of them every minute = 5000 milliseconds
//edit the location of your clienraw.txt twice!! (here and in the body onload)
	setTimeout("reset_ajax_color('')",flashtime); // change text back to default color 
    setTimeout("ajaxLoader('clientraw.txt?'+new Date())", 10000); // get new data after 5 secs
  }
} // 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 genarrow( nowTemp, yesterTemp, Legend, textUP, textDN) {
  var diff = nowTemp.toFixed(3) - yesterTemp.toFixed(3);
  var absDiff = Math.abs(diff);
  var diffStr = '' + diff.toFixed(1);  // sprintf("%01.0f",$diff);
  var absDiffStr = '' + absDiff.toFixed(1); // sprintf("%01.0f",$absDiff);
  var image = '';
  var msg = '';
  
  if (diff == 0) {
 // no change

    image = '&nbsp;'; 
  
  } else if (diff > 0) {
// today is greater 
//    msg = textUP + " by " + diff.toFixed(1); // sprintf($textDN,$absDiff); 
	msg = textUP.replace(/\%s/,absDiffStr);
    image = "<img src=\"/ajax-1-04/images/rising.gif\" alt=\"" + msg + 
	"\" title=\""+ msg + 
	"\" width=\"7\" height=\"8\" style=\"border: 0; margin: 1px 3px;\" />";
  } else {
// today is lesser
    msg = textDN.replace(/\%s/,absDiffStr); // sprintf($textDN,$absDiff); 
//	msg = textDN.replace(/\%s/,absDiffStr);
    image = "<img src=\"/ajax-1-04/images/falling.gif\" alt=\"" + msg + 
	"\" title=\""+ msg + 
	"\" width=\"7\" height=\"8\" style=\"border: 0; margin: 1px 3px;\" />";
   
  }

   if (Legend) {
       return (diff + Legend + image);
	} else {
	   return image;
	}
} // end genarrow function


// ]]>
