// <![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 = '../clientraw.txt'; // location of clientraw.txt relative to this page on website
var clientrawFile2 = '../wx38.html'; // 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 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;


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 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=\"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 {  
	    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("Calma"); }
  if (wind < 4 ) {return("Ventolina"); }
  if (wind < 7 ) {return("Frouxiño"); }
  if (wind < 11 ) {return("Frouxo"); }
  if (wind < 17 ) {return("Bonancible"); }
  if (wind < 22 ) {return("Fresquiño"); }
  if (wind < 28 ) {return("Fresco"); }
  if (wind < 34 ) {return("Frescachón"); }
  if (wind < 41 ) {return("Temporal"); }
  if (wind < 48 ) {return("Temporal forte"); }
  if (wind < 56 ) {return("Temporal duro"); }
  if (wind < 64 ) {return("Temporal moi duro"); }
  if (wind >= 64 ) {return("Temporal furacanado"); }
  return("Descoñecido " + 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("Descoñecido " + wind);
}

function ajax_bfgraph ( wind ) { 
// Devuelve un vúmetro de intensidad de viento
  if (wind < 1 ) {return("<img src=\"" + imagedir + "/" + "bf0.gif\" + title=\"Forza 0, Calma\" alt=\"Forza 0, Calma\"  />"); }
  if (wind < 4 ) {return("<img src=\"" + imagedir + "/" + "bf1.gif\" + title=\"Forza 1, Ventolina\" alt=\"Forza 1, Ventolina\"  />"); }
  if (wind < 7 ) {return("<img src=\"" + imagedir + "/" + "bf2.gif\" + title=\"Forza 2, Frouxiño\" alt=\"Forza 2, Frouxiño\"  />"); }
  if (wind < 11 ) {return("<img src=\"" + imagedir + "/" + "bf3.gif\" + title=\"Forza 3, Frouxo\" alt=\"Forza 3, Frouxo\"  />"); }
  if (wind < 17 ) {return("<img src=\"" + imagedir + "/" + "bf4.gif\" + title=\"Forza 4, Bonancible\" alt=\"Forza 4, Bonancible\"  />"); }
  if (wind < 22 ) {return("<img src=\"" + imagedir + "/" + "bf5.gif\" + title=\"Forza 5, Fresquiño\" alt=\"Forza 5, Fresquiño\"  />"); }
  if (wind < 28 ) {return("<img src=\"" + imagedir + "/" + "bf6.gif\" + title=\"Forza 6, Fresco\" alt=\"Forza 6, Fresco\"  />"); }
  if (wind < 34 ) {return("<img src=\"" + imagedir + "/" + "bf7.gif\" + title=\"Forza 7, Frescachón\" alt=\"Forza 7, Frescachón\"  />"); }
  if (wind < 41 ) {return("<img src=\"" + imagedir + "/" + "bf8.gif\" + title=\"Forza 8, Temporal\" alt=\"Forza 8, Temporal\"  />"); }
  if (wind < 48 ) {return("<img src=\"" + imagedir + "/" + "bf9.gif\" + title=\"Forza 9, Temporal forte\" alt=\"Forza 9, Temporal forte\"  />"); }
  if (wind < 56 ) {return("<img src=\"" + imagedir + "/" + "bf10.gif\" + title=\"Forza 10, Temporal duro\" alt=\"Forza 10, Temporal duro\"  />"); }
  if (wind < 64 ) {return("<img src=\"" + imagedir + "/" + "bf11.gif\" + title=\"Forza 11, Temporal moi duro\" alt=\"Forza 11, Temporal moi duro\"  />"); }
  if (wind >= 64 ) {return("<img src=\"" + imagedir + "/" + "bf12.gif\" + title=\"Forza 12, Temporal furacanado\" alt=\"Forza 12, Temporal furacanado\"  />"); }
  return("Desconecido " + 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("Estable"); }
   if ((btrnd > 0.4) && (btrnd < 1.0)) { return("Subindo a modiño"); }
   if (btrnd >= 1.0) { return("Subindo rápidamente"); }
   if ((btrnd < -0.4) && (btrnd > -1.0)) { return("Baixando a modiño"); }
   if (btrnd <= -1.0) { return("Baixando rápidamente"); }
  return(btrnd);
}

