// <![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 - Ken True  24-Nov-2006
//
// --- Version 2.00 - 13-Dec-2006 -- Ken True -repackaged AJAX function, added metric/english units
//     also included Mike Challis' counter script to display seconds since last update and error
//     handling for the fetch to fix to fix random error: NS_ERROR_NOT_AVAILABLE
//     Mike's site: http://www.carmosaic.com/weather/index.php
//     Thanks to FourOhFour on wxforum.net ( http://skigod.us/ ) for replacing all the
//     x.responseText.split(' ')[n] calls with a simple array lookup.. much better speed and a
//     streamlined version of getUVrange.
//
// for updates to this script, see http://saratoga-weather.org/scripts-WD-AJAX.php
// announcements of new versions will be on weather-watch.com and wxforum.net

// -- begin settings --------------------------------------------------------------------------
//var limiter_on = false;
var maxupdates = 50;   		// Maxium Number of updates allowed .. 0 disables it      600=30min
                             // maxupdates * reloadTime / 1000 = number of seconds to update
//var flashcolor = '#00CC00'; // color to flash for changed observations RGB      
var flashcolor = '#000000'; // color to flash for changed observations RGB      
//var topcolor = '#999999';
var topcolor = '#000000';
var flashtime  = 200;    // miliseconds to keep flash color on (2000 = 2 seconds);
var reloadTime = 10000;      // reload AJAX conditions every 5 seconds (= 5000 ms)  20/min @ 3 sec
//var reload2Time = 3000;
var reloadTags = 60000;      // reload tags every minute 60000
//var reloadTags = 5000;
var reloadRadars = 300000;      // reload images every 5 minutes 300000
var clientrawFile = '/clientraw.txt'; // location of clientraw.txt relative to this page on website
var clientraw2File = '/customclientraw.txt';
var tagsFile = '/wddata.txt'; // location of custom data file
//var yoFile = '/yowindow-string.txt';
var dummyFile = '/clientrawextra.txt'; // location of custom data file
var ajaxLoaderInBody = false; // set to true if you have <body onload="ajaxLoader(..."
var imagedir = './ajax-images';  // place for wind arrows, rising/falling arrows, etc.
var useunits = 'E';         // 'E'=USA(English) or 'M'=Metric
var useKnots = false;       // set to true to use wind speed in Knots (otherwise 
							// wind in km/hr for Metric or mph for English will be used.										
var showUnits = false;       //  set to false if no units are to be displayed
// -- end of settings -------------------------------------------------------------------------
// --- you don't need to customize the stuff below, the actions are controlled by the 
//  settings above.  
//windowFocused = true;    // in case the focus javascript hasn't been placed in the <head>
var windowFocused = true;

var saveReload = 0;
var ie4=document.all;
var browser = navigator.appName;
// Added from http://www.wxforum.net/index.php?topic=3719.msg31040#msg31040
var ie8 = false;
if (ie4 && /MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=8) {
   ie4=false;
   ie8=true;
 }
}

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
var updates = 0;      // Start counter

// handle setup options for units-of-measure and whether to show them at all
var uomTemp = '&deg;F';
var uomWind = ' mph';
var uomBaro = ' inHg';
var uomRain = ' in';
var uomHeight = ' ft';
var dpBaro = 2;
var dpRain = 2;


function ajax_set_units( units ) {
  var useunits = units;
  if (useunits != 'E') { // set to metric
	uomTemp = '&deg;C';
	uomWind = ' km/h';
	uomBaro = ' hPa';
	uomRain = ' mm';
	uomHeight = ' m';
	dpBaro = 1;
	dpRain = 1;
  }
  if(useKnots) { uomWind = ' kts'; }
  if (! showUnits) {
	uomTemp = '';
	uomWind = '';
	uomBaro = '';
	uomRain = '';
	uomHeight = '';
  }
}

ajax_set_units(useunits);

// utility functions to navigate the HTML tags in the page
function get_ajax_tags ( ) {
// search all the span tags and return the list with class="ajax" in it
//
  if (ie4 && browser != "Opera" && ! ie8) {
  //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();
	 var att="";
	 var i,iarr=0;
     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 (unescape(value) != unescape(lastobs)) {
          element.style.color=flashcolor;
		  element.innerHTML =  value;
		}
}

function set_ajax_obsT( name, value ) {               // Does the subdued top updates
// 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 (unescape(value) != unescape(lastobs)) {
          element.style.color=topcolor;
		  element.innerHTML =  value;
		  
		}
		//element.style.color=flashcolor;  //for testing
}

function set_ajax_obsW( name, value ) {               // Does the subdued top updates
// 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 (unescape(value) != unescape(lastobs)) {
          element.style.color="#FFFFFF";
		  element.innerHTML =  value;
		  
		}
		//element.style.color=flashcolor;  //for testing
}

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='inline';
		} else {
          element.style.display='none';
		}
}

