
// <![CDATA[

// Special thanks to: Kevin Reed http://www.tnetweather.com/
// Kevin was the first to decode the clientraw in PHP
// Special thanks to: Pinto http://www.joske-online.be/
// Pinto wrote the basic AJAX code for this page!
// Cheerfully borrowed from Tom at CarterLake.org and adapted by
// Ken True - Saratoga-weather.org  21-May-2006
// --- added flash-green on data update functions - saratoga-weather.org  24-Nov-2006
//code brought up to date 3/09 by www.nhpaweather.com
// -- begin settings
var flashcolor = '#00CC00'; // color to flash for changed observations
var flashtime = '2000'; // miliseconds to keep flash color on (2000 = 2 seconds);
var ie4=document.all;
var browser = navigator.appName;
var ie8 = false;
if (ie4 && /MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=8) {
   ie4=false;
   ie8=true;
 }
}

// -- end of settings






function get_ajax_tags ( ) {
// search all the span tags and return the list with class="ajax" in it
//
  if (ie4 && browser != "Opera" && ! ie8) {
     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 convertRain ( rawrain ) {
	if (useunits == 'E') { // convert mm to inches
	   return (rawrain * .0393700787);
	} else {
	   return (rawrain * 1.0); // leave in mm
	}
}

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
  element = document.getElementById(name);
  if (! element) { return; } // don't store if no <span> tag found for this id=
  lastobs = element.getAttribute("lastobs");
  element.setAttribute("lastobs",value);
  if (value != lastobs) {
    element.style.color=flashcolor;
  }
  element.innerHTML = value;
}

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 RoundToInteger(X, N) { 
  var T = Math.pow(10, N)
  return Math.round(X*T)/T 
}

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;

  }
}

