﻿var stnicon = histstnicon = badstnicon = tsunamicon = null;
//var map = null;
var stations = new Array();
var owners = new Array();
var BuoyMarkers = new Array();
var WindBarbs = new Array();
var PressureLabels = new Array();
var WaterTempLabels = new Array();

function BuoyData(el){
	if (el.value == 'Show') {
		el.value = 'Clear';
		DisplayData();
	} else {
		el.value = 'Show';
		RemoveBuoyMarkers();
	}
}


function ShowNoData(chk) {
	for (var i = 0; i < BuoyMarkers.length; i++) {
		if ((!(chk.checked)) && (BuoyMarkers[i].mydata != 'y')){
			BuoyMarkers[i].hide();
		} else {
			BuoyMarkers[i].show();
		}
	}
}

function ShowNoHist(chk) {
	for (var i = 0; i < BuoyMarkers.length; i++) {
		if ((!(chk.checked)) && (BuoyMarkers[i].mystatus != 'E')){
			BuoyMarkers[i].hide();
		} else {
			BuoyMarkers[i].show();
		}
	}
}

//var station_data = get_data();
// downloads json data and returns object
function get_data()
{
	if( typeof XMLHttpRequest == "undefined" )
	{
		XMLHttpRequest = function()
		{
			try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
			try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
			try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
			try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
			throw new Error( "This browser does not support XMLHttpRequest." )
		}
	}
	var request =  new XMLHttpRequest();
	request.open( "GET" , "http://weather.stormctr.com/bocafalls/buoys/getbuoydata.php" , false) ;
	request.send( "" );
	eval( "var n = " + request.responseText );
	return n;
}

//"created":"2010-05-21T00:55:01UTC",
//"count":"1291",
//"program":["International Partners","IOOS Partners","NDBC Meteorological/Ocean","NERRS","NOS/CO-OPS","Oil and Gas Industry","TAO","Tsunami"],
//"owner":["Amerada Hess","Anadarko","AOML","ATP","Australian Bureau of Meteorology","BHP","BP Inc","Brazilian Navy Hydrographic Center","California Polytechnic State University","California State University, East Bay","Caribbean Integrated Coastal Ocean Observing System (CarICoos)","CaroCOOPS","Chesapeake Bay Interpretive Buoy System (CBIBS)","Chesapeake Biological Lab","Chevron","COMPS","ConocoPhillips","CORIE","CORMP","Dauphin Island Sea Lab","Delaware Coastal Management Program","DIMAR Colombia","El Paso E&P Company, L.P.","Energy Resources Technologies/Remington","ENI Petroleum","Environment Canada","Esso Petroleum, Australia","Everglades National Park","ExxonMobil","GLERL","GoMOOS","Humboldt State University","Hydrographic and Oceanographic Service of the Chilean Navy (SHOA)","Icelandic Maritime Administration","Indonesian Agency for Assessment and Application of Technology (BPPT)","INPE Brazil","Integrated Coral Observing Network (ICON)","Japanese Meteorological Agency","Kerr-McGee","King Abdullah University for Science and Tech (KAUST)","LLOG","Long Island Ferry","LSU CSI","LUMCON","Maersk Drilling USA","Marathon Oil","Marine Exchange of Alaska","Mariner Energy Inc.","MBARI","Met Eireann","Meteo France","Meteorological Dept, States of Jersey","Moss Landing Marine Lab","Murphy","MYSOUND","National Estuarine Research Reserve System","National Institute for Ocean Technology","NC-COOS","NDBC","Newfield Exploration Company","Nexen Petroleum USA","NOAA/PMEL","Noble Energy","NOS","NWS Alaska Region","NWS Central Region","NWS Eastern Region","Oregon Coastal Ocean Observing System","Petrobras","Petrolia","Prediction and Research Moored Array in the Atlantic","Private Industry Oil Platform","Puerto Rico Seismic Network","Repsol","San Francisco State","SCCOOS","SCRIPPS","Shell Oil","Skidaway","South Carolina Nearshore Monitoring System","Statoil Hydro","Stevens","TABS","Tana Exploration Company","TCOON","Terra Ceia Aquatic Preserve","Thailand Meteorological Department","The Scottish Association for Marine Science (SAMS)","Total USA","U.S. Army Corps of Engineers","UK Met Office","University of Hawaii","University of Maryland Horn Point Laboratory","University of Michigan","University of New Hampshire","USM","Virginia Institute of Marine Science (VIMS)","Walter Oil and Gas","Williams","Woods Hole Oceanographic Institution"],
//"datatype":[],
//"station":[
//{"id":"13001","lat":"12","lon":"-23","name":"NE Extension","owner":"70","program":"0","status":"E","data":"y","type":"buoy"},
//{"id":"13002","lat":"21","lon":"-23","name":"NE Extension","owner":"70","program":"0","status":"E","data":"y","type":"buoy"},
//{"id":"13008","lat":"15","lon":"-38","name":"Reggae","owner":"70","program":"0","status":"E","data":"y","type":"buoy"},
//]}

