/* skigod.us wx ajax update thingy
   based vaguly on the ajax VWS scripts at
   http://saratoga-weather.org/scripts-VWS-AJAX.php 
   
   Placed into the Public Domain. Enjoy, but don't complain to me.
*/
// SETTINGS
var polltime_cur  =  3001; // delay between updates for the current conditions
var polltime_hilo = 60000; // and the hi/lo file
var flashtime 	  =  2500; // and how long should new data flash, all in ms

var temp_in_window_title = 1;  // 0: no; 1: before; 2: after
var bad_data_count = 0;

// end SETTINGS

// setup the xmlhttp objects
var xmlhttp = new Array;
if(document.getElementById) {
	if(window.ActiveXObject) {
		xmlhttp[0] = new ActiveXObject('Microsoft.XMLHTTP');
		xmlhttp[1] = new ActiveXObject('Microsoft.XMLHTTP');
		xmlhttp[2] = new ActiveXObject('Microsoft.XMLHTTP');
	} else {
		xmlhttp[0] = new XMLHttpRequest();
		xmlhttp[1] = new XMLHttpRequest();
		xmlhttp[2] = new XMLHttpRequest();
	}
	
	if(xmlhttp[0]) {
		// we got an xml request thingy, let's set the timers
		setTimeout(wx_update_conds_one, polltime_cur);
		//setTimeout(wx_update_hilo_one, polltime_hilo);
		wx_update_warn_one();
	}
}

var wx_flash_timer = null;
var old_arrow_dir = null;
var w_context = null;

function setup_wind_canvas() {
	try {
		var canvas = document.getElementById('wndcanvas');
		w_context = canvas.getContext('2d');
	
		// set up the canvas
		w_context.scale(canvas.width/100, canvas.height/100);
		w_context.translate(50,50);
		
		// FIXME: pull colors from the document styles
		w_context.strokeStyle = "#cacada";
		w_context.fillStyle = "#cacada";
		w_context.lineWidth = 2;
		w_context.lineJoin = 'bevel';
		
		// draw the compass
		w_context.beginPath();
		w_context.arc(0,0,47,Math.PI*1.42,Math.PI*1.58,1);
		w_context.stroke();
		
		w_context.beginPath();
		w_context.moveTo(-4,-40);
		w_context.lineTo(-4,-50);
		w_context.lineTo( 4,-40);
		w_context.lineTo( 4,-50);
		w_context.stroke();
	} catch(e) {
		w_context = null;
		return;
	}
	
	add_class('with_canvas', document.body);
}
setup_wind_canvas();

function draw_arrow(dir, glow) {
	if(w_context==null) {
		// nothing to do
		return;
	}
	w_context.save();
	w_context.lineJoin = 'miter';
	w_context.rotate(dir * (Math.PI / 180));
	
	if(glow) {
		w_context.fillStyle = "#ffe6bf";
	}
	
	w_context.beginPath();
	w_context.moveTo( 0,-37);
	w_context.lineTo(-8,-30);
	w_context.lineTo( 8,-30);
	w_context.closePath();
	w_context.fill();
	//w_context.stroke();
	
	w_context.restore();
}

function clear_arrow() {
	
	w_context.save();
	w_context.rotate(old_arrow_dir * (Math.PI / 180));
	w_context.clearRect(-9,-37,18,8);
	w_context.restore();
}

function update_arrow(dir) {
	if(w_context==null) {
		// nothing to do
		return;
	}
	if(dir != old_arrow_dir) {
		clear_arrow();
		draw_arrow(dir,1);
		setTimeout(unglow_arrow,flashtime);
		old_arrow_dir = dir;
	}
}

function unglow_arrow() {
	clear_arrow();
	draw_arrow(old_arrow_dir,0);
}


function wx_update_conds_one() {
	// step one: fetch the current conditions
	xmlhttp[0].open("GET", "/data.php?bs=" + (new Date).getTime());
	xmlhttp[0].onreadystatechange = wx_update_conds_two;
	xmlhttp[0].send(null);
}

