

var map;
var plot;
var placeholder;
var choiceContainer;

var url = "/";
//var url = "/p/PAMZ/website/";

var markers = [];
var displayArray = [];
var ticks = [];
var finaldata = [];
var labels = [];
var zeroSpan = [];
var zoomed = false;
var pamzDebug = false;


var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];



var floptions = {
	colors: ["#edc240", "#afd8f8", "#4da74d", "#9440ed", "#ffe84c", "#9b7a16", "#3979ab", "#b6e5b6", "#dfc0ff", "#999999"],
	series: {
		lines: { show: true, lineWidth: 1 },
		points: { show: true }
	},
	points: {
		radius: 2
	},
	grid: {
		hoverable: true, 
		clickable: true,
		backgroundColor: { colors: ["#fff", "#eee"] },
		markings: function () { return zeroSpan }

	},
	zoom: {
		amount: 2         // 2 = 200% (zoom in), 0.5 = 50% (zoom out)
	},
	xaxis: {
		ticks: ticks
 	},
	yaxis: { zoomRange: [null, 0.001], tickFormatter: function (v, axis) { return v.toFixed(1) +"&nbsp;ppb" } },
	y2axis: { zoomRange: [null, 0.001], tickFormatter: formatY2  },
	selection: { mode: "x" },
	legend: { labelFormatter: function(label, series) {
			return '<a href="#' + label + '" title="' + measure[label][0] + ' (' + measure[label][1] + ')">' + label + '</a>';
	}, position: "ne" }
	

};




function formatY2(v, axis)
{	
	return "<span class='yaxis'>" + v.toFixed(axis.tickDecimals) + "&nbsp;<span class='uom'></span></span>";
}





$(document).ready(function(){


	$("#tabs").tabs({ cookie: { name: 'pamztab', path: '/', expires: 7 } });


	$('#tabs').bind('tabsshow', function(event, ui) {
		if (ui.panel.id == "display-map") {
			setupMap();
		}
	});



	$("#dateselect").hide();


	
	$(".curdate a").click(function() {
		$("#dateselect").toggle("fast");
	});



	$("#d").datepicker({ dateFormat: 'yymmdd' });


	$("#slider").slider({
		value: $("#t").val(),
		min: 0,
		max: 2300,
		step: 100,
		slide: function(event, ui) {
			$("#t").val(pad(ui.value,4));
		}
	});



	$(".next a").click(function() {
		go('next');
	});
	

	$(".prev a").click(function() {
		go('prev');
	});


	$(".passiveParams").find("input").click(plotCircles);


	$(".pprev a").click(function() {
		newCircles($('#passiveDate').val(),'prev');
	});


	$(".pnext a").click(function() {
		newCircles($('#passiveDate').val(),'next');
	});


	$(".help a").click(function() {

		if($("#help").is(':visible'))
		{
			$("#help").fadeOut();			
		} else {
			$("#help").fadeIn();
		}
		
	});


	$("#help").click(function() {
		$(this).fadeOut();
	});
	

});





function addDaysToDate(myDate,days) {
	return new Date(myDate.getTime() + days*24*60*60*1000);
}


function addMonthsToDate(startDate, numMonths) {
	var addYears = Math.floor(numMonths/12);
	var addMonths = numMonths - (addYears * 12);
	var newMonth = startDate.getMonth() + addMonths;
	if (startDate.getMonth() + addMonths > 11) {
		++addYears;
		newMonth = startDate.getMonth() + addMonths - 12;
	}
	
	var newDate = new Date(startDate.getYear()+addYears,newMonth,startDate.getDate(),startDate.getHours(),startDate.getMinutes(),startDate.getSeconds());

	// adjust to correct month
	while (newDate.getMonth() != newMonth) {
		newDate = addDaysToDate(newDate, -1);
	}

	return newDate;
}