// main AJAX routine .. load and format clientraw.txt
function ajaxLoader(url) {
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  }
  
  
  
  if (x) {
    x.onreadystatechange = function() {
      if (x.readyState == 4 && x.status == 200) {
//alert(x.responseText)

		//Temp
		temp = (1.8 * x.responseText.split(' ')[4]) + 32.0; 
		set_ajax_obs("ajaxtemp",  temp.toFixed(1) + "&deg;F");

		temptrend = ((1.8 * x.responseText.split(' ')[4]) + 32.0) - ((1.8 * x.responseText.split(' ')[90]) + 32.0);
		if (temptrend > 0) {
			temptrend = "+" + temptrend.toFixed(1);
			set_ajax_obs("ajaxtemptrendgraphic", '&nbsp;<img src="./arrows2/upred.gif" height="14" width="14" alt="Temperature Rising" title="Temperature Rising">');
		} else if (temptrend < 0) {
			temptrend = temptrend.toFixed(1);
			set_ajax_obs("ajaxtemptrendgraphic", '&nbsp;<img src="./arrows2/down.gif" height="14" width="14" alt="Temperature Falling" title="Temperature Falling">');
		} else {
			temptrend = "+" + temptrend.toFixed(1);
			set_ajax_obs("ajaxtemptrendgraphic", '&nbsp;<img src="./arrows2/steady.gif" height="14" width="14" alt="Temperature Steady" title="Temperature Steady">');
		}

		// FeelsLike
		temp = x.responseText.split(' ')[4];
		if (temp <= 16.0 ) {
			feelslike = x.responseText.split(' ')[44]; //use WindChill
			feelslike  = (1.8 * feelslike) + 32.0;
			set_ajax_obs("ajaxfeelslike", "&nbsp;&nbsp;Wind Chill: " + feelslike.toFixed(1) + " &deg;F");
		} else if (temp >=27.0) {
			feelslike = x.responseText.split(' ')[112]; //use Heat Index
			feelslike  = (1.8 * feelslike) + 32.0;
			set_ajax_obs("ajaxfeelslike", "&nbsp;&nbsp;Heat Index: " + feelslike.toFixed(1) + " &deg;F");
		} else {
			set_ajax_obs("ajaxfeelslike", "");
		}

		//Pressure...
		press = x.responseText.split(' ')[6] / 33.86388158;
		set_ajax_obs("ajaxbaro", (press.toFixed(2)) + " in.");

		presstrend = x.responseText.split(' ')[50] / 33.86388158;
		if (presstrend > 0) {
			presstrend = "+" + presstrend.toFixed(3);
			set_ajax_obs("ajaxpresstrendgraphic", '&nbsp;<img src="./arrows2/up.gif" height="14" width="14" alt="Pressure Rising" title="Pressure Rising">');
		} else if (presstrend < 0) {
			presstrend = presstrend.toFixed(3);
			set_ajax_obs("ajaxpresstrendgraphic", '&nbsp;<img src="./arrows2/down.gif" height="14" width="14" alt="Pressure Falling" title="Pressure Falling">');
		} else {
		set_ajax_obs("ajaxpresstrendgraphic", '&nbsp;<img src="./arrows2/steady.gif" height="14" width="14" alt="Pressure Trend Steady" title="Pressure Trend Steady">');		
		}

		//Windspeed ...
		wind = x.responseText.split(' ')[2]* 1.1507794;
		set_ajax_obs("ajaxwind", "&nbsp;" + (wind.toFixed(1)) + " mph");

		val = windDir(x.responseText.split(' ')[3]);
 		set_ajax_obs("ajaxwinddir", "&nbsp;" + val);
 		set_ajax_obs("ajaxwindicon", '&nbsp;<img src=./arrows/' + val + '.gif width="10" height="10" alt="Wind from ' + val + '" title="Wind from ' + val + '"></img>');


		//Rain ...
		rain = x.responseText.split(' ')[7]* .0393700787;
		set_ajax_obs("ajaxrain", rain.toFixed(2));

		//Humidity ...
		humidity = x.responseText.split(' ')[5];
		set_ajax_obs("ajaxhumidity", humidity + "%");
		
		// currently text
		wdtxt = x.responseText.split(' ')[49];
		wdtxt = wdtxt.replace(/_/g,' ');
		wdtxt = wdtxt.replace(/^\/Dry\//g,'');
		wdtxt = wdtxt.replace(/\\/g,', ');
		wdtxt = wdtxt.replace(/\//g,', ');
		set_ajax_obs("ajaxwdtxt", wdtxt);
		
		//Solar ...
                solar = x.responseText.split(' ')[34];
                set_ajax_obs("ajaxsolar", solar + "%");
		
		//UV
		uv = x.responseText.split(' ')[79];
		set_ajax_obs("ajaxuv", uv);
		
		//--- begin cloud height graphic -----------------------------------------------
      useunits = 'E';
      useKnots = false;	
      useMPS = false;
      var uomTemp = '&deg;F';
      var uomWind = ' mph';
      var uomBaro = ' inHg';
      var uomRain = ' in';
      var uomHeight = ' ft';
      var dpBaro = 2;
      var dpRain = 2;
      stationAlt = 147.218; // your station altitude in meters if you want ASL (meters = ft / 3.2808399)
      temp1 = x.responseText.split(' ')[4];
      dewp = x.responseText.split(' ')[72];
      pres = press;
      //wind1 = convertWind(x.responseText.split(' ')[1]); // gust = clientraw[2]
      wdir = val;
      cloudheight = Math.max(0,(temp1-dewp)/0.00802)*1.0 + stationAlt; // in meters
      altitude = (useunits=="E") ? Math.round(cloudheight*3.2808399) : Math.round(cloudheight);
      above = (stationAlt>0)? ' ASL' : ' AGL';
      cloudText = altitude.toString() + uomHeight + above;
      param = '?uom=' + useunits + '&alti=' + uomHeight + '&wind=' + uomWind + '&buster=' + altitude + pres + wind + wdir + rain;
      set_ajax_obs("ajaxcloudheightimg"
         ,'<img src="cloud-base.php' + param
         + '" alt="'    + cloudText
         + '" title="'  + cloudText
         + '" width="100" height="200" hspace="0" vspace="0" align="" border="0" style="" />');
//--- end cloud height graphic -------------------------------------------------
		
		ajaxdatetimeformat = x.responseText.split(' ')[32];
		ajaxdatetimeformat = ajaxdatetimeformat.replace( /_/g , " ");
		ajaxdatetimeformat = ajaxdatetimeformat.replace( "-" , " ");
		
		set_ajax_obs("ajaxdatetime", ajaxdatetimeformat.substring(15) + ' ET'); 
				
   }
    }
    x.open("GET", url, true);
    x.send(null);

//set_ajax_color('#00CC00'); // change all the ajax text to green
//setTimeout("set_ajax_color('')",2000); // change text back to default color after 2 secs
//setTimeout("reset_ajax_color()",2000); // change text back to default color after 2 secs
setTimeout("reset_ajax_color('')",flashtime); // change text back to default color 
//edit the location of this file twice!! (here and in the body onload)
  setTimeout("ajaxLoader('clientraw.txt?'+new Date())", 10000); // get new data after 10 secs
  }
} // end ajaxLoader function

// ----------------------------------------------------------------------
// Rotate content display -- Ken True -- saratoga-weather.org
var ajaxrotatedelay=3000; // gizmo speed
//var ie4 = 0;
var ajaxcurindex = 0;
var ajaxtotalcontent = 0;
var ajaxrunrotation = 1;
var ie4=document.all;
var browser = navigator.appName;
var ie8 = false;
if (ie4 && /MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=8) {
   ie4=false;
   ie8=true;
 }
}
//var browser = navigator.appName;

