// <![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
// --- Version 2.06 - 24-Jun-2007 -- added '/' as delimiter for currentcond
//
// 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 = '#00CC00'; // color to flash for changed observations RGB
var flashtime  = 2000;    // miliseconds to keep flash color on (2000 = 2 seconds);
var reloadTime = 5000;      // reload AJAX conditions every 5 seconds (= 5000 ms)
var clientrawFile = './assets/wxgraphic/data.html'; // location of clientraw.txt relative to this page on website
var ajaxLoaderInBody = true; // set to true if you have <body onload="ajaxLoader(..."
var imagedir = './arrows';  // place for wind arrows, rising/falling arrows, etc.
var useunits = 'E';         // 'E'=USA(English) or 'M'=Metric
var useKnots = false;       // set to true to use wind speed in Knots (otherwise 
							// wind in km/hr for Metric or mph for English will be used.
var 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 = '&#160;&#176;F';
var uomWind = '&#160;mph';
var uomBaro = '&#160;hPa';
var uomRain = '&#160;in';
var uomRainR= '&#160;in/hr';
var uomHeight = '&#160;ft';
var uomSolar = '&#160;W/m&#178;';
var uomHumidity = '&#37;';
var dpBaro = 1;
var dpRain = 2;


function ajax_set_units( units ) {
  useunits = units;
  if (useunits != 'E') { // set to metric
	uomTemp = '&#160;&#176;C';
	uomWind = '&#160;km/h';
	if(useMPS)   { uomWind = '&#160;m/s'; }
	uomBaro = '&#160;hPa';
	uomRain = '&#160;mm';
	uomHeight = '&#160;m';
	dpBaro = 1;
	dpRain = 1;
  } 
  if(useKnots) { uomWind = '&#160;kts'; }
  if (! showUnits) {
	uomTemp = '';
	uomWind = '';
	uomBaro = '';
	uomRain = '';
	uomRainR= '';
	uomHeight = '';
	uomSolar = '';
	uomHumidity = '';
  }
}

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