function newCircles(date,dir)
{

	var y = date.substring(0,4);
	var m = date.substring(4,6);
	var d = date.substring(6,8);
	var h = date.substring(8,10);
	var min = date.substring(10,12);

	var newDate = new Date();
	newDate.setFullYear(y);


	switch(dir)
	{
		case 'prev':

			if(m == 1)
			{
				newDate.setFullYear(parseInt(y)-1);
				newDate.setMonth(11);			
			} else {
				m = parseInt(m,10)-2; // minus 2 because js array is out by one, and we want to decrease by one
				newDate.setMonth(m);
			}
	
			break;

			
		case 'next':

	
			if(m == 12)
			{
				newDate.setFullYear(parseInt(y)+1);
				newDate.setMonth(0);		
			} else {
				newDate.setMonth(parseInt(m,10));	
			}
		
			break;
	}



	newDate.setDate(d);
	newDate.setHours(h);
	newDate.setMinutes(min);

	var newString;
	newString = newDate.getFullYear() + "" + pad((newDate.getMonth()+1),2) + "" + pad(newDate.getDate(),2) + "" + pad(newDate.getHours(),2) + "" + pad(newDate.getMinutes(),2);

	//alert("cur => " + date + " new => " + newString);

	$.get(url + 'getcircledata.php?d=' + newString, function(data) {

		if(data)
		{
			$('#newPassiveData').html(data);
			$('#passiveDate').val(newString);
			$('.pcur').html(newPassiveDate);
			plotCircles(true);
		} else {
			alert("No Data");
		}
	});

}




function go(where) {

	var curdate = $('#d').val();
	var curtime = $('#t').val();

	var curview = $("#graphview").html();
	var curdur = parseInt($("#graphduration").html());


	var y = curdate.substring(0,4);
	var m = curdate.substring(4,6);
	var d = curdate.substring(6,8);
	var h = curtime.substring(0,2);
	var min = curtime.substring(2,4);

	var startDate = new Date();
	startDate.setFullYear(y);
	startDate.setMonth(m);
	startDate.setDate(d);
	startDate.setHours(h);
	startDate.setMinutes(min);

	
	var newdate;
	var newtime;
	var factor;	


	switch(curview)
	{
		case 'month':

			factor = (curdur/12); 

			switch(where)
			{
				case 'prev':
					startDate.setMonth(startDate.getMonth()-(factor+1)); // +1 because js months start at 0
					break;
				case 'next':
					startDate.setMonth(startDate.getMonth()+(factor-1));
					break;
			}			
			
			newdate = startDate.getFullYear() + "" + pad((startDate.getMonth()+1),2) + "" + pad(startDate.getDate(),2);
			newtime = curtime;
			$('#d').val(newdate);
			break;

		case 'hour':

			factor = (curdur/24); 
		
			switch(where)
			{
				case 'prev':
					startDate.setDate(startDate.getDate()-factor); // +1 because js months start at 0
					break;
				case 'next':
					startDate.setDate(startDate.getDate()+factor);
					break;
			}			
			
			newdate = startDate.getFullYear() + "" + pad(startDate.getMonth(),2) + "" + pad(startDate.getDate(),2);
			newtime = curtime;
			$('#d').val(newdate);
			break;

		case 'minute':

			factor = (curdur/60); 
		
			switch(where)
			{
				case 'prev':
					startDate.setHours(startDate.getHours()-factor); // +1 because js months start at 0
					break;
				case 'next':
					startDate.setHours(startDate.getHours()+factor);
					break;
			}			
			
			newdate = startDate.getFullYear() + "" + pad(startDate.getMonth(),2) + "" + pad(startDate.getDate(),2);
			newtime = pad(startDate.getHours(),2) + "" + pad(startDate.getMinutes(),2);			
			$('#d').val(newdate);
			$('#t').val(newtime);
			break;


			
	}


	var cururl = document.URL;
	var newurl;
	
	
	var frags = cururl.split('/');


	// dev server	

	//if(frags.length >= 9)
	//{
	//	newurl = 'http://' + frags[2] + '/' + frags[3] + '/' + frags[4] + '/' + frags[5] + '/' + frags[6] + '/' + frags[7] + '/' + newdate + newtime + '/';	
	//}


	// live server
	if(frags.length >= 5)
	{
		newurl = 'http://' + frags[2] + '/' + frags[3] + '/' + frags[4] + '/' + newdate + newtime + '/';
	}


	window.location=newurl;

}









