/*
 * realtime.js -- a script providing realtime updates of weather information
 * using the realtime.txt file generated by Cumulus.
 */

/* Configuration variables. */
var realtimeURL = '/cumulus/realtime.txt';
var tagPrefix = '.cu';
var timerInterval = 30;
var instantUpdate = true;
var trackDewpoint = true;
var trackHeatIndex = true;
var trackWindChill = true;
var trackInsideTemperature = true;

/* getCurrentTime(): Returns the current time in HH:MM format (24-hour). */
function getCurrentTime()
{
	var d = new Date();
	var hour = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
	var min = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
	
	return hour + ":" + min
}

/* parseDate(date): Takes date of form DD/MM/YY[YY] and returns it in the form
 * MM/DD/YY[YY]. (brackets indicate optional formatting: 10 is just as
 * acceptable as 2010).
 */
function parseDate(d)
{
	var e = d.split('/')
	return e[1] + '/' + e[0] + '/' + e[2]
}

/* trackExtremes(newVal, highEl, lowEl, highTimeEl, lowTimeEl): 
 * Tracks the extremes of two elements by comparing them with the new value
 * newVal. The element containing the high and low values should be given in
 * the highEl and lowEl arguments, respectively. The elements containing the
 * times when the high and low values occurred should be given in the
 * highTimeEl and lowTimeEl arguments, respectively. Does not return a value.
 */
function trackExtremes(newVal, highEl, lowEl, highTimeEl,
	lowTimeEl)
{
	var curTime = getCurrentTime();
	var highVal = parseFloat($(tagPrefix + highEl).contents().text());
	var lowVal = parseFloat($(tagPrefix + lowEl).contents().text());
	if (newVal > highVal || isNaN(highVal))
	{
		$(tagPrefix + highEl).text(newVal);
		$(tagPrefix + highTimeEl).text(curTime);
	}
	
	if (newVal < lowVal || isNaN(lowVal))
	{
		$(tagPrefix + lowEl).text(newVal);
		$(tagPrefix + lowTimeEl).text(curTime);
	}
}

/* makeRequest(): Performs an AJAX request for the realtime.txt file specified
 * by the global variable realtimeURL. Upon success, realtimeUpdate will be
 * called. Upon failure, nothing will happen.
 */
function makeRequest()
{
	$.ajax({
		url: realtimeURL,
		dataType: 'text',
		success: realtimeUpdate,
		});
	/* Initiate another timer, same as before. */
	setTimeout("makeRequest()", timerInterval * 1000);
}

/* realtimeUpdate(response): Reads the realtime.txt file string response.
 * This function should be called upon a successful ajax request.
 */
function realtimeUpdate(response)
{
	/* For use with dewpoint/indoor temperature tracking, if enabled. */
	var curTime = getCurrentTime();
	/* Tag names as they appear in the realtime.txt file.
	 * See: http://wiki.sandaysoft.com/a/Realtime.txt
	 * for information on these tags.
 	 */
	var tags = new Array();
	tags = ['date', 'time', 'temp', 'hum', 'dew', 'wspeed', 'wlatest',
		'bearing', 'rrate', 'rfall', 'press', 'currentwdir',
		'beaufort', 'windunit', 'tempunit', 'pressunit', 'rainunit',
		'windrun', 'presstrendval', 'rmonth', 'ryear', 'rfallY',
		'intemp', 'inhum', 'wchill', 'temptrend', 'tempTH',
		'TtempTH', 'tempTL', 'TtempTL', 'windTM', 'TwindTM',
		'wgustTM', 'TwgustTM', 'pressTH', 'TpressTH', 'pressTL',
		'TpressTL', 'version', 'build', 'wgust', 'heatindex',
		'humidex', 'UV', 'ET', 'SolarRad', 'avgbearing', 'rhour',
		'forecastnumber', 'isdaylight', 'SensorContactLost', 'wdir', 'cloudbase', 'cloudbaseunit', 'apptemp'];
	/* Data in realtime.txt is space-delineated. */
	var data = response.split(' ')
	/* If everything matches up right, loop through 'tags' and update
	 * all tags that match the tagPrefix + tag[index]
	 */
	if (tags.length <= data.length)
	{
		for (t in tags)
		{
			$(tagPrefix + tags[t]).text(data[t]);
		}
	}
	
	/* Add americanized date tag -- yes, it's ugly! */
	$(tagPrefix + 'americandate').text(parseDate(data[0]));

	/* Extreme values tracking. */
	if (trackDewpoint)
	{
		// Dewpoint is at index 4 -- update this if tags array changes.
		trackExtremes(parseFloat(data[4]), 'dewTH', 'dewTL', 'TdewTH',
			'TdewTL');
	}
	
	if (trackHeatIndex)
	{
		/* Heat index is at index 41 -- update this if tags array
		 * changes. */
		trackExtremes(parseFloat(data[41]), 'heatindexTH',
			'heatindexTL', 'TheatindexTH', 'TheatindexTL');
	}
	
	if (trackWindChill)
	{
		/* Wind chill is at index 24 -- update this if tags array
		 * changes. */
		trackExtremes(parseFloat(data[24]), 'wchillTH', 'wchillTL',
			'TwchillTH', 'TwchillTL');
	}

	if (trackInsideTemperature)
	{
		/* Indoor temperature is at index 22 -- update this if tags
		 * array changes.
		 */
		trackExtremes(parseFloat(data[22]), 'intempTH', 'intempTL',
			'TintempTH', 'TintempTL');
	}
	
}

/* Start a timer. */
$(document).ready(function(){
	/* If instantUpdate is true, we should force an update now. */
	if (instantUpdate)
	{
		makeRequest();
		setTimeout("makeRequest()", timerInterval * 1000);
	}
	else
	{
		/* setTimeout takes its interval in milliseconds. */
		setTimeout("makeRequest()", timerInterval * 1000);
	}
})
