// <![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
//     for his streamlined version of getUVrange.
// --- Version 2.01 - 17-Dec-2006 -- Corrected cloud height calculation
// --- Version 2.02 - 20-Dec-2006 -- added unescape to set_ajax_obs comparison for lastobs
// --- Version 2.03 - 07-Jan-2006 -- added wind m/s or km/h for metric variables
// --- Version 2.04 - 08-Jan-2006 -- use epoch time for get (thanks to johnnywx on WD forum)
//                                   so a numeric time without HTMLencoded characters is used
// --- Version 2.05a - 30-Jan-2006 -- added new 'anti-NaN' check from johnnywx to make sure full
//                                   clientraw.txt is read by looking for
//                                   '12345' at start and '!!' at end of record
//
// 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 flashcolor  = '#FF0000'; // color to flash for changed observations RGB
var flashtime   = 2000;    // miliseconds to keep flash color on (2000 = 2 seconds);
var reloadTime  = 6000;      // reload AJAX conditions every 6 seconds (= 6000 ms)
var reloadTime2 = 120000;      // reload AJAX conditions every 150 seconds (= 150000 ms)
var clientrawFile = '../../wd/clientraw.txt'; // location of clientraw.txt relative to this page on website
var clientrawFile2 = '../../wd/customclientraw.txt'; // location of wx38.html relative to this page on website
//var clientrawFile2 = '/estmeteo/wd/customclientraw.txt'; // location of wx38.html relative to this page on website
var ajaxLoaderInBody = true; // set to true if you have <body onload="ajaxLoader(..."
var ajaxLoaderInBody2 = true; // set to true if you have <body onload="ajaxLoader(..."
var imagedir = '../../ajax-images';  // place for wind arrows, rising/falling arrows, etc.
var altitude = 481;		// altitude in meters.
var runway = 40;		// lowest runway in magnetic degrees

var useunits = 'M';         // 'E'=USA(English) or 'M'=Metric
var useKnots = true;       // set to true to use wind speed in Knots (otherwise 
							// wind in km/hr for Metric or mph for English will be used.
var useMPS   = false;       // set to true for meters/second for metric wind speeds, false= km/h
var showUnits = true;       //  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.  

var ie4=document.all;
var browser = navigator.appName;
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

// 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 uomSolar = ' w/m2';
var uomHeight = ' ft';
var dpBaro = 2;
var dpRain = 2;
var pi = 3.141592;