function get_content_tags ( tag ) {
// search all the span tags and return the list with class=tag 
//
 if (ie4 && browser != "Opera" && ! ie8) {
    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 == tag) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }

     return arr;
}




function ajax_get_total() {
  if (ie4) {
//    while (eval("document.all.content"+ajaxtotalcontent)) {
//      ajaxtotalcontent++;
	  ajaxtotalcontent = 7;
//	}
  } else{
//    while (var elements = document.getElementsByName("content"+ajaxtotalcontent)) {
//      var nelements = elements.length;
//	  alert("content"+ajaxtotalcontent + " length=" +nelements);
	  ajaxtotalcontent = 7;
//	}
  }
}

function ajax_contract_all() {
  for (var y=0;y<ajaxtotalcontent;y++) {
      var elements = get_content_tags("content"+y);
	  var numelements = elements.length;
//	  alert("ajax_contract_all: content"+y+" numelements="+numelements);
	  for (var index=0;index!=numelements;index++) {
         var element = elements[index];
		 element.style.display="none";
      }
  }
}

function ajax_expand_one(which) {
  ajax_contract_all();
  var elements = get_content_tags("content"+which);
  var numelements = elements.length;
  for (var index=0;index!=numelements;index++) {
     var element = elements[index];
	 element.style.display="inline";
  }
}
function ajax_step_content() {
  ajax_get_total();
  ajax_contract_all();
  ajaxcurindex=(ajaxcurindex<ajaxtotalcontent-1)? ajaxcurindex+1: 0;
  ajax_expand_one(ajaxcurindex);
}
function ajax_set_run(val) {
  ajaxrunrotation = val;
  ajax_rotate_content();
}
function ajax_rotate_content() {
  if (ajaxrunrotation) {
    ajax_get_total();
    ajax_contract_all();
    ajax_expand_one(ajaxcurindex);
    ajaxcurindex=(ajaxcurindex<ajaxtotalcontent-1)? ajaxcurindex+1: 0;
    setTimeout("ajax_rotate_content()",ajaxrotatedelay);
  }
}

ajax_rotate_content();

// ]]>

