
var thesite = "";
var thesitedata = {};
var thetab = "sensors";
var drawlast = false;
var timezoff = (new Date()).getTimezoneOffset()/60 * 3600000;
var chours = 6;
var cmins = 0;
var csecs = 0;
var themaxdate = null;
var themaxdate = 1270058400000;

// These are for normailizing all of the data. Each site's data will have to be loaded sequentially.
var prj = {};
var ynorm = 'normal';

$(document).ready(function() {
	$.ajax({
		url: 'graph-proxy.php',
		dataType: 'html',
		success: function(data){
			resetprj();
			fetchprojectinfo();
			
			// Tab action
			countr();
			
		}
	});
	graphtabs();
		
	$('.nofunc').bind('click', function(){
		alert('This function is still in development. Please look for updates in the future.');
		$(this).blur();
		return false;
	});
});

function countr(){
	csecs-=1 ;
	if (csecs < 0){
		csecs = 59;
		cmins -= 1;
	}
	if (cmins < 0){
		csecs = 59;
		cmins = 59;
		chours -= 1;
	}
	
	if (chours == 0 && cmins == 0 && csecs == 0){
		$.ajax({
			url: 'graph-proxy.php',
			dataType: 'html',
			success: function(data){
				chours = 6; cmins = 0; csecs = 0;
				fetchcon();
			}
		});
	}
	
	stext = '' + csecs;
	if (csecs < 10){
		stext = '0' + csecs;
	}
	
	mtext = '' + cmins;
	if (cmins < 10){
		mtext = '0' + cmins;
	}
	$('p.countr').html('Next update in ' + chours + ':' + mtext + ':' + stext);
	setTimeout("countr()",1000);
} 


function maptools(){
	var rsite = ['Access Road', 'Thaw Lake', 'On/Off  Pingo', 'Pipe Pile 64'];
	var markr = [];
	
	for (var i = 0; i < prj.sites.length; i++){
		var mobj = {};
		mobj.latitude = prj.sites[i].lat - 35;
		mobj.longitude = prj.sites[i].long + 45;
		mobj.html = '<h3>' + rsite[i] + '</h3>';
		mobj.html += '<h4><a href="#" onClick="mapbtn(\'' + prj.sites[i].id + '\')" class="maprbtn" id="mapr' + prj.sites[i].id + '>Show Graph</a></h4>';
		markr.push(mobj);
	}
	
	$('#themap').gMap({
		markers: markr,
		zoom: 10,
		maptype: G_SATELLITE_MAP,
		scrollwheel: false
	});
}

function mapbtn(id){
	$.scrollTo('#carousel', 1200, {
		easing: 'swing'
	});
	thesite = id;
	thetab = 'sensors';
	
	fetchcon();
	
	
	$(this).blur();
	return false;
}

function ytools(){
	$('#ynorm').bind('click', function(){
		if (!$(this).hasClass('current')){
			$('#ytools a').removeClass('current');
			
			ynorm = 'all';
			$(this).addClass('current');
			
			fetchcon();
		}
		$(this).blur();
		return false;
	});
	
	$('#ydefault').bind('click', function(){
		if (!$(this).hasClass('current')){
			$('#ytools a').removeClass('current');
			
			ynorm = 'normal';
			$(this).addClass('current');
			
			fetchcon();
		}
		$(this).blur();
		return false;
	});
	
	$('#ycustom').bind('click', function(){
		if (!$(this).hasClass('current')){
			$('#ytools a').removeClass('current');
			
			var minv = new Number($('#ytools #minval').val());
			var maxv = new Number($('#ytools #maxval').val());
			if (minv && maxv){
				if (minv > maxv){
					$('#ytools #maxval').val(minv);
					$('#ytools #minval').val(maxv);
					
					var t = minv;
					minv = maxv;
					maxv = t;
				}
				
				prj.cmin = minv;
				prj.cmax = maxv;
			
				ynorm = 'custom';
				//$(this).addClass('current');
				
				fetchcon();
			}			
		}
		$(this).blur();
		return false;
	});
}

