// <![CDATA[

/*
 beteljuice has adapted Ken Trues AJAX script so it can be used with Cumulus 1.8.3 or higher
 beteljuice October 2008
 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

 V1.x open
 The idea is you edit / add / modify for yourself ;-)
 for updates to this script, see - haven't decided yet
 announcements of new versions will be on - somewhere to be announced
*/
var ajax_attempt = 0;

// -- begin settings --------------------------------------------------------------------------
var here = 'http://www.wheelocknet.net/betel/';  // URL PATH to the directory for this script (include trailing / )
var currdatFile = 'http://www.wheelocknet.net/cumulus/slowtime.txt'; // URL location of realtime.txt 
var station_day = 0;	// when does your data 'day' begin - 0 = 00:00, 1 = 09:00
var station_alt = 50;	// height of baro Above Sea Level - METRES please !
var imagedir = 'http://www.wheelocknet.net/betel/ajax-images';  // place for wind arrows, rising/falling arrows, etc.
var flashcolor = '#FF0000'; // color to flash for changed observations RGB
var flashtime  = 2000;       // miliseconds to keep flash color on (2000 = 2 seconds);
var reloadTime = 1000000;       // reload AJAX conditions every 10 seconds (= 10000 ms)
var maxupdates = 0;	         // Maxium Number of updates allowed (set to zero for unlimited)
                             // maxupdates * reloadTime / 1000 = number of seconds to update
var ajaxLoaderInBody = false; // set to true if you have <body onload="ajaxLoader(..."

// optional settings for the Wind Rose graphic in ajaxwindiconwr as wrName + winddir + wrType
var wrName   = 'wr-';       // first part of the graphic filename (followed by winddir to complete it)
var wrType   = '.gif';      // extension of the graphic filename
var wrHeight = '58';        // windrose graphic height=
var wrWidth  = '58';        // windrose graphic width=
var wrCalm   = 'wr-calm.gif';  // set to full name of graphic for calm display ('wr-calm.gif')
// -- end of settings -------------------------------------------------------------------------



var ie4=document.all;
var browser = navigator.appName;
var ie8 = false;   // this and below NEW for IE8
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 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 (tweaked for IE8)

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();
    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;
}   // END function get_ajax_tags


function check_ajax_class(elem) {   // tweaked for IE8
// check element id for class="ajax" in it

  if (ie4 && browser != "Opera" && ! ie8) {
   var lookfor = 'className';
  } else {
   var lookfor = 'class';
  }

  var class_check = "";
  var att = elem.getAttribute(lookfor);
  if(att == 'ajax') {
       class_check = 1;
   }
   return class_check;
}
// --- END function check_ajax_class()
// --- END function check_ajax_class()



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 get_last( name ) {
// return STORED value - best use BEFORE Rset_ajax_obs ! - typically used for 'change since last'
		var element = document.getElementById(name);
		if (! element ) { return ; } // V1.04 -- don't set if missing the <span id=name> tag
		var prevobs = element.getAttribute("lastobs");
		return prevobs;
}



// **************************
function Rset_ajax_obs( name, value, uom ) {
// store away the current value in both the doc and the span as lastobs="value" and forward Unit Of Measure (or user suffix)

		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");
//		if (value != unescape(lastobs)) {
		if (value != lastobs) {
			element.setAttribute("lastobs",value);

  			if(check_ajax_class(element) ) {	// only change text colour if class = 'ajax'
           			element.style.color=flashcolor;
 			}

 			element.innerHTML =  value+uom;
		 	 if ( doTooltip ) { element.setAttribute("title",'AJAX tag:  '+name); }
		}
}



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






// ------------------------------------------------------------------------------------------
//  main function.. read realtime.txt and format <span class="ajax" id="......"></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 currdat = x.responseText.replace(/\r\n/g, "");	// this gets rid of any line ending
 //  	var currdat = currdat.split(' ');	// populate the array

  var currdat = x.responseText;
      var currdat = currdat.split('\n');   // populate the array
<!-- new stuff -->
//var output = "";
//for (var index = 0;index < currdat.length ;index++) {
 //        output += "currdat[" + index + "] = " + currdat[index] + "<br />";
//}



//document.getElementById('mytest').innerHTML = output;
document.getElementById('time_tag').innerHTML = currdat[114];
document.getElementById('sunrise_tag').innerHTML = currdat[130];
document.getElementById('sunset_tag').innerHTML = currdat[131];
document.getElementById('sunset_tag_t').innerHTML = currdat[131];
document.getElementById('latitude_tag').innerHTML = currdat[116];
document.getElementById('longitude_tag').innerHTML = currdat[117];
document.getElementById('altitude_tag').innerHTML = currdat[118];
document.getElementById('dawn_tag').innerHTML = currdat[134];
document.getElementById('sunrise_tag_t').innerHTML = currdat[130];
document.getElementById('moonrise_tag').innerHTML = currdat[138];
document.getElementById('dusk_tag').innerHTML = currdat[135];
document.getElementById('sunset_tag').innerHTML = currdat[135];
document.getElementById('moonset_tag').innerHTML = currdat[139];
document.getElementById('day_light_length_tag').innerHTML = currdat[136];
document.getElementById('day_length_tag').innerHTML = currdat[132];
document.getElementById('moonphase_tag').innerHTML = currdat[137];