function loadData(type,duration)
{

	//alert("loadData => " + type);

	zoomed = false;

	startLoader();
	var curstation = $('#stations :selected').text();

	var curdate = $('#d').val();
	var curtime = $('#t').val();

	var data;

	for(key in stations)
	{
		if(stations[key].name == curstation)
		{
			if(type == 'hour')
			{
				data = stations[key].seventy.join("_");
			} else if(type == 'minute') {
				data = stations[key].two.join("_");
			}
		}
	}


	var endDate=new Date(); // end date is the current date (or at least the currently selected date)
	endDate.setFullYear(curdate.substr(0,4),(curdate.substr(4,2)-1),curdate.substr(6,2));
	endDate.setHours(curtime.substr(0,2),curtime.substr(2,2));




	var startDate=new Date();
	var factor;
	var num;



	switch(type) 
	{
		case 'hour':
			factor = (duration / 24);
			num = duration;
			startDate.setTime(endDate.getTime()-(factor*86400000)); // 86400000 = seconds in a day
			startDate.setHours(curtime.substr(0,2),curtime.substr(2,2));	
			break;
			
		case 'minute':
			factor = (duration / 60);
			num = (12*factor);
			//startDate.setDate(endDate.getDate());
			startDate.setTime(endDate.getTime()-(factor*3600)); // 3600 = seconds in an hour
			//startDate.setHours((curtime.substr(0,2)-factor),curtime.substr(2,2));				
			break;
			
	}


	//alert("startDate => " + startDate + "\n" + "endDate => " + endDate);


	var postdata = {
					cols:data,
					airshed:$('#airshed').val(),
					num:num,
					fyear:startDate.getFullYear(),
					fmonth:(startDate.getMonth()+1),
					fday:startDate.getDate(),
					fhour:(startDate.getHours()+1),
					fmin:startDate.getMinutes()
					};


	$.post( url + "getlivedata.php", postdata, function(data){

		if(data)
		{
			stopLoader();
			$("#table").html(data);
			
			zoomed = false;

			setupGraph(type,duration);

		} else {
		
			alert("Error Loading Data");
			stopLoader();
			
		}
	
	});

}