function xtools(){
	$('#days').bind('click', function(){
		if (!$(this).hasClass('current')){
			$('#xtools a').removeClass('current');
			$(this).addClass('current');
			
			// sets the preset up
			spangraph('-2d');
			resetprj();
			fetchcon();
		}
		
		$(this).blur();
		return false;
	});
	$('#week').bind('click', function(){
		if (!$(this).hasClass('current')){
			$('#xtools a').removeClass('current');
			$(this).addClass('current');
			
			spangraph('-7d');
			resetprj();
			fetchcon();
		}
		$(this).blur();
		return false;
	});
	$('#month').bind('click', function(){
		if (!$(this).hasClass('current')){
			$('#xtools a').removeClass('current');
			$(this).addClass('current');
			
			spangraph('-1m');
			resetprj();
			fetchcon();
		}
		$(this).blur();
		return false;
	});
	
	// initializes the calendar widgets for use
	$("#begdate").datepicker({
		dateFormat: 'yy-mm-dd',
		maxDate: (ifmaxdate(604800000) || '-1d'),
		onSelect: function(dateText, inst){
			spancheck();
			resetprj();
			fetchcon();
			//fetchgraphinfo();
		}
	}).datepicker('setDate','-7d');
	$("#enddate").datepicker({
		dateFormat: 'yy-mm-dd',
		maxDate: (ifmaxdate(0) || '+0d'),
		onSelect: function(dateText, inst){
			maxdate = new Date($("#enddate").datepicker('getDate').getTime() - (1000*60*60*24));
			$("#begdate").datepicker('option', 'maxDate', maxdate);
			
			if (maxdate < $("#begdate").datepicker('getDate')){
				$("#begdate").datepicker('setDate', maxdate);
			}
			spancheck();
			//fetchgraphinfo();
			resetprj();
			fetchcon();
		}
	}).datepicker('setDate','+0d');
	$("#ui-datepicker-div").hide();
}

function ifmaxdate(offset){
	if (themaxdate){
		return new Date(themaxdate - offset);
	} else {
		return null;
	}
}

function resetprj(){
	prj.name = "ns_project";
	prj.data = {};
	prj.tmin = null;
	prj.tmax = null;
	prj.bmin = null;
	prj.bmax = null;
	prj.amin = null;
	prj.amax = null;
	prj.cmax = null;
	prj.cmin = null;
}
function fetchcon(){
	emptygraph();
	
	if (ynorm != 'all'){
		if (prj.data[thesite]){
			drawlastdata();
			graphr();
		} else {
			fetchgraphinfo();
		}
	} else {
		tgo = true;
		for (var i = 0; i < prj.sites.length - 1; i++){
			if (!prj.data[prj.sites[i].id]){
				tgo = false;
			}
		}
		if (!tgo){
			fetchAllSiteGraphs();
		} else {
			findextremes();
			graphr();
		}
	}
}


fetchAllSiteGraphs = function(){
	// initializes the sendstring
	var sendstring = 'com=ynorm&sites=';
	for (var i = 0; i < prj.sites.length; i++){
		sendstring += prj.sites[i].id;
		if (i < prj.sites.length - 1){
			sendstring += ",";
		}
	}
	sendstring += getdates();
	$.ajax({
		url: 'http://www.beadedstream.com/data/home/bsws-data_con.php?' + sendstring,
		dataType: 'script',
		success: function(data){
			resetprj();
			prj.data = theresult;
			ynorm = true;
			findextremes();
			graphr();
		}
	});
}