document.getElementById('today_temp_hi_tag').innerHTML = currdat[46];
document.getElementById('today_temp_hi_time_tag').innerHTML = currdat[12];
document.getElementById('today_temp_lo_tag').innerHTML = currdat[47];
document.getElementById('today_temp_lo_time_tag').innerHTML = currdat[13];

document.getElementById('yester_temp_hi_tag').innerHTML = currdat[48];
document.getElementById('yester_temp_hi_time_tag').innerHTML = currdat[14];
document.getElementById('yester_temp_lo_tag').innerHTML = currdat[49];
document.getElementById('yester_temp_lo_time_tag').innerHTML = currdat[15];



document.getElementById('today_rain_tag').innerHTML = currdat[71];
document.getElementById('yester_rain_tag').innerHTML = currdat[72];

document.getElementById('today_rain_rate_tag').innerHTML = currdat[80];
//document.getElementById('today_rain_rate_tag').innerHTML = "5.5"
document.getElementById('today_rain_rate_time_tag').innerHTML = currdat[33];

document.getElementById('yester_rain_rate_tag').innerHTML = currdat[81];
document.getElementById('yester_rain_rate_time_tag').innerHTML = currdat[34];

document.getElementById('today_max_gust_tag').innerHTML = currdat[100];
document.getElementById('today_max_gust_time_tag').innerHTML = currdat[28];
document.getElementById('yester_max_gust_tag').innerHTML = currdat[101]
document.getElementById('yester_max_gust_time_tag').innerHTML = currdat[29];
document.getElementById('today_max_wind_tag').innerHTML = currdat[98];
document.getElementById('today_max_wind_time_tag').innerHTML = currdat[26];
document.getElementById('yester_max_wind_tag').innerHTML = currdat[99];
document.getElementById('yester_max_wind_time_tag').innerHTML = currdat[27];

document.getElementById('today_hi_beau_tag').innerHTML = currdat[109];
document.getElementById('yester_hi_beau_tag').innerHTML = currdat[110];


document.getElementById('today_windrun_tag').innerHTML = currdat[94];
document.getElementById('yester_windrun_tag').innerHTML = currdat[95];
document.getElementById('tpressth').innerHTML = currdat[62];
document.getElementById('tpressth_time').innerHTML = currdat[20];
document.getElementById('ypressth').innerHTML = currdat[64];
document.getElementById('ypressth_time').innerHTML = currdat[22];

document.getElementById('tpressth_lo').innerHTML = currdat[63];
document.getElementById('tpressth_time_lo').innerHTML = currdat[21];
document.getElementById('ypressth_lo').innerHTML = currdat[65];
document.getElementById('ypressth_time_lo').innerHTML = currdat[23];
<!-- End new stuff -- >

	// now make sure we got a realtime.txt with minimum content
	// If we have a valid currdat file AND updates is < maxupdates
	if(currdat[137] && ( updates <= maxupdates || maxupdates > 0  ) ) {
		if (maxupdates > 0 ) {updates++; } // increment counter if needed

// ----- time / date  --------------------------------------------------------------- ORDER CHANGED from original
 		ajaxtimeformat = currdat[11];

		if(lastajaxtimeformat != ajaxtimeformat ) {		//  filestamp  check





// --------- END Extras and Duplicates ---------------------

			counterSecs = 0;                      // reset timer
			lastajaxtimeformat = ajaxtimeformat; // remember this time

		
		} // END filestamp check


		// 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 */
			Rset_ajax_obs("ajaxindicator",langPauseMsg, "");
		}
		Rset_ajax_obs('ajaxupdatecount',updates, "");       /* for test pages */
		Rset_ajax_obs('ajaxmaxupdatecount',maxupdates, ""); /* for test pages */


 	  } // END if(currdat content checks)

	 } // 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(currdatFile + '?' + new Date().getTime())", reloadTime); // get new data 
//(!document.getElementById('ajaxEND') ? thisTime = 200 : thisTime = reloadTime);
// betel(document.getElementById('ajaxEND'));
// 	     setTimeout("ajaxLoader(currdatFile + '?' + new Date().getTime())", thisTime); // get new data 
    }
  }
} // end ajaxLoader function


// window.setInterval("ajax_countup()", 1000); // run the counter for seconds since update


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

function start_up() {
	if(document.getElementById('ajaxEND')) {
		ajaxLoader(currdatFile + '?' + new Date().getTime());
 window.setInterval("ajax_countup()", 1000); // run the counter for seconds since update
	} else {
		ajax_attempt++;
		if(ajax_attempt >= 50) {
			betel('Page has failed to download fully'); // 50 attempts for page to format
		} else {
			setTimeout('start_up()', 200);
		}
	}
}

start_up();


/* this is for debug - errors within ajax can do all sorts of strange things !
   normal alert may or may not work, this being called outside of the loop is more likely
   to work (depends on the error)
   line before or line after where you think the problem is use
   betel("Here");
   or 
   betel(varname);
*/

function betel(msg) {
alert(msg);
}

// ]]>