function ajax_getUVrange ( uv ) { // code simplified by FourOhFour on wxforum.net
   var uvword = "Non especificado.";
   if (uv <= 0) {
       uvword = "Nulo";
   } else if (uv < 3) {
       uvword = "<span style=\"border: solid 1px; background-color: #A4CE6a;\">&nbsp;Baixo&nbsp;</span>";
   } else if (uv < 6) {
       uvword = "<span style=\"border: solid 1px; background-color: #FBEE09;\">&nbsp;Medio&nbsp;</span>";
   } else if (uv < 8) {
       uvword =  "<span style=\"border: solid 1px; background-color: #FD9125;\">&nbsp;Alto&nbsp;</span>";
   } else if (uv < 11) {
       uvword =  "<span style=\"border: solid 1px; color: #FFFFFF; background-color: #F63F37;\">&nbsp;Moi&nbsp;Alto&nbsp;</span>";
   } else {
       uvword =  "<span style=\"border: solid 1px; color: #FFFF00; background-color: #807780;\">&nbsp;Extremo&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 = "<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++;
 }
}

// ------------------------------------------------------------------------------------------
//  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+'  MAIS que fai unha hora.',
			 '%s'+uomTemp+'  MENOS que fai unha hora.',1)
		   );	
	    temprate = temp - templast;
		temprate = temprate.toFixed(1);
		if (temprate > 0.0) { temprate = '+' + temprate;} // add '+' for positive rates
		set_ajax_obs("ajaxtemprate",temprate + uomTemp);

		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 <= 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);
		
		// 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, '', 
			 'Subindo a %s '+uomBaro+'/hora.',
			 'Baixando a %s '+uomBaro+'/hora.',2)
			 );	
		
		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",'Calma');
		}

		//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]);
				
		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);
		
       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","Calma");
		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=\"Vento do" + 
		val + "\" title=\"Vento do " + val + "\" /> ");
		set_ajax_obs("ajaxwinddir",val);
	   } else {
 		set_ajax_obs("ajaxwindicon","<img src=\"" + imagedir + "/" + "calm.gif\" width=\"70\" height=\"70\" alt=\"Vento en calma\" 				 		title=\"Vento en calma\" /> ");
		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(1));
		set_ajax_obs("ajaxwindmph",windmph.toFixed(1));
		set_ajax_obs("ajaxwindms",windms.toFixed(1));
		set_ajax_obs("ajaxwindkmh",windkmh.toFixed(1));
		set_ajax_obs("ajaxbigwindkts",windkts.toFixed(1) + " kts");
		// 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) ;

		uvword = ajax_getUVrange(uv);
		set_ajax_obs("ajaxuvword",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(/\r|\n/g,'');
		
//		currentcond = currentcond.split("-",2);


			switch(currentcond)
			{
			case 'Clear':
				currentcond = 'Despexado'
				break			
			case 'A few clouds at 4500 ft':
				currentcond = 'Few a 4500 pés (1400 m)'
				break
			case 'partly cloudy':
				currentcond = 'Parcialmente anubrado'
				break
			case 'Scattered clouds at 2000 ft':
				currentcond = 'Scattered a 2000 pés (700 m)'
				break
			case 'Scattered clouds at 3000 ft':
				currentcond = 'Scattered a 3000 pés (1000 m)'
				break
			case 'Scattered clouds at 4500 ft':
				currentcond = 'Scattered a 4500 pés (1400 m)'
				break
			case 'Scattered clouds at 5000 ft':
				currentcond = 'Scattered a 5000 pés (1600 m)'
				break
			case 'Scattered clouds at 20000 ft':
				currentcond = 'Scattered a 20000 pés (6600 m)'
				break
			case 'Cloudy with clear patches at 5000 ft':
				currentcond = 'Anubrado, claros a 5000 pés (1600 m)'
				break
			case 'Cloudy with clear patches at 22000 ft':
				currentcond = 'Anubrado, claros a 22000 pés (7300 m)'
				break
			case 'mostly cloudy':
				currentcond = 'Moi anubrado'
				break 
			case 'mostly cloudy - light_rain':
				currentcond = 'Moi anubrado - Choiva feble'
				break
			case 'mostly cloudy - rain':
				currentcond = 'Moi anubrado - Choiva'
				break
			case 'overcast':
				currentcond = 'Cuberto'
				break
			case 'overcast - drizzle':
				currentcond = 'Cuberto - Llovizna'
				break
			case 'overcast - light rain':
				currentcond = 'Cuberto - Choiva feble'
				break
			/*default:
			  currentcond = 'default'*/
			}
		
		set_ajax_obs("ajaxcurrentcond",currentcond);
		
		// cloud height
		cloudheight = clientraw[73];
		set_ajax_obs("ajaxcloudheight",convertHeight(cloudheight) + uomHeight);
		set_ajax_obs("ajaxcloudheightft",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

		//Time ...
		// set_ajax_obs("ajaxgetrawtime", wx30[1]);
		
		//Sun stuff
		sunrise = wx30[1].toLowerCase();				//Orto
		set_ajax_obs("ajaxsunrise", sunrise);
		
		sunset = wx30[2].toLowerCase();					//Ocaso
		set_ajax_obs("ajaxsunset", 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);
		
		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);
		

		// 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
		
		
		//Wetbulb
		wetbulb = parseFloat(wx30[147]);
		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 MAIS que onte.',
			 '%s ºC MENOS que onte.',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 + " /día");

		
		// humidity trend 1 hour
		humidity = parseFloat(wx30[46]);
		humlasthour = parseFloat(wx30[47]);
		humdiff = humidity - humlasthour;
		set_ajax_obs("ajaxhumarrow",
		   ajax_genarrow(humidity, humlasthour, '', 
			 'Subindo %s % na derradeira hora.',
			 'Baixando %s % na derradeira hora.',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 % MAIS que onte.',
			 '%s % MENOS que onte.',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 + "% /d&iacute;a");


		//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 MAIS que onte.',
			 '%s hPa MENOS que onte.',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 + " /día");
		

		//Humidity day high low
		timelower = wx30[9].toLowerCase();
		humday = parseFloat(wx30[8]);
		set_ajax_obs("ajaxhumdayhigh", humday.toFixed(0) + '% as ' + timelower);
		timelower = wx30[11].toLowerCase();
		humday = parseFloat(wx30[10]);
		set_ajax_obs("ajaxhumdaylow", humday.toFixed(0) + '% as ' + 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 + ' as ' + timelower);

		solarmax = parseFloat(wx30[57]);		//Solar max possible
		set_ajax_obs("ajaxsolarmax", solarmax.toFixed(0) + uomSolar);
		
		

		//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. MAIS que fai unha hora.',
			 '%s kt. MENOS que fai unha hora.',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. MAIS que onte.',
			 '%s kt. MENOS que onte.',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 /día");


		//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 MAIS que fai unha hora.',
			 '%s W/m2 MENOS que fai unha hora.',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 MAIS que onte.',
			 '%s W/m2 MENOS que onte.',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 /día");






        element = document.getElementById("ajaxradar");
		if (element) {
		  element.src = "/radar/miniradar.jpg"+"?"+new Date();
		}

        element = document.getElementById("ajaxclwebcam");
		if (element) {
		  element.src = "carterlakecamlivethumb.jpg"+"?"+new Date();
		}
        element = document.getElementById("ajaxcitycam");
		if (element) {
		  element.src = "webcam2.jpg"+"?"+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); }


// ]]>