// --- end of flash-green functions

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
{
   var 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 lightningDir (winddir)  // For Lightning
{
   var windlabel = new Array("North", "NNE", "NE", "ENE", "East", "ESE", "SE", "SSE", "South", "SSW", "SW", "WSW", "West", "WNW", "NW", "NNW");
   return windlabel[Math.floor(((parseInt(winddir) + 11) / 22.5) % 16 )];
}

function ajax_wxIcon ( iconWD ) { 
// perform a lookup and return the graphic for the condition icon (using anole's
// wxsticker icon names
  var iconList = new Array(
	"day_clear.gif",           //  0 imagesunny.visible
	//"sunny.png",               //  0 imagesunny.visible
	"night_clear.gif",         //  1 imageclearnight.visible
	//"nclear.png",              //  1 imageclearnight.visible
	"day_partly_cloudy.gif",   //  2 imagecloudy.visible
	//"partlycloudy.png",        //  2 imagecloudy.visible
	"day_partly_cloudy.gif",   //  3 imagecloudy2.visible
	//"fewclouds.png",           //  3 imagecloudy2.visible
	"night_partly_cloudy.gif", //  4 imagecloudynight.visible
	//"npartly.png",             //  4 imagecloudynight.visible
	"day_partly_cloudy.gif",           //  5 imagedry.visible
	//"sunny.png",               //  5 imagedry.visible
	"fog.gif",                 //  6 imagefog.visible
	//"fog.png",                 //  6 imagefog.visible	
	"haze.gif",                //  7 imagehaze.visible
	//"haze.png",                //  7 imagehaze.visible
	"day_heavy_rain.gif",      //  8 imageheavyrain.visible
	//"rain.png",                //  8 imageheavyrain.visible
	"day_mostly_sunny.gif",    //  9 imagemainlyfine.visible
	//"fewclouds.png",           //  9 imagemainlyfine.visible
	"mist.gif",                // 10 imagemist.visible
	//"mist.png",                // 10 imagemist.visible
	"fog.gif",                 // 11 imagenightfog.visible
	//"fog.png",                 // 11 imagenightfog.visible
	"night_heavy_rain.gif",    // 12 imagenightheavyrain.visible
	//"rain.png",                // 12 imagenightheavyrain.visible
	"night_cloudy.gif",        // 13 imagenightovercast.visible
	//"nclouds.png",             // 13 imagenightovercast.visible
	"night_rain.gif",          // 14 imagenightrain.visible
	//"rain.png",                // 14 imagenightrain.visible
	"night_light_rain.gif",    // 15 imagenightshowers.visible
	//"rain.png",                // 15 imagenightshowers.visible
	"night_snow.gif",          // 16 imagenightsnow.visible
	//"snow.png",                // 16 imagenightsnow.visible
	"night_tstorm.gif",        // 17 imagenightthunder.visible
	//"thunderstorm.png",        // 17 imagenightthunder.visible
	"day_cloudy.gif",          // 18 imageovercast.visible
	//"overcast.png",            // 18 imageovercast.visible
	"day_partly_cloudy.gif",   // 19 imagepartlycloudy.visible
	//"partlycloudy.png",        // 19 imagepartlycloudy.visible
	"day_rain.gif",            // 20 imagerain.visible
	//"rain.png",                // 20 imagerain.visible
	"day_rain.gif",            // 21 imagerain2.visible
	//"rain.png",                // 21 imagerain2.visible
	"day_light_rain.gif",      // 22 imageshowers2.visible
	//"day_light_rain.gif",      // 22 imageshowers2.visible
	"sleet.gif",               // 23 imagesleet.visible
	//"freezingrain.png",        // 23 imagesleet.visible
	"sleet.gif",               // 24 imagesleetshowers.visible
	//"sleet.png",               // 24 imagesleetshowers.visible
	"day_snow.gif",            // 25 imagesnow.visible
	//"snow.png",                // 25 imagesnow.visible	
	"day_snow.gif",            // 26 imagesnowmelt.visible
	//"flurries.png",            // 26 imagesnowmelt.visible	
	"day_snow.gif",            // 27 imagesnowshowers2.visible
	//"showers.png",             // 27 imagesnowshowers2.visible
	"day_clear.gif",           // 28 imagesunny.visible
	//"sunny.png",               // 28 imagesunny.visible
	"day_tstorm.gif",          // 29 imagethundershowers.visible
	//"thunder.png",           // 29 imagethundershowers.visible
	"day_tstorm.gif",          // 30 imagethundershowers2.visible
	//"thunderstorm.png",        // 30 imagethundershowers2.visible
	"day_tstorm.gif",          // 31 imagethunderstorms.visible
	//"thunderstorm.png",        // 31 imagethunderstorms.visible
	"tornado.gif",             // 32 imagetornado.visible  ***************
	//"thunder.png",             // 32 imagetornado.visible
	"windy.gif",               // 33 imagewindy.visible
	//"windy.png",               // 33 imagewindy.visible
	"day_partly_cloudy.gif",   // 34 stopped rainning
	//"fewclouds.png",           // 34 stopped rainning ***************
	"day_partly_cloudy.gif",   // 35 // imagewindyrain.visible
//	"dawnn.jpg",				   // 36 added by jmcmurry  ***************"dawn.gif"
//	"duskn.jpg"				   // 37 added by jmcmurry  **************"dusk.gif"
	"sunrise.gif",				   // 36 added by jmcmurry  ***************"dawn.gif"
	"sunset.gif"				   // 37 added by jmcmurry  **************"dusk.gif"	
	);					

  if (iconWD >= 0 && iconWD <= 37) { 
    return ("<img src=\"" + imagedir + "/" + iconList[iconWD] + "\" " +
				"width=\"25\" height=\"25\" alt=\"Current condition icon\" />" );
  } else {
	return '';
  }

}

// utility functions to handle conversions from clientraw data to desired units-of-measure
function convertTemp ( rawtemp ) {
	if (useunits == 'E') { // convert C to F
		return( (1.8 * rawtemp) + 32.0);
	} else {  // leave as C
		return (rawtemp * 1.0);
	}
}

function convertWind  ( rawwind ) {
	if (useKnots) { return(rawwind * 1.0); } //force usage of knots for speed
	if (useunits == 'E') { // convert knots to mph
		return(rawwind * 1.1507794);
	} else {  // convert knots to km/hr
		return (rawwind * 1.852);
	}
}

function convertBaro ( rawpress ) {
	if (useunits == 'E') { // convert hPa to inHg
	   return (rawpress  / 33.86388158);
	} else {
	   return (rawpress * 1.0); // leave in hPa
	}
}

function convertRain ( rawrain ) {
	if (useunits == 'E') { // convert mm to inches
	   return (rawrain * .0393700787);
	} else {
	   return (rawrain * 1.0); // leave in mm
	}
}

function convertHeight ( rawheight ) {
	if (useunits == 'E') { // convert feet to meters if metric
	   return (Math.round(rawheight * 1.0).toFixed(0)); // leave in feet
	} else {
	   return (Math.round(rawheight / 3.2808399).toFixed(0));
	}
}

function ajax_get_beaufort ( wind ) { 
// return a phrase for the beaufort scale based on wind knots (native WD format)
  if (wind < 1 ) {return("Calm Winds"); }
  if (wind < 4 ) {return("Wisp of Wind"); }
  if (wind < 7 ) {return("Gentle Breeze"); }
  if (wind < 11 ) {return("Light Wind"); }
  if (wind < 17 ) {return("Moderate Wind"); }
  if (wind < 22 ) {return("Strong Wind"); }
  if (wind < 28 ) {return("Very Strong Wind"); }
  if (wind < 34 ) {return("Near Gale Winds"); }
  if (wind < 41 ) {return("Gale Winds"); }
  if (wind < 48 ) {return("Strong Gale Winds"); }
  if (wind < 56 ) {return("Storm Winds"); }
  if (wind < 64 ) {return("Violent Storm Winds"); }
  if (wind >= 64 ) {return("Tornado Winds"); }
  return("unknown " + wind);
}


function ajax_get_barotrend(btrnd) {
// routine from Anole's wxsticker PHP (adapted to JS by Ken True)
// input: trend in hPa or millibars
//   Barometric Trend(3 hour)

// 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
// Rising Rapidly
// Rising Slowly
// Steady
// Falling Slowly
// Falling Rapidly

// 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.7) && (btrnd <= 0.7)) { return("Steady"); }
   if ((btrnd > 0.7) && (btrnd < 2.0)) { return("Rising Slowly"); }
   if (btrnd >= 2.0) { return("Rising Rapidly"); }
   if ((btrnd < -0.7) && (btrnd > -2.0)) { return("Falling Slowly"); }
   if (btrnd <= -2.0) { return("Falling Rapidly"); }
  return(btrnd);
}

function ajax_getUVrange ( uv ) { // code simplified by FourOhFour on wxforum.net
   var uvword = "Unspec.";
   if (uv <= 0) {
       uvword = "";           // Removed "None"
   } else if (uv < 3) {
       uvword = "<span style=\"border: solid 1px; background-color: #A4CE6a;\">&nbsp;Low&nbsp;</span>";
   } else if (uv < 6) {
       uvword = "<span style=\"border: solid 1px; background-color: #FBEE09;\">&nbsp;Moderate&nbsp;</span>";
   } else if (uv < 8) {
       uvword =  "<span style=\"border: solid 1px; background-color: #FD9125;\">&nbsp;High&nbsp;</span>";
   } else if (uv < 11) {
       uvword =  "<span style=\"border: solid 1px; color: #FFFFFF; background-color: #F63F37;\">&nbsp;Very&nbsp;High&nbsp;</span>";
   } else {
       uvword =  "<span style=\"border: solid 1px; color: #FFFF00; background-color: #807780;\">&nbsp;Extreme&nbsp;</span>";
   }
   return uvword;
} // end ajax_getUVrange function

function ajax_genarrow( nowTemp, yesterTemp, Legend, textUP, textDN, numDp) {
// generate an <img> tag with alt= and title= for rising/falling values	
	
  var diff = nowTemp.toFixed(3) - yesterTemp.toFixed(3);
  var absDiff = Math.abs(diff);
  var diffStr = '' + diff.toFixed(numDp);  // sprintf("%01.0f",$diff);
  var absDiffStr = '' + absDiff.toFixed(numDp); // 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=\"" + imagedir + "/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=\"" + imagedir + "/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

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

function trim(s)      // trim white space from both ends
{
    var l=0; var r=s.length -1;
    while(l < s.length && s[l] == ' ')
    {     l++; }
    while(r > l && s[r] == ' ')
    {     r-=1;     }
    return s.substring(l, r+1);
} 
// ------------------------------------------------------------------------------------------
//  main function.. read clientraw.txt and format <span class="ajax" id="ajax..."></span> areas
// ------------------------------------------------------------------------------------------
function ajaxLoader(url) {
if (windowFocused) {	
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
  }
  if (x) { // got something back
    x.onreadystatechange = function() {
    try { if (x.readyState == 4 && x.status == 200) { // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE 
	    var clientraw = x.responseText.split(' ');  
	// now make sure we got the entire clientraw.txt  -- thanks to Johnnywx
	// valid clientraw.txt has '12345' at start and '!!' at end of record
	var wdpattern=/\d+\.\d+.*!!/; // looks for '!!nn.nn!!' version string 
	if(clientraw[0] == '12345' && wdpattern.test(x.responseText) && 
	    ( updates <= maxupdates || maxupdates > 0  ) ) {
		if (maxupdates > 0 ) {updates++; } // increment counter if needed
		
//		var y = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest("/yowindow-string.txt");
//		var yodata = y.responseText.split(' ');
//		clientraw[48] = yodata[1];
//		clientraw[49] = yodata[3];


/*
		//YoWindow
		if (updates == 2) {			
			var preloaded = document.getElementById("yowindow");
			if (preloaded) {                                       // then this id is on the page
				var target = document.getElementById("yoicon");
				target.style.visibility = "hidden";				
				var caption = document.getElementById("caption");  // make the mask visible
				caption.style.visibility = "visible";				
				preloaded.style.left = "0px";                      // move down into positon
				preloaded.style.top = "0px";
			}
		}
*/		
		//Temperature
		var temp = convertTemp(clientraw[4]);
		if (temp == "-0.0") {
			temp = "0";
		}
		set_ajax_obs("ajaxtemp", temp.toFixed(1) + uomTemp);
		set_ajax_obsT("ajaxbigtemp",temp.toFixed(0) + uomTemp);
		var templast = convertTemp(clientraw[90]);
		set_ajax_obs("ajaxtemparrow", 
		   ajax_genarrow(temp, templast, '', 
			 'Warmer %s'+uomTemp+' than last hour.',
			 'Colder %s'+uomTemp+' than last hour.',1)
		   );	
	    var temprate = temp - templast;
		temprate = temprate.toFixed(1);
		if (temprate > 0.0) { temprate = '+' + temprate;} // add '+' for positive rates
		set_ajax_obs("ajaxtemprate",temprate + uomTemp);
		
		var tempmax = convertTemp(clientraw[46]);
		set_ajax_obs("ajaxtempmax",tempmax.toFixed(1) + uomTemp);

		var tempmin = convertTemp(clientraw[47]);
		set_ajax_obs("ajaxtempmin",tempmin.toFixed(1) + uomTemp);

		//Humidity ...
		var humidity = clientraw[5];
		set_ajax_obs("ajaxhumidity",humidity);
		// sorry.. no min/max data for humidity in clientraw
		
		//Dewpoint ...
		var dew = convertTemp(clientraw[72]);
		set_ajax_obs("ajaxdew",dew.toFixed(1) + uomTemp);
		
		var dewmin = convertTemp(clientraw[139]);
		set_ajax_obs("ajaxdewmin",dewmin.toFixed(1) + uomTemp);
		var dewmax = convertTemp(clientraw[138]);
		set_ajax_obs("ajaxdewmax",dewmax.toFixed(1) + uomTemp);

		// Humidex
		var humidex = convertTemp(clientraw[45]);
		set_ajax_obs("ajaxhumidex",humidex.toFixed(1) + uomTemp);
		var humidexmin = convertTemp(clientraw[76]);
		set_ajax_obs("ajaxhumidexmin",humidexmin.toFixed(1) + uomTemp);
		var humidexmax = convertTemp(clientraw[75]);
		set_ajax_obs("ajaxhumidexmax",humidexmax.toFixed(1) + uomTemp);

		//  WindChill
		var windchill = convertTemp(clientraw[44]);
		set_ajax_obs("ajaxwindchill",windchill.toFixed(1) + uomTemp);
		var windchillmin = convertTemp(clientraw[78]);
		set_ajax_obs("ajaxwindchillmin",windchillmin.toFixed(1) + uomTemp);
		var windchillmax = convertTemp(clientraw[77]);
		set_ajax_obs("ajaxwindchillmax",windchillmax.toFixed(1) + uomTemp);

		// Heat Index
		var heatidx = convertTemp(clientraw[112]);
		set_ajax_obs("ajaxheatidx",heatidx.toFixed(1) + uomTemp);
		var heatidxmin = convertTemp(clientraw[111]);
		set_ajax_obs("ajaxheatidxmin",heatidxmin.toFixed(1) + uomTemp);
		var heatidxmax = convertTemp(clientraw[110]);
		set_ajax_obs("ajaxheatidxmax",heatidxmax.toFixed(1) + uomTemp);

		// FeelsLike
		var feelslike = 0;
		var temp = clientraw[4]; // note.. temp in C
        if (temp <= 16.0 ) {
		  feelslike = clientraw[44]; //use WindChill
		} else if (temp >=27.0) {
		  feelslike = clientraw[45]; //use Humidex
		} else {
		  feelslike = temp;   // use temperature
		}
		feelslike  = Math.round(convertTemp(feelslike));
        set_ajax_obs("ajaxfeelslike",feelslike + uomTemp);
		set_ajax_obsT("ajaxfeelslike1",feelslike + uomTemp);
		
		// Apparent temperature
		var apparenttemp = convertTemp(clientraw[130]);
		set_ajax_obs("ajaxapparenttemp",apparenttemp.toFixed(1) + uomTemp);
		var apparenttempmin = convertTemp(clientraw[136]);
		set_ajax_obs("ajaxapparenttempmin",apparenttempmin.toFixed(1) + uomTemp);
		var apparenttempmax = convertTemp(clientraw[137]);
		set_ajax_obs("ajaxapparenttempmax",apparenttempmax.toFixed(1) + uomTemp);
		
		//Pressure...
		var pressure = convertBaro(clientraw[6]);
		set_ajax_obs("ajaxbaro",pressure.toFixed(dpBaro) + uomBaro);
		var pressuretrend = convertBaro(clientraw[50]);
		pressuretrend = pressuretrend.toFixed(dpBaro+1);
		if (pressuretrend > 0.0) {pressuretrend = '+' + pressuretrend; } // add '+' to rate
		set_ajax_obs("ajaxbarotrend",pressuretrend + uomBaro);
		set_ajax_obs("ajaxbaroarrow",
		   ajax_genarrow(pressure, pressure-pressuretrend, '', 
			 'Rising %s '+uomBaro+'/hour.',
			 'Falling %s '+uomBaro+'/hour.',2)
			 );	
		
		set_ajax_obs("ajaxbarotrendtext",ajax_get_barotrend(clientraw[50]));

		var pressuremin = convertBaro(clientraw[132]);
		set_ajax_obs("ajaxbaromin",pressuremin.toFixed(dpBaro) + uomBaro);
		var pressuremax = convertBaro(clientraw[131]);
		set_ajax_obs("ajaxbaromax",pressuremax.toFixed(dpBaro) + uomBaro);
		// and milibars	
		set_ajax_obs("ajaxmb",clientraw[6]); //Milibars added by jmcmurry


        //Wind gust
		var gust    = convertWind(clientraw[140]);
		var maxgust = convertWind(clientraw[71]);
		if (maxgust > 0.0 ) {
		  set_ajax_obs("ajaxmaxgust",maxgust.toFixed(1) + uomWind);
		} else {
		  set_ajax_obs("ajaxmaxgust",'None');
		}

		//Windspeed ...
		var wind = convertWind(clientraw[2]);
		//beaufort = ajax_get_beaufort(clientraw[2]);      // Not used by me
		//set_ajax_obs("ajaxbeaufort",beaufort);

       //WIND DIRECTION ...
        var val = windDir(clientraw[3]);

       if (wind > 0.0) {
		set_ajax_obs("ajaxwind",wind.toFixed(1)  + '<span style="font-size: x-small"> mph</span>');  
		//set_ajax_obs("ajaxwind",wind.toFixed(1) + uomWind);
		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.toFixed(1) + uomWind);
		set_ajax_uom("ajaxgustuom",true);
	   } else {
		//set_ajax_obs("ajaxgust","None");
		set_ajax_obs("ajaxgust","0");
		set_ajax_uom("ajaxgustuom",false);
	   }
	   
   	   //if (gust > 0.0 || wind > 0.0) {
		if (wind > 0.0) {   
 		set_ajax_obs("ajaxwindicon","<img src=\"" + imagedir + "/" +  val + ".gif\" width=\"14\" height=\"14\" alt=\"Wind from" + 
		val + "\" title=\"Wind from " + val + "\" /> ");
		set_ajax_obs("ajaxwinddir",val);
	   } else {
 		set_ajax_obs("ajaxwindicon","");
		set_ajax_obs("ajaxwinddir"," ");
	   }

		var windmaxavg = convertWind(clientraw[113]);
		set_ajax_obs("ajaxwindmaxavg",windmaxavg.toFixed(1) + uomWind);
		
		//Gusts hour/day  -  These two added from previous script by jmcmurry
		var gusthour = x.responseText.split(' ')[133]* 1.1507794;
		set_ajax_obs("ajaxgusthour", gusthour.toFixed(1) + " mph at ");
		var gusthourtime = x.responseText.split(' ')[134];
		gusthourtime = gusthourtime.replace( "_" , " ");
		set_ajax_obs("ajaxgusthourtime", gusthourtime.toLowerCase());

		var gusttoday = x.responseText.split(' ')[71]* 1.1507794;
		set_ajax_obs("ajaxgusttoday", gusttoday.toFixed(1) + " mph at ");
		var gustdaytime = x.responseText.split(' ')[135];
		gustdaytime = gustdaytime.replace( "_" , " ");
		set_ajax_obs("ajaxgusttodaytime", gustdaytime.toLowerCase());
		

		//  Solar Radiation
		var solar    = clientraw[127] * 1.0;
		set_ajax_obs("ajaxsolar",solar.toFixed(0));

        var solarpct = clientraw[34];
		set_ajax_obs("ajaxsolarpct",solarpct);
		
		// UV Index		
		var uv       = clientraw[79];
		set_ajax_obs("ajaxuv",uv) ;

		var uvword = ajax_getUVrange(uv);
		set_ajax_obs("ajaxuvword",uvword);

		//Rain ...
		var rain = convertRain(clientraw[7]);
		set_ajax_obs("ajaxrain",rain.toFixed(dpRain) + uomRain);


		var rainydy = convertRain(clientraw[19]);
		set_ajax_obs("ajaxrainydy",rainydy.toFixed(dpRain)+ uomRain);

		var rainmo = convertRain(clientraw[8]);
		set_ajax_obs("ajaxrainmo",rainmo.toFixed(dpRain) + uomRain);

		var rainyr = convertRain(clientraw[9]);
		set_ajax_obs("ajaxrainyr",rainyr.toFixed(dpRain) + uomRain);

		var rainratehr = convertRain(clientraw[10]) * 60; // make per hour rate.
		set_ajax_obs("ajaxrainratehr",rainratehr.toFixed(dpRain+1) + uomRain);
		//set_ajax_obs("ajaxrainratehr",rainratehr.toFixed(dpRain) + uomRain);

		// current date and time of observation in clientraw.txt
		//ajaxtimeformat = clientraw[32];
		//ajaxdateformat = clientraw[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
		//}
		
// current condition icon and description
/*
		var dawndusk = x.responseText.split(' ')[49];
		dawndusk = dawndusk.substr(0,4);
		if (dawndusk == "Dawn") {
			
			set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(36));
		} else if (dawndusk == "Dusk") {
			
			set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(37));
		} else {
			set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(x.responseText.split(' ')[48]));
		}	
*/		
		
//		set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(y.responseText.split(' ')[1]));
		
/* Why is this here?  How did it get here?
		
//		metcond = x.responseText.split('|')[130];
		if ((metcond.indexOf("mist") != -1) && (Precip.indexOf("Dry") != -1)) {
			Precip = "Mist";
		}
*/
//set_ajax_obs("ajaxdebug",clientraw[49] + "x");

		var currentcond = clientraw[49];
		currentcond = currentcond.replace(/_/g,' ');
		currentcond = currentcond.replace(/^\/Dry\//g,'');
		currentcond = currentcond.replace(/\\/g,', ');
		currentcond = currentcond.replace(/\//g,', ');
		//currentcond = currentcond.(/Dry/g, '');                     //broken
		set_ajax_obs("ajaxcurrentcond",currentcond);
		
		
		// Date 'N Time	 - These use a special "set_ajax_obsW" so they stay white
		var ajaxdateformat = x.responseText.split(' ')[74];
		set_ajax_obsW("ajaxdate",ajaxdateformat + "  ");

		var ajaxtimeformat = x.responseText.split(' ')[32];
		ajaxtimeformat = ajaxtimeformat.split('-')[1];
		ajaxtimeformat = ajaxtimeformat.replace( "_" , " ");
		var ajaxhour = ajaxtimeformat.split(':')[0];
		var ajaxminute = ajaxtimeformat.split(':')[1];
		var ajaxsecond = ajaxtimeformat.split(':')[2];		
		ajaxsecond = ajaxsecond.split(' ')[0];
//		var ajaxampm = ajaxtimeformat.split(' ')[1];

  		var now    = new Date();
   		var hour   = now.getHours();
		var ajaxampm = "AM";
		if (hour >= 12) ajaxampm = "PM";
				
		set_ajax_obsW("ajaxhr",ajaxhour + ":");
		set_ajax_obsW("ajaxmin",ajaxminute + ":");
		set_ajax_obsW("ajaxsec",ajaxsecond);
		set_ajax_obsW("ajaxap",ajaxampm);

/*
		// cloud height/ frostbite time   137 & 138

		var FBTime = FrostbiteTime( "C", clientraw[4], clientraw[1]*1.85);
//		var FBTime = FrostbiteTime( "C", -20, 40);
//set_ajax_obsT("ajaxdebug", FBTime);		
		if (FBTime > 0) {
			document.getElementById("ajaxFBhead").innerHTML = "Frostbite Time:";
			set_ajax_obs("ajaxFB",FBTime + " Minutes");	
			if (FBTime < 60) {
				document.getElementById("ajaxFrostWarn").innerHTML = "Caution - Frostbite Can Occur Within " + FBTime + " Minutes on Unprotected Skin";
//				set_ajax_obs("ajaxFrostWarn","Warning - Frostbite Can Occur Within " + FBTime + " Minutes");		
			} else if (FBTime < 30) {
				document.getElementById("ajaxFrostWarn").innerHTML = "Warning - Frostbite Can Occur Within " + FBTime + " Minutes on Unprotected Skin";
			}
		} else {
			document.getElementById("ajaxFBhead").innerHTML = "Cloud Potential:";
			var cloudheight = clientraw[73];
			set_ajax_obs("ajaxFB",convertHeight(cloudheight) + " ft");			
		}
*/

		if (maxupdates > 0 && updates > maxupdates-1) { // chg indicator to pause message 
			set_ajax_obs("ajaxindicator","<b>Paused (Refresh)</b>");			
		} 

 	  } // END if(clientraw[0] = '12345' and '!!' at end)
	 } // END if (x.readyState == 4 && x.status == 200)
    } // END try
   	catch(e){}  // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE
    } // END x.onreadystatechange = function() {
    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 
	if ( (maxupdates == 0) || (updates < maxupdates-1)) {
      setTimeout("ajaxLoader(clientrawFile + '?' + new Date().getTime())", reloadTime); // get new data 
    }
  }
  
} else { // window not focused
	setTimeout("ajaxLoader(clientrawFile + '?' + new Date().getTime())", reloadTime); // get new data 
}
  
} // end ajaxLoader function

// FrostbiteTime
// version: 1.1
// date: 6 Jan 2011
// author: WIEST
//
// Function to return Time to Frostbite in minutes.
//
// Parameters:
//
// FBScale - Use "F" for Fahrenheit/mph, or "C" for Celsius/kph
// FBtemp - Temperature in the scale selected by FBScale
// FBwind - Wind speed in the scale selected by FBScale
//
// Return Values:
//
// If the temperature is between -50F and 10F with a wind speed
// between 0 mph and 50 mph, or -15C and -50C with a wind speed
// between 0 kph and 80 kph, the returned value will be the
// calculated potential time to Frostbite.
//
//  0 = Not calculated or Out of Range
// -1 = Little or no Frostbite risk
//
// Frostbite times obtained from the charts at:
// http://www.ofcm.gov/jagti/r19-ti-plan/pdf/03_chap3.pdf
//
// Version history:
// 1.0  4 Jan 2011 first version
// 1.1  6 Jan 2011 added -10C, changed "out of range" return value to 0
//


function FrostbiteTime( FBScale, FBtemp, FBwind ) {

  var FBTarray = new Array();
  FBtemp = Number(FBtemp);
  FBtemp = Math.round((FBtemp+50) / 5);
  if ( FBScale=="F" ) {
    FBwind = Math.round((FBwind / 5 ) -1 );
  } else {
    FBwind = Math.round((FBwind / 10 ) -1 );
  }

  if (( FBScale=="F" ) && ( FBtemp <= 13 ) && ( FBtemp >= 0 ) && ( FBwind <= 9 )) {

    FBTarray[0] = new Array( 7, 8, 9, 11, 12, 14, 17, 22, 31, 180, 180, 180, 180 );
    FBTarray[1] = new Array( 5, 6, 7, 7, 9, 10, 12, 15, 19, 28, 180, 180, 180 );
    FBTarray[2] = new Array( 4, 4, 5, 6, 7, 8, 9, 12, 15, 20, 33, 180, 180);
    FBTarray[3] = new Array( 3, 4, 4, 5, 6, 8, 8, 9, 12, 16, 23, 180, 180 );
    FBTarray[4] = new Array( 3, 3, 4, 4, 5, 6, 7, 8, 10, 13, 19, 42, 180 );
    FBTarray[5] = new Array( 2, 3, 3, 4, 4, 5, 6, 7, 9, 12, 16, 28, 180 );
    FBTarray[6] = new Array( 2, 2, 3, 3, 4, 4, 5, 6, 8, 10, 14, 23, 180 );
    FBTarray[7] = new Array( 2, 2, 2, 3, 3, 4, 5, 6, 7, 9, 13, 20, 180 );
    FBTarray[8] = new Array( 2, 2, 2, 3, 3, 4, 4, 5, 7, 8, 12, 18, 180 );
    FBTarray[9] = new Array( 2, 2, 2, 2, 3, 3, 4, 5, 6, 8, 11, 16, 180 );

    FBTreturn = FBTarray[FBwind][FBtemp];
  }
  else if (( FBScale=="C" ) && ( FBtemp <= 9 ) && ( FBtemp >= 0 ) && ( FBwind <= 7 )) {

    FBTarray[0] = new Array( 6, 7, 8, 11, 15, 22, 180, 180, 180 );
    FBTarray[1] = new Array( 4, 5, 6, 7, 10, 14, 180, 180, 180 );
    FBTarray[2] = new Array( 3, 4, 4, 6, 8, 11, 18, 180, 180 );
    FBTarray[3] = new Array( 2, 3, 4, 5, 6, 9, 14, 42, 180 );
    FBTarray[4] = new Array( 2, 2, 3, 4, 5, 8, 12, 27, 180 );
    FBTarray[5] = new Array( 2, 2, 3, 3, 5, 7, 10, 22, 180 );
    FBTarray[6] = new Array( 2, 2, 2, 3, 4, 6, 9, 18, 180 );
    FBTarray[7] = new Array( 1, 2, 2, 3, 4, 5, 8, 16, 180 );

    FBTreturn = FBTarray[FBwind][FBtemp];
  }

  else { if ( FBScale == "F" || "C" ) { FBTreturn = 0; } }

  if (FBTreturn == 180) { FBTreturn = -1; }
  return FBTreturn;
}

function FrostbiteTime2( FBScale, FBtemp, FBwind ) {

  if ( FBTScale == "F" ) {
    FBT2 = ((-24.5 * ((0.667 * ((FBTwind * 8) / 5)) + 4.8)) + 2111) * (Math.pow(-4.8 - (((FBTtemp - 32) * 5) / 9),-1.668));
  } else if ( FBTScale == "C" ) {
    FBT2 = ((-24.5 * ((0.667 * FBTwind) + 4.8)) + 2111) * (Math.pow(-4.8 - FBTtemp,-1.668));
  }

  return Math.round(FBT2);
}

function min2hours(minutes) {
	var hours = minutes/60;
	hours = Math.floor(hours);
	minutes = minutes - (hours * 60); 
	if (minutes < 10){
		minutes = "0" + minutes;
	}
	if (hours == 24) {
		hours = "00";	
	}	
	return hours + ":" + minutes;
}

function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}

function UCWords(instr) {
	var doneStr = '';
	var len = instr.length;
	var wordIdx = 0;
	var ch;
	for (var i = 0;i < len;i++) {
		ch = instr.substring(i,i + 1);
		if (' -/#$&'.indexOf(ch) > -1) {
			wordIdx = -1;
		}
		if (wordIdx == 0) {
			ch = ch.toUpperCase();
		} else if (wordIdx > 0) {
			ch = ch.toLowerCase();
		}
		doneStr += ch;
		wordIdx++;
	}
	return doneStr;
}



// ------------------------------------------------------------------------------------------
//  Second Loader for wdtag.txt info
//  Credit to Tom Chaplin from carterlake.org for the second loader concept and most of the handlers.
// ------------------------------------------------------------------------------------------
function ajaxLoader2(url) {
if (windowFocused) {		
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
  }
  //if (x) { // got something back
// If we have a valid clientraw file AND updates is < maxupdates
	if (x && ( updates <= maxupdates || maxupdates > 0  )) { // got something back
    x.onreadystatechange = function() {
    try { if (x.readyState == 4 && x.status == 200) { // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE 
	    var wdtags = x.responseText.split(' '); 

		//Time ...
		set_ajax_obs("ajaxgetrawtime", x.responseText.split('|')[1]);

		//Time last tip ...
		var tiptime = ' Last at ' + x.responseText.split('|')[43];
		tiptime = tiptime.replace( " Last at -" , "");
		set_ajax_obs("ajaxtimeoflastrain", tiptime);
		
		//Storm Rain
		var stormrain = parseFloat(x.responseText.split('|')[89]);
		if (stormrain != 0) {
		set_ajax_obs("ajaxstorm", '<br/>' + stormrain.toFixed(2) + ' <span style="font-size: x-small"> in. Last 24 hrs</span>');
		} 	
		
		//Rain days
		set_ajax_obs("ajaxraindays", x.responseText.split('|')[44]);		

		//Rain last hour
		//set_ajax_obs("ajaxrainhour", x.responseText.split('|')[33] + ' /hr');

		//Rain last 3 hours
		var threehour = parseFloat(x.responseText.split('|')[45]);
		set_ajax_obs("ajaxrain3hour", threehour.toFixed(2));
		
		//Temp day high low
		var timelower = x.responseText.split('|')[17].toLowerCase();
		var tempday = parseFloat(x.responseText.split('|')[16]);
		set_ajax_obs("ajaxtempdayhigh", tempday.toFixed(1) + ' &deg;F at ' + timelower);
		timelower = x.responseText.split('|')[19].toLowerCase();
		tempday = parseFloat(x.responseText.split('|')[18]);
		set_ajax_obs("ajaxtempdaylow", tempday.toFixed(1) + ' &deg;F at ' + timelower);
		
		//Temp trend 2 hour
		var temptrend = parseFloat(x.responseText.split('|')[5]) - parseFloat(x.responseText.split('|')[28]);
		if (temptrend > 0) {
			temptrend = "+" + temptrend.toFixed(1);
		} else if (temptrend < 0) {
			temptrend = temptrend.toFixed(1);
		} else {
			temptrend = "+" + temptrend.toFixed(1);
		}
		set_ajax_obs("ajaxtemptrend2hour", temptrend);

		//Humidity day high low
		var timelower = x.responseText.split('|')[21].toLowerCase();
		var humday = parseFloat(x.responseText.split('|')[20]);
		set_ajax_obs("ajaxhumdayhigh", humday .toFixed(0) + '% at ' + timelower);
		timelower = x.responseText.split('|')[23].toLowerCase();
		humday = parseFloat(x.responseText.split('|')[22]);
		set_ajax_obs("ajaxhumdaylow", humday.toFixed(0) + '% at ' + timelower);
		
		//Humidity trend 
		var humtrend = x.responseText.split('|')[15] - x.responseText.split('|')[26];
		
		var element = document.getElementById("ajaxhumtrendgraphic");
		if (element ) { 
			if (humtrend > 0) {
				humtrend = "+" + humtrend.toFixed(0);
				document.getElementById("ajaxhumtrendgraphic").innerHTML = '&nbsp;<img src=\"/images/rising.gif\" height=\"8\" width=\"7\" alt="Humidity Rising" title="Humidity Rising">';
			} else if (humtrend < 0) {
				humtrend = humtrend.toFixed(0);
				document.getElementById("ajaxhumtrendgraphic").innerHTML = '&nbsp;<img src=\"/images/falling.gif\" height=\"8\" width=\"7\" alt="Humidity Falling" title="Humidity Falling">';
			} else {
				humtrend = "+" + humtrend.toFixed(0);
				document.getElementById("ajaxhumtrendgraphic").innerHTML = '';
			}
			set_ajax_obs("ajaxhumtrend", humtrend);
		}
		
		//Humidity trend 2 hour
		humtrend = parseFloat(x.responseText.split('|')[15]) - parseFloat(x.responseText.split('|')[29]);
		if (humtrend > 0) {
			humtrend = "+" + humtrend.toFixed(0);
		} else if (humtrend < 0) {
			humtrend = humtrend.toFixed(0);
		} else {
			humtrend = "+" + humtrend.toFixed(0);
		}
		set_ajax_obs("ajaxhumtrend2hour", humtrend);

		
		//Pressure day high low
		var timelower = x.responseText.split('|')[33].toLowerCase();
		var pressday = parseFloat(x.responseText.split('|')[32]);
		set_ajax_obs("ajaxpressdayhigh", pressday .toFixed(1) + ' mb at ' + timelower);
		timelower = x.responseText.split('|')[35].toLowerCase();
		pressday = parseFloat(x.responseText.split('|')[34]);
		set_ajax_obs("ajaxpressdaylow", pressday.toFixed(1) + ' mb at ' + timelower);
		
		//Pressure trend 1 hour
		var presstrend2 = parseFloat(x.responseText.split('|')[37]) - parseFloat(x.responseText.split('|')[27]);
		if (presstrend2 > 0) {
			presstrend2 = "+" + presstrend2.toFixed(1);
		} else if (presstrend2 < 0) {
			presstrend2 = presstrend2.toFixed(1);
		} else {
			presstrend2 = "+" + presstrend2.toFixed(1);
		}
		set_ajax_obs("ajaxpresstrend", presstrend2);		
		
				
		//Pressure trend 2 hour
		presstrend2 = parseFloat(x.responseText.split('|')[37]) - parseFloat(x.responseText.split('|')[30]);
		if (presstrend2 > 0) {
			presstrend2 = "+" + presstrend2.toFixed(1);
		} else if (presstrend2 < 0) {
			presstrend2 = presstrend2.toFixed(1);
		} else {
			presstrend2 = "+" + presstrend2.toFixed(3);
		}
		set_ajax_obs("ajaxpresstrend2hour", presstrend2);		

		
		//Wind Trend
		var w1 = parseFloat(x.responseText.split('|')[38]);
		var w2 = parseFloat(x.responseText.split('|')[39]);
		var w3 = parseFloat(x.responseText.split('|')[40]);
		var w4 = parseFloat(x.responseText.split('|')[41]);
		if (w1 == '-') {w1 = 0;}
		if (w2 == '-') {w2 = 0;}
		if (w3 == '-') {w3 = 0;}
		if (w4 == '-') {w4 = 0;}		

		var windtrendhour = ((w1 + w2 + w3 + w4) / 4) - (parseFloat(x.responseText.split('|')[42]));
		if (windtrendhour > 0) {
			windtrendhour = ("+" + windtrendhour.toFixed(0));
		} else {
			windtrendhour = 0;
			//windtrendhour = windtrendhour.toFixed(0); //Leave alone .. already has "-"
		}
		set_ajax_obs("ajaxwindtrendhour", windtrendhour);

		
//  Solar
		var timelower = x.responseText.split('|')[47].toLowerCase();
		var solarwm = parseFloat(x.responseText.split('|')[46]);
		set_ajax_obs("ajaxsolardayhigh", solarwm .toFixed(1) + ' W/m2 at ' + timelower);

//Solar Trend
		solarwm = parseFloat(x.responseText.split('|')[73]);
		if (solarwm > 0) {
			avewm = ( parseFloat(x.responseText.split('|')[73]) + parseFloat(x.responseText.split('|')[74]) + parseFloat(x.responseText.split('|')[75]) + parseFloat(x.responseText.split('|')[76]) + parseFloat(x.responseText.split('|')[77]) ) / 5;
			set_ajax_obs("ajaxsolararrow",
			   ajax_genarrow(solarwm, avewm, '', 					 
				 'Rising %s W/m2',
				 'Falling %s W/m2', 1)
				 );	
		} else {
			set_ajax_obs("ajaxsolararrow","");
		}
		
// Evapo for solar line on index page
		var evapoday = x.responseText.split('|')[50];		
		set_ajax_obs("ajaxevapoday",evapoday);
		var evapomonth = x.responseText.split('|')[51];
		set_ajax_obs("ajaxevapomonth",evapomonth);		
		
//UV
		var timelower = x.responseText.split('|')[67].toLowerCase();
		var uv = parseFloat(x.responseText.split('|')[66]);
		set_ajax_obs("ajaxuvdayhigh", uv .toFixed(1) + ' uvi at ' + timelower);
		set_ajax_obs("ajaxburntime",x.responseText.split('|')[70]);

//UV Trend
		uv = parseFloat(x.responseText.split('|')[78]);
		if (uv > 0) {
			var aveuv = ( parseFloat(x.responseText.split('|')[78]) + parseFloat(x.responseText.split('|')[79]) + parseFloat(x.responseText.split('|')[80]) + parseFloat(x.responseText.split('|')[81]) + parseFloat(x.responseText.split('|')[82]) ) / 5;
			set_ajax_obs("ajaxuvarrow",
			   ajax_genarrow(uv, aveuv, '', 
				 'Rising %s UVI',
				 'Falling %s UVI',1)
				 );	
		} else {
			set_ajax_obs("ajaxuvarrow","");
		}

// Dew Point Trend
		var dp = parseFloat(x.responseText.split('|')[83]);
		var avedp = ( parseFloat(x.responseText.split('|')[83]) + parseFloat(x.responseText.split('|')[84]) + parseFloat(x.responseText.split('|')[85]) + parseFloat(x.responseText.split('|')[86]) + parseFloat(x.responseText.split('|')[87]) ) / 5;
		set_ajax_obs("ajaxdparrow",
		   ajax_genarrow(dp, avedp, '', 
			 'Rising %s &deg;F',
			 'Falling %s &deg;F',1)
			 );	

		//Wetbulb
		var wetbulb = parseFloat(x.responseText.split('|')[52]);
		set_ajax_obs("ajaxwetbulb", wetbulb.toFixed(1));


/*
		var dawndusk = x.responseText.split(' ')[49];
		dawndusk = dawndusk.substr(0,4);
		if (dawndusk == "Dawn") {
			
			set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(36));
		} else if (dawndusk == "Dusk") {
			
			set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(37));
		} else {
			set_ajax_obsT("ajaxconditionicon", ajax_wxIcon(x.responseText.split(' ')[48]));
		}	
*/		


//set_ajax_obsT("ajaxdebug", ".");
/*
		//Header Weather Conditions  -  Requires "include metar cloud conditions at night" set in the solar section
		var sdesc = x.responseText.split('|')[1];   // solardescription
		sdesc = sdesc.replace("Fog",'Sky Obscured');		
		sdesc = sdesc.replace("/Dry",'');
		sdesc = sdesc.replace("Dry",'');		
		sdesc = sdesc.replace("/Humid",'');		
		sdesc = sdesc.replace("/Drizzle",'');
		sdesc = sdesc.replace("/Light Rain",'');
		sdesc = sdesc.replace("/Moderate Rain",'');		
		sdesc = sdesc.replace("/Recent Showers",'');
		sdesc = sdesc.replace("/Stopped Raining",'');
		sdesc = sdesc.replace("/Heavy Thunderstorm",'');		
		sdesc = sdesc.replace("/Fog",'');
		sdesc = sdesc.replace("/Snow",'');	
		sdesc = sdesc.replace("Night/",'');	
		sdesc = sdesc.replace("mostly_cloudy",'Mostly Cloudy');	
		sdesc = sdesc.replace("mostly cloudy",'Mostly Cloudy');	
		
		sdesc = sdesc.replace(" -",'');
		sdesc = sdesc.replace(/\//g,'#');
//		set_ajax_obs("ajaxdebug",sdesc + "x");

		
		if (sdesc.indexOf('#') != -1) {                      //Must be night so there's a weather conition there
			var stringarr = sdesc.split("#"); 
			var first = stringarr[0];
			var second = stringarr[1];
			//tester = second.toLowerCase();
			var tester = second.toLowerCase().replace(/^\s+|\s+$/g, '');
			tester = trim(tester);
			//set_ajax_obs("ajaxdebug","(" + tester + ")");
			
			switch (tester) {
				case "obscurred":                    // obscurred
					second = "Foggy";
					break;
				case "cloudy with clear p":          // Cloudy with clear p 
					second = "Mostly Cloudy";
					break;
				case "cloudy with clear patches":          // Cloudy with clear patches 
					second = "Mostly Cloudy";
					break;
				case "sc":                           // Night/Sc   Now Works
					second = "Partly Cloudy";
					break;
				case "scattered clouds":              // Scattered clouds
					second = "Partly Cloudy";
					break;					
				case "a few clouds":                 // A few clouds
					second = "Partly Cloudy";
					break;
				case "clear skies":                  // Clear skies       
					second = "Clear";
					break;
				case "obscured - precipit":          // obscured - precipit        
					second = "Mist";            
					break;
				case "overcast - precipit":          // overcast - precipit        
					second = "Mist";            
					break;
				case "Dry":          // overcast - precipit        
					second = "";            
					break;
					
				//default : second = "Clouds";
			endswitch;
			} // end swith statement
			if (second == "") {
				sdesc = first;  
			} else {
				sdesc = first + " , " + second;
			}
		} // end if statement
*/		
		var beaufort = ajax_get_beaufort(x.responseText.split('|')[58]);
		
		var metvis = x.responseText.split('|')[4];
        if (metvis.substr(metvis.length-3,1) == "("){  //This just because Brian often leaves it off
			metvis = trim(metvis) + "s)";
	    }
/*		
		var Precip = x.responseText.split('|')[3];
		if (Precip.indexOf("Dry") != -1) {
			Precip = "";
		} else {
			Precip = Precip + " , ";
		}

		var metcond = x.responseText.split('|')[130];
		if ((metcond.indexOf("mist") != -1) && (Precip.indexOf("Dry") != -1)) {
			Precip = "Mist , ";
		}
		if ((metcond.indexOf("snow") != -1) && (metcond.indexOf("ground") < 1)) {
			Precip = "Snow , ";
		}

		if (sdesc.length > 2) {     // apparently isn't ""
			sdesc = sdesc + " , ";	
		}
*/		

//get_TextFileData("yowindow-xml-test.php?send=direct", "|", yoarray);

// afab

		
//		var finalstr = yoarray[5] + " , " + x.responseText.split('|')[2] + " , " + beaufort + " & Visibility " + UCWords(metvis);
		
//		set_ajax_obsT("ajaxfirstline", finalstr);
		
url = "yowindow-xml-plus.php?send=direct";

var yo = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
if (yo) { 
	yo.onreadystatechange = function() {
		try { if (yo.readyState == 4 && yo.status == 200) { 
				yoarray = yo.responseText.split("|"); 
				set_ajax_obsT("ajaxconditionicon", "<img src=\"rainer/small/" + yoarray[1] + "\" " + "width=\"31\" height=\"25\" alt=\"Current condition icon\" />" );				
				set_ajax_obsT("ajaxfirstline", yoarray[10]);				
		} 	
		} catch(e){}  
	} 
	yo.open("GET", url, true);
	yo.send(null);
}
//    return ("<img src=\"" + imagedir + "/" + iconList[iconWD] + "\" " +
//				"width=\"25\" height=\"25\" alt=\"Current condition icon\" />" );
		// cloud height/ frostbite time   137 & 138
		var TempF = x.responseText.split('|')[137];
		var WindMph = x.responseText.split('|')[138];
		var FBTime = FrostbiteTime( "F", TempF, WindMph);
//set_ajax_obsT("ajaxdebug", TempF + " - " + WindMph);		
		if (FBTime > 0) {
			document.getElementById("ajaxFBhead").innerHTML = "Frostbite Time:";
			set_ajax_obs("ajaxFB",FBTime + " Minutes");	
			if (FBTime < 45) {
				document.getElementById("ajaxFrostWarn").innerHTML = "Caution - Frostbite Can Occur Within " + FBTime + " Minutes on Unprotected Skin";
			} else if (FBTime < 15) {
				document.getElementById("ajaxFrostWarn").innerHTML = "Warning - Frostbite Can Occur Within " + FBTime + " Minutes on Unprotected Skin";
			}
		} else {
			document.getElementById("ajaxFBhead").innerHTML = "Cloud Potential:";
			var cloudheight = clientraw[73];
			set_ajax_obs("ajaxFB",convertHeight(cloudheight) + " ft");			
		}

//set_ajax_obsT("ajaxdebug", ".");
		
		   
    } // END if (x.readyState == 4 && x.status == 200)
	} // END try
	catch(e){}  // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE
    } // x.onreadystatechange = function()
    x.open("GET", url, true);
    x.send(null);
	setTimeout("reset_ajax_color('')",flashtime); // change text back to default color 
	if ( (maxupdates == 0) || (updates < maxupdates-1)) {
      setTimeout("ajaxLoader2(tagsFile + '?' + new Date().getTime())", reloadTags); // get new data 
    }
  }  // end of 'got something back'
} else { // window not focused
	setTimeout("ajaxLoader2(tagsFile + '?' + new Date().getTime())", reloadTags); // get new data 
}  
} // end ajaxLoader2 function