function DisplayData(){
	var jBuoys = get_data();
	var stationsData = jBuoys.station;
	var programs = jBuoys.program;
	var owners = jBuoys.owner;
	var dataCount = jBuoys.count;
	var dataDate = jBuoys.created;
	for (var i = 0; i < stationsData.length; i++) {


			BuoyMarkers.push(createBuoyMarker(
				stationsData[i].id, //id
				stationsData[i].name, //name
				jBuoys.owner[stationsData[i].owner], //owner (relational)
				jBuoys.program[stationsData[i].program], //program (relational)
				stationsData[i].status, //status
				stationsData[i].data, //data
				//stationsData.station[i].seq, //seq??
				stationsData[i].lat, //latitude
				stationsData[i].lon //longitude
				)
			);
	}
	load_icons();
	//document.getElementById("info").innerHTML = pgm.count;
	//document.getElementById("info").innerHTML = txt;
}


function load_icons() {
	var i = 0;
	var ro = new RepeatingOperation(function() {
		map.addOverlay(BuoyMarkers[i]);
		if ((!(document.getElementById("chkData").checked)) && (BuoyMarkers[i].mydata != 'y')){BuoyMarkers[i].hide()};
		if ((!(document.getElementById("chkHist").checked)) && (BuoyMarkers[i].mystatus != 'E')){BuoyMarkers[i].hide()};
		if (++i < BuoyMarkers.length) {
			ro.step(); 
		}
	},150);
	ro.step(); 

	//for (var i = 0; i < BuoyMarkers.length; i++) {
	//	map.addOverlay(BuoyMarkers[i]);
	//}
}

function makeTop (marker,b) {
        return google.maps.Overlay.getZIndex(marker.getPoint().lat()) + 90000000;
}

//function createMarker(stn,stnname,owner,pgm,status,data,seq,lat,lon) {
function createBuoyMarker(stn,stnname,owner,pgm,status,data,lat,lon) {
	var stnpos = new google.maps.LatLng(lat,lon);
	//bounds.extend(stnpos);
	var marker = null;
	var title = stn.toUpperCase();
	if (stnname) { title += ' - '+stnname; }
	if (status == 'E') {
		if (data == 'y') {
	
			//if(array_match(event_dataaa,stn)){
	
			//	var setIndex = google.maps.Overlay.getZIndex(stnpos.lat()) + 9000000;
			//	marker = new google.maps.Marker(stnpos,{title:title,icon:tsunamicon,zIndexProcess:makeTop});

			//}else{

				marker = new google.maps.Marker(stnpos,{title:title,icon:stnicon,zIndexProcess:makeTop});
			//}
		} else {
			marker = new google.maps.Marker(stnpos,{title:title,icon:badstnicon});
			
			
		}
	} else {
		marker = new google.maps.Marker(stnpos,{title:title,icon:histstnicon});
	}
	google.maps.Event.addListener(marker, "click", function() {
		var html = null;
		if (pgm == 'TAO' && seq != null) {
			html = '<strong>Station '+stn.toUpperCase()+'<br />'+owner+'<br />Location:<\/strong> '+formatLat(lat)+' '+formatLon(lon)+'<br /><a href="http://tao.noaa.gov/refreshed/site.php?site='+seq+'" target="_blank">View Details<\/a> <img src="images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/>';
		//} else if (pgm == 'Tsunami') {
		//	html = '<img src="/plot_dart.php?station='+stn+'&uom=M&width=400&height=220" height="220" width="400" alt="Five-day plot of water level at '+stn+'"/><br />';
		//	if (dartevents['s'+stn]) {
		//		html += '<a href="http://www.ndbc.noaa.gov/station_page.php?station='+stn+'&type=2&seriestime='+dartevents['s'+stn]+'" target="_blank">View Event Details<\/a> <img src="images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/>';
		//	} else {
		//		html += '<a href="http://www.ndbc.noaa.gov/station_page.php?station='+stn+'" target="_blank">View Details<\/a> <img src="images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/>';
		//	}
		} else {
			populateInfoWindow(stn,stnpos,owner);
		}
		if (html != null) { map.openInfoWindowHtml(stnpos,html); }
	});
	marker.myowner = owner;
	marker.mypgm = pgm;
	marker.mystatus = status;
	marker.mydata = data;
	//marker.myseq = seq;
	marker.mystn = stn;
	marker.myeventtime = null;
	//if (!document.getElementById("chkData").checked && (data != 'y')){marker.hide()};
	//if (!document.getElementById("chkHist").checked && (status != 'E')){marker.hide()};

	return marker;
}