function wx_update_conds_two() {
	if(xmlhttp[0].readyState == 4) {
		if(xmlhttp[0].status == 200) {
			// we got the conditions CSV
			
			var data = xmlhttp[0].responseText.split(',');
			
			if(typeof(data[1]) == 'undefined') {
				// data is bogus/unavailable.
				bad_data_count++;
				
				// schedule another update
				var delay = polltime_cur;
				
				if(bad_data_count < 5) {
					delay *= 2.2;
				} else {
					delay *= 5;
				}
				setTimeout(wx_update_conds_one, delay);
			return;
			}
			bad_data_count = 0;
			
			wx_update_field("wxdate",   data[ 1]);
			wx_update_field("wxtime",   data[ 2]); //twelve_hr_time(data[4],data[5],data[6]));
			
			wx_update_field("tempcur",  data[ 3]);
			wx_update_field("humidcur", data[ 4]);
			wx_update_field("dewpt",	data[ 5]);
			wx_update_field("hidxcur",  data[ 6]);
			wx_update_field("chillcur", data[ 7]);
			
			wx_update_field("wndcur",   data[ 8]);
			wx_update_field("wnddir",   wind_dir_abbr(data[9]));
			update_arrow(data[9]);
			
			wx_update_field("barocur",  data[10]);
			wx_update_field("barotrend",data[11]);
			
			wx_update_field("rainrate", data[12]);
			wx_update_field("raindy",   data[13]);
			wx_update_field("rainstorm",data[14]);
			wx_update_field("rainstormstart",data[15]);
			//battery status			data[16]
			
			// No wind chill above 50 degrees
			if(document.getElementById('chillcell')) {
			  document.getElementById('chillcell').style.display = (data[3] < 50 ? '' : 'none');
			// or heat index under 68
			  document.getElementById('hidxcell').style.display = (data[3] > 68 ? '' : 'none');
        	}
        	
        	// humidity or rain
        	if(document.getElementById('raincell')) {
        		document.getElementById('humidcell').style.display = (data[12] < 0.05 ? '' : 'none');
        		document.getElementById('raincell').style.display = (data[12] >= 0.05 ? '' : 'none');
        	}
			//FIXME: update titlebar
			
		}
		// finally, schedule another update
		setTimeout(wx_update_conds_one, polltime_cur);
	}
}

function wx_update_hilo_one() {
	// step one: fetch the current conditions
	xmlhttp[1].open("GET", "/data/hilo.csv");
	xmlhttp[1].onreadystatechange = wx_update_hilo_two;
	xmlhttp[1].send(null);
}

function wx_update_hilo_two() {
	if(xmlhttp[0].readyState == 4) {
		if(xmlhttp[0].status == 200) {
			// we got the conditions CSV
			
			var data = xmlhttp[1].responseText.split(',');
			if(typeof(data[1]) == 'undefined') {
				// data is bogus/unavailable.
				bad_data_count++;
				
				// schedule another update
				var delay = polltime_hilo;
				
				if(bad_data_count < 5) {
					delay *= 2.2;
				} else {
					delay *= 5;
				}
				setTimeout(wx_update_hilo_one, delay);
			return;
			}
			bad_data_count = 0;
			
			wx_update_field("temphi",   	data[ 0]);
			wx_update_field("temphitime",   data[ 1]);
			wx_update_field("templo",   	data[ 2]);
			wx_update_field("templotime",   data[ 3]);
			
			wx_update_field("chillhi",  	data[ 4]);
			wx_update_field("chillhitime",  data[ 5]);
			wx_update_field("chilllo",  	data[ 6]);
			wx_update_field("chilllotime",  data[ 7]);
			wx_update_field("chillrate",	data[ 8]);
			
			wx_update_field("humidhi",  	data[ 9]);
			wx_update_field("humidhitime",  data[10]);
			wx_update_field("humidlo",  	data[11]);
			wx_update_field("humidlotime",  data[12]);
			
			wx_update_field("hidxhi",   	data[13]);
			wx_update_field("hidxhitime",   data[14]);
			wx_update_field("hidxlo",   	data[15]);
			wx_update_field("hidxlotime",   data[16]);
			wx_update_field("hidxrate", 	data[17]);
			
			wx_update_field("wndhi",		data[18]);
			wx_update_field("wndhitime",	data[19]);
			wx_update_field("wndlo",		data[20]);
			wx_update_field("wndlotime",	data[21]);
			wx_update_field("wndrate",  	data[22]);
			
			wx_update_field("barohi",   	data[23]);
			wx_update_field("barohitime",   data[24]);
			wx_update_field("barolo",   	data[25]);
			wx_update_field("barolotime",   data[26]);
		}
		
		// finally, schedule another update
		setTimeout(wx_update_hilo_one, polltime_hilo);
	}
}