// 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("Near gale"); }
  if (wind < 41 ) {return("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_getUVrange ( uv ) { // code simplified by FourOhFour on wxforum.net
   var uvword = "Unspec.";
   if (uv <= 0) {
       uvword = "None";
   } else if (uv < 3) {
       uvword = "<span style=\"border: solid 1px; background-color: #A4CE6a;\">&#160;Low&#160;</span>";
   } else if (uv < 6) {
       uvword = "<span style=\"border: solid 1px; background-color: #FBEE09;\">&#160;Medium&#160;</span>";
   } else if (uv < 8) {
       uvword =  "<span style=\"border: solid 1px; background-color: #FD9125;\">&#160;High&#160;</span>";
   } else if (uv < 11) {
       uvword =  "<span style=\"border: solid 1px; color: #FFFFFF; background-color: #F63F37;\">&#160;Very&#160;High&#160;</span>";
   } else {
       uvword =  "<span style=\"border: solid 1px; color: #FFFF00; background-color: #807780;\">&#160;Extreme&#160;</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 = '&#160;'; 
  } else if (diff > 0) {
// today is greater 
//    msg = textUP + " by " + diff.toFixed(1); // sprintf($textDN,$absDiff); 
	msg = textUP.replace(/\%s/,absDiffStr);
    image = "<img src=\"" + imagedir + "/rising.gif\" alt=\"" + msg + 
	"\" title=\""+ msg + 
	"\" width=\"7\" height=\"8\" style=\"border: 0; margin: 1px 3px;\" />";
  } else {
// today is lesser
    msg = textDN.replace(/\%s/,absDiffStr); // sprintf($textDN,$absDiff); 
//	msg = textDN.replace(/\%s/,absDiffStr);
    image = "<img src=\"" + imagedir + "/falling.gif\" alt=\"" + msg + 
	"\" title=\""+ msg + 
	"\" width=\"7\" height=\"8\" style=\"border: 0; margin: 1px 3px;\" />";
   
  }

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

// Mike Challis' counter function (adapted by Ken True)
//
function ajax_countup() {
 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 = false;
    try {
		x = new XMLHttpRequest(url);
	} catch (trymicrosoft) {
		try {
			x = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				x = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				x = false;
			}
		}
	}
	if (!x) {
		alert("Error initializing XMLHttpRequest!");
	}
    
  }
  if (x) { 
    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(',');
		
	var temp = clientraw[2];
		set_ajax_obs("ajaxtemp", temp + uomTemp);
//		set_ajax_obs("ajaxbigtemp",temp + uomTemp);

	var humidity = clientraw[5];
		set_ajax_obs("ajaxhumidity",humidity + uomHumidity);
		
	var dew = clientraw[6];
		set_ajax_obs("ajaxdew",dew + uomTemp);
		
	if (temp > 80) {		
		var heatidx = 16.923 
					+ (1.85212 * Math.pow(10,-1) * temp)
					+ (5.37941 * humidity)
					- (1.00254 * Math.pow(10,-1) * temp * humidity)
					+ (9.41695 * Math.pow(10,-3) * Math.pow(temp,2)) 
					+ (7.28898 * Math.pow(10,-3) * Math.pow(humidity,2)) 
					+ (3.45372 * Math.pow(10,-4) * Math.pow(temp,2) * humidity) 
					- (8.14971 * Math.pow(10,-4) * temp * Math.pow(humidity,2)) 
					+ (1.02102 * Math.pow(10,-5) * Math.pow(temp,2) * Math.pow(humidity,2)) 
					- (3.86460 * Math.pow(10,-5) * Math.pow(temp,3))
					+ (2.91583 * Math.pow(10,-5) * Math.pow(humidity,3)) 
					+ (1.42721 * Math.pow(10,-6) * Math.pow(temp,3) * humidity) 
					+ (1.97483 * Math.pow(10,-7) * temp * Math.pow(humidity,3)) 
					- (2.18429 * Math.pow(10,-8) * Math.pow(temp,3) * Math.pow(humidity,2)) 
					+ (8.43296 * Math.pow(10,-10) * Math.pow(temp,2) * Math.pow(humidity,3)) 
					- (4.81975 * Math.pow(10,-11) * Math.pow(temp,3) * Math.pow(humidity,3));
		if (heatidx < temp) {
			heatidx = temp;
		} else {
			set_ajax_obs("ajaxheatidx",heatidx.toFixed(1) + uomTemp);
		}
	}

/*
		var feelslike = temp;
		if (temp < 50 && windchill < temp) {
			feelslike = windchill; //use WindChill
		} else if (temp > 80 && heatidx > temp) {
			feelslike = heatidx; //use Humidex
		} else {
			feelslike = temp;   // use temperature
		}
		feelslike  = Math.round(convertTemp(feelslike));
		set_ajax_obs("ajaxfeelslike",feelslike + uomTemp);
*/

	var pressure = clientraw[7];
//			pressure = pressure * 1.0;
		set_ajax_obs("ajaxbaro",pressure + uomBaro);
		set_ajax_obs("ajaxbarotrendtext",clientraw[8]);
		
	var wind = clientraw[9];

	var gust    = convertWind(clientraw[12]);

// 		beaufort = ajax_get_beaufort(clientraw[9]);
// 		set_ajax_obs("ajaxbeaufort",beaufort);

	var val = windDir(clientraw[10]);

	if (wind > 0.0) {
		set_ajax_obs("ajaxwind",wind + uomWind);
//		set_ajax_uom("ajaxwinduom",true);
		set_ajax_obs("ajaxwindicon","<img src=\"" + imagedir + "/" +  val + ".gif\" width=\"14\" height=\"14\" alt=\"Wind from" + val + "\" title=\"Wind from " + val + "\" />");
		set_ajax_obs("ajaxwinddir",val);
	} else {
		set_ajax_obs("ajaxwind","Calm");
//		set_ajax_uom("ajaxwinduom",false);
		set_ajax_obs("ajaxwindicon","&#160;");
		set_ajax_obs("ajaxwinddir","");
	}
	   
/*
		if (gust > 0.0) {
		 	set_ajax_obs("ajaxgust",gust + uomWind);
		 	set_ajax_uom("ajaxgustuom",true);
		} else {
		 	set_ajax_obs("ajaxgust","None");
		 	set_ajax_uom("ajaxgustuom",false);
		}
*/

/*
		if (wind > 0.0) {
			set_ajax_obs("ajaxwindicon","<img src=\"" + imagedir + "/" +  val + ".gif\" width=\"14\" height=\"14\" alt=\"Wind from" + val + "\" title=\"Wind from " + val + "\" />");
			set_ajax_obs("ajaxwinddir",val);
		} else {
			set_ajax_obs("ajaxwindicon","&#160;");
			set_ajax_obs("ajaxwinddir","");
		}
*/

	if (temp < 50) {
		var windchill 	= 35.74
						+ 0.6215 * temp
						- 35.75 * Math.pow(wind, 0.16)
						+ 0.4275 * temp * Math.pow(wind, 0.16);
		if (windchill > temp) {
			windchill = temp;
		} else {
			set_ajax_obs("ajaxwindchill",windchill.toFixed(1) + uomTemp);
		}
	}

	var rain = clientraw[11];

	var rainratehr = clientraw[20];

/*
	if (rain == 0) {
		set_ajax_obs("ajaxrain","&#8212;");
		set_ajax_obs("ajaxrainratehr","");
	} else {
*/
		set_ajax_obs("ajaxrain",rain + uomRain);
		set_ajax_obs("ajaxrainratehr",rainratehr + uomRainR);
//	}

	var uv = clientraw[16];

	var uvword = ajax_getUVrange(uv);


	if (uv == 0) {
//		set_ajax_obs("ajaxuv","&#8212;");
		set_ajax_obs("ajaxuv",uv);
		set_ajax_obs("ajaxuvword","");
		set_ajax_uom("ajaxuvword",false);
	} else {

		set_ajax_obs("ajaxuv",uv);
		set_ajax_obs("ajaxuvword",uvword);
		set_ajax_uom("ajaxuvword",true);
	}

	var solar = clientraw[17];

//	if (solar == 0) {
//		set_ajax_obs("ajaxsolar","&#8212;");
//	} else {
		set_ajax_obs("ajaxsolar",solar + uomSolar);
//	}

/*
	var rainmo = clientraw[18];
		set_ajax_obs("ajaxrainmo",rainmo + uomRain);
 
	var rainyr = clientraw[19];
		set_ajax_obs("ajaxrainyr",rainyr + uomRain);
*/

		// current date and time of observation in clientraw.txt
	var ajaxtimeformat = clientraw[0];
	var ajaxdateformat = clientraw[1];
		//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);
		
		var datetime = new Date();
		var ts = datetime.getTime();
		
		if (lastajaxtimeformat != ajaxtimeformat) {
			if (lastajaxtimeformat == 'unknown' || ajaxtimeformat > lastajaxtimeformat + 2) {
// 				set_ajax_obs("ajaxtrafficmapLA","<img src=\"http://pems.eecs.berkeley.edu/Snapshots/District/map-speed-7.png?x=" + ts + "\" alt=\"Los Angeles Traffic\" title=\"Los Angeles County Traffic\" /> ");
// 				set_ajax_obs("ajaxtrafficmapOC","<img src=\"http://pems.eecs.berkeley.edu/Snapshots/District/map-speed-12.png?x=" + ts + "\" alt=\"Orange County Traffic\" title=\"Orange County Traffic\" /> ");
// 				set_ajax_obs("ajaxtrafficmapIE","<img src=\"http://pems.eecs.berkeley.edu/Snapshots/District/map-speed-8.png?x=" + ts + "\" alt=\"Inland Empire Traffic\" title=\"Inland Empire Traffic\" /> ");
// 				set_ajax_obs("ajaxtrafficmapSD","<img src=\"http://pems.eecs.berkeley.edu/Snapshots/District/map-speed-11.png?x=" + ts + "\" alt=\"San Diego Traffic\" title=\"San Diego County Traffic\" /> ");

				set_ajax_obs("ajaxtrafficmapLA","<img src=\"assets/trafficmap7.png?x=" + ts + "\" alt=\"Los Angeles Traffic\" title=\"Los Angeles County Traffic\" /> ");
				set_ajax_obs("ajaxtrafficmapOC","<img src=\"assets/trafficmap12.png?x=" + ts + "\" alt=\"Orange County Traffic\" title=\"Orange County Traffic\" /> ");
				set_ajax_obs("ajaxtrafficmapIE","<img src=\"assets/trafficmap8.png?x=" + ts + "\" alt=\"Inland Empire Traffic\" title=\"Inland Empire Traffic\" /> ");
				set_ajax_obs("ajaxtrafficmapSD","<img src=\"assets/trafficmap11.png?x=" + ts + "\" alt=\"San Diego Traffic\" title=\"San Diego County Traffic\" /> ");

// 				//set_ajax_obs("ajaxtrafficmap","<img src=\"http://www.duarteweather.com/assets/wxgraphic/wxgraphic.php?type=banner_big&amp;" + ts + "\" alt=\"Traffic Conditions\" title=\"Traffic Conditions\" /> ");
			}
			counterSecs = 0;                      // reset timer
			lastajaxtimeformat = ajaxtimeformat; // remember this time
		}
		       
       element = document.getElementById("ajaxindicator");
		if (element) {
          element.style.color = flashcolor;
		}

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

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


// ]]>