function update_map( name, value ) {
		var element = document.getElementById(name);
		if (! element ) { return; }  
		document.getElementById(name).src = value;	
}

// Third loader just for refreshing images.  Credit to Tom Chaplin from carterlake.org for developing this technique
function ajaxLoaderR(url) {
if (windowFocused) {		
  if (document.getElementById) {
    var y = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
  }
  //if (y) { // got something back
  if (y && ( updates <= maxupdates || maxupdates > 0  )) { // got something back  
    y.onreadystatechange = function() {
			update_map("ajaxgr3","/gr3/animatedgr3.gif"+"?"+new Date());
			update_map("ajaxbr","/gr3/mbr1_0.jpg"+"?"+new Date());
			update_map("ajaxet","/gr3/met_0.jpg"+"?"+new Date());
			update_map("ajaxsrv","/gr3/msrv1_0.jpg"+"?"+new Date());
			update_map("ajaxohr","/gr3/mohr_0.jpg"+"?"+new Date());
			update_map("ajaxstr","/gr3/mstr_0.jpg"+"?"+new Date());
			update_map("ajaxnational","http://www.strikestarus.com/FREE/strikestar60.png"+"?"+new Date());
			update_map("ajaxregional","http://www.strikestarus.com/FREE/NCUS60.png"+"?"+new Date());
			//update_map("ajaxlcllight","/lightning/nexstorm.png"+"?"+new Date());
			update_map("ajaxsmalllight","/lightning/resize-nexstorm-png.php"+"?"+new Date());
			update_map("ajaxwasp2","/lightning/showwasp.htm"+"?"+new Date());
//			update_map("ajaxwasp2","/lightning/wasp2.png"+"?"+new Date());
			//update_map("ajax24","curr24hourgraph.gif"+"?"+new Date());
			//update_map("ajax72","curr72hourgraph.gif"+"?"+new Date());
			update_map("ajaxficon","forecasticon.gif"+"?"+new Date());
			update_map("ajaxsmallgr3","/gr3/smallgr3.php"+"?"+new Date());
			update_map("ajaxswebcam","/camera/swebcam.php"+"?"+new Date());
			update_map("ajaxbwebcam","/camera/1.jpg"+"?"+new Date());
			update_map("ajaxsolar","vprealtimegraph.gif"+"?"+new Date());
			update_map("ajaxbiggraph","frgraph.jpg"+"?"+new Date());
//			update_map("sunpathgraph","sunpath.php"+"?"+new Date());
			

    } // end of function

    y.open("GET", url, true);
    y.send(null);
	if ( (maxupdates == 0) || (updates < maxupdates-1)) {
      setTimeout("ajaxLoaderR(dummyFile + '?' + new Date().getTime())", reloadRadars); // get new data 
    }
  } // end got something back
} else { // window not focused
	setTimeout("ajaxLoaderR(dummyFile + '?' + new Date().getTime())", reloadRadars); // get new data 
}  
} // end ajaxLoaderR function


