// <![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
// --- 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
//
// 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

var xmlWeatherData = 'dataweather.txt';
var lastUpdate = 'actual_localdate2';
var currentPressure = 'actual_thb0_sealevel_hpa';
var last_60minutes_pressure = 'last60m_thb0_sealevel_hpa';
var today_max_pressure='day1_thb0_sealevelmax_hpa';
var today_min_pressure='day1_thb0_sealevelmin_hpa';
var currentTemperature='actual_th0_temp_c';
var today_max_temperature='day1_th0_tempmax_c';
var today_min_temperature='day1_th0_tempmin_c';
var current_wind_direction = 'actual_wind0_dir_en';
var current_wind_gust = 'actual_wind0_gustspeed_kmh';
var current_wind_speed = 'actual_wind0_speed_kmh';
var current_rain_rate = 'actual_rain0_rate_mm';
var today_max_hum = 'day1_th0_hummax_rel';
var today_min_hum = 'day1_th0_hummin_rel';
var current_hum = 'actual_th0_hum_rel';
var today_total_rain = 'day1_rain0_total_mm';
var last_24hours_rain = 'last24h_rain0_total_mm';
var last_60minutes_rain = 'last60m_rain0_total_mm';
var feels_like = 'actual_wind0_chill_c';
var last_60minutes_temp = 'last60m_th0_temp_c';
var yesterday_max_temp = 'seqday1_th0_tempmax_c';													
var yesterday_min_temp = 'seqday1_th0_tempmin_c';													
var yesterday_rain = 'seqday1_rain0_total_mm';
var yesterday_gust = 'seqday1_wind0_gustspeed_kn';
var month_max_temp = 'month1_th0_tempmax_c';
var month_min_temp = 'month1_th0_tempmin_c';
var month_avg_temp = 'month1_th0_temp_c';
var month_rain_total = 'month1_rain0_total_mm';
var month_max_gust = 'month1_wind0_gustspeedmax_kmh';
var month_avg_gust = 'month1_wind0_speed_kmh';
var month_max_press = 'month1_thb0_sealevelmax_hpa';
var month_min_press = 'month1_thb0_sealevelmin_hpa';
var month_avg_press = 'month1_thb0_sealevel_hpa';



// -- 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 = 'clientraw.txt'; // location of clientraw.txt relative to this page on website
var ajaxLoaderInBody = false; // set to true if you have <body onload="ajaxLoader(..."
var imagedir = './ajax-images';  // place for wind arrows, rising/falling arrows, etc.
var useunits = 'M';         // '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 useMPH   = false;       // set to true to force MPH for both English and Metric units
var useFeet  = false;       // set to true to force Feet for height in both English and Metric
var showUnits = true;       //  set to false if no units are to be displayed
var thermometer = './thermometer.php'; // script for dynamic thermometer PNG image (optional)
// -- end of settings -------------------------------------------------------------------------

// -- language settings -- you don't need to customize this area if you are using English -----

var langMonths = new Array ( "Janeiro","Fevereiro","Mar&ccedil;o","Abril","Maio",
			"Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro");
var langDays = new Array ( "Dom","Seg","Ter","Qua","Qui","Sex","S&aacute;b","Dom");	

var langBaroTrend = new Array ("Est&aacute;vel", "Subir Lentamente", "Subir Rapidamente", "Cair Lentamente", "Cair Rapidamente");

var langUVWords = new Array (
 "None", "Low", "Medium", "High",
 "Very&nbsp;High", /* be sure to include &nbsp; for space */
 "Extreme" );

var langBeaufort = new Array ( /* Beaufort 0 to 12 in array */
 "Calmo", "Aragem", "Brisa ", "Brisa suave", "Brisa moderada", "Brisa fresca",
 "Brisa forte", "Rajada moderada", "Rajada fresca", "Rajada forte", "Rajada total",
 "Tempestade", "Furacão"
);

var langWindDir = new Array( /* used for alt and title tags on wind dir arrow and wind direction display */
	"N", "NNE", "NE", "ENE", 
	"E", "ESE", "SE", "SSE", 
	"Sul", "SSW", "SW", "WSW", 
	"W", "WNW", "NW", "NNW");