function setupGraph(type,duration)
{

	//alert("SetupGraph => " + type);



	$("#graphview").html(type);
	$("#graphduration").html(duration);


	var graphdata = [];
	var axises = [];
	var uaxises = [];

	var tickcounter = 0;
	var rowcounter = 0;
	var tempcounter = 0;
	var tcounter = 0;

	var displayFactor;
	
	if(type == 'month')
	{
		displayFactor = (duration/12);
	} else {
		displayFactor = (duration/24);		
	}


	labels = [];
	finaldata = [];
	zeroSpan = [];
	ticks.length = 0;



	placeholder = $("#graph");


	$("#table > table").find('tr').each(function (row) {

		var className = $(this).attr("class");

		if(className == 'dataParam')
		{
			
			$(this).find('td').each(function (col) {

				if(col > 0)
				{
					labels.push($(this).html());
					graphdata[tcounter] = [];
					
					if((measure[$(this).html()][2] != undefined) && (type != 'month'))
					{
					
						labels.push($(this).html() + " - " + measure[$(this).html()][2][0]);
						
						var word;

						if(measure[$(this).html()][2][0].indexOf("AAAQG") == -1)
						{
							word = " Objective ";
						} else {
							word = " Guideline ";
						}
						
						
						measure[$(this).html() + " - " + measure[$(this).html()][2][0]] = new Array( $(this).html() + word + measure[$(this).html()][2][1] + " " + measure[$(this).html()][2][2],measure[$(this).html()][2][2]);

						tcounter++;
						graphdata[tcounter] = [];
						
						axises[tcounter] = measure[$(this).html()][2][2];
						
					}
					
					tcounter++;
					
				}
							
			});

		}



		if(className == 'dataUnits')
		{

			var nothertempcount = 0;
			
			
			$(this).find('td').each(function (col) {
			
				if(col > 0)
				{

					while(nothertempcount < tcounter)
					{
						if(axises[nothertempcount] == undefined)
						{
							break;
						}

						
						nothertempcount++;
					}

					axises[nothertempcount] = $(this).html();
					
					
					if($.inArray($(this).html(), uaxises))
					{
						uaxises.push($(this).html());						
					}
				
				}

			});
		}



		// first couple of rows are just labels and infos

		if(tempcounter > 3)
		{

			var tempcount = 0;

			$(this).find('td').each(function (col) {
			
				
				if(col == 0)
				{

					var curtick = $(this).html().split(' ');

					var tickclass;
					var a = tickcounter % displayFactor;
					
					if(a==0)
					{
						tickclass = "xticks";
					} else {
						tickclass = "blank";
					}

					
					if(type == 'month')
					{
						ticks.push([tickcounter, "<span class='" + tickclass + "'>" + curtick[0] + " " + curtick[1] + "</span>" ]);

					} else {

						var tempdate = curtick[0].split('/');

						//ticks.push([tickcounter, "<span class='" + tickclass + "'>" + months[(parseInt(tempdate[1])-1)] + " " + tempdate[2] + " " + curtick[1] + "</span>" ]);
						ticks.push([tickcounter, "<span class='" + tickclass + "'>" + months[(parseInt(tempdate[1],10)-1)] + " " + tempdate[2] + " " + curtick[1] + "</span>" ]);
					}

					
					tickcounter ++;



				} else {


					var value = $(this).html().split(',');

					//passive data
					if(value[1] == undefined)
					{
						value[1] = 1;
					}	

					var temp = parseInt(tempcount);

					graphdata[temp].push([ rowcounter, value[0], value[1] ]);


					if(value[0] == "MS" || value[0] == "Z" || value[0] == "C")
					{

						if(value[0] == "Z")
						{
							zeroSpan.push({ xaxis: { from: rowcounter - 0.5, to: rowcounter + 0.5 }, color: "#cccccc" });
							$(this).html("CAL");

						} else {

							$(this).html("&nbsp;");
						}
					
					} else {
						
						$(this).html(value[0]);
					
					}	


					


					if((measure[labels[tempcount]][2] != undefined) && type != 'month')
					{
						tempcount++;
						graphdata[tempcount].push([rowcounter,measure[labels[(tempcount-1)]][2][1],1]);						
					} 
					
					tempcount++;
					
				}

			});
			
			rowcounter ++;
			
		}

		tempcounter ++;

	});





	if(pamzDebug == true)
	{

		$('body').append( "<div class='cb'></div>" );


		$('body').append( "<p><strong>GraphData</strong</p>" );
		
		for(var x=0; x < (graphdata.length); x++)
		{
			$('body').append( x + ") " + graphdata[x] + "<br />");
		}
	
		$('body').append( "<hr>" );
	

		$('body').append( "<p><strong>Labels</strong</p>" );
	
		for(var x=0; x < (labels.length); x++)
		{
			$('body').append( x + ")" + labels[x] + "<br />");
		}

		$('body').append( "<hr>" );


		$('body').append( "<p><strong>Ticks</strong</p>" );

		for(var x=0; x < (ticks.length); x++)
		{
			$('body').append( x + ")" + ticks[x] + "<br />");
		}


		$('body').append( "<hr>" );


		$('body').append( "<p><strong>Zero Span</strong</p>" );

		for(var x=0; x < (zeroSpan.length); x++)
		{
			$('body').append( x + ")" + zeroSpan[x] + "<br />");
		}




	}



	// setup checkboxes 

	$("#choices").html('');
	choiceContainer = $("#choices");


	var displayOptions;
	
	
	
	if($.cookie("displayOptions"))
	{
		displayOptions = $.cookie("displayOptions");
	} else {
		//displayOptions = labels[0] + " " + labels[1] + " " + labels[2];
		displayOptions = "SO2,NO2,O3";
	}
		


	var atLeastOne = false;
	var numvals = graphdata.length;
	var valcounter = 0;
	var displayCount = 0;


	$.each(graphdata, function(index) {
		
		window['l' + index] = $(this);


		if(index <= (graphdata.length-1))
		{

			var item = '';
			var checked = '';


			var curDisplay = displayOptions.split(',');		
			for(var i in curDisplay)
			{
				if(labels[index] == curDisplay[i])
				{

					checked = ' checked="checked"';
					atLeastOne = true;
					displayCount++;
				
				
				}
			
			
			}		


			//if((displayOptions.indexOf(labels[index]) > -1) && displayCount<3)
			//{
				//checked = ' checked="checked"';
				//atLeastOne = true;
				//displayCount++;
			//}


			choiceContainer.append('<div class="graphlabel"><input type="checkbox" name="' + index +
                               '"' + checked + ' id="id' + index + '"> ' +
                               '<label for="id' + index + '">'
                                + labels[index] + ' - ' + axises[index] + ' <em>(' + measure[labels[index]][0] + ')</em></label></div>');



			
                          
		}

		
	});



	// if nothing selected, graph doesn't render

	if(atLeastOne == false)
	{
		$("#choices input[type='checkbox']:eq(0)").attr('checked', true);
	}


	$.each(labels, function(index) {


		if(axises[index] == 'ppb')
		{

			if(labels[index].indexOf("AAAQ") == -1)
			{
				finaldata.push({ label: labels[index], data: window['l' + ( index )], color: index });
			} else {
				finaldata.push({ data: window['l' + ( index )], color: "#FF0000", threshold: true, tlabel: measure[labels[index]][0], colnumber: index, points:{show: false} });
			}


		}  else {


			if(labels[index].indexOf("AAAQ") == -1)
			{
				finaldata.push({ label: labels[index], data: window['l' + ( index )], color: index , yaxis: 2 });
			} else {
				finaldata.push({ data: window['l' + ( index )], color: "#FF0000", yaxis: 2, threshold: true, tlabel: measure[labels[index]][0], colnumber: index, points:{show: false} });
			}
			
		
		}

	});



	choiceContainer.find("input").click(plotAccordingToChoices);


	plotAccordingToChoices();
	

	var previousPoint = null;


	placeholder.bind("plothover", function (event, pos, item) {

		if (item)
		{
			if (previousPoint != item.datapoint) 
			{
				previousPoint = item.datapoint;
                    
				$("#tooltip").remove();

				var x = ticks[item.datapoint[0]][1],
				y = item.datapoint[1].toFixed(1);				
				
				var column;
				var row = item.datapoint[0];



				if(item.series.threshold == true)
				{
					column = item.series.colnumber;
					
				} else {
			
					for(key in labels)
					{
						if(labels[key] == item.series.label)
						{
							column = key;
						}
					
					}
				
				}


				
				var blurb = "Note: This is raw data that has not been through QA/QC";
				
				
				var pointinfo = new String(graphdata[column][row]);

				var curpoint = pointinfo.split(',');


				if(curpoint[2] == 1)
				{
					blurb = "This data has been through QA/QC";
				}


				if(item.series.threshold == true)
				{

					showTooltip(item.pageX, item.pageY,item.series.tlabel);
				
				
				} else {
                    
					showTooltip(item.pageX, item.pageY,
						measure[item.series.label][0] + " @ " + x + " = " + y + measure[item.series.label][1] + "<br />" + blurb);

				}
					
				
				
					
					
			}


		} else {
		
			$("#tooltip").remove();
			previousPoint = null;            

		}
		
	});





	placeholder.bind("plotzoom", function() {


		var type = $("#graphview").html();

		//alert("zoomed => " + zoomed + " type => " + type);


		// zoom out function
				
		if(zoomed == true)
		{
			
			// if we're already zoomed in, reset to default view
			zoomed = false;
			plotAccordingToChoices();
			placeholder.unbind("plotzoom");
			

		} else {
			
			// without this, we end up with multiple graphs and unexpected behaviour

			placeholder.unbind("plotzoom");
			
			switch(type)
			{
				case 'month':
  					$("#graphduration").html(parseInt($("#graphduration").html()) + 12);

					startLoader();
					
					var stationid = $('#stationid').val();


					$.get( url + "getpassivedata.php", { sid: stationid, num: parseInt($("#graphduration").html()), start: $('#d').val() },
						function(data){

							if(data)
							{
								stopLoader();
								$("#table").html(data);
	
								zoomed = false;

								setupGraph('month',parseInt($("#graphduration").html()));
								
							} else {
				
								alert("Error Loading Data");
								stopLoader();
					
							}
		
					});


  					
					break;

				case 'hour':
					$("#graphduration").html(parseInt($("#graphduration").html()) + 24);
					zoomed = false;					
					loadData('hour',parseInt($("#graphduration").html()));
					break;

				case 'minute':
					$("#graphduration").html(parseInt($("#graphduration").html()) + 120);
					zoomed = false;					
					loadData('minute',parseInt($("#graphduration").html()));
					break;
			}

			
		}


	});




	placeholder.bind("plotselected", function (event, ranges) {

		// zoom in function
		
		var targetRange = (Math.ceil(ranges.xaxis.to) - Math.floor(ranges.xaxis.from));

		if(type == 'hour' && targetRange<=2)		
		{

			var targettime = ticks[Math.ceil(ranges.xaxis.to)][1];

			//alert(targettime);			
			
			targettime = targettime.replace("<span class='xticks'>", "");
			targettime = targettime.replace("<span class='blank'>", "");
			targettime = targettime.replace("</span>", "");

			targettime = targettime.split(' ');

			var finaltime = targettime[2];		
			
			$('#t').val(finaltime.replace(":", ""));
			$('#slider').slider('option', 'value', $("#t").val());


			var targetyear = $('#d').val().slice(0,4);
			

			var targetmonth;

			for(var key in months)
			{
				if(months[key] == targettime[0])
				{
					targetmonth = pad((parseInt(key)+1),2);					
				}
			}


			var targetday = pad(targettime[1],2);			

			//alert(targetyear +"-"+ targetmonth +"-"+ targetday);

			 
			$('#d').val(targetyear +""+ targetmonth +""+ targetday);

			

			placeholder.unbind("plotselected");

			
			loadData("minute",120);
			
		
		} else {

			// plot according to choices

			$("#zoomout").remove();

			var tempOptions = [];

			var data = [];

			choiceContainer.find("input:checked").each(function () {
				var key = $(this).attr("name");
				if (key && finaldata[key])
				{
					data.push(finaldata[key]);
					tempOptions.push(labels[key]);				
				}
			});

			
			if (data.length > 0)
			{
				plot = $.plot(placeholder, data,
					$.extend(true, {}, floptions, {
						xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
					}));
						
			}

			
			

			var finalOptions = tempOptions.join(",");

			$.cookie("displayOptions", finalOptions, { path: '/', expires: 7 });


			$('<div id="zoomout">zoom out</div>').appendTo(placeholder).click(function (e) {
				e.preventDefault();
				plot.zoomOut();
			});



			$('<div id="reset">reset</div>').appendTo(placeholder).click(function (e) {
				reset();
			});


			if (data.length > 0 && zeroSpan.length > 0)
				$(".legend table tbody").append("<tr><td class='legendColorBox'><div style='border: 1px solid #ccc; padding: 1px'><div style='width:4px; height: 0; border: 5px solid rgb(204,204,204); overflow: hidden;'></div></div></td><td class='legendLabel'><a href='/resources/glossary/#zero-span' title='Sensor Calibration (click for info)'>CAL</a></td></tr>");


			zoomed = true;

		
		}
	
			
    });


	
}






