var demoData = true;
function xmlhttpPost(strURL, arg) {
	if (demoData == true) {
		updateRandomData (arg);
		return;
	}
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
			if (arg==100)
				updateAllData (self.xmlHttpReq.responseText);
			else
	            updatedata(self.xmlHttpReq.responseText, arg);
        }
    }
    self.xmlHttpReq.send(null);
}
function updateAll() {
	//print order : water temp, ph, gps, air temp, humidity, turbidity
	if (demoData == true) {
		for (var i=0; i< 6; i++) {
			updateRandomData (i);	
		}	
	}
	else
		xmlhttpPost("/cgi-bin/wqmApp.cgi?all", 100);
}
function updateAllData (str) {
	
	var allStr = new Array();
		allStr = str.split (";");
		for (var i=0; i< allStr.length; i++) {
			updatedata (allStr[i], i);	
		}
}

function updateGPS () {
	xmlhttpPost("/cgi-bin/wqmApp.cgi?gps",2);
}
function updateWaterTemp () {
	xmlhttpPost("/cgi-bin/wqmApp.cgi?watertemp",0);	
}
function updatePh() {
	xmlhttpPost("/cgi-bin/wqmApp.cgi?ph",1);	
}
function updateAirTemp () {
	xmlhttpPost("/cgi-bin/wqmApp.cgi?airtemp",3);	
}
function updateHumidity() {
	xmlhttpPost("/cgi-bin/wqmApp.cgi?humid+77",4);	
}
function updateTurbidity() {
	xmlhttpPost("/cgi-bin/wqmApp.cgi?turbid",5);	
}
function updatedata (str, displayNum) {		
		var node = getSelectedNode ();
		//GPS Coordinates
		
		switch (displayNum) {
			case 0: //str = Math.floor(Math.random()*100)
					waterTemp[node] = parseFloat(removeTags(str)).toFixed(1);
					if (getSelectedNode() > 0)
						waterTemp[node] = str = parseFloat(Math.random()*10+parseFloat(waterTemp[node])).toFixed(1);
						str = waterTemp[node] += " &deg; F";
					updateMarker (node);
					break;
			case 1: //str = Math.floor(Math.random()*10)
					str = phLevel[node] = parseFloat(removeTags(str)).toFixed(1);
					
					if (getSelectedNode() > 0)
						phLevel[node] = str = parseFloat(Math.random()*10+parseFloat(phLevel[node])).toFixed(1);
					updateMarker (node);
					break;
			case 2:	if (map!=null) {
						gpsText[node]=removeTags (str);
						if (gpsText[node].indexOf() != -1 ) {
						var coords = gpsText[node].split(",");
						//latlng [node]= new GLatLng(parseFloat(coords[0]),parseFloat(coords[1]));
						//random points for testing purposes only
						if (getSelectedNode() > 0) {
							coords[0] = Math.random()*.006+parseFloat(coords[0]);	
							coords[1] = Math.random()*.006+parseFloat(coords[1]);
						}
						latlng [node]= new GLatLng(coords[0],coords[1]);
						
						map.setCenter(latlng[node], 16);
						if (marker[node]!=null)
							//todo : when cloud is open, it doesn't move the cloud
							//need to close cloud first then move it.
							marker[node].setLatLng(latlng[node]);
						else
							map.addOverlay(createMarker(latlng[node], node));
						openMarker(node);	
						gpsText[node] = str = convertDecDeg (coords[0], coords[1]);
						}
						
							
					}
					break;
			case 3:
					airTemp[node] = parseFloat(removeTags(str)).toFixed(1);
					if (getSelectedNode() > 0)
						airTemp[node] = str = parseFloat(Math.random()*10+parseFloat(airTemp[node])).toFixed(1);
					str = airTemp[node] += " &deg; F";
					updateMarker (node);
					break;
			case 4:
										humidity[node] = parseFloat(removeTags(str)).toFixed(1);
					if (getSelectedNode() > 0)
						humidity[node] = str = parseFloat(Math.random()*10+parseFloat(humidity[node])).toFixed(1);
					str = humidity[node] += " %";
					updateMarker (node);
					break;
			case 5:
					turbidity[node] = parseInt(removeTags(str));
					if (getSelectedNode() > 0)
						turbidity[node] = str = parseInt(Math.random()*4+parseInt(turbidity[node]));
					turbidity[node] = str = decodeTurbidity (turbidity[node]);
					updateMarker (node);
					break;
			default: break;
		}
		//document.getElementById("data"+displayNum).innerHTML = str;
		updateStrByElemID ("data"+displayNum, str);
}
function updateRandomData (displayNum) {		
		var node = getSelectedNode ();
		var str;
		//GPS Coordinates
		
		switch (displayNum) {
			case 0: do {
						str = Math.floor(Math.random()*100)
					} while (str <38);
					waterTemp [node] = str += " &deg; F";
					updateMarker (node);
					break;
			case 1: phLevel[node] = str = Math.floor(Math.random()*10)
					updateMarker (node);
					break;
			case 2:	if (map!=null) {
						/*
						gpsText[node]=removeTags (str);
						if (gpsText[node].indexOf() != -1 ) {
						var coords = gpsText[node].split(",");
						//latlng [node]= new GLatLng(parseFloat(coords[0]),parseFloat(coords[1]));
						//random points for testing purposes only
						*/
						var coords = new Array();
						coords [0] = 37.659906;
						coords [1] = -122.269249;
						if (getSelectedNode() > 0) {
							coords[0] = Math.random()*.025+parseFloat(coords[0]);	
							coords[1] = Math.random()*-.08+parseFloat(coords[1]);
						}
						latlng [node]= new GLatLng(coords[0],coords[1]); 
						latlngCenter [node]= new GLatLng(coords[0],coords[1] + (-1.2));
						map.setCenter(latlngCenter[node], 11);
						if (marker[node]!=null)
							//todo : when cloud is open, it doesn't move the cloud
							//need to close cloud first then move it.
							marker[node].setLatLng(latlng[node]);
						else
							map.addOverlay(createMarker(latlng[node], node));
						openMarker(node);	
						gpsText[node] = str = convertDecDeg (coords[0], coords[1]);
					}
					break;
			case 3:do {
						str = Math.floor(Math.random()*100)
					} while (str <32);
					airTemp[node] = str += " &deg; F";
					updateMarker (node);
					break;
			case 4: 
					str = Math.floor(Math.random()*100)
					humidity[node] = str += " %";
					updateMarker (node);
					break;
			case 5:	str = Math.floor(Math.random()*4)
					turbidity[node] = str = decodeTurbidity (str);
					updateMarker (node);
					break;
			default: break;
		}
		//document.getElementById("data"+displayNum).innerHTML = str;
		updateStrByElemID ("data"+displayNum, str);
}
function decodeTurbidity (turbid) {
	if (turbid >= 2.75)
		return "Extremely Cloudy";	
	else if (turbid >= 2.00)
		return "Very Cloudy";	
	else if (turbid >= 1.00)
		return "Cloudy";
	else if (turbid >= 0.31)
		return "Partially Cloudy";
	else
		return "Not Cloudy";

}
function updateTableData () {
	var node = getSelectedNode ();
	//water temp
	updateStrByElemID ("data0", waterTemp[node]);
	//pH
	updateStrByElemID ("data1", phLevel[node]);
	//gps
	updateStrByElemID ("data2", gpsText[node]);
	openMarker(node);
	//air temp
	updateStrByElemID ("data3", airTemp[node]);
	//humidity
	updateStrByElemID ("data4", humidity[node]);
	//turbidity
	updateStrByElemID ("data5", turbidity[node]);
}
function convertDecDeg (deg1, deg2) {
	var gpsdeg2 = parseInt (deg2);
	var remainder2 = deg2 - (gpsdeg2 * 1.0);
	var gpsmin2 = remainder2 * 60.0;
	
	var gpsdeg1 = parseInt (deg1);
	var remainder1 = deg1 - (gpsdeg1 * 1.0);
	var gpsmin1 = remainder1 * 60.0;
	if (gpsdeg1 <0)
		gpsdeg1 = "S" + Math.abs(gpsdeg1) + "&deg; " + Math.abs(gpsmin1).toFixed(4);
	else
		gpsdeg1 = "N " + gpsdeg1 + "&deg; " + gpsmin1.toFixed(4);
		
	if (gpsdeg2 <0)
		gpsdeg2 = "<br>W " + Math.abs(gpsdeg2) + "&deg; " + Math.abs(gpsmin2).toFixed(4);
	else
		gpsdeg1 = "<br>E " + gpsdeg2 + " &deg; " + gpsmin2.toFixed(4);		
		
	return (gpsdeg1 + gpsdeg2);
}

	
function updateStrByElemID (elemID, str) {
	if (str==null)
		str = "Needs Update";
	document.getElementById(elemID).innerHTML = str;
	
	
}
function getSelectedNode (){
	return document.getElementById("selectedNode").selectedIndex;
}
function removeTags (str) {
	return str.substring(3, str.length-4);
}
function updateMarker (node) {
	
	var wrkMarker = document.getElementById("marker"+node);
	if (marker[node]!=null && wrkMarker!=null) {
		wrkMarker.innerHTML=getMarkerText(node);			
	}
}
function getMarkerText (node) {
	var watTemp = waterTemp[node];
	var ph = phLevel[node];
	var air = airTemp[node];
	var humi = humidity[node];
	var turbid = turbidity [node];
	
	if (watTemp==null)
		watTemp="Needs update";
	if (ph==null)
		ph="Needs update";
	if (air==null)					
		air="Needs update";
	if (humi==null)
		humi="Needs update";
	if (turbid==null)
		turbid="Needs update";
		
/*		
	return "<p id=\"marker"+node+"\"><b>Sensor Node " + letter[node] + "</b><br />Water Temperature = " + watTemp +"<br />pH Level = " + ph + "<br />Air Temperature = " + air + "<br />Humidity = " + humi + "<br />Turbidity = "+ turbid "</p>";*/ 

return "<p id=\"marker"+node+"\"><b>Sensor Node " + letter[node] + "</b><br />Water Temperature = " + watTemp +"<br />pH Level = " + ph + "<br />Air Temperature = " + air + "<br />Humidity = " + humi +"<br />Turbidity = " + turbid + "<br /><br /><font size=\"1.5\" color=\"#666\"><i>This is random data generated for the web demo only.  <br />There are no nodes connected to this server.</i></font>" + "</p>";
}
function openMarker(node) {
		if (marker[node]!=null) {
            marker[node].openInfoWindowHtml(getMarkerText(node));
			document.getElementById("selectedNode").selectedIndex = node;
			
			//updateTableData ();
		}
}
function loadMap() {
  	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(15.284185, -72.421875), 1);
		map.enableDoubleClickZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setMapType(G_PHYSICAL_MAP);
		//map.setMapType(G_HYBRID_MAP);
  	}
}
function createMarker(point, node) {
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		var baseIcon = new GIcon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
			
        // Create a lettered icon for this point using our icon class
        letter [node]= String.fromCharCode("A".charCodeAt(0) + node);
        var letteredIcon = new GIcon(baseIcon);
        letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter[node] + ".png";

        // Set up our GMarkerOptions object
        markerOptions = { icon:letteredIcon };
		marker[node] = new GMarker(point, markerOptions);

		
		GEvent.addListener(marker[node], "click", function() {
            marker[node].openInfoWindowHtml(getMarkerText(node));
			document.getElementById("selectedNode").selectedIndex = node;
			updateTableData ();
        });
        return marker[node];
}

//global variables
var map=null;
var marker = new Array();
var waterTemp = new Array();
var phLevel = new Array();
var latlng = new Array();
var latlngCenter = new Array();
var gpsText = new Array();
var letter = new Array();
var airTemp = new Array ();
var humidity = new Array ();
var turbidity = new Array ();