var langWindCalm = 'Calmo';
var langGustNone = 'n/d';
var langWindFrom = 'Wind from '; /* used on alt/title tags on wind direction arrow*/

// -- end of language 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
var doTooltip = 0;   // set to 1 to have ajaxed variable names appear as tooltips (except for graphics)

// 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 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';
	uomBaro = ' hPa';
	uomRain = ' mm';
	uomHeight = ' m';
	dpBaro = 1;
	dpRain = 1;
  }
  if(useKnots) { uomWind = ' kts'; }
  if(useMPS)   { uomWind = ' m/s'; }
  if(useMPH)   { uomWind = ' mph'; }
  if(useFeet)  { uomHeight = ' ft'; }
  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();
	 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 set_ajax_obs( name, value ) {
		var element = document.getElementById(name);	
		element.innerHTML =  value;
}


function aux_get_yesterday_value(value) {
  return value.split("_")[0];
}

function aux_convert_kn_in_km(value) {
  return Math.round(value * 1.852*100)/100 ;
}

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(xmlWeatherData);
  }
   	
	if (x) {	 // got something back
    x.onreadystatechange = function() {
    try { // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE 
		if (x.readyState == 4 && x.status == 200) 
		{ 
		  
			lines = x.responseText.split("\n");
			for(i=0;i<lines.length;i++)
			{
			 
			 if (lines[i].split(" ")[0] == lastUpdate) {
			  ajaxtimeformat = lines[i].split(" ")[1] + " " + lines[i].split(" ")[2];
				if (lastajaxtimeformat != ajaxtimeformat) {
					counterSecs = 0;                      // reset timer
					lastajaxtimeformat = ajaxtimeformat; // remember this time
					}
				set_ajax_obs("ajaxdatetime", lines[i].split(" ")[1] + " " + lines[i].split(" ")[2]);	
			 }
			 if (lines[i].split(" ")[0] == currentPressure) {
					actual_press = lines[i].split(" ")[1];
					set_ajax_obs("ajaxbaro", actual_press + uomBaro);	
				}
				if (lines[i].split(" ")[0] == last_60minutes_pressure) {
					previous_press = lines[i].split(" ")[1];
					sign = "";
					trend = actual_press - previous_press;					 
					if (trend > 0){sign="+";}
					set_ajax_obs("ajaxbarotrendtext",sign +  Math.round((actual_press - previous_press)*1000)/1000 + uomBaro);	
				}

			 if (lines[i].split(" ")[0] == today_max_pressure) {set_ajax_obs("ajaxbaromax", lines[i].split(" ")[1] + uomBaro);	}
			 if (lines[i].split(" ")[0] == today_min_pressure) {set_ajax_obs("ajaxbaromin", lines[i].split(" ")[1] + uomBaro);	}
			 if (lines[i].split(" ")[0] == currentTemperature) {
					actual_temp = lines[i].split(" ")[1];
					set_ajax_obs("ajaxtemp", actual_temp + uomTemp);	
			 }
			 if (lines[i].split(" ")[0] == last_60minutes_temp) {	  
					previous_temp = lines[i].split(" ")[1];
					trend = actual_temp - previous_temp;
					sign = "";
					if (trend > 0){sign="+";}
					
					set_ajax_obs("ajaxtemprate",sign +  Math.round((actual_temp - previous_temp)*100)/100 + uomTemp);	
			 }			 			 
			 if (lines[i].split(" ")[0] == today_max_temperature) {set_ajax_obs("ajaxtempmax", lines[i].split(" ")[1] + uomTemp);	}
			 if (lines[i].split(" ")[0] == today_min_temperature) {set_ajax_obs("ajaxtempmin", lines[i].split(" ")[1] + uomTemp);	}
			 if (lines[i].split(" ")[0] == current_wind_direction) {set_ajax_obs("ajaxwinddir", lines[i].split(" ")[1]);	}
			 if (lines[i].split(" ")[0] == current_wind_speed) {set_ajax_obs("ajaxgust", lines[i].split(" ")[1] + uomWind);	}	  
			 if (lines[i].split(" ")[0] == current_wind_gust) {set_ajax_obs("ajaxmaxgust", lines[i].split(" ")[1] + uomWind);	}	  
			 if (lines[i].split(" ")[0] == current_hum) {set_ajax_obs("ajaxhumidity", lines[i].split(" ")[1] );	}	  
			 if (lines[i].split(" ")[0] == today_max_hum) {set_ajax_obs("ajaxmaxhum", lines[i].split(" ")[1] );	}	  
			 if (lines[i].split(" ")[0] == today_min_hum) {set_ajax_obs("ajaxminhum", lines[i].split(" ")[1] );	}	  
			 if (lines[i].split(" ")[0] == today_total_rain) {set_ajax_obs("ajaxrain", lines[i].split(" ")[1] + uomRain );	}	  
			 if (lines[i].split(" ")[0] == last_24hours_rain) {set_ajax_obs("ajaxrain24h", lines[i].split(" ")[1] + uomRain );	}	  
			 if (lines[i].split(" ")[0] == last_60minutes_rain) {set_ajax_obs("ajaxrain60min", lines[i].split(" ")[1] + uomRain )};	  
			 if (lines[i].split(" ")[0] == feels_like) {set_ajax_obs("ajaxfeelslike", lines[i].split(" ")[1] + uomTemp );	}	  
			 if (lines[i].split(" ")[0] == yesterday_max_temp) {set_ajax_obs("ajaxyestempmax", aux_get_yesterday_value(lines[i].split(" ")[1]) + uomTemp );	}	  
			 if (lines[i].split(" ")[0] == yesterday_min_temp) {set_ajax_obs("ajaxyestempmin", aux_get_yesterday_value(lines[i].split(" ")[1]) + uomTemp );	}	  
			 if (lines[i].split(" ")[0] == yesterday_rain) {set_ajax_obs("ajaxyesrain", aux_get_yesterday_value(lines[i].split(" ")[1]) + uomRain ); 	}	  
			 if (lines[i].split(" ")[0] == yesterday_gust) {set_ajax_obs("ajaxyesgust", aux_convert_kn_in_km(aux_get_yesterday_value(lines[i].split(" ")[1])) + uomWind ); 	}	  
			 
			 if (lines[i].split(" ")[0] == month_max_temp) {set_ajax_obs("ajaxmonthtempmax", lines[i].split(" ")[1] + uomTemp);}	  
			 if (lines[i].split(" ")[0] == month_min_temp) {set_ajax_obs("ajaxmonthtempmin", lines[i].split(" ")[1] + uomTemp);}	  
			 if (lines[i].split(" ")[0] == month_avg_temp) {set_ajax_obs("ajaxmonthavg", lines[i].split(" ")[1] + uomTemp);}	  
			 if (lines[i].split(" ")[0] == month_rain_total) {set_ajax_obs("ajaxmonthrain", lines[i].split(" ")[1] + uomRain );	}	  
			 
			 if (lines[i].split(" ")[0] == month_max_gust) {set_ajax_obs("ajaxmonthgust", lines[i].split(" ")[1] + uomWind);	}	  
			 if (lines[i].split(" ")[0] == month_avg_gust) {set_ajax_obs("ajaxmonthwind", lines[i].split(" ")[1] + uomWind);	}	  
			 
			 if (lines[i].split(" ")[0] == month_max_press) {set_ajax_obs("ajaxmonthpressmax", lines[i].split(" ")[1] + uomBaro);	}
			 if (lines[i].split(" ")[0] == month_min_press) {set_ajax_obs("ajaxmonthpressmin", lines[i].split(" ")[1] + uomBaro);	}
			 if (lines[i].split(" ")[0] == month_avg_press) {set_ajax_obs("ajaxpressavg", lines[i].split(" ")[1] + uomBaro);	}
			 if (lines[i].split(" ")[0] == current_rain_rate) {set_ajax_obs("ajaxcurrentrainrate", lines[i].split(" ")[1] + uomRain );	}	 

			} //for(i=0;i<lines.length;i++)
  		 
			
		} // 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", xmlWeatherData, true);
    x.send(null);
		
		setTimeout("ajaxLoader(xmlWeatherData + '?' + 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(xmlWeatherData + '?' + new Date().getTime(), reloadTime); }


// ]]>