//
// Script to update the 'now' conditions web page
//
// M Crossley 01 Nov 2011
//

var objXML;						//global XMLHttpRequest object
var lastVals = new Object();	//stores all the last values to see if they have changed.
var cumulus = new Object();		//stores all the data from cumulus
var update = false;				//initial load or update?
var count = 60;					//countdown timer, 1 min
var xmlHttpTimeout;				//global to hold XMLHTTP timeout function
var httpError = 0;
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];


function getData(){
	setStatus("Downloading...");
	if (objXML==null){
		if (window.XMLHttpRequest){     // Object of the current windows
			objXML = new XMLHttpRequest();     // Firefox, Safari, IE7,8...
		} else if (window.ActiveXObject){   // ActiveX version - Internet Explorer 5,6
			 try {
				objXML = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					objXML = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (E) {
						objXML = false;
						setStatus("Failed to create XMLHttp object");
					}
			}
		}
		if (objXML){
            // Check response
            objXML.onreadystatechange = checkDataResp;
            // Check for errors
            objXML.onabort = checkDataError;
            objXML.onerror = checkDataError;
			objXML.onTimeout = checkDataError;
		}
        
	}
	if (objXML) {
		// use random # as cache defeat
		objXML.open('GET', 'cumuluswebtags.js?'+Math.random(), true);                  
		objXML.send(null); // Go get it
		xmlHttpTimeout = setTimeout(ajaxTimeout,10000); //set a 10 second timeout
	}
}


function ajaxTimeout(){
   objXML.abort();
}


function checkDataResp(){
	if(objXML.readyState  == 4){

		//stop the timeout function
		clearTimeout(xmlHttpTimeout);

		if(objXML.status  == 200){
			httpError = 0;
			//run the downloaded code - dodgy, but we are controlling the code source.
			eval(objXML.responseText);

			var str = cumulus.LastRainTipISO.split(" ");
			var dt = str[0].split("-");
			var tm = str[1].split(":");
			var today = new Date();
			var then = new Date();
			var thenPlus1 = new Date();
			today.setHours(0,0,0,0);
			then.setFullYear(dt[0],dt[1]-1,dt[2]);
			then.setHours(tm[0],tm[1],0,0);
			thenPlus1.setTime(then.getTime() + 86400000);
			if (then.getTime() >= today.getTime()) {
				cumulus.LastRainTipISO = "Today at "+str[1];
			} else if (thenPlus1.getTime() >= today.getTime()) {
				cumulus.LastRainTipISO = "Yesterday at "+str[1];
			} else {
				cumulus.LastRainTipISO = "" + then.getDate() + " " + months[then.getMonth()] + " at " + str[1];
			}
			var status = document.getElementById("led");
			if (cumulus.SensorContactLost==1) {
				status.src="dbimages/red-on-16.png";
				status.alt="Remote sensor contact lost";
				status.title="Remote sensor contact lost";
			} else {
				status.src="dbimages/green-on-16.png";
				status.alt="Remote sensor OK";
				status.title="Remote sensor OK";
			}
			cumulus.ConsecutiveRainDaysTitle = "Consecutive Rain Days (incl. today)";
			if (+cumulus.rfall >= 0.2) {
				cumulus.ConsecutiveRainDays = (+cumulus.ConsecutiveRainDays + 1).toString()
			} else {
				cumulus.ConsecutiveRainDaysTitle = "Consecutive Rain Days (excl. today)";
			}

			if (cumulus.rrate > 50.0){
				cumulus.rrateText = "extreme rain!";
			} else if (cumulus.rrate >= 16.0){
				cumulus.rrateText = "very heavy rain";
			} else if (cumulus.rrate >= 4.0){
				cumulus.rrateText = "heavy rain";
			} else if (cumulus.rrate >= 1.0){
				cumulus.rrateText = "moderate rain";
			} else if (cumulus.rrate >= 0.25){
				cumulus.rrateText = "light rain";
			} else if (cumulus.rrate > 0.0){
				cumulus.rrateText = "very light rain";
			} else {
				cumulus.rrateText = "not raining";
			}

			//update the page
			doUpdate();
			//start the count for next update
			countDown();
			//time a page update to clear any fields flagged as updated - after 10 seconds
			window.setTimeout("doUpdate();", 10*1000);
		}else if (objXML.status > 200){
			setStatus("HTTP request failed, error: "+objXML.status+" Retrying..");
			httpError = objXML.status;
			setTimeout("getData()",3000);
		}
	}
}

function checkDataError(){
    setStatus("HTTP request failed, error: "+objXML.status+" Retrying..");
    setTimeout("getData()",3000);
}

function setStatus(str){
	document.getElementById("status").innerHTML = str;
}

function doUpdate(){
	//get all the spans on the page
	var spans = document.getElementsByTagName("span");
	//loop through the spans to update them
	for(var i=0; i<spans.length; i++){
		var id = spans[i].id;
		eval("var val=cumulus."+id+";");		//get the cumulus value
		if(val != null){						//do we have a cumulus value for this field?
			eval("var last=lastVals."+id+";");	//do we have a lastVal?
			spans[i].innerHTML = val;			//set the field text
			if(last==val){						//not updated
				spans[i].style.color = "";		//clear any red flag
			}else{								
				if(update && id != "time"){			//not initial page load, or the time field
					spans[i].style.color = "red";	//flag red
					//if(id!="time") spans[i].innerHTML +='['+last+']';	//put old val in brackets
				}
				eval("lastVals."+id+"=val;");		//store new val as last
				
			}
		}
	}
	update=true;	//no longer intial load
}

function countDown(){
	count--;
	if(count==0){
		getData();
		count=60;
	}else{
		setTimeout("countDown()",1000);
		if(httpError==0){
			setStatus("Next update in "+count+" secs");
		}else{
			setStatus("HTTP request failed, error:"+httpError+" Retry:"+count+"s");
		}
	}
}

// start it all off...
getData();



