// <![CDATA[

//**
// * @author James Martin
// * @copyright 2008
// */

// This code is a modified version of the code from CarterLake.org used to decode the
// clientraw.txt file from Weather Display but used here to decode a csv file derived from
// the Instromet MetLoG datalogger and Met4NeT software by the author.

// 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
//                                   metlogcsv.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
// --- Version 2.07 - 21-Sep-2007 -- added support for dynamic thermometer.php display refresh
// --- Version 2.08 - 07-Nov-2007 -- added useMPH to force wind display in Miles-per-hour and
//                                   added optional Wind-Rose, optional new current icon display graphics
// --- Version 2.09 - 23-Dec-2007 -- added maxupdates feature, new ajax variables from K. Reed www.tnetweather.com
// --- Version 2.10 - 18-Jan-2008 -- fixed icon=34 for ra1.jpg
// --- Version 2.11 - 21-Feb-2008 -- added icon=35 for windyrain.gif/.jpg
// --- Version 2.12 - 07-Mar-2008 -- added fix for 'flashing icon/thermometer' from Jim at jcweather.us
// --- Version 2.13 - 11-Mar-2008 -- changed Wind-rose defaults to .png type (Carterlake/AJAX/PHP templates)
// --- Version 2.14 - 29-Mar-2008 -- fixed UV words with  color: black; for display on dark/black template (MCHALLIS)
////
// 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  = 4000;       // miliseconds to keep flash color on (2000 = 2 seconds);
var reloadTime = 5000;       // reload AJAX conditions every 5 seconds (= 5000 ms)
var maxupdates = 0;	         // Maxium Number of updates allowed (set to zero for unlimited)
                             // maxupdates * reloadTime / 1000 = number of seconds to update
var metlogcsvdat = 'metlogcsv.txt'; // location of metlogcsv.txt relative to this page on website
var ajaxLoaderInBody = false; // set to true if you have <body onload="ajaxLoader(..."
var langPauseMsg = 'Updates paused - reload page to start'; // substitute this for ajaxindicator when
                             // maxupdates has been reached and updating paused.

// -- end of settings -------------------------------------------------------------------------

var ie4=document.all;
var browser = navigator.appName;
var counterSecs = 0;  // for MCHALLIS counter script from weather-watch.com (adapted by K. True)
var updates = 0;		// update counter for limit by maxupdates
var lastajaxtimeformat = 'unknown'; //used to reset the counter when a real update is done
var doTooltip = 0;   // set to 1 to have ajaxed variable names appear as tooltips (except for graphics)


// 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();
	 var iarr = 0;
     for(var i = 0; i < elem.length; i++) {
          var 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;
		  if ( doTooltip ) { element.setAttribute("title",'AJAX tag '+name); }
		}
		element.innerHTML =  value;
}
// Mike Challis' counter function (adapted by Ken True)
//
function ajax_countup() {
 element = document.getElementById("ajaxcounter");
 if (element) {
  element.innerHTML = counterSecs;
  counterSecs++;
 }
}