// hunts down and finds the max and min values.
function findextremes(){
	if (ynorm){
		var i, j, k, t
		tmin = 1000;
		tmax = -1000;
		bmin = 1000;
		bmax = -1000;
		amin = 1000;
		amax = -1000;
		
		for (i = 0; i < prj.sites.length - 1; i++){
			for (j = 0; j < prj.data[prj.sites[i].id].series.length; j++){
				for(k = 0; k < prj.data[prj.sites[i].id].series[j].data.length; k++){
					t = prj.data[prj.sites[i].id].series[j].data[k][1];
					//console.log(t);
					if (t < tmin){
						tmin = t;
					}
					if (t > tmax){
						tmax = t;
					}
				}
			}
			for (j = 0; j < prj.data[prj.sites[i].id].battery.length; j++){
				for(k = 0; k < prj.data[prj.sites[i].id].battery[j].data.length; k++){
					t = prj.data[prj.sites[i].id].battery[j].data[k][1];
					//console.log(t);
					if (t < bmin){
						bmin = t;
					}
					if (t > bmax){
						bmax = t;
					}
				}
			}
			for (j = 0; j < prj.data[prj.sites[i].id].ambient.length; j++){
				for(k = 0; k < prj.data[prj.sites[i].id].ambient[j].data.length; k++){
					t = prj.data[prj.sites[i].id].ambient[j].data[k][1];
					//console.log(t);
					if (t < amin){
						amin = t;
					}
					if (t > amax){
						amax = t;
					}
				}
			}
		}
		
		prj.tmin = tmin;
		prj.tmax = tmax;
		prj.bmin = bmin;
		prj.bmax = bmax;
		prj.amin = amin;
		prj.amax = amax;		
	}
}
function graphtabs(){
	// adds functionality to the tabs
	$.each($('#graphtabs li a'), function(){
		if ($.browser.msie && $.browser.version < 8){
			$(this).find('.title').width(100);
		}
		$(this).find('.botc, .c').width($(this).find('.title').outerWidth());
		$(this).find('.bc').width($(this).find('.title').outerWidth() + 6);
		
		if (!$(this).hasClass('current')){		
			if ($.support.opacity){
				$(this).find('.hi').stop().animate({'top' : 8, 'opacity' : 0}, 100, 'swing');
				$(this).find('.med').stop().animate({'top' : 8}, 100, 'swing');
			} else {
				$(this).find('.hi, .med').stop().animate({'top' : 8}, 100, 'swing');
				$(this).find('.hi').hide();
			}
			$(this).find('.title').stop().animate({'paddingTop' : 12}, 100, 'swing');
		} else {
			if ($.support.opacity){
				$(this).find('.hi').stop().animate({'opacity' : 0}, 100, 'swing');
			} else {
				$(this).find('.hi').hide();
			}
		}
		$(this).bind('mouseenter', function(){
			if (!$(this).hasClass('current')){
				if ($.support.opacity){
					$(this).find('.hi').stop().animate({'top' : 0, 'opacity' : 1}, 100, 'swing');
					$(this).find('.med').stop().animate({'top' : 0}, 100, 'swing');
				} else {
					$(this).find('.hi, .med').stop().animate({'top' : 0}, 100, 'swing');
					$(this).find('.hi').show();
				}
				$(this).find('.title').stop().animate({'paddingTop' : 8}, 100, 'swing');
			}
			}).bind('mouseleave', function(){
				if (!$(this).hasClass('current')){
					if ($.support.opacity){
						$(this).find('.hi').stop().animate({'top' : 8, 'opacity' : 0}, 100, 'swing');
						$(this).find('.med').stop().animate({'top' : 8}, 100, 'swing');
					} else {
						$(this).find('.hi, .med').stop().animate({'top' : 8}, 100, 'swing');
						$(this).find('.hi').hide();
					}
					$(this).find('.title').stop().animate({'paddingTop' : 12}, 100, 'swing');
				}
			}).bind('click', function(){
				if (!$(this).hasClass('current')){
					$.each($('#graphtabs li a'), function(){
						if ($(this).hasClass('current')){
							if ($.support.opacity){
								$(this).find('.hi').stop().animate({'top' : 8, 'opacity' : 0}, 100, 'swing');
								$(this).find('.med').stop().animate({'top' : 8}, 100, 'swing');
							} else {
								$(this).find('.hi, .med').stop().animate({'top' : 8}, 100, 'swing');
								$(this).find('.hi').hide();
							}
						$(this).find('.title').stop().animate({'paddingTop' : 12}, 100, 'swing');
					}
					$(this).removeClass('current');
				});
				if ($.support.opacity){
					$(this).find('.hi').stop().animate({'top' : 0, 'opacity' : 0}, 100, 'swing');
					$(this).find('.med').stop().animate({'top' : 0}, 100, 'swing');
				} else {
					$(this).find('.hi, .med').stop().animate({'top' : 0}, 100, 'swing');
					$(this).find('.hi').hide();
				}
				$(this).find('.title').stop().animate({'paddingTop' : 8}, 100, 'swing');
				$(this).addClass('current');
			};
			
			thetab = $(this).attr('id');
			graphr();
			
			$(this).blur();
			return false;
		});
	});
}
function drawlastdata(){
	// populates the last data chart
	$('#lastdata p').remove();
	
	var d= new Date(prj.data[thesite].series[0].data[prj.data[thesite].series[0].data.length - 1][0]);
	
	ltext = '<li class="title"><b>Most Recent Data</b><br/>' + d.toDateString() + ' ' + d.getHours() + ':00</li>';
	for (var i = 0; i < prj.data[thesite].series.length; i++){
		ltext += '<li><span>' + prj.data[thesite].series[i].name + '</span><span>' + prj.data[thesite].series[i].data[prj.data[thesite].series[i].data.length - 1][1].toFixed(2) + '</span></li>';
	}
	ltext += '<li class="title"><b>Ambient Air Temperature</b></li>';
	ltext += '<li class="cntr">' + prj.data[thesite].ambient[0].data[prj.data[thesite].ambient[0].data.length - 1][1].toFixed(2) + '</li>';
	ltext += '<li class="title"><b>Modem Battery Voltage</b></li>';
	ltext += '<li class="cntr">' + prj.data[thesite].battery[0].data[prj.data[thesite].battery[0].data.length - 1][1].toFixed(2) + 'V</li>';
	ltext += '<li class="title"><b>Logger Battery Voltage</b></li>';
	ltext += '<li class="cntr">' + prj.data[thesite].battery[1].data[prj.data[thesite].battery[1].data.length - 1][1].toFixed(2) + 'V</li>';
	
	$('#sidenav ul#lastdata').html(ltext);
}
function fetchprojectinfo(){
	var sendstring = 'com=info&project=' + prj.name;
	$.ajax({
		url: 'http://www.beadedstream.com/data/home/bsws-data_con.php?' + sendstring,
		dataType: 'script',
		success: function(data) {
			thedata = theresult;
			
			// initializes the tools.
			
			// H1 title replace
			//$('h1.top').html(thedata.title + ' Temperature Data Center');
			$('h1.top').html('Temperature Data Center'); // this is not yet public.
			
			// tools initialize
			$('.subtools input').bind('focusin focusout', function(){
				$(this).toggleClass('active');
			});
			
			thesite = thedata.ids[0].id;
			prj.sites = thedata.ids;
			prj.coords = thedata.coords;
			
			xtools();
			ytools();
			maptools();
			
			
			drawsites();
			fetchcon();
		}
	});
}
// draws the site buttons underneath the graph.
function drawsites(){
	// to remove identifier info
	var rsite = ['Access Road', 'Thaw Lake', 'On/Off  Pingo', 'Pipe Pile 64'];
	
	// adds title and normalize button
	ltext = '<h3>Choose Site</h3>';
	for (var i = 0; i < thedata.ids.length; i ++){
		//ltext+= '<a href="#" id="site-'+ i + '">' + prj.sites[i] + '</a>';
		ltext+= '<a href="#" id="site-'+ i + '">' + rsite[i] + '</a>';
	}
	$('#sites').html(ltext);
	
	// adds the button functionality
	for (i = 0; i < prj.sites.length; i ++){
		$('#site-' + i).data('site', prj.sites[i].id).bind('click', function(){
			if (!$(this).hasClass('current')){
				$('#sites a').removeClass('current');
				$(this).addClass('current');
				
				//prj.name = $(this).data('project');
				thesite = $(this).data('site');
				//fetchgraphinfo();
				fetchcon();
				
				drawlast = false;
				
				$(this).blur();
				return false;
			}
		})
	}
	$('#sites a#site-0').addClass('current');
}
function emptygraph(){
	$('#thegraph').empty();
	$('#thegraph').css({
		'background' : 'url(../bsws-graph/loading.gif) center center no-repeat'
	});	
}