function populateInfoWindow(stn,stnpos,owner) {
	//google.maps.DownloadUrl("http://www.ndbc.noaa.gov/get_observation_as_xml.php?station="+stn, function(data, responseCode) {
	google.maps.DownloadUrl("http://weather.stormctr.com/bocafalls/buoys/GetBuoyDetail.php?stn="+stn, function(data, responseCode) {
		var html = null;
		//alert(data);
		//alert(responseCode);
		if(data=="" || !(responseCode==200||responseCode==304) ) {
			html = '<strong>Station '+stn.toUpperCase()+'<br />'+owner+'<br />Location:<\/strong> '+formatLat(stnpos.lat())+' '+formatLon(stnpos.lng())+'<br />There are no recent (&lt; 8 hours) meteorological data for this station.<br .>Click <a href="http://www.ndbc.noaa.gov/station_page.php?station='+stn+'" target="_blank">here<\/a> <img src="images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/> - <a href="http://www.ndbc.noaa.gov/station_history.php?station='+stn+'" target="_blank">View History<\/a> <img src="images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/> for other data from this station.';
		} else {
			var xml = google.maps.Xml.parse(data);
			if(xml.documentElement) {
				var data = {datetime:null, name:null, lat:null, lon:null, winddir:null, windspeed:null, windgust:null, waveht:null, domperiod:null, meanwavedir:null, pressure:null, airtemp:null, watertemp:null, dewpoint:null, tide:null, visibility:null};
				data['id'] = xml.documentElement.getAttribute('id');
				data['name'] = xml.documentElement.getAttribute('name');
				data['lat'] = xml.documentElement.getAttribute('lat');
				data['lon'] = xml.documentElement.getAttribute('lon');
				var items=xml.documentElement.childNodes;
				for (var i=0;i<items.length;i++) {
					if (items[i].nodeType == 1) {
						switch (items[i].nodeName) {
							case 'datetime':
								data[items[i].nodeName] = parseiso8601(items[i].childNodes[0].nodeValue);
								break;
							case 'winddir':
								var dir = deg2dir(items[i].childNodes[0].nodeValue);
								if (dir != null) {
									data[items[i].nodeName] = dir +' ('+items[i].childNodes[0].nodeValue+'&#176;)';
								} else {
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue+'&#176;';
								}
								break;
							case 'meanwavedir':
								var dir = deg2dir(items[i].childNodes[0].nodeValue);
								if (dir != null) {
									data[items[i].nodeName] = dir +' ('+items[i].childNodes[0].nodeValue+'&#176;)';
								} else {
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue+'&#176;';
								}
								break;
							case 'pressure':
								var uom = items[i].getAttribute('uom');
								if (uom != null) {
									if (uom == 'in') {uom += ' (' + (Math.round(items[i].childNodes[0].nodeValue * 33.863886 * 100)/100) + ' mb)'};
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue + ' ' +uom;
									var label = new ELabel(new GLatLng(parseFloat(data['lat']),parseFloat(data['lon'])), (Math.round(items[i].childNodes[0].nodeValue * 33.863886 * 10)/10), "style1", new GSize(0,-5), 40 );
									label.id = data['id'];
									for (var j = 0; j < PressureLabels.length; j++) {
										if (PressureLabels[j].id == label.id){
											map.removeOverlay(PressureLabels[j]);
											PressureLabels.splice(j,1);
											break;
										}
									}
									PressureLabels.push(label);
									map.addOverlay(label);
								} else {
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue;
								}
								var ptend = items[i].getAttribute('tendency');
								if (ptend != null) {
									data[items[i].nodeName] += ' and ' + ptend;
								}
								break;
							case 'wbFileName':
								var width = items[i].getAttribute('width');
								var height = items[i].getAttribute('height');
								var fName = items[i].childNodes[0].nodeValue;
								if ((width != null) && (height != null)) {
				//alert('id:' + data['id'] + 'fn:' + fName + '  w:' + width  + '   h:' + height  + '   lat:' + data['lat'] + '   lon:' + data['lon']);
									CreateWindBarbIcon(data['id'], fName, parseInt(width), parseInt(height), parseFloat(data['lat']), parseFloat(data['lon']));
								}
								break;
							case 'watertemp':
								var uom = items[i].getAttribute('uom');
								if (uom != null) {
									var wTmpC = items[i].childNodes[0].nodeValue;
									if (uom == 'F') wTmpC = Math.round(((wTmpC - 32) * 5 / 9)*10)/10;
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue + ' ' +uom;
									var label = new ELabel(new GLatLng(parseFloat(data['lat']),parseFloat(data['lon'])), wTmpC + 'C', "style1", new GSize(0,23), 40 );
									label.id = data['id'];
									for (var j = 0; j < WaterTempLabels.length; j++) {
										if (WaterTempLabels[j].id == label.id){
											map.removeOverlay(WaterTempLabels[j]);
											WaterTempLabels.splice(j,1);
											break;
										}
									}
									WaterTempLabels.push(label);
									map.addOverlay(label);
								} else {
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue;
								}
								break;
							default:
								var uom = items[i].getAttribute('uom');
								if (uom != null) {
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue + ' ' +uom;
								} else {
									data[items[i].nodeName] = items[i].childNodes[0].nodeValue;
								}
						}
					}
				}
				var now = new Date();
				var cutoff = new Date(Date.UTC(now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate(),now.getUTCHours(),now.getUTCMinutes(),now.getUTCSeconds())-8*60*60*1000);
				if (data['id'] != null && data['datetime'] != null && data['lat'] != null && data['lon'] != null && data['datetime'] >= cutoff) {
					var title = '<strong>Station '+data['id'].toUpperCase()+'<br />'+owner+'<br />Location:<\/strong> '+formatLat(data['lat'])+' '+formatLon(data['lon'])+'<br /><strong>Conditions as of:<br />'+data['datetime'].toUTCString().replace("GMT","UTC")+'<\/strong><br />';
					var body = '';
					var winds = '';
					if (data['winddir'] != null) { winds += data['winddir']; }
					if (data['windspeed'] != null) { winds += ' at '+data['windspeed']; }
					if (data['windgust'] != null) { winds += ' gusting to '+data['windgust']; }
					if (winds) {
						body += '<strong>Winds:<\/strong> '+winds+'<br />';
					}
					if (data['waveht'] != null) { body += '<strong>Significant Wave Height:<\/strong> '+data['waveht']+'<br />'; }
					if (data['domperiod'] != null) { body += '<strong>Dominant Wave Period:<\/strong> '+data['domperiod']+'<br />'; }
					if (data['meanwavedir'] != null) { body += '<strong>Mean Wave Direction:<\/strong> '+data['meanwavedir']+'<br />'; }
					if (data['pressure'] != null) { body += '<strong>Atmospheric Pressure:<\/strong> '+data['pressure']+'<br />'; }
					if (data['airtemp'] != null) { body += '<strong>Air Temperature:<\/strong> '+data['airtemp']+'<br />'; }
					if (data['dewpoint'] != null) { body += '<strong>Dew Point:<\/strong> '+data['dewpoint']+'<br />'; }
					if (data['watertemp'] != null) { body += '<strong>Water Temperature:<\/strong> '+data['watertemp']+'<br />'; }
					if (data['visibility'] != null) { body += '<strong>Visibility:<\/strong> '+data['visibility']+'<br />'; }
					if (data['tide'] != null) { body += '<strong>Tide:<\/strong> '+data['tide']+'<br />'; }
					html = title+'<div style="max-height:120px;max-width:300px;overflow:auto;">'+body+'<\/div><a href="http://www.ndbc.noaa.gov/station_page.php?station='+stn+'" target="_blank">View Details<\/a> <img src="http://weather.stormctr.com/bocafalls/buoys/images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/> - <a href="http://www.ndbc.noaa.gov/station_history.php?station='+stn+'" target="_blank">View History<\/a> <img src="http://weather.stormctr.com/bocafalls/buoys/images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/>';
				} else {
					html = '<strong>Station '+stn.toUpperCase()+'<br />'+owner+'<br />Location:<\/strong> '+formatLat(stnpos.lat())+' '+formatLon(stnpos.lng())+'<br />There are no recent (&lt; 8 hours) meteorological data for this station.<br .>Click <a href="http://www.ndbc.noaa.gov/station_page.php?station='+stn+'" target="_blank">here<\/a> <img src="http://weather.stormctr.com/bocafalls/buoys/images/new_window.png" width="16" height="16" alt="Opens in new window" title="Opens in new window" style="vertical-align:text-top" \/> for other data from this station.';
				}
			} else {
				html = "Sorry!  Your browser does not support this application.";
				return;
			}
		}
		html = '<div id="infow">' + html + '</div>';
		if (html != null) { map.openInfoWindowHtml(stnpos,html); }
	});
}