function wx_update_warn_one() {
	xmlhttp[2].open("GET", "/warn.php");
	xmlhttp[2].onreadystatechange = wx_update_warn_two;
	xmlhttp[2].send(null);
}

function wx_update_warn_two() {
	if(xmlhttp[2].readyState == 4 && xmlhttp[2].status == 200) {
	// we got the conditions CSV
		var warnings = xmlhttp[2].responseText
		if(warnings == null || warnings == '') {
			document.getElementById('warnlist').innerHTML = '';
			//document.getElementById('warnhead').style.display = 'none';
			document.getElementById('warnlist').style.display = 'none';
		} else {
			document.getElementById('warnlist').innerHTML = warnings;
			//document.getElementById('warnhead').style.display = 'block';
			document.getElementById('warnlist').style.display = 'block';
		}
	
		setTimeout(wx_update_warn_one, polltime_hilo);
	}
}

function wx_update_field(id, data) {
	if(element = document.getElementById(id)) {
		if(element.innerHTML != data) {
			element.innerHTML = data;
			add_class('ajaxhighlight', element);
			if(wx_flash_timer == null) {
				wx_flash_timer = setTimeout(wx_clear_flash, flashtime);
			}
		}
	}
}

function wx_clear_flash() {
	var allspans = document.getElementsByTagName('span');
	
	var r = /\bajaxhighlight\b/;
	for(var i=0; i < allspans.length; i++) {
		if(r.test(allspans[i].className)) {
			del_class('ajaxhighlight', allspans[i]);
		}
	}
 
	wx_flash_timer = null;
}

// SUPPORT FUNCTIONS
function add_class(newclass, element) {
	element.className += (element.className ? ' ' + newclass : newclass);
}

function del_class(delclass, element) {
	var r = new RegExp('\\s*' + delclass);
	element.className = element.className.replace(r,'');
}

function baro_trend_phrase(trend) {
	if(trend <= -0.06)  { return "Falling Rapidly"; }
	if(trend <  -0.02)  { return "Falling Slowly";  }
	if(trend <=  0.02)  { return "Steady";  		}
	if(trend <   0.06)  { return "Rising Slowly";   }
						{ return "Rising Rapidly";  }  
}


// Take wind direction value, return the
// text label based upon 16 point compass -- function by beeker425
//  see http://www.weather-watch.com/smf/index.php/topic,20097.0.html
function wind_dir_abbr(wind) {
	return Array("N", "NNE", "NE", "ENE",
				"E", "ESE", "SE", "SSE",
				"S", "SSW", "SW", "WSW",
				"W", "WNW", "NW", "NNW")
		[Math.floor(((parseInt(wind) + 11) / 22.5) % 16)];
}

function twelve_hr_time(hrs,mins,secs) {
	var ampm = "am";
	if(mins < 10)   { mins = "0" + mins; }
	if(secs < 10)   { secs = "0" + secs; }
	
	if(hrs >= 12) { ampm = "pm"; }
	if(hrs >  12) { hrs -= 12;   }
	if(hrs == 0 ) { hrs = 12;	}
	
	return hrs + ":" + mins + ":" + secs + " " + ampm;
}

function pop(src,w,h,nocrap) {
	var opts = "innerWidth=" + w + ",innerHeight=" + h;
	
	if(nocrap) {
		opts += ',location=no,scrollbars=no,toolbar=no';
	}
	window.open(src.getAttribute('href'),'',opts);
	return false;
}