function plotAccordingToChoices() {

	var choicecount = 0;

	choiceContainer.find("input:checked").each(function () {
		choicecount++;
	});

	
	if(choicecount > 3)
	{
		alert("Please select no more than three (3) graph parameters at one time.");
		return false;
	}	
	
	
	
	var tempOptions = [];

	var data = [];
	
	var uom;
	var numUom = 0;
	var alerted = false;

	choiceContainer.find("input:checked").each(function () {
		var key = $(this).attr("name");
		if (key && finaldata[key])
		{
			data.push(finaldata[key]);
			tempOptions.push(labels[key]);



			if(measure[labels[key]][1] != 'ppb')
			{

				if(numUom > 0)
				{

					if((measure[labels[key]][1] != uom) && (alerted != true))
					{
						alert("Note: Graph can only display one unit of measure on 2nd Y axis.");
						alerted = true;
						$(this).attr("checked", false);
						data.pop();
						tempOptions.pop();
					}
					
				} else {
				
					uom = measure[labels[key]][1];
				}
			
			
				numUom++;
			
			}


			
		}
	});



	if (data.length > 0)
		plot = $.plot( placeholder, data, floptions );

	//plot.setSelection({ x1: 4, x2: 6 },true);
	//plot.setSelection({ x1: 14, x2: 18 },true);


	
	$('.uom').html(uom);


	var finalOptions = null;
	
	finalOptions = tempOptions.join(",");
	

	$.cookie("displayOptions", finalOptions, { path: '/', expires: 7 });


	$('<div id="zoomout">zoom out</div>').appendTo(placeholder).click(function (e) {		
		e.preventDefault();
		plot.zoomOut();
	});


	$('<div id="reset">reset</div>').appendTo(placeholder).click(function (e) {
		reset();
	});


	if (data.length > 0 && zeroSpan.length > 0)
		$(".legend table tbody").append("<tr><td class='legendColorBox'><div style='border: 1px solid #ccc; padding: 1px'><div style='width:4px; height: 0; border: 5px solid rgb(204,204,204); overflow: hidden;'></div></div></td><td class='legendLabel'><a href='/resources/glossary/#zero-span' title='Sensor Calibration (click for info)'>CAL</a></td></tr>");



	//$('<div id="zerospan"><a href="/glossary/#zero-span" title="Sensor Calibration (click for info)">Zero Span</a></div>').appendTo(placeholder);




}