function CreateWindBarbIcon(id, fName, width, height,lat,lon){
	var stnpos = new google.maps.LatLng(lat,lon);
	wbicon = new google.maps.Icon();
	wbicon.image = 'http://weather.stormctr.com/bocafalls/buoys/' + fName;
	wbicon.shadow = null;
	wbicon.iconSize = new google.maps.Size(width, height);
	wbicon.shadowSize = null;
	wbicon.iconAnchor = new google.maps.Point(Math.floor(width/2), Math.floor(height/2));
	wbicon.infoWindowAnchor = new google.maps.Point(Math.floor(width/2), Math.floor(height/2));
	var marker = null;
	marker = new google.maps.Marker(stnpos,{icon:wbicon});
	marker.id = id;
	marker.fname = 'http://weather.stormctr.com/bocafalls/buoys/' + fName;
	for (var i = 0; i < WindBarbs.length; i++) {
		if (WindBarbs[i].id == id){
			map.removeOverlay(WindBarbs[i]);
			WindBarbs.splice(i,1);
		}
	}
	WindBarbs.push(marker);
	map.addOverlay(marker);
}


function formatLat(lat) {
	if (isNaN(lat)) { return lat; }
	if (lat < 0) { return Math.abs(lat).toString()+'S'; }
	if (lat > 0) { return lat.toString()+'N'; }
	return lat.toString();
}