fetchgraphinfo = function(){
	var sendstring = 'com=graph&project=' + prj.name + '&site=' + thesite + getdates();
	
	$.ajax({
		url: 'http://www.beadedstream.com/data/home/bsws-data_con.php?' + sendstring,
		dataType: 'script',
		success: function(data) {
			prj.data[thesite] = theresult;
			if (!drawlast){				
				//thesitedata = theresult;
			}
			
			drawlastdata();
			graphr();
		}
	});
}

// draws the graph with the highcharts engine
function graphr(){
	var gseries = {};
	var graphtitle = "";
	var yaxislabel = "";
	var yunit = "";
	
	var ymin = null;
	var ymax = null;
	
	var minmax = [null, null];
	switch(thetab){
		case 'sensors':
			gseries = prj.data[thesite].series;
			//thetitle = thesitedata.title + ' : Ground Temperatures (&deg;C)';
			graphtitle = 'Ground Temperatures (&deg;C)';
			yaxislabel = 'Temperature (&deg;C)';
			yunit = '&deg;';
			
			ymin = prj.tmin;
			ymax = prj.tmax;
			
			minmax = returny(ymin, ymax);
			
			break;
		case 'battery':
			gseries = prj.data[thesite].battery;
			//thetitle = thesitedata.title + ' : Battery Voltage Levels';
			graphtitle = 'Battery Voltage Levels';
			yaxislabel = 'Modem Voltages';
			yunit = 'V';
			
			ymin = prj.bmin;
			ymax = prj.bmax;
			minmax = returny(ymin, ymax);
			
			break;
		case 'ambient':
			gseries = prj.data[thesite].ambient;
			//thetitle = thesitedata.title + ' : Ambient Air Temperature (&deg;C)';
			graphtitle = 'Ambient Air Temperature (&deg;C)';
			yaxislabel = 'Ambient Air Temperature';
			yunit = '&deg;';
			
			ymin = prj.amin;
			ymax = prj.amax;
			minmax = returny(ymin, ymax);
			
			break;
		default:
			gseries = prj.data[thesite].series;
			//thetitle = thesitedata.title + ' : Ground Temperatures (&deg;C)';
			graphtitle = 'Ground Temperatures (&deg;C)';
			yaxislabel = 'Temperature (&deg;C)';
			yunit = '&deg;';
			
			ymin = prj.tmin;
			ymax = prj.tmax;
			minmax = returny(ymin, ymax);
			
			break;
	}
	
	chartobj = {
		chart: {
			renderTo: 'thegraph',
			defaultSeriesType: 'line',
			margin: [30, 122, 20, 24],
			zoomType: "x",
			events : {
				load: function(){
					$('input#minval').val(this.yAxis[0].getExtremes().min);
					$('input#maxval').val(this.yAxis[0].getExtremes().max);
					$('#thegraph').css({
						'background' : 'none'
					});	
				}
			}
		},
		plotOptions : {
			line: {
				shadow: true,
				lineWidth: 1.5,
				marker: {
					radius: 2
				}
			}
		},
		title: {
			text: graphtitle,
			style: {
				margin: '0px 100px 0 0', // center it
				color: '#71BDFF'
			}
		},
		xAxis: {
			//categories: seclist,
			title: {
				text: 'Date'
			},
			gridLineColor : '#303235',
			lineColor : '#45484c',
			tickColor : '#45484c',
			lineWidth : 1,
			gridLineWidth : 1,
			type: 'datetime',
			endOnTick: true
		},
		yAxis: {
			title: {
				text: yaxislabel,
				enabled: true,
				rotation : 270,
				margin: 5,
				style : {
					color: '#71BDFF'
				}
			},
			min: minmax[0],
			max: minmax[1],
			gridLineColor : '#45484c',
			lineColor : '#303235',
			tickColor : '#45484c',
			lineWidth : 1,
			gridLineWidth : 1,
			labels : {
				align: 'left',
				x: 806,
				formatter : function(){
					return this.value + yunit;
				}
			}
		},
		tooltip: {
			formatter: function() {			
				var d= new Date(this.x + timezoff);
				var dstr = d.toDateString() + "<br/>" + d.getHours() + ":00 Alaskan Time";
				return '<b>' + this.series.name + '</b><br/>' + dstr  +':<br/>'+ this.y.toFixed(2) +'&deg;C';
			}
		},
		legend: {
			layout: 'vertical',
			style: {
				left: 'auto',
				bottom: 'auto',
				right: '0px',
				top: '17px',
				float: 'right',
				margin: 0
			},
			itemStyle : {
				color: '#71BDFF',
				padding: 0,
				float: 'left',
				clear: 'both',
				margin: '0 0 5px 0'
			},
			itemHoverStyle : {
				color: '#FFFFFF'
			},
			itemHiddenStyle : {
				color: '#3E576F'					
			}
		},
		series: gseries,
		credits: {
			enabled : false
		},
		toolbar: {
			itemStyle: {
				color: '#4572A7',
				fontSize: '9pt',
				cursor: 'pointer',
				margin: '2px 0 0 10px'
			}
		}
	};
	var chart = new Highcharts.Chart(chartobj);
};