/*
if (iconWD >= 0 && iconWD <= 35) { 
    return ("<img src=\"" + imagedir + "/" + $iconList[iconWD] + "\" " +
				"width=\"25\" height=\"25\" alt=\"Current condition icon\" />" );
  } else {
	return '';
  }

}

function ajax_wxIconJPG ( iconWD ) { 
// perform a lookup and return the graphic for the condition icon (using NWS icons)
  $iconList = new Array(
  
  "ra1.jpg",			//  0 nothing
  "ra1.jpg",			//	1 drizzle	
  "ra1.jpg",			//	2 light rain
  "ra.jpg",				//  3 rain
  "ra.jpg",				//  4 Moderate rain
  "ra.jpg",				//  5 Heavy rain
  "ra.jpg",				//  6 Very Heavy rain
  "ra.jpg",				//  7 Downpour 
  "ra.jpg",				//  8 Torrential rain
  "ovc.jpg",          	//  9 imageovercast.visible
  "bkn.jpg",            // 10 imagecloudy.visible
  "sct.jpg",            // 11 imagedry.visible
  "few.jpg",          	// 12 imagemainlyfine.visible
  "skc.jpg",            // 13 imagesunny.visible


  
    /*
    "skc.jpg",          //  0 imagesunny.visible
	"nskc.jpg",         //  1 imageclearnight.visible
	"bkn.jpg",          //  2 imagecloudy.visible
	"sct.jpg",          //  3 imagecloudy2.visible
	"nbkn.jpg",         //  4 imagecloudynight.visible
	"sct.jpg",          //  5 imagedry.visible
	"fg.jpg",           //  6 imagefog.visible
	"hazy.jpg",         //  7 imagehaze.visible
	"ra.jpg",           //  8 imageheavyrain.visible
	"few.jpg",          //  9 imagemainlyfine.visible
	"mist.jpg",         // 10 imagemist.visible
	"nfg.jpg",          // 11 imagenightfog.visible
	"nra.jpg",          // 12 imagenightheavyrain.visible
	"novc.jpg",         // 13 imagenightovercast.visible
	"nra.jpg",          // 14 imagenightrain.visible
	"nshra.jpg",        // 15 imagenightshowers.visible
	"nsn.jpg",          // 16 imagenightsnow.visible
	"ntsra.jpg",        // 17 imagenightthunder.visible
	"ovc.jpg",          // 18 imageovercast.visible
	"bkn.jpg",          // 19 imagepartlycloudy.visible
	"ra.jpg",           // 20 imagerain.visible
	"ra.jpg",           // 21 imagerain2.visible
	"shra.jpg",         // 22 imageshowers2.visible
	"ip.jpg",           // 23 imagesleet.visible
	"ip.jpg",           // 24 imagesleetshowers.visible
	"sn.jpg",           // 25 imagesnow.visible
	"sn.jpg",           // 26 imagesnowmelt.visible
	"sn.jpg",           // 27 imagesnowshowers2.visible
	"skc.jpg",          // 28 imagesunny.visible
	"scttsra.jpg",      // 29 imagethundershowers.visible
	"hi_tsra.jpg",      // 30 imagethundershowers2.visible
	"tsra.jpg",         // 31 imagethunderstorms.visible
	"nsvrtsra.jpg",     // 32 imagetornado.visible
	"wind.jpg",         // 33 imagewindy.visible
	"ra1.jpg",          // 34 stopped rainning
	"windyrain.jpg"     // 35 windy/rain (new with V2.11)
	
	);					
*/
/*
  if (iconWD >= 0 && iconWD <= 35) { 
    return ("<img src=\"" + imagedir + "/" + $iconList[iconWD] + "\" " +
				"width=\"55\" height=\"58\" alt=\"Current condition icon\" />" );
  } else {
	return '';
  }

}
*/
// ------------------------------------------------------------------------------------------
//  main function.. read metlogcsv.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 metlogcsv = x.responseText.split(',');
	// now make sure we got the entire metlogcsv.txt  -- thanks to Johnnywx.  Not used here
	// valid metlogcsv.txt has 'metlog' at start of record
	
	// If we have a valid metlogcsv file AND updates is < maxupdates
	if(metlogcsv[0] == 'metlog' && 
	   ( updates <= maxupdates || maxupdates > 0  ) ) {
		if (maxupdates > 0 ) {updates++; } // increment counter if needed.
		
		
//DATA EXTRACT SECTION
		
// Rain data and date and time.

		raintoday=metlogcsv[1]+" mm"; // 
		//raintoday=raintoday.toFixed(2)+" mm";// not required?
		set_ajax_obs("ajaxrain",raintoday);
		
		timelastrain=metlogcsv[2];//+", "+metlogcsv[3]+", "+metlogcsv[4];// where metlogcsv[2]= day name, metlogcsv[3]= day and month last rain, metlogcsv[4] =time last rain.
		set_ajax_obs("ajaxtimelastrain",timelastrain);
		
		rainrate=metlogcsv[3]+" mm/hr";// current rain rate.
		set_ajax_obs("ajaxrainrate",rainrate);

		
		maxrainrate=metlogcsv[6]+" mm/hr";// maximum rain rate today.
		set_ajax_obs("ajaxmaxrainrate",maxrainrate);
		
		timemaxrainrate=metlogcsv[7]+", "+metlogcsv[8];// where metlogcsv[7]= day name, metlogcsv[8]= time maximum rain.  Valid only on rain today.
		set_ajax_obs("ajaxtimemaxrainrate",timemaxrainrate);

// Sun data and date and time.

		suntoday=metlogcsv[7]+" hrs";// metlogcsv[9] = sunshine hours.
		set_ajax_obs("ajaxsun",suntoday);

			
		timelastsun=metlogcsv[8]+" "+metlogcsv[9]+" "+metlogcsv[10];//where metlogcsv[10]= day name, metlogcsv[11]= day and month last sun, metlogcsv[12] =time last sun.
		set_ajax_obs("ajaxtimelastsun",timelastsun);
		
// Weather conditions description text.

		currcond=metlogcsv[11];//current weather conditions from Met4Net data.  Only valid between dawn and dusk.
		set_ajax_obs("ajaxcurrcond",currcond);
		
// Weather conditions icon.  Currently not used.
		
		currcondicon=metlogcsv[1];
		set_ajax_obs("ajaxcurrcondicon",currcondicon);

//Metlog date andtime
		clocktime=metlogcsv[13];
		set_ajax_obj("ajaxclocktime",clocktime);


		
// current date and time.  Only used in this program to reset counter.

		ajaxtimeformat ='Harrow,_UK-'+ new Date().getTime();
		ajaxdateformat =  new Date();
		
		//set_ajax_obs("ajaxdatetime",ajaxdateformat + " " +ajaxtimeformat);
		set_ajax_obs("ajaxdate",ajaxdateformat);
		set_ajax_obs("ajaxtime",ajaxtimeformat);
		
		if (lastajaxtimeformat != ajaxtimeformat) {
			counterSecs = 0;                      // reset timer
			lastajaxtimeformat = ajaxtimeformat; // remember this time
		}
		
// now ensure that the indicator flashes on every AJAX fetch

        element = document.getElementById("ajaxindicator");
		if (element) {
          element.style.color = flashcolor;
		}
		if (maxupdates > 0 && updates > maxupdates-1) { /* chg indicator to pause message */
			set_ajax_obs("ajaxindicator",langPauseMsg);
		}
		set_ajax_obs('ajaxupdatecount',updates);       /* for test pages */
		set_ajax_obs('ajaxmaxupdatecount',maxupdates); /* for test pages */

 	  } 

	 } // 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);

//  reset the flash colors, and restart the update unless maxupdate limit is reached

    setTimeout("reset_ajax_color('')",flashtime); // change text back to default color 

	if ( (maxupdates == 0) || (updates < maxupdates-1)) {
      setTimeout("ajaxLoader(metlogcsvdat + '?' + new Date().getTime())", reloadTime); // get new data 
    }
  }
} // 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(metlogcsvdat + '?' + new Date().getTime(), reloadTime); }

// ]]>