function ajax_set_units( units ) {
  useunits = units;
  if (useunits != 'E') { // set to metric
	uomTemp = ' &deg;C';
	uomWind = ' km/h';
	if(useMPS)   { uomWind = ' m/s'; }
	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") {
    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 != unescape(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='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
{
   $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 windDirfull ($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("North", "North-Northeast", "Northeast", "East-Northeast", "East", "East-Southeast", "Southeast", "South-Southeast", "South", "South-Southwest", "Southwest", "West-Southwest", "West", "West-Northwest", "Northwest", "North-Northwest");
   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
  $iconList = new Array(
	"day_clear.gif",           //  0 imagesunny.visible
	"night_clear.gif",         //  1 imageclearnight.visible
	"day_partly_cloudy.gif",   //  2 imagecloudy.visible
	"day_partly_cloudy.gif",   //  3 imagecloudy2.visible
	"night_partly_cloudy.gif", //  4 imagecloudynight.visible
	"day_clear.gif",           //  5 imagedry.visible
	"fog.gif",                 //  6 imagefog.visible
	"haze.gif",                //  7 imagehaze.visible
	"day_heavy_rain.gif",      //  8 imageheavyrain.visible
	"day_mostly_sunny.gif",    //  9 imagemainlyfine.visible
	"mist.gif",                // 10 imagemist.visible
	"fog.gif",                 // 11 imagenightfog.visible
	"night_heavy_rain.gif",    // 12 imagenightheavyrain.visible
	"night_cloudy.gif",        // 13 imagenightovercast.visible
	"night_rain.gif",          // 14 imagenightrain.visible
	"night_light_rain.gif",    // 15 imagenightshowers.visible
	"night_snow.gif",          // 16 imagenightsnow.visible
	"night_tstorm.gif",        // 17 imagenightthunder.visible
	"day_cloudy.gif",          // 18 imageovercast.visible
	"day_partly_cloudy.gif",   // 19 imagepartlycloudy.visible
	"day_rain.gif",            // 20 imagerain.visible
	"day_rain.gif",            // 21 imagerain2.visible
	"day_light_rain.gif",      // 22 imageshowers2.visible
	"day_sleet.gif",           // 23 imagesleet.visible
	"day_sleet.gif",           // 24 imagesleetshowers.visible
	"day_snow.gif",            // 25 imagesnow.visible
	"day_snow.gif",            // 26 imagesnowmelt.visible
	"day_snow.gif",            // 27 imagesnowshowers2.visible
	"day_clear.gif",           // 28 imagesunny.visible
	"day_tstorm.gif",          // 29 imagethundershowers.visible
	"day_tstorm.gif",          // 30 imagethundershowers2.visible
	"day_tstorm.gif",          // 31 imagethunderstorms.visible
	"tornado.gif",             // 32 imagetornado.visible
	"windy.gif",               // 33 imagewindy.visible
	"day_partly_cloudy.gif"    // 34 stopped rainning
	);					

  if (iconWD >= 0 && iconWD <= 34) { 
    return ("<img src=\"" + imagedir + "/" + $iconList[iconWD] + "\" " +
				"width=\"25\" height=\"25\" alt=\"Present conditions 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 {  
	    if (useMPS) { // convert knots to m/s
		  return (rawwind * 0.514444444);
		} 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"); }
  if (wind < 4 ) {return("Light Air"); }
  if (wind < 7 ) {return("Light Breeze"); }
  if (wind < 11 ) {return("Gentle Breeze"); }
  if (wind < 17 ) {return("Moderate Breeze"); }
  if (wind < 22 ) {return("Fresh Breeze"); }
  if (wind < 28 ) {return("Strong Breeze"); }
  if (wind < 34 ) {return("Moderate Gale"); }
  if (wind < 41 ) {return("Fresh Gale"); }
  if (wind < 48 ) {return("Strong Gale"); }
  if (wind < 56 ) {return("Storm"); }
  if (wind < 64 ) {return("Violent Storm"); }
  if (wind >= 64 ) {return("Hurricane"); }
  return("Unknown " + wind);
}

function ajax_get_force ( wind ) { 
// return a number for the beaufort force scale based on wind knots (native WD format)
  if (wind < 1 ) {return("F0"); }
  if (wind < 4 ) {return("F1"); }
  if (wind < 7 ) {return("F2"); }
  if (wind < 11 ) {return("F3"); }
  if (wind < 17 ) {return("F4"); }
  if (wind < 22 ) {return("F5"); }
  if (wind < 28 ) {return("F6"); }
  if (wind < 34 ) {return("F7"); }
  if (wind < 41 ) {return("F8"); }
  if (wind < 48 ) {return("F9"); }
  if (wind < 56 ) {return("F10"); }
  if (wind < 64 ) {return("F11"); }
  if (wind >= 64 ) {return("F12"); }
  return("Unknown " + wind);
}

function ajax_bfgraph ( wind ) { 
// Devuelve un vúmetro de intensidad de viento
  if (wind < 1 ) {return("<img src=\"" + imagedir + "/" + "bf0.gif\" + title=\"Force 0, Calm\" alt=\"Force 0, Calm\" />"); }
  if (wind < 4 ) {return("<img src=\"" + imagedir + "/" + "bf1.gif\" + title=\"Force 1, Light Air\" alt=\"Force 1, Light Air\"  />"); }
  if (wind < 7 ) {return("<img src=\"" + imagedir + "/" + "bf2.gif\" + title=\"Force 2, Light Breeze\" alt=\"Force 2, Light Breeze\"  />"); }
  if (wind < 11 ) {return("<img src=\"" + imagedir + "/" + "bf3.gif\" + title=\"Force 3, Gentle Breeze\" alt=\"Force 3, Gentle Breeze\"  />"); }
  if (wind < 17 ) {return("<img src=\"" + imagedir + "/" + "bf4.gif\" + title=\"Force 4, Moderate Breeze\" alt=\"Force 4, Moderate Breeze\"  />"); }
  if (wind < 22 ) {return("<img src=\"" + imagedir + "/" + "bf5.gif\" + title=\"Force 5, Fresh Breeze\" alt=\"Force 5, Fresh Breeze\"  />"); }
  if (wind < 28 ) {return("<img src=\"" + imagedir + "/" + "bf6.gif\" + title=\"WARNING: Force 6, Strong Breeze\" alt=\"WARNING: Force 6, Strong Breeze\"  />"); }
  if (wind < 34 ) {return("<img src=\"" + imagedir + "/" + "bf7.gif\" + title=\"WARNING: Force 7, Moderate Gale\" alt=\"WARNING: Force 7, Moderate Gale\"  />"); }
  if (wind < 41 ) {return("<img src=\"" + imagedir + "/" + "bf8.gif\" + title=\"WARNING: Force 8, Fresh Gale\" alt=\"WARNING: Force 8, Fresh Gale\"  />"); }
  if (wind < 48 ) {return("<img src=\"" + imagedir + "/" + "bf9.gif\" + title=\"DANGER !!: Force 9, Strong Gale\" alt=\"DANGER !!: Force 9, Strong Gale\"  />"); }
  if (wind < 56 ) {return("<img src=\"" + imagedir + "/" + "bf10.gif\" + title=\"DANGER !!: Force 10, Storm\" alt=\"DANGER !!: Force 10, Storm\"  />"); }
  if (wind < 64 ) {return("<img src=\"" + imagedir + "/" + "bf11.gif\" + title=\"DANGER !!: Force 11, Violent Storm\" alt=\"DANGER !!: Force 11, Violent Storm\"  />"); }
  if (wind >= 64 ) {return("<img src=\"" + imagedir + "/" + "bf12.gif\" + title=\"DANGER !!: Force 12, Hurricane\" alt=\"DANGER !!: Force 12, Hurricane\"  />"); }
  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.4) && (btrnd <= 0.4)) { return("Steady"); }
   if ((btrnd > 0.4) && (btrnd < 1.0)) { return("Rising slowly"); }
   if (btrnd >= 1.0) { return("Rising quickly"); }
   if ((btrnd < -0.4) && (btrnd > -1.0)) { return("Falling slowly"); }
   if (btrnd <= -1.0) { return("Falling quickly"); }
  return(btrnd);
}


function ajax_get_temptrend(ttrnd) {
   if ((ttrnd >= -0.2) && (ttrnd <= 0.2)) { return("Steady"); }
   if ((ttrnd > 0.2) && (ttrnd < 1.0)) { return("Rising slowly"); }
   if (ttrnd >= 1.0) { return("Rising quickly"); }
   if ((ttrnd < -0.2) && (ttrnd > -1.0)) { return("Falling slowly"); }
   if (ttrnd <= -1.0) { return("Falling quickly"); }
  return(ttrnd);
}


function ajax_getUVrange ( uv ) { // code simplified by FourOhFour on wxforum.net
   var uvword = "Not specified";
   if (uv <= 0) {
       uvword = "Nulo";
   } 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;Medium&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 degtorad (angle) {					// pasa grados a radianes
	rad = angle * (pi / 180);
	return rad;
}


function rwydesigner ( rwy ) {  			// convierte el rumbo de pista a su indicador
	designer = rwy / 10;
	if (designer < 10) {
		designer = "0" + designer;
	}
	return designer;
}

function ajax_getrunway ( dir, vel) { // Calcula la pista en servicio segun el viento
	
	lowend = runway - 90;
	if (lowend < 0) { lowend = 360 - Math.abs(lowend); }
	highend = runway + 90;	
	if (highend > 360) { highend = highend - 360; }		
	
	if (vel <= 3) {
       actrunway = "Either";
	} else {
		if (dir > lowend) {
			actrunway = rwydesigner(runway);
			}
		else if (dir < highend) {
			actrunway = rwydesigner(runway);
			}
			else {
				actrunway = rwydesigner(runway + 180);
				}
	}
	return actrunway;
} // end ajax_getrunway function


function ajax_getcrosswind ( dir, vel) {		// Calcula la componente de viento cruzado en pista

	// virtualwind = Math.abs(dir - runway);
	virtualwind = (dir - runway);
	if (virtualwind < 0) {
		virtualwind = virtualwind + 360;
	}
	
	// if (vel <= 3) {
	if (vel <=3 || (virtualwind < 30 || virtualwind > 330)) {  // si viento es menor de 3 nudos o el ángulo menor de 30 a cada lado de la pista en servicio
		crosswind = "---";
	} else {
		if (virtualwind >= 0 && virtualwind < 90) {
			angle = Math.abs(0 - virtualwind);
			angle = degtorad(angle);
			crossspeed = Math.sin(angle) * vel;
			crosswind = "Right crosswind " + crossspeed.toFixed(0) + uomWind;
		} else {
			if (virtualwind >= 90 && virtualwind < 180) {
				angle = Math.abs((90 - virtualwind) + 90);
				angle = degtorad(angle);
				crossspeed = Math.sin(angle) * vel;
				if (virtualwind > 150) {
					crosswind = "---";
				} else {
					crosswind = "Left crosswind " + crossspeed.toFixed(0) + uomWind;
				}
			} else {
				if (virtualwind >= 180 && virtualwind < 270) {
					angle = Math.abs(180 - virtualwind);
					angle = degtorad(angle);
					crossspeed = Math.sin(angle) * vel;
					if (virtualwind < 210) {
						crosswind = "---";
					} else {
						crosswind = "Right crosswind " + crossspeed.toFixed(0) + uomWind;
					}
				} else {
					angle = Math.abs((270 - virtualwind) + 90);
					angle = degtorad(angle);
					crossspeed = Math.sin(angle) * vel;
					crosswind = "Left crosswind " + crossspeed.toFixed(0) + uomWind;
				}
			}
		}
	}
	return crosswind;
} // end ajax_getcrosswind 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 = "<img src=\"" + imagedir + "/steady.gif\" alt=\"" + msg + 
	"\" title=\""+ msg + 
	"\" width=\"21\" height=\"24\" style=\"border: 0; margin: 1px 3px;\" />"; 
  } 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=\"21\" height=\"24\" 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=\"21\" height=\"24\" 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() {
 element = document.getElementById("ajaxcounter");
 if (element) {
  element.innerHTML = counterSecs;
  counterSecs++;
 }
}

// ------------------------------------------------------------------------------------------
//  Loader-1 main function.. read clientraw.txt and format <span class="ajax" id="ajax..."></span> areas
// ------------------------------------------------------------------------------------------
function ajaxLoader(url) {
  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) ) { // got it.. process clientraw.txt

		//Temperature
		temp = convertTemp(clientraw[4]);
		set_ajax_obs("ajaxtemp", temp.toFixed(1) + uomTemp);
		set_ajax_obs("ajaxbigtemp",temp.toFixed(1) + uomTemp);

		templast = convertTemp(clientraw[90]);
		set_ajax_obs("ajaxtemparrow", 
		   ajax_genarrow(temp, templast, '', 
			 '%s'+uomTemp+'  MORE than 1 hour ago.',
			 '%s'+uomTemp+'  LESS than 1 hour ago.',1)
		   );	
	    temprate = temp - templast;
		temprate = temprate.toFixed(1);
		if (temprate > 0.0) { temprate = '+' + temprate;} // add '+' for positive rates
		set_ajax_obs("ajaxtemprate",temprate + uomTemp + ' /hr');
		temptrendtxt = ajax_get_temptrend(temprate);
		set_ajax_obs("ajaxtemptrendtxt",temptrendtxt);  // tendencia en texto		

		tempmax = convertTemp(clientraw[46]);
		set_ajax_obs("ajaxtempmax",tempmax.toFixed(1) + uomTemp);

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

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

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

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

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

		// FeelsLike
		temp = clientraw[4]; // note.. temp in C
        if (temp <= 15.0 ) {
		  feelslike = clientraw[44]; //use WindChill
		} else if (temp >=20.0) {
		  feelslike = clientraw[112]; //use Heat Index
//		  feelslike = clientraw[45]; //use Humidex
		} else {
		  feelslike = temp;   // use temperature
		}
		feelslike  = Math.round(convertTemp(feelslike));
        set_ajax_obs("ajaxfeelslike",feelslike + uomTemp);
		
		// Apparent temperature
		apparenttemp = convertTemp(clientraw[130]);
		set_ajax_obs("ajaxapparenttemp",apparenttemp.toFixed(1) + uomTemp);
		apparenttempmin = convertTemp(clientraw[136]);
		set_ajax_obs("ajaxapparenttempmin",apparenttempmin.toFixed(1) + uomTemp);
		apparenttempmax = convertTemp(clientraw[137]);
		set_ajax_obs("ajaxapparenttempmax",apparenttempmax.toFixed(1) + uomTemp);
		
		//Pressure...
		pressure = convertBaro(clientraw[6]);
		set_ajax_obs("ajaxbaro",pressure.toFixed(dpBaro) + uomBaro);
		set_ajax_obs("ajaxbigbaro",pressure.toFixed(dpBaro) + uomBaro);
		pressuretrend = convertBaro(clientraw[50]);
		pressuretrend = pressuretrend.toFixed(dpBaro);
		trendtxt = ajax_get_barotrend(pressuretrend);
		set_ajax_obs("ajaxprestrendtxt",trendtxt);  // tendencia en texto
		if (pressuretrend > 0.0) {pressuretrend = '+' + pressuretrend; } // add '+' to rate
		set_ajax_obs("ajaxbarotrend",pressuretrend + uomBaro + " /hr");
		set_ajax_obs("ajaxbaroarrow",
		   ajax_genarrow(pressure, pressure-pressuretrend, '', 
			 'Rising at %s '+uomBaro+' per hour.',
			 'Falling at %s '+uomBaro+' per hour.',1)
			 );	
		
		set_ajax_obs("ajaxbarotrendtext",ajax_get_barotrend(clientraw[50]));
		
		qfe = convertBaro(clientraw[6]);
		qfe = qfe - (altitude/9);
		set_ajax_obs("ajaxqfe", qfe.toFixed(dpBaro) + uomBaro); 

		pressuremin = convertBaro(clientraw[132]);
		set_ajax_obs("ajaxbaromin",pressuremin.toFixed(dpBaro) + uomBaro);
		pressuremax = convertBaro(clientraw[131]);
		set_ajax_obs("ajaxbaromax",pressuremax.toFixed(dpBaro) + uomBaro);

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

		//Windspeed ...
		wind = convertWind(clientraw[2]);
		beaufort = ajax_get_beaufort(clientraw[2]);
		bigbeaufort = ajax_get_beaufort(clientraw[140]);
		force = ajax_get_force(clientraw[2]);
		bfgraph = ajax_bfgraph(clientraw[140]);
		set_ajax_obs("ajaxbeaufort",beaufort);
		set_ajax_obs("ajaxbigbeaufort",bigbeaufort);
		set_ajax_obs("ajaxforce",force);
		set_ajax_obs("ajaxbfgraph",bfgraph);

       //WIND DIRECTION ...
        val = windDir(clientraw[3]);
        valfull = windDirfull(clientraw[3]);
		set_ajax_obs("ajaxwinddirfull",valfull);
				
		winddirdeg = clientraw[3];// Luis: para tener la direccion del viento en grados
				
		//Poner ceros delante si es necesario
		if (winddirdeg < 10) {
			winddirdeg = "00" + winddirdeg + "º";
		} else {
			if (winddirdeg < 100) {
				winddirdeg = "0" + winddirdeg + "º";
			} else {
				winddirdeg = winddirdeg + "º";
			}
		}

		set_ajax_obs("ajaxwinddirdeg",winddirdeg);
		set_ajax_obs("ajaxbigwinddirdeg",winddirdeg);
		
		winddirdeg = clientraw[3];			// Luis: calculo de la pista en servicio segun el viento, y componente cruzada
		wind = convertWind(clientraw[2]);
		activerwy = ajax_getrunway(winddirdeg,wind);
		crosswnd = ajax_getcrosswind(winddirdeg,wind);
		set_ajax_obs("ajaxactiverwy",activerwy);
		set_ajax_obs("ajaxcrosswind",crosswnd);
		
		
       if (wind > 0.0) {
		set_ajax_obs("ajaxwind",wind.toFixed(1) + uomWind);
		set_ajax_uom("ajaxwinduom",true);
	   } else {
		set_ajax_obs("ajaxwind","0 kts");
		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","Calm");
		set_ajax_uom("ajaxgustuom",false);
	   }
	   
   	   if (gust > 0.0 || wind > 0.0) {
 		set_ajax_obs("ajaxwindicon","<img src=\"" + imagedir + "/" +  val + ".gif\" width=\"70\" height=\"70\" alt=\"Wind from " + 
		val + "\" title=\"Wind from " + val + "\" /> ");
		set_ajax_obs("ajaxwinddir",val);
	   } else {
 		set_ajax_obs("ajaxwindicon","<img src=\"" + imagedir + "/" + "calm.gif\" width=\"70\" height=\"70\" alt=\"Wind calm\" 				 		title=\"Wind calm\" /> ");
		set_ajax_obs("ajaxwinddir","");
	   }

		windmaxavg = convertWind(clientraw[113]);
		set_ajax_obs("ajaxwindmaxavg",windmaxavg.toFixed(1) + uomWind);
		
		
		//average wind speed in various units
        set_ajax_obs("ajaxwinddiravg",windDir(clientraw[117])); // Average Wind Direction last 10 mins
		windkts = clientraw[2] * 1.0;     // wind is in knots in clientraw[2]
		windmph = windkts  * 1.1507794;   // convert knots to mph
		windms  = windkts  * 0.514444444; // convert knots to m/s
		windkmh = windkts  * 1.852;       // convert knots to km/hr
		set_ajax_obs("ajaxwindkts",windkts.toFixed(0));
		set_ajax_obs("ajaxwindmph",windmph.toFixed(0));
		set_ajax_obs("ajaxwindms",windms.toFixed(1));
		set_ajax_obs("ajaxwindkmh",windkmh.toFixed(0));
		set_ajax_obs("ajaxbigwindkts",windkts.toFixed(0) + " kts");
		set_ajax_obs("ajaxbigwindkmh",windkmh.toFixed(0) + " km/h");
		// note: ajaxbeaufort already contains the Beaufort text

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

        solarpct = clientraw[34];
		set_ajax_obs("ajaxsolarpct",solarpct + "%");
		set_ajax_obs("ajaxbigsolarpct",solarpct + "%");
		
		// UV Index		
		uv       = clientraw[79];
		set_ajax_obs("ajaxuv",uv);
		set_ajax_obs("ajaxbiguv",uv);

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

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

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

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

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

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


		// 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);
		set_ajax_obs("ajaxbigtime",ajaxtimeformat);
		
		if (lastajaxtimeformat != ajaxtimeformat) {
			counterSecs = 0;                      // reset timer
			lastajaxtimeformat = ajaxtimeformat; // remember this time
		}
		
		// current condition icon and description
		set_ajax_obs("ajaxconditionicon",
			ajax_wxIcon(clientraw[48])
			);

		currentcond = clientraw[49];
		
		currentcond = currentcond.replace(/_/g,' ');
		currentcond = currentcond.replace(/\\/g,', ');
		currentcond = currentcond.replace(/\//g,' - ');
		currentcond = currentcond.replace(/\n/g,'');
		currentcond = currentcond.replace(/\r/g,'');
//		currentcond = currentcond.split("-",2);

		currentcond = currentcond.replace(/Soleado/g,'Sunny');
		currentcond = currentcond.replace(/Cielo cubierto/g,'Overcast');
		
		currentcond = currentcond.replace(/Tiempo seco/g,'Dry');
		currentcond = currentcond.replace(/Llovizna/g,'Drizzle');
		
		currentcond = currentcond.replace(/Bruma/g,'Haze');
		currentcond = currentcond.replace(/Viento/g,'Windy');


		set_ajax_obs("ajaxcurrentcond",currentcond);
		set_ajax_obs("ajaxbigcurrentcond",currentcond);
		
		// cloud height
		cloudheight = clientraw[73];
		set_ajax_obs("ajaxcloudheight",convertHeight(cloudheight) + uomHeight);
		set_ajax_obs("ajaxcloudheightft",cloudheight + " ft");
		set_ajax_obs("ajaxbigcloudheight",convertHeight(cloudheight) + uomHeight);
		set_ajax_obs("ajaxbigcloudheightft",cloudheight + " ft");
		
		// now ensure that the indicator flashes on every AJAX fetch
        element = document.getElementById("ajaxindicator");
		if (element) {
          element.style.color = flashcolor;
		}

 	  } // 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 
    setTimeout("ajaxLoader(clientrawFile + '?' + new Date().getTime())", reloadTime); // get new data after 5 secs
  }
} // end ajaxLoader function

//element = document.getElementById("ajaxcounter");
//if (element) {
  window.setInterval("ajax_countup()", 1000); // run the counter for seconds since update
//}

// invoke when first loaded on page
if (! ajaxLoaderInBody) { ajaxLoader(clientrawFile + '?' + new Date().getTime(), reloadTime); }



// ------------------------------------------------------------------------------------------
//  Loader-2 main function.. read wx38.html and format <span class="ajax" id="ajax..."></span> areas
// ------------------------------------------------------------------------------------------

function ajaxLoader2(url) {
  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 wx30 = x.responseText.split('|');  // Unpack the wx30.html file once for faster use

		// Indoor ...
		indoortemp = wx30[133];
		indoorhum = wx30 [134];
		set_ajax_obs("ajaxindoortemp", indoortemp + uomTemp);
		set_ajax_obs("ajaxindoorhum", indoorhum + " %");
		
		//Sun Moon stuff
		sunrise = wx30[1].toLowerCase();				//Orto
		set_ajax_obs("ajaxsunrise", sunrise);
		set_ajax_obs("ajaxbigsunrise", sunrise);
		
		sunset = wx30[2].toLowerCase();					//Ocaso
		set_ajax_obs("ajaxsunset", sunset);
		set_ajax_obs("ajaxbigsunset", sunset);
		
		maxdayhours = wx30[3].toLowerCase();			//Duración del día
		set_ajax_obs("ajaxmaxdayhours", maxdayhours);
		
		suntransit = wx30[4].toLowerCase(); 			//Tránsito solar, cenit.
		suntransit = suntransit.split(" ",1);
		set_ajax_obs("ajaxsuntransit", suntransit);
		set_ajax_obs("ajaxbigsuntransit", suntransit);
		
		dayornight = wx30[5];							//Día o noche, según las horas de orto y ocaso.
		set_ajax_obs("ajaxdayornight", dayornight);
		
		timegreeting = wx30[6];							//Mañana, Tarde, Noche....
		set_ajax_obs("ajaxtimegreeting", timegreeting);
		
		
		moonrise = wx30[103];							//moon rise time
		set_ajax_obs("ajaxmoonrise", moonrise);
		moonset = wx30[104];							//moon set time
		set_ajax_obs("ajaxmoonset", moonset);
		moonrisedate = wx30[105];						//moon rise date
		set_ajax_obs("ajaxmoonrisedate", moonrisedate);
		moonsetdate = wx30 [106];						//moon set date
		set_ajax_obs("ajaxmoonsetdate", moonsetdate);
		moonage = wx30[107];							//current age of the moon (days since new moon)
		set_ajax_obs("ajaxmoonage", moonage);

		moonphasename = wx30[108];						//Moon age description
		set_ajax_obs("ajaxmoonphasename", moonphasename);
		
		moonphase = wx30[109];							//Moon phase %
		set_ajax_obs("ajaxmoonphase", moonphase);
		marchequinox = wx30[110];						//March equinox date
		set_ajax_obs("ajaxmarchequinox", marchequinox);
		junesolstice = wx30[111];						//June solstice date
		set_ajax_obs("ajaxjunesolstice", junesolstice);
		sepequinox = wx30[112];							//September equinox date
		set_ajax_obs("ajaxsepequinox", sepequinox);
		decsolstice = wx30[113];						//December solstice date
		set_ajax_obs("ajaxdecsolstice", decsolstice);
		moonperihel = wx30[114];						//Next Moon perihel date
		set_ajax_obs("ajaxmoonperihel", moonperihel);
		moonaphel = wx30[115];							//Next moon aphel date
		set_ajax_obs("ajaxmoonaphel", moonaphel);
		moonperigee = wx30[116];						//Next moon perigee date
		set_ajax_obs("ajaxmoonperigee", moonperigee);
		moonapogee = wx30[117];							//Next moon apogee date
		set_ajax_obs("ajaxmoonapogee", moonapogee);
		newmoon = wx30[118];							//Date/time of the next/last new moon
		set_ajax_obs("ajaxnewmoon", newmoon);
		nextnewmoon = wx30[119];						//Date/time of the next new moon for next month
		set_ajax_obs("ajaxnextnewmoon", nextnewmoon);
		firstquarter = wx30[120];						//Date/time of the next/last first quarter moon
		set_ajax_obs("ajaxfirstquarter", firstquarter);
		lastquarter = wx30[121];						//Date/time of the next/last last quarter moon
		set_ajax_obs("ajaxlastquarter", lastquarter);
		fullmoon = wx30[122];							//Date/time of the next/last full moon
		set_ajax_obs("ajaxfullmoon", fullmoon);
		fullmoondate = wx30[123];						//Date of the next/last full moon (date only)
		set_ajax_obs("ajaxfullmoondate", fullmoondate);

		suneclipse = wx30[124];							//Next sun eclipse
			//suneclipse = suneclipse.replace(/Partial/g,'Parcial ');
		set_ajax_obs("ajaxsuneclipse", suneclipse);
			
		mooneclipse = wx30[125];						//Next moon eclipse date
			//mooneclipse = mooneclipse.replace(/Partial/g,'Parcial ');
		set_ajax_obs("ajaxmooneclipse", mooneclipse);
		moontransit = wx30[126].toLowerCase();			//Moon transit time
		moontransit = moontransit.split(" ",1);
		set_ajax_obs("ajaxmoontransit", moontransit);
		changeinday = wx30[127];						//Hours and fraction of an hour the day length has changed since yesterday
		set_ajax_obs("ajaxchangeinday", changeinday);
		changeindaydec = wx30[128];						//Hours and fraction of an hour the day length has changed since 21st Dec
		set_ajax_obs("ajaxchangeindaydec", changeindaydec);
		changeindayjun = wx30[129];						//Hours and fraction of an hour the day length has changed since 21st Jun
		set_ajax_obs("ajaxchangeindayjun", changeindayjun);
		hoursofpossibledaylight = wx30[130];			//Total hours/minutes of possible daylight for today
		set_ajax_obs("ajaxhoursofpossibledaylight", hoursofpossibledaylight);
		daylengthyesterday = wx30[131];					//Yesterdays' reading (updated at 11:46pm)
		set_ajax_obs("ajaxdaylengthyesterday", daylengthyesterday);
		
		
		// Sensaciones
		condcolourtext = wx30[7];						//Sensación térmica en texto (viene de conditionscolour).
		set_ajax_obs("ajaxcondcolourtext", condcolourtext);


		//Rain stuff
		tiptime = ' a las ' + wx30[40];					//Time last tip
		tiptime = tiptime.replace( " at -" , "");
		tipdate = wx30[41];	
		set_ajax_obs("ajaxtimeoflastrain", tipdate + tiptime);
		
		set_ajax_obs("ajaxrainduration", wx30[39] + ' min');		//Last rain duration
		
		set_ajax_obs("ajaxraindays", wx30[37]);			//Rain days
				
		set_ajax_obs("ajaxnoraindays", wx30[36]);		//NO rain days

		set_ajax_obs("ajaxrainhour", wx30[33] + uomRain + ' /hr');		//Rain last hour
		
		set_ajax_obs("ajaxrain3hour", wx30[146] + uomRain + ' /3 hr');	//Rain last 3 hours
		
		isozero = wx30[166];								//Snow height, used as isozero level
		set_ajax_obs("ajaxisozeroft", isozero + " ft");
		isozerom = convertHeight(isozero);
		set_ajax_obs("ajaxisozerom", isozerom + uomHeight);
		
		
		// Rain monthly averages (all time)
		avrainjan = (wx30[147]);
		avrainfeb = (wx30[148]);
		avrainmar = (wx30[149]);
		avrainapr = (wx30[150]);
		avrainmay = (wx30[151]);
		avrainjun = (wx30[152]);
		avrainjul = (wx30[153]);
		avrainaug = (wx30[154]);
		avrainsep = (wx30[155]);
		avrainoct = (wx30[156]);
		avrainnov = (wx30[157]);
		avraindec = (wx30[158]);
		set_ajax_obs("ajaxavrainjan", avrainjan + uomRain);
		set_ajax_obs("ajaxavrainfeb", avrainfeb + uomRain);
		set_ajax_obs("ajaxavrainmar", avrainmar + uomRain);
		set_ajax_obs("ajaxavrainapr", avrainapr + uomRain);
		set_ajax_obs("ajaxavrainmay", avrainmay + uomRain);
		set_ajax_obs("ajaxavrainjun", avrainjun + uomRain);
		set_ajax_obs("ajaxavrainjul", avrainjul + uomRain);
		set_ajax_obs("ajaxavrainaug", avrainaug + uomRain);
		set_ajax_obs("ajaxavrainsep", avrainsep + uomRain);
		set_ajax_obs("ajaxavrainoct", avrainoct + uomRain);
		set_ajax_obs("ajaxavrainnov", avrainnov + uomRain);
		set_ajax_obs("ajaxavraindec", avraindec + uomRain);
		
		// Rain monthly averages (last year)
		rainjan = (wx30[167]);
		rainfeb = (wx30[168]);
		rainmar = (wx30[169]);
		rainapr = (wx30[170]);
		rainmay = (wx30[171]);
		rainjun = (wx30[172]);
		rainjul = (wx30[173]);
		rainaug = (wx30[174]);
		rainsep = (wx30[175]);
		rainoct = (wx30[176]);
		rainnov = (wx30[177]);
		raindec = (wx30[178]);
		set_ajax_obs("ajaxrainjan", rainjan + uomRain);
		set_ajax_obs("ajaxrainfeb", rainfeb + uomRain);
		set_ajax_obs("ajaxrainmar", rainmar + uomRain);
		set_ajax_obs("ajaxrainapr", rainapr + uomRain);
		set_ajax_obs("ajaxrainmay", rainmay + uomRain);
		set_ajax_obs("ajaxrainjun", rainjun + uomRain);
		set_ajax_obs("ajaxrainjul", rainjul + uomRain);
		set_ajax_obs("ajaxrainaug", rainaug + uomRain);
		set_ajax_obs("ajaxrainsep", rainsep + uomRain);
		set_ajax_obs("ajaxrainoct", rainoct + uomRain);
		set_ajax_obs("ajaxrainnov", rainnov + uomRain);
		set_ajax_obs("ajaxraindec", raindec + uomRain);
		
		// Rain monthly averages (current year)
		nowrainjan = (wx30[179]);
		nowrainfeb = (wx30[180]);
		nowrainmar = (wx30[181]);
		nowrainapr = (wx30[182]);
		nowrainmay = (wx30[183]);
		nowrainjun = (wx30[184]);
		nowrainjul = (wx30[185]);
		nowrainaug = (wx30[186]);
		nowrainsep = (wx30[187]);
		nowrainoct = (wx30[188]);
		nowrainnov = (wx30[189]);
		nowraindec = (wx30[190]);
		set_ajax_obs("ajaxnowrainjan", nowrainjan + uomRain);
		set_ajax_obs("ajaxnowrainfeb", nowrainfeb + uomRain);
		set_ajax_obs("ajaxnowrainmar", nowrainmar + uomRain);
		set_ajax_obs("ajaxnowrainapr", nowrainapr + uomRain);
		set_ajax_obs("ajaxnowrainmay", nowrainmay + uomRain);
		set_ajax_obs("ajaxnowrainjun", nowrainjun + uomRain);
		set_ajax_obs("ajaxnowrainjul", nowrainjul + uomRain);
		set_ajax_obs("ajaxnowrainaug", nowrainaug + uomRain);
		set_ajax_obs("ajaxnowrainsep", nowrainsep + uomRain);
		set_ajax_obs("ajaxnowrainoct", nowrainoct + uomRain);
		set_ajax_obs("ajaxnowrainnov", nowrainnov + uomRain);
		set_ajax_obs("ajaxnowraindec", nowraindec + uomRain);
		
		
		
		//Wetbulb
		wetbulb = parseFloat(wx30[132]);
		set_ajax_obs("ajaxwetbulb", wetbulb.toFixed(1) + uomTemp);


		//Temp trend 24 hour
		temp = parseFloat(wx30[45]);
		temp24hour = parseFloat(wx30[25]);
		temp24change = parseFloat(wx30[22]);
		
		set_ajax_obs("ajaxtemp24arrow",
		   ajax_genarrow(temp, temp24hour, '', 
			 '%s ºC MORE tha yesterday.',
			 '%s ºC LESS than yesterday.',1)
			 );
		
		if (temp24change > 0) {
			temp24change = "+" + temp24change.toFixed(1);
		} else if (temp24change < 0) {
			temp24change = temp24change.toFixed(1);
		} else {
			temp24change = "+" + temp24change.toFixed(1);
		}
		set_ajax_obs("ajaxtemp24change", temp24change + uomTemp + " /day");

		
		// humidity trend 1 hour
		humidity = parseFloat(wx30[46]);
		humlasthour = parseFloat(wx30[47]);
		humdiff = humidity - humlasthour;
		set_ajax_obs("ajaxhumarrow",
		   ajax_genarrow(humidity, humlasthour, '', 
			 'Rising %s % in the last hour.',
			 'Falling %s % in the last hour.',0)
			 );
		if (humdiff > 0) {
			humdiff = "+" + humdiff.toFixed(0);
		} else if (humdiff < 0) {
			humdiff = humdiff.toFixed(0);
			} else {
				humdiff = "+" + humdiff.toFixed(0);
			}
		set_ajax_obs("ajaxhumdiff", humdiff + "% /hr");
		
		// humidity trend 24 hours
		humidity = parseFloat(wx30[46]);
		humlast24hour = parseFloat(wx30[30]);
		humdiff = humidity - humlast24hour;
		set_ajax_obs("ajaxhum24arrow",
		   ajax_genarrow(humidity, humlast24hour, '', 
			 '%s % MORE than yesterday.',
			 '%s % LESS tha yesterday.',0)
			 );
		if (humdiff > 0) {
			humdiff = "+" + humdiff.toFixed(0);
		} else if (humdiff < 0) {
			humdiff = humdiff.toFixed(0);
			} else {
				humdiff = "+" + humdiff.toFixed(0);
			}
		set_ajax_obs("ajaxhum24diff", humdiff + "% /day");


		//Pressure trend 24 hour
		press = parseFloat(wx30[50]);
		press24hour = parseFloat(wx30[26]);
		presstrend = press - press24hour;
		
		set_ajax_obs("ajaxpress24arrow",
		   ajax_genarrow(press, press24hour, '', 
			 '%s hPa MORE tha yesterday.',
			 '%s hPa LESS than yesterday.',1)
			 );
		
		if (presstrend > 0) {
			presstrend = "+" + presstrend.toFixed(1);
		} else if (presstrend < 0) {
			presstrend = presstrend.toFixed(1);
		} else {
			presstrend = "+" + presstrend.toFixed(1);
		}
		set_ajax_obs("ajaxpress24trend", presstrend + uomBaro + " /day");
		

		//Humidity day high low
		timelower = wx30[9].toLowerCase();
		humday = parseFloat(wx30[8]);
		set_ajax_obs("ajaxhumdayhigh", humday.toFixed(0) + '% at ' + timelower);
		timelower = wx30[11].toLowerCase();
		humday = parseFloat(wx30[10]);
		set_ajax_obs("ajaxhumdaylow", humday.toFixed(0) + '% at ' + timelower);

		//Pressure day high low
		timelower = wx30[17].toLowerCase();
		pressday = parseFloat(wx30[16]);
				//set_ajax_obs("ajaxpressdayhigh", pressday .toFixed(3) + uomBaro + ' a las ' + timelower);
		set_ajax_obs("ajaxpressdayhigh", timelower);
		timelower = wx30[19].toLowerCase();
		pressday = parseFloat(wx30[18]);
				//set_ajax_obs("ajaxpressdaylow", pressday.toFixed(3) + uomBaro + ' a las ' + timelower);
		set_ajax_obs("ajaxpressdaylow", timelower);

		//Temp day high low
		timelower = wx30[13].toLowerCase();
		tempday = parseFloat(wx30[12]);
				//set_ajax_obs("ajaxtempdayhigh", tempday.toFixed(1) + uomTemp + ' a las ' + timelower);
		set_ajax_obs("ajaxtempdayhigh", timelower);
		timelower = wx30[15].toLowerCase();
		tempday = parseFloat(wx30[14]);
				//set_ajax_obs("ajaxtempdaylow", tempday.toFixed(1) + uomTemp + ' a las ' + timelower);
		set_ajax_obs("ajaxtempdaylow", timelower);
		
		
		//Solar day high
		timelower = wx30[53].toLowerCase();
		solarday = parseFloat(wx30[51]);
		set_ajax_obs("ajaxsolardayhigh", solarday.toFixed(0) + uomSolar + ' at ' + timelower);

		solarmax = parseFloat(wx30[57]);		//Solar max possible
		set_ajax_obs("ajaxsolarmax", solarmax.toFixed(0) + uomSolar);
		
		timelower = wx30[205].toLowerCase();
		uvday = parseFloat(wx30[204]);
		set_ajax_obs("ajaxuvdayhigh", uvday.toFixed(1) + ' a las ' + timelower);
		
	
		//Wind Trends
		
		wind = parseFloat(wx30[64]);
		windlasthour = parseFloat(wx30[65]);
		wind24hour = parseFloat(wx30[27]);
		windtrend = wind - windlasthour;
		wind24trend = wind - wind24hour;
		
		//1 hour
		set_ajax_obs("ajaxwindarrow",
		   ajax_genarrow(wind, windlasthour, '', 
			 '%s kt. MORE than 1 hour ago.',
			 '%s kt. LESS than 1 hour ago.',0)
			 );
		
		if (windtrend > 0) {
			windtrend = "+" + windtrend.toFixed(0);
		} else if (windtrend < 0) {
			windtrend = windtrend.toFixed(0);
		} else {
			windtrend = "+" + windtrend.toFixed(0);
		}
		set_ajax_obs("ajaxwindtrend", windtrend + " W/m2 /hr");
		
		//24 hour
		set_ajax_obs("ajaxwind24arrow",
		   ajax_genarrow(wind, wind24hour, '', 
			 '%s kt. MORE than yesterday.',
			 '%s kt. LESS than yesterday.',0)
			 );
		
		if (wind24trend > 0) {
			wind24trend = "+" + wind24trend.toFixed(0);
		} else if (wind24trend < 0) {
			wind24trend = wind24trend.toFixed(0);
		} else {
			wind24trend = "+" + wind24trend.toFixed(0);
		}
		set_ajax_obs("ajaxwind24trend", wind24trend + " W/m2 /day");


		//Solar trends  (w/m2)
		
		solar = parseFloat(wx30[48]);
		solarlasthour = parseFloat(wx30[49]);
		solar24hour = parseFloat(wx30[32]);
		solartrend = solar - solarlasthour;
		solar24trend = solar - solar24hour;
		
		//1 hour
		set_ajax_obs("ajaxsolararrow",
		   ajax_genarrow(solar, solarlasthour, '', 
			 '%s W/m2 MORE than 1 hour ago.',
			 '%s W/m2 LESS than 1 hour ago.',0)
			 );
		
		if (solartrend > 0) {
			solartrend = "+" + solartrend.toFixed(0);
		} else if (solartrend < 0) {
			solartrend = solartrend.toFixed(0);
		} else {
			solartrend = "+" + solartrend.toFixed(0);
		}
		set_ajax_obs("ajaxsolartrend", solartrend + " W/m2 /hr");
		
		//24 hour
		set_ajax_obs("ajaxsolar24arrow",
		   ajax_genarrow(solar, solar24hour, '', 
			 '%s W/m2 MORE than yesterday.',
			 '%s W/m2 LESS than yesterday.',0)
			 );
		
		if (solar24trend > 0) {
			solar24trend = "+" + solar24trend.toFixed(0);
		} else if (solar24trend < 0) {
			solar24trend = solar24trend.toFixed(0);
		} else {
			solar24trend = "+" + solar24trend.toFixed(0);
		}
		set_ajax_obs("ajaxsolar24trend", solar24trend + " W/m2 /day");
		
		
		// METAR
//		metarlest = (wx30[160]);
//		metarleco = (wx30[161]);
//		metarlevx = (wx30[162]);
//		metarleas = (wx30[163]);
//		metarleln = (wx30[164]);
//		metarlppr = (wx30[165]);
//		set_ajax_obs("ajaxmetarlest", metarlest);
//		set_ajax_obs("ajaxmetarleco", metarleco);
//		set_ajax_obs("ajaxmetarlevx", metarlevx);
//		set_ajax_obs("ajaxmetarleas", metarleas);
//		set_ajax_obs("ajaxmetarleln", metarleln);
//		set_ajax_obs("ajaxmetarlppr", metarlppr);
		
		
		// Fire Weather Index
		fwiffmc = (wx30[160]);
		fwidmc = (wx30[161]);
		fwidc = (wx30[162]);
		fwiisi = (wx30[163]);
		fwibui = (wx30[164]);
		fwifwi = (wx30[165]);
		set_ajax_obs("ajaxfwiffmc", fwiffmc);
		set_ajax_obs("ajaxfwidmc", fwidmc);
		set_ajax_obs("ajaxfwidc", fwidc);
		set_ajax_obs("ajaxfwiisi", fwiisi);
		set_ajax_obs("ajaxfwibui", fwibui);
		set_ajax_obs("ajaxfwifwi", fwifwi);
		
		
		// Temp monthly averages (all time)
		avgtempjan = (wx30[135]);
		avgtempfeb = (wx30[136]);
		avgtempmar = (wx30[137]);
		avgtempapr = (wx30[138]);
		avgtempmay = (wx30[139]);
		avgtempjun = (wx30[140]);
		avgtempjul = (wx30[141]);
		avgtempaug = (wx30[142]);
		avgtempsep = (wx30[143]);
		avgtempoct = (wx30[144]);
		avgtempnov = (wx30[145]);
		avgtempdec = (wx30[146]);
		set_ajax_obs("ajaxavgtempjan", avgtempjan + uomTemp);
		set_ajax_obs("ajaxavgtempfeb", avgtempfeb + uomTemp);
		set_ajax_obs("ajaxavgtempmar", avgtempmar + uomTemp);
		set_ajax_obs("ajaxavgtempapr", avgtempapr + uomTemp);
		set_ajax_obs("ajaxavgtempmay", avgtempmay + uomTemp);
		set_ajax_obs("ajaxavgtempjun", avgtempjun + uomTemp);
		set_ajax_obs("ajaxavgtempjul", avgtempjul + uomTemp);
		set_ajax_obs("ajaxavgtempaug", avgtempaug + uomTemp);
		set_ajax_obs("ajaxavgtempsep", avgtempsep + uomTemp);
		set_ajax_obs("ajaxavgtempoct", avgtempoct + uomTemp);
		set_ajax_obs("ajaxavgtempnov", avgtempnov + uomTemp);
		set_ajax_obs("ajaxavgtempdec", avgtempdec + uomTemp);
		
		// Temp monthly averages (current year)
		avgtempjan2 = (wx30[191]);
		avgtempfeb2 = (wx30[192]);
		avgtempmar2 = (wx30[193]);
		avgtempapr2 = (wx30[194]);
		avgtempmay2 = (wx30[195]);
		avgtempjun2 = (wx30[196]);
		avgtempjul2 = (wx30[197]);
		avgtempaug2 = (wx30[198]);
		avgtempsep2 = (wx30[199]);
		avgtempoct2 = (wx30[200]);
		avgtempnov2 = (wx30[201]);
		avgtempdec2 = (wx30[202]);
		set_ajax_obs("ajaxavgtempjan2", avgtempjan2 + uomTemp);
		set_ajax_obs("ajaxavgtempfeb2", avgtempfeb2 + uomTemp);
		set_ajax_obs("ajaxavgtempmar2", avgtempmar2 + uomTemp);
		set_ajax_obs("ajaxavgtempapr2", avgtempapr2 + uomTemp);
		set_ajax_obs("ajaxavgtempmay2", avgtempmay2 + uomTemp);
		set_ajax_obs("ajaxavgtempjun2", avgtempjun2 + uomTemp);
		set_ajax_obs("ajaxavgtempjul2", avgtempjul2 + uomTemp);
		set_ajax_obs("ajaxavgtempaug2", avgtempaug2 + uomTemp);
		set_ajax_obs("ajaxavgtempsep2", avgtempsep2 + uomTemp);
		set_ajax_obs("ajaxavgtempoct2", avgtempoct2 + uomTemp);
		set_ajax_obs("ajaxavgtempnov2", avgtempnov2 + uomTemp);
		set_ajax_obs("ajaxavgtempdec2", avgtempdec2 + uomTemp);


		// Davis forecast
		vpforecasttext = (wx30[203]);
		set_ajax_obs("ajaxvpforecasttext", vpforecasttext);


		// Station status
		consolbat = (wx30[206]);
		issbat = (wx30[207]);
		commreception = (wx30[208]);
		commreception2 = (wx30[209]);
		commreception2 = commreception2.split(" ");
		
		set_ajax_obs("ajaxconsolbat", consolbat + ' volts');
		set_ajax_obs("ajaxissbat", issbat);
		set_ajax_obs("ajaxcommreception", commreception);
		set_ajax_obs("ajaxcommok", commreception2[0]);
		set_ajax_obs("ajaxcommnok", commreception2[1]);
		set_ajax_obs("ajaxcommsync", commreception2[2]);
		set_ajax_obs("ajaxcommrow", commreception2[3]);
		set_ajax_obs("ajaxcommcrc", commreception2[4]);
		
		freememory = (wx30[211]);
		wdstartdate = (wx30[212]);
		wdstarttime = (wx30[213]);
		datareceived = (wx30[214]);
		
		set_ajax_obs("ajaxfreememory", freememory);
		set_ajax_obs("ajaxwdstartdate", wdstartdate);
		set_ajax_obs("ajaxwdstarttime", wdstarttime);
		set_ajax_obs("ajaxdatareceived", datareceived);
	
		windowsuptime = (wx30[210]);
		windowsuptime = windowsuptime.replace(/Days/g,'D');
		windowsuptime = windowsuptime.replace(/Hours/g,'h');
		windowsuptime = windowsuptime.replace(/Minutes/g,'m');
		windowsuptime = windowsuptime.replace(/Seconds/g,'s');
		
		set_ajax_obs("ajaxwindowsuptime", windowsuptime);
		
		
		// Air density
		airdensity = (wx30[215]);
		densityalt = (wx30[216]);
		
		set_ajax_obs("ajaxairdensity", airdensity);
		set_ajax_obs("ajaxdensityalt", densityalt);
		

		// Imagenes
        element = document.getElementById("ajaxcondcolour");
		if (element) {
		  element.src = "/wd/conditionscolour.jpg"+"?"+new Date();  //
		}

        element = document.getElementById("ajaxcloudcover");
		if (element) {
		  element.src = "/php/solarpct.php"+"?"+new Date();
		}
		
        element = document.getElementById("ajaxsunpos");
		if (element) {
		  element.src = "/php/sunpos.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphtemp");
		if (element) {
		  element.src = "/php/temp.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphpressure");
		if (element) {
		  element.src = "/php/pressure.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphhumidity");
		if (element) {
		  element.src = "/php/humidity.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphwind");
		if (element) {
		  element.src = "/php/wind.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphwinddirn");
		if (element) {
		  element.src = "/php/winddirn.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphrain");
		if (element) {
		  element.src = "/php/rain.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphsolar");
		if (element) {
		  element.src = "/solar.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphhelio");
		if (element) {
		  element.src = "/php/heliograph.php"+"?"+new Date();
		}
		
		element = document.getElementById("ajaxgraphcloudheight");
		if (element) {
		  element.src = "/php/cloudheight.php"+"?"+new Date();
		}
		

   } // 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 = 6000 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("ajaxLoader2(clientrawFile2 + '?' + new Date().getTime())", reloadTime2); // get new data
  }
} // end ajaxLoader2 function

// invoke when first loaded on page
if (! ajaxLoaderInBody2) { ajaxLoader2(clientrawFile2 + '?' + new Date().getTime(), reloadTime2); }

// ]]>