function reset() {
	startLoader();
	window.location.reload();
}






function startLoader() {

	$("#table").html('');
	$("#graph").html('');
	$("#choices").html('');
	

	$("#tabs").prepend('<div id="loader"></div>');	
}





function stopLoader() {
	$("#loader").remove();
}





function pad(number, length)
{
	var str = '' + number;
	while (str.length < length) {
		str = '0' + str;
	}
   
	return str;
}






function showTooltip(x, y, contents) {
	$('<div id="tooltip">' + contents + '</div>').css( {
		position: 'absolute',
		display: 'none',
		top: y + 5,
		left: x + 10,
		border: '1px solid #666',
		padding: '2px',
		'background-color': '#ccc',
		opacity: 0.90
	}).appendTo("body").fadeIn(200);
}





// silly browser - e don't do indexOf


if(!Array.indexOf){
   Array.prototype.indexOf = function(obj){
      for(var i=0; i<this.length; i++){
         if(this[i]===obj){
            return i;
         }
      }
      return -1;
   }
}





function isArray(obj)
{
	if (obj.constructor.toString().indexOf("Array") == -1)
		return false;
	else
		return true;
}






function hideMarkers()
{
	for (var i = 0; i < markers.length; i++) 
	{
		markers[i].hide();
	}

}