// This function just for NSLog Lightning Data
function ajaxLoaderL(url) {
	var rate = "Normal";
if (windowFocused) {			
  if (document.getElementById) {
    var z = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
  }
	if (z && ( updates <= maxupdates || maxupdates > 0  )) { // got something back
    z.onreadystatechange = function() {
    try { if (z.readyState == 4 && z.status == 200) { // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE 
	    var realtime = z.responseText.split(','); 

		var lightcounts = realtime[24];
//		var lightdist = realtime[7];
//		var lightdirec = lightningDir (realtime[6]);
		var lightdist = realtime[45];
		var lightdirec = lightningDir (realtime[44]);
		
		if (lightcounts > 1) {                    // Increase this to a significant level
//			set_ajax_obsT("ajaxlightning", "Activity " + lightcounts + "/min  " + lightdirec + " @ " + lightdist + " mi " );
			
			set_ajax_obsT("ajaxlightning", "Activity " + lightdist + " mi " + lightdirec + " at " + lightcounts + "/min" );
		} else {
			set_ajax_obsT("ajaxlightning", realtime[15]  + " Strikes Since Midnight");
		}
		rate = realtime[39];
    } // END if (x.readyState == 4 && x.status == 200)
	} // END try
	catch(e){}  // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE
    } // x.onreadystatechange = function()
    z.open("GET", url, true);
    z.send(null);
	setTimeout("reset_ajax_color('')",flashtime); // change text back to default color 
	if ( (maxupdates == 0) || (updates < maxupdates-1)) {
		if (rate == "High") {
      		setTimeout("ajaxLoaderL('NSRealtime.txt?' + new Date().getTime())", 5000); // get new data every 5 seconds
		} else {
      		setTimeout("ajaxLoaderL('NSRealtime.txt?' + new Date().getTime())", 15000); // get new data every 15 seconds
		}	  
    }
  }  // end of 'got something back'
  
} else { // window not focused
	setTimeout("ajaxLoaderL('NSRealtime.txt?' + new Date().getTime())", 5000); // get new data every 5 seconds
}
  
} // end ajaxLoaderL function

// invoke when first loaded on page
//if (! ajaxLoaderInBody) { ajaxLoader(clientrawFile + '?' + new Date().getTime()); ajaxLoader2(tagsFile + '?' + new Date().getTime()); ajaxLoaderR(dummyFile + '?' + new Date().getTime());}
if (! ajaxLoaderInBody) { ajaxLoader(clientrawFile + '?' + new Date().getTime()); ajaxLoader2(tagsFile + '?' + new Date().getTime()); ajaxLoaderR(dummyFile + '?' + new Date().getTime());ajaxLoaderL('NSRealtime.txt?' + new Date().getTime());}

//setTimeout("runSlideShow2()",5000)
// ]]>
