/* ---------------------------------------------------------------------------
Copyright:
	Davis Instruments, (c) 2010

Code by:
	Author:  Andy Schmidt
	Created: 01/15/2010

Notes:
	Best viewed with TAB-Size = 4

ToDo:
	Todo items are marked with a $$$ comment

Revisions:

--------------------------------------------------------------------------- */

//-------------------------------------
// Ajax related variables
//-------------------------------------
var oAjaxRequest	= null;				// Ajax Request Object
var oAjaxData		= null;				// Ajax Response Data

//--------------------------------------
// Sends a Ajax request
//--------------------------------------
function ajaxSendRequest(sRequest) {

	dbgPrint("ajaxSendRequest: " + sRequest);

	// Check for existing requests
	if ((oAjaxRequest != null) && (oAjaxRequest.readyState != 0) && (oAjaxRequest.readyState != 4) ) {
		oAjaxRequest.abort();
	}

	// Reset current Ajax objects
	oAjaxRequest	= null;
	oAjaxData		= null;

	// Instantiate object for Firefox, Nestcape, etc.
	try {
		oAjaxRequest = new XMLHttpRequest();
	} catch(ex) {

		// Instantiate object for Internet Explorer
		try {
			oAjaxRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
		} catch(ex) {
			try {
				oAjaxRequest = new ActiveXObject("Msxml2.XMLHTTP.3.0");
			} catch(ex) {
				try {
					oAjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(ex) {
					try {
						oAjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(ex) {
						alert(
							"ERROR: This browser does not support Ajax XMLHttpRequest()!\n" +
							"Module: ajaxSendRequest()\n"
						);
						return false;
					}
				}
			}
		}
	}

	// Assign state handler callback
	oAjaxRequest.onreadystatechange = ajaxResponseCallback;

	// Open socket connection
	oAjaxRequest.open('GET',sRequest,true);
	oAjaxRequest.send(null);
}

//--------------------------------------
// Callback function for the Ajax call.
// This will parse the data according to the caller type.
//--------------------------------------
function ajaxResponseCallback() {

	//dbgPrint("ajaxResponseCallback: readyState = " + oAjaxRequest.readyState);
	//dbgPrint("ajaxResponseCallback: status = " + oAjaxRequest.status);
	//dbgPrint("ajaxResponseCallback: responseText = " + oAjaxRequest.responseText);

	// If the request is completed
	if (oAjaxRequest.readyState == 4) {

		// If status == 200 continue
		if (oAjaxRequest.status == 200) {

			oAjaxData = oAjaxRequest.responseText;

			// 404 Error?
			if (oAjaxData.indexOf("404<br>") != -1) {

				alert(
					"ERROR: Failed to get Station Data from Server!\n" +
					"Module: MapAjax.ajaxResponseCallback()\n" +
					"Response: 404 - File not found!\n"
				);

				setMapInfo("Error loading Stations!");
				showStatusText("Error loading Stations!");

			} else {

				// JSON File?
				if (oAjaxData.substr(0,8) == "var json") {
					loadJson();
				} else {
					doGetStationDetails();	// Process the Station Details
				}
			}

		} else {
			alert(
				"ERROR: Failed to get Ajax Response from Server!\n" +
				"Module: MapAjax.ajaxResponseCallback()\n" +
				"Response: " + oAjaxRequest.responseText + "\n" +
				"Details: " + oAjaxRequest.statusText
			);
		}
	}
}

//--------------------------------------
// Loads the json file that holds the station data
// into a javascript array
//--------------------------------------
function loadJson() {

	if (oAjaxData != "") {

		eval(oAjaxData);

		if (json != null) {
			if (oGMap != null) {

				setMapInfo("" + json.length + " active stations reporting");

				showStatusText("Creating Station Map ...");
				oMapClusterManager = new MapClusterManager(json);

				// Delete the temp json array
				json = [];
				json = null;

			} else {
				alert("Map Error:\nGoogle Maps not loaded! Check your Browser settings.");
			}
		} else {
			alert("Map Error:\nMap Station data corrupt! json.eval() failed.");
		}
	} else {
		alert("Map Error:\nCould not load Map Station data!");
	}
}

//--------------------------------------
// Process the Station Details
//--------------------------------------
function doGetStationDetails() {
var dar,idx,sHtml,sLink,sUnits,iAgeDisplay;
var iAgeHours,iAgeDays,sUserName,sStationName,dtDateUploaded,sOutsideTemp
var sOutsideHumidity,sWindSpeed,sWindDirection,sBarometer,sBarTrend;

	dbgPrint("doGetStationDetails: " + oAjaxData);

	if (oAjaxData != "NODATA") {

		dar	= oAjaxData.split('|');
		if (dar.length > 0) {

			idx = 0;
			iAgeHours			= parseInt(dar[idx++]);
			iAgeDays			= parseInt(dar[idx++]);
			sUserName			= dar[idx++];
			sStationName		= dar[idx++];
			dtDateUploaded		= dar[idx++];
			sOutsideTemp		= dar[idx++];
			sOutsideHumidity	= dar[idx++];
			sWindSpeed			= dar[idx++];
			sWindDirection		= dar[idx++];
			sBarometer			= dar[idx++];
			sBarTrend			= dar[idx++];

			dbgPrint("> iAgeHours = " + iAgeHours);
			dbgPrint("> iAgeDays = " + iAgeDays);
			dbgPrint("> sUserName = " + sUserName);
			dbgPrint("> sStationName = " + sStationName);
			dbgPrint("> dtDateUploaded = " + dtDateUploaded);
			dbgPrint("> sOutsideTemp = " + sOutsideTemp);
			dbgPrint("> sOutsideHumidity = " + sOutsideHumidity);
			dbgPrint("> sWindSpeed = " + sWindSpeed);
			dbgPrint("> sWindDirection = " + sWindDirection);
			dbgPrint("> sBarometer = " + sBarometer);
			dbgPrint("> sBarTrend = " + sBarTrend);

			sLink = "<a href=\"" + sMapDomain + "/user/" + sUserName + "\" target=\"_blank\">";
			sLink += sStationName + "<\/a>";

			sHtml = "<table cellspacing=0 cellpadding=0>" +
					"<tr><td><font size=1>&nbsp;</font><\/td><td><font size=1>&nbsp;</font><\/td><\/tr>" +
					"<tr><td>Station:&nbsp;<\/td><td>" + sLink + "<\/td><\/tr>";

			if ((iAgeDays == 0) && (iAgeHours < 2)) {

				sHtml +=
					"<tr><td>Temperature:&nbsp;<\/td><td>" + sOutsideTemp + "<\/td><\/tr>" +
					"<tr><td>Humidity:&nbsp;<\/td><td>" + sOutsideHumidity + "<\/td><\/tr>" +
					"<tr><td>Wind:&nbsp;<\/td><td>" + sWindSpeed + " " + sWindDirection + "<\/td><\/tr>" +
					"<tr><td>Barometer:&nbsp;<\/td><td>" + sBarometer + " - " + sBarTrend + "<\/td><\/tr>" +
					"<\/table>";
			} else {

				sUnits		= "Days";
				iAgeDisplay	= iAgeDays;

				if (iAgeDays == 0) {
					sUnits = "hours";
					if (iAgeHours == 1) { sUnits = "hour"; }
					iAgeDisplay = iAgeHours;
				} else {
					if (iAgeDays == 1) { sUnits = "day"; }
				}

				sHtml +=
					"<tr><td>Last Update:&nbsp;<\/td><td>" + iAgeDisplay + " " + sUnits + " ago<\/td><\/tr>" +
					"<\/table>";
			}
		}

	} else {
		sHtml = "No current Station Data available!";
	}

	// Open the Map Info Window with the Stations details
	if (oInfoWindowLoc != null) {
		oGMap.openInfoWindowHtml(oInfoWindowLoc, sHtml);
	}

}