function formatLon(lon) {
	if (isNaN(lon)) { return lon; }
	if (lon < 0) { return Math.abs(lon).toString()+'W'; }
	if (lon > 0) { return lon.toString()+'E'; }
	return lon.toString();
}

function parseiso8601(isodate) {
	var p = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})UTC$/;
	var m = isodate.match(p);
	if (m == null || m.length != 7) { return null; }
	var d = new Date();
	d.setUTCFullYear(m[1]);
	d.setUTCMonth(m[2]-1);
	d.setUTCDate(m[3]);
	d.setUTCHours(m[4]);
	d.setUTCMinutes(m[5]);
	d.setUTCSeconds(m[6]);
	d.setUTCMilliseconds(0);
	return d;
}

function deg2dir(deg){
	if (isNaN(deg)|| deg < 0 || deg > 360) { return null;}
	dir = new Array('N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N');
	return dir[Math.round(deg/22.5)];
}

RepeatingOperation = function(op, yieldEveryIteration) {
	var count = 0;
	var instance = this;
	this.step = function(args) { 
		if (++count >= yieldEveryIteration) { 
			count = 0;
			setTimeout(function() { op(args); }, 1, [])
			return;
		}
		op(args); 
	}; 
};

function RemoveBuoyMarkers(){
	for (var i = 0; i < BuoyMarkers.length; i++) {
	    BuoyMarkers[i].remove();
	}
	BuoyMarkers.length = 0;
}

function RemoveWindBarbs(){
	for (var i = 0; i < WindBarbs.length; i++) {
		map.removeOverlay(WindBarbs[i]);
	    WindBarbs[i].remove();
	}
	WindBarbs.length = 0;
}

function HideWindBarbs(el){
	for (var i = 0; i < WindBarbs.length; i++) {
		if (el.value == 'Hide') {
			WindBarbs[i].hide();
		} else {
			WindBarbs[i].show();
		}
	}
	if (el.value == 'Show'){
		el.value = 'Hide';
	} else {
		el.value = 'Show';
	}
}

function RemovePressureLabels(){
	for (var i = 0; i < PressureLabels.length; i++) {
		map.removeOverlay(PressureLabels[i]);
	    PressureLabels[i].remove();
	}
	PressureLabels.length = 0;
}

function HidePressureLabels(el){
	for (var i = 0; i < PressureLabels.length; i++) {
		if (el.value == 'Hide') {
			PressureLabels[i].hide();
		} else {
			PressureLabels[i].show();
		}
	}
	if (el.value == 'Show'){
		el.value = 'Hide';
	} else {
		el.value = 'Show';
	}
}

function RemoveWaterTempLabels(){
	for (var i = 0; i < WaterTempLabels.length; i++) {
		map.removeOverlay(WaterTempLabels[i]);
	    WaterTempLabels[i].remove();
	}
	WaterTempLabels.length = 0;
}

function HideWaterTempLabels(el){
	for (var i = 0; i < WaterTempLabels.length; i++) {
		if (el.value == 'Hide') {
			WaterTempLabels[i].hide();
		} else {
			WaterTempLabels[i].show();
		}
	}
	if (el.value == 'Show'){
		el.value = 'Hide';
	} else {
		el.value = 'Show';
	}
}

window.onload=initialize;

