// DailyRecords.js
//
// These functions are used to load an parse a file which contains
// the record highs, lows and precipitation.

// Daily Record Properties
function DailyRecord(line)
{
	this.Month = line[0];
	this.Day = line[1];
	this.MaxAvg = line[2];
	// line[3] Number of years with data for this entry
	this.MaxHi = line[4];
	this.MaxHiYear = line[5];
	this.MaxLo = line[6];
	this.MaxLoYear = line[7];
	
	this.MinAvg = line[8];
	// line[9] Number of years with data for this entry
	this.MinHi = line[10];
	this.MinHiYear = line[11];
	this.MinLo = line[12];
	this.MinLoYear = line[13];
	
	this.PrecipAvg = line[14];
	// line[15] Number of years with data for this entry
	this.PrecipHi = line[16];
	this.PrecipYear = line[17];
	
	this.SnowfallAvg = line[18];
	// line[19] Number of years with data for this entry
	this.SnowfallHi = line[19];
	this.SnowfallYear = line[20];
	
	this.SnowdepthAvg = line[21];
	// line[22] Number of years with data for this entry
	this.SnowdepthHi = line[23];
	this.SnowdepthYear = line[24];
}

// Public function
//	LoadDailyRecords(url, handler)
//		Loads the daily records from the given url and then
//		invokes the user specified handler
//
//	url		url where the records are located
//	handler	function to call when the records have been loaded and parsed
function LoadDailyRecords(url, handler)
{
	if (document.getElementById)
	{
		var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	}

	if (x)
	{
		var uniqueUrl = url + '?' + new Date();
		x.open("GET", uniqueUrl, true);
		x.onreadystatechange = function()
		{
			if (x.readyState != 4 || x.status != 200)
			{
				return;
			}
			var records = parseDailyRecords(x.responseText);
			eval(handler + "(records)");
		}

		x.send(null);
	}
}

// Private function
//	parseDailyRecords(str)
//		Parse the table of records
//	str		The records table, delimited by \r\n
//	Returns
//		An array of records, indexed by the month/day as a string, ie "5/9"
function parseDailyRecords(str)
{
	// Remove extra blank lines
	str = compressLines(str);

	// Remove everything between the header and the trailer
	var result = splitBetween(str, "MO DY", "\n");
	result = splitAtString(result.after, "---");

	result = result.before.split("\n");
	
	// Create a new records array
	dailyRecords = new Array();

	for (var i=0; i<result.length; i++)
	{
		str = compressSpaces(result[i]);
		if (str.length > 0)
		{
			var record = new DailyRecord(str.split(" "));
			dailyRecords[record.Month + "/" + record.Day] = record;
		}
	}

	return dailyRecords;
}