function showMarkers()
{
	for (var i = 0; i < markers.length; i++) 
	{
		markers[i].show();
	}

}



function setupMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));	
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(52.09638241034153, -115.1202392578125), 7);        


		var gx = new GGeoXml("http://www.pamz.org/kml/pamz.region.kmz");
		map.addOverlay(gx);



		var greenIcon = new GIcon(G_DEFAULT_ICON);
		greenIcon.image = "http://www.pamz.org/gfx/green-dot.png";
		greenIcon.iconSize = new GSize(32, 32);
		greenIcon.shadowSize = new GSize(64, 32);
		greenIcon.infoWindowAnchor = new GPoint(16, 1);

		var dkGreenIcon = new GIcon(G_DEFAULT_ICON);
		dkGreenIcon.image = "http://www.pamz.org/gfx/dkgreen-dot.png";
		dkGreenIcon.iconSize = new GSize(32, 32);
		dkGreenIcon.shadowSize = new GSize(64, 32);
		dkGreenIcon.infoWindowAnchor = new GPoint(16, 1);

		var blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.image = "http://www.pamz.org/gfx/blue-dot.png";
		blueIcon.iconSize = new GSize(32, 32);
		blueIcon.shadowSize = new GSize(64, 32);
		blueIcon.infoWindowAnchor = new GPoint(16, 1);


		function createMarker(point,name,html,colour) {

			if(colour == 'blue')
			{
				markerOptions = { icon:blueIcon };
			} else if(colour == 'green') {
				markerOptions = { icon:greenIcon };
			} else if(colour == 'dkgreen') {
				markerOptions = { icon:dkGreenIcon };
			}

			var marker = new GMarker(point,markerOptions);
			//var marker = new GMarker(point);

			GEvent.addListener(marker, "click", function() {
				$.cookie('pamztab', '1', { path: '/', expires: 7 });
				location = url + "data/" + name + "/";
			});

			GEvent.addListener(marker, "mouseover", function() {
				marker.openInfoWindowHtml(html);
			});
			
			return marker;
		}



		for(var i=0; i<stations.length; i++)
		{
			if(stations[i].loc[0] != 0 && stations[i].loc[1] != 0)
			{
				var point = new GLatLng(stations[i].loc[0],stations[i].loc[1]);



				var tempLat = Math.round(stations[i].loc[0]*1000)/1000;
				var tempLong = Math.round(stations[i].loc[1]*1000)/1000;
				
				var info = "<div class='infowin'><p><strong>" + stations[i].name + "</strong></p><p>Legal: " + stations[i].legal + "<br />Lat: " + tempLat + "<br />Long: " +  tempLong + "<br />";
				
				if(stations[i].historical)
				{
					var tempstart = stations[i].startdate.split(" ");
					var tempend = stations[i].enddate.split(" ");

					info += "Dates: " + tempstart[0] + " to " + tempend[0];
				}

				info += "</p></div>";


				var colour;

				if(stations[i].historical == undefined)
				{
					if(stations[i].two == undefined)
					{
						colour = "blue";
					} else {
						colour = "green";
					}
				
				} else {

					colour = "dkgreen";
				
				}			

				
				var marker = createMarker(point,stations[i].url,info,colour);
				markers.push(marker);
				map.addOverlay(marker);
				
				if(stations[i].className == 'selected')
				{
					marker.openInfoWindowHtml(info);
				}
			}
		}
		




		function mapLegend() {}
		mapLegend.prototype = new GControl;
		mapLegend.prototype.initialize = function(map) {
			var legend = this;
			legend.panel = document.createElement("div");
			legend.panel.style.width = "140px";
			legend.panel.style.height = "60px";
			legend.panel.style.padding = "15px";
			legend.panel.style.color = "#ffffff";
			legend.panel.style.background = "#5ba835";
			
			legend.panel.innerHTML = "Click on a site to view station data.";
			map.getContainer().appendChild(legend.panel);
			return legend.panel;
		};

		mapLegend.prototype.getDefaultPosition = function() {
			return new GControlPosition(
				G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 40));
		};

		mapLegend.prototype.getPanel = function() {
			return legend.panel;
		}

		map.addControl(new mapLegend());




	}

}