function returny(tmin, tmax){
	switch(ynorm){
		case 'all':
			// do nothing
			break;
		case 'custom':					
			tmin = prj.cmin;
			tmax = prj.cmax;
		
			break;
		case 'normal':
			tmin = null;
			tmax = null;
			
			break;
	}
	
	return [tmin, tmax];
}

// if a user selects one of the quick date buttons snaps the widgets to those dates
function spangraph(ndays){
	if (ndays == '-2d'){
		d = ifmaxdate(2 * 86400000);
	} else if (ndays == '-7d'){
		d = ifmaxdate(7 * 86400000);
	} else if (ndays == '-1m'){
		d = ifmaxdate(30 * 86400000);
	}
	
	$("#begdate").datepicker('setDate', (d || new Date()));
	$("#begdate").datepicker('option', 'maxDate', (d || new Date()));
	$("#begdate").datepicker('setDate', (d || ndays));
	
	$("#enddate").datepicker('setDate', (ifmaxdate(0) || new Date()));
	$("#enddate").datepicker('setDate','+0d');
}

// checks to see whether a user selects through the widget a span that a button is made for
function spancheck(){
	tend = $("#enddate").datepicker('getDate');
	d = new Date();
	d.setHours(0, 0, 0, 0);
	
	$('#xtools a').removeClass('current');
	
	if (Date.parse(d) == Date.parse(tend)){
		tbeg = $("#begdate").datepicker('getDate');
		
		t1 = new Date(); t1.setHours(0, 0, 0, 0); t1.setDate(t1.getDate() - 2);
		t2 = new Date(); t2.setHours(0, 0, 0, 0); t2.setDate(t2.getDate() - 7);
		t3 = new Date(); t3.setHours(0, 0, 0, 0); t3.setMonth(t3.getMonth() - 1);
		
		if (Date.parse(tbeg) == Date.parse(t1)){
			$('#xtools a#days').addClass('current');
		} else if (Date.parse(tbeg) == Date.parse(t2)){
			$('#xtools a#week').addClass('current');
		} else if (Date.parse(tbeg) == Date.parse(t3)){
			$('#xtools a#month').addClass('current');			
		}
	}
}

// offsets the dates in the returned data
function fdate(t){	
	return Date.parse(t) - timezoff;
}
function getdates(){
	ret = "";
	ret += "&beg=" + $.datepicker.formatDate('yy/mm/dd', $("#begdate").datepicker('getDate'));
	ret += "&end=" + $.datepicker.formatDate('yy/mm/dd', $("#enddate").datepicker('getDate'));
	
	return ret;
}