function plotCircles(ajax)
{

	if(ajax != true)
	{
		$(".passiveParams").find("input:checked").not(this).each(function () {
			$(this).attr('checked', false);
		});
	}

	var displayMarkers = true;	

	for(h in displayArray)
	{
		map.removeOverlay(displayArray[h]);
	}


	$(".passiveParams").find("input:checked").each(function () {
		var key = $(this).attr("name");
		displayCircle(key);
		displayMarkers = false;
	});
	

	if(displayMarkers == true)
	{
		showMarkers();
	} else {
		hideMarkers();
	}

}








function displayCircle(k)
{

	var colour;
	var scale;
	
	
	switch(k)
	{
		case "so2":
			colour = "#edc240";
			scale = 50;
			break;
		case "no2":
			colour = "#afd8f8";
			scale = 10;
			break;
		case "o3":
			colour = "#cb4b4b";
			scale = 5;
			break;
	
	}


	for(var i = 0; i < passive.length; i++)
	{
		for(var j = 0; j < stations.length; j++)
		{
			if( stations[j].name == passive[i].name )
			{
				drawCircle("<p><strong>" + stations[j].name + "</strong></p><p>Date: " + $('.pcur').html()  + "<br />" + k.toUpperCase() + " = " + passive[i][k] + " ppb</p>", new GLatLng(stations[j].loc[0], stations[j].loc[1]), ((passive[i][k]/1000)*scale), colour, 1, 1, colour, 0.8);			
			}
		
		}
	}


}









function drawCircle(info, center, radius, bordercolour, borderthickness, borderopacity, fillcolour, fillopacity) {
	//Function created by Chris Haas
	//Tweaked by Tony @ Focus Design - Thanks Chris!
	var circleQuality = 5;			//1 is best but more points, 5 looks pretty good, too
	var M = Math.PI / 180;			//Create Radian conversion constant
	var L = map.getBounds();		//Holds copy of map bounds for use below
	var sw = L.getSouthWest();
	var ne = L.getNorthEast();

	//The map is not completely square so this calculates the lat/lon ratio
	// this works because we create a square map
	//var circleSquish = (ne.lng() - sw.lng()) / (ne.lat() - sw.lat());

	// actually, we're not using a square map, so we'll use a rough approximation
	var circleSquish = 1.6;

	var points = [];							//Init Point Array
	//Loop through all degrees from 0 to 360
	for(var n=0; n<360; n+=circleQuality){
		var P = new GLatLng(
			center.lat() + (radius * Math.sin(n * M)),
			center.lng() + (radius * Math.cos(n * M)) * circleSquish
			);
		points.push(P);
	}
	points.push(points[0]);	// close the circle


	var polygon = new GPolygon(points, bordercolour, borderthickness, borderopacity, fillcolour, fillopacity);
	map.addOverlay(polygon);
	displayArray.push(polygon);

	GEvent.addListener(polygon,"click",function(point) {
		map.openInfoWindowHtml(point, info); 		
	});	


	
}



