var map;
var aqiStations = [];
var snohomishTodayForecast;
var kingTodayForecast;
var pierceTodayForecast;
var kitsapTodayForecast;
var snohomishTomorrowForecast;
var kingTomorrowForecast;
var pierceTomorrowForecast;
var kitsapTomorrowForecast;
var snohomishTodayShapes = [];
var kingTodayShapes = [];
var pierceTodayShapes = [];
var kitsapTodayShapes = [];
var snohomishTomorrowShapes = [];
var kingTomorrowShapes = [];
var pierceTomorrowShapes = [];
var kitsapTomorrowShapes = [];
var aqiLegend;

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(47.52, -122.2), 9);
		map.setMapType(G_HYBRID_MAP);
		map.addControl(new GMapTypeControl(true), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10)));
		map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(62,35)));
		aqiLegend = new Legend("./images/aqi_newlegend.gif", 136, 261)
		GDownloadUrl("./stationdata.xml", LoadStationXml);
	} else {
		var containerNode = document.getElementById("text_twocolumn");
		while (containerNode.firstChild) {
			containerNode.removeChild(containerNode.firstChild);
		};
		var errNode = document.createElement("h2");
		errNode.style.textAlign = "center";
		var errMsg = document.createTextNode("Sorry, but we cannot display the network map in your browser.");
		errNode.appendChild(errMsg);
		containerNode.appendChild(errNode);
	}
}

/* Initialize all monitoring stations and load data into station properties */
function LoadStationXml(data) {
	var xml = GXml.parse(data);
	var stationCodes = xml.documentElement.getElementsByTagName("stationCode");
	var stationNames = xml.documentElement.getElementsByTagName("name");
	var latitudes = xml.documentElement.getElementsByTagName("latitude");
	var longitudes = xml.documentElement.getElementsByTagName("longitude");
	var elevations = xml.documentElement.getElementsByTagName("elevation");
	var owners = xml.documentElement.getElementsByTagName("owner");
	var pollutants = xml.documentElement.getElementsByTagName("pollutants");
	var pmAqis = xml.documentElement.getElementsByTagName("pmAqi");
	var ozoneAqis = xml.documentElement.getElementsByTagName("ozoneAqi");
	var forecasts = xml.documentElement.getElementsByTagName("county");
		
	for (var i = 0; i < stationCodes.length; i++) {
		var newStation = new Station(GXml.value(stationCodes[i]));
		newStation.setStationName(GXml.value(stationNames[i]));
		newStation.setStationLatitude(GXml.value(latitudes[i]));
		newStation.setStationLongitude(GXml.value(longitudes[i]));
		newStation.setStationElevation(GXml.value(elevations[i]));
		newStation.setStationOwner(GXml.value(owners[i]));
		newStation.setStationPollutants(GXml.value(pollutants[i]));
		newStation.setStationPmAqi(GXml.value(pmAqis[i]));
		newStation.setStationOzoneAqi(GXml.value(ozoneAqis[i]));
		// Array length is always 1 higher than the largest integer subscript.
		// The following is equivalent to aqiStations.push(newStation):
		aqiStations[aqiStations.length] = newStation;
	}
		
	for (var i = 0, theStation; theStation = aqiStations[i++];) {
		// Set the point for locating the station.
		var point = new GLatLng(theStation.getStationLatitude(), theStation.getStationLongitude());
		
		/* Build the new InfoWindow HTML for each station */
		var html = '<div style="width:300px; height:160px; font-family:Verdana, Arial, sans-serif;">';
		html += '<p style="font-weight:bold; font-size:1.2em; text-align:center;">' + theStation.getStationName() + '<br><br>';
		if (theStation.getStationOwner() == "P") {
			html += '<img src="./images/pscaa_logo.jpg" width="150" height="58" border="0">';
		} else {
			html += '<img src="./images/ecy_logo.gif" width="167" height="45" border="0">';
		}
		html += '</p><hr size="2">';
		
		html += '<p style="font-size:1.2em; text-align:left;">';
		html += '<strong>Elevation:</strong> ' + theStation.getStationElevation();
		if (theStation.getStationElevation() != "N/A") {
			html += ' feet';
		}
		html += '<br>';
		html += '<strong>Parameters:</strong> ' + theStation.getStationPollutants();
		
		if (theStation.getStationPmAqi()) {
			html += '<br>';
			if (theStation.getStationPmAqi() < 51) {
				html += '<span style="color: #000; background-color: #00E400;">';
			} else if (theStation.getStationPmAqi() < 101) {
				html += '<span style="color: #000; background-color: #FFFF00;">';
			} else if (theStation.getStationPmAqi() < 151) {
				html += '<span style="color: #FFF; background-color: #FF7E00;">';
			} else if (theStation.getStationPmAqi() < 201) {
				html += '<span style="color: #FFF; background-color: #FF0000;">';
			} else {
				html += '<span>';
			}
			html += '<strong>PM AQI:</strong> ' + theStation.getStationPmAqi() + '</span>'; 
		}
		
		if (theStation.getStationOzoneAqi()) {
			html += '<br>';
			if (theStation.getStationOzoneAqi() < 51) {
				html += '<span style="color: #000; background-color: #00E400;">';
			} else if (theStation.getStationOzoneAqi() < 101) {
				html += '<span style="color: #000; background-color: #FFFF00;">';
			} else if (theStation.getStationOzoneAqi() < 151) {
				html += '<span style="color: #FFF; background-color: #FF7E00;">';
			} else if (theStation.getStationOzoneAqi() < 201) {
				html += '<span style="color: #FFF; background-color: #FF0000;">';
			} else {
				html += '<span>';
			}
			html += '<strong>Ozone AQI:</strong> ' + theStation.getStationOzoneAqi() + '</span>'; 
		}
		
		html += '</p>';
				
		/* Create AQI marker, logic to determine which value to pass as aqi parameter */
		var pmAqi = theStation.getStationPmAqi();
		var o3Aqi = theStation.getStationOzoneAqi();
					
		var aqiParam;
		
		// Check #1: PM and O3 both exist but both N/A -> send "N/A"
		if (pmAqi && o3Aqi && pmAqi == "N/A" && o3Aqi == "N/A") {
			aqiParam = "N/A";
		}
		
		// Check #2: PM and O3 both exist and neither N/A -> send greater of the 2 values
		if (pmAqi && o3Aqi && pmAqi != "N/A" && o3Aqi != "N/A") {
			if (parseInt(pmAqi, 10) >= parseInt(o3Aqi, 10)) {
				aqiParam = parseInt(pmAqi, 10);
			} else {
				aqiParam = parseInt(o3Aqi, 10);
			}
		}

		// Check #3: PM and O3 both exist but O3 is N/A -> send PM AQI
		if (pmAqi && o3Aqi && pmAqi != "N/A" && o3Aqi == "N/A") {
			aqiParam = parseInt(pmAqi, 10);
		}
		
		// Check #4: PM and O3 both exist but PM is N/A -> send Ozone AQI
		if (pmAqi && o3Aqi && pmAqi == "N/A" && o3Aqi != "N/A") {
			aqiParam = parseInt(o3Aqi, 10);
		}
		
		// Check #5: PM only exists -> send PM AQI
		if (pmAqi && !o3Aqi) {
			aqiParam = parseInt(pmAqi, 10);
		}
		
		// Check #6: Ozone only exists -> send Ozone AQI
		if (!pmAqi && o3Aqi) {
			aqiParam = parseInt(o3Aqi, 10);
		}
		
		// Check #7: Neither PM nor Ozone exist -> send "N/A"
		if (!pmAqi && !o3Aqi) {
			aqiParam = "N/A";
		}
		
		createAqiMarker(point, aqiParam, html);
	}
	
	// Assign forecast to the county forecast variables.
	for (var i = 0; i < forecasts.length; i++) {
		var countyName = forecasts[i].getAttribute("name");
		var todayForecast = forecasts[i].getAttribute("todayForecast");
		var tomorrowForecast = forecasts[i].getAttribute("tomorrowForecast");
		if (countyName == "Snohomish") {
			snohomishTodayForecast = todayForecast;
			snohomishTomorrowForecast = tomorrowForecast;
		} else if (countyName == "King") {
			kingTodayForecast = todayForecast;
			kingTomorrowForecast = tomorrowForecast;
		} else if (countyName == "Pierce") {
			pierceTodayForecast = todayForecast;
			pierceTomorrowForecast = tomorrowForecast;
		} else if (countyName == "Kitsap") {
			kitsapTodayForecast = todayForecast;
			kitsapTomorrowForecast = tomorrowForecast;
		}
	}
	
	// Load each county's shapes into the corresponding arrays
	snohomishTodayShapes.push(loadShape(36, snohomishTodayForecast));
	snohomishTodayShapes.push(loadShape(37, snohomishTodayForecast));
	snohomishTodayShapes.push(loadShape(45, snohomishTodayForecast));
	kingTodayShapes.push(loadShape(49, kingTodayForecast));
	kingTodayShapes.push(loadShape(55, kingTodayForecast));
	pierceTodayShapes.push(loadShape(56, pierceTodayForecast));
	pierceTodayShapes.push(loadShape(57, pierceTodayForecast));
	pierceTodayShapes.push(loadShape(58, pierceTodayForecast));
	pierceTodayShapes.push(loadShape(60, pierceTodayForecast));
	pierceTodayShapes.push(loadShape(63, pierceTodayForecast));
	pierceTodayShapes.push(loadShape(65, pierceTodayForecast));
	pierceTodayShapes.push(loadShape(67, pierceTodayForecast));
	kitsapTodayShapes.push(loadShape(48, kitsapTodayForecast));
	kitsapTodayShapes.push(loadShape(50, kitsapTodayForecast));
	kitsapTodayShapes.push(loadShape(53, kitsapTodayForecast));
	
	snohomishTomorrowShapes.push(loadShape(36, snohomishTomorrowForecast));
	snohomishTomorrowShapes.push(loadShape(37, snohomishTomorrowForecast));
	snohomishTomorrowShapes.push(loadShape(45, snohomishTomorrowForecast));
	kingTomorrowShapes.push(loadShape(49, kingTomorrowForecast));
	kingTomorrowShapes.push(loadShape(55, kingTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(56, pierceTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(57, pierceTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(58, pierceTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(60, pierceTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(63, pierceTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(65, pierceTomorrowForecast));
	pierceTomorrowShapes.push(loadShape(67, pierceTomorrowForecast));
	kitsapTomorrowShapes.push(loadShape(48, kitsapTomorrowForecast));
	kitsapTomorrowShapes.push(loadShape(50, kitsapTomorrowForecast));
	kitsapTomorrowShapes.push(loadShape(53, kitsapTomorrowForecast));
}
	
function createAqiMarker(point, aqi, html) {
	// Define the base icon properties
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(18, 18);
	baseIcon.shadowSize = new GSize(28, 18);
	baseIcon.shadow = "./images/marker_shadow_small.png";
	baseIcon.iconAnchor = new GPoint(10, 10);
	baseIcon.infoWindowAnchor = new GPoint(10, 4);
	
	// Good icon
	var goodIcon = new GIcon(baseIcon);
	goodIcon.image = "./images/marker_good_small.png";
	
	// Moderate icon
	var moderateIcon = new GIcon(baseIcon);
	moderateIcon.image = "./images/marker_moderate_small.png";
	
	// Unhealthy for Sensitive Groups icon
	var usgIcon = new GIcon(baseIcon);
	usgIcon.image = "./images/marker_usg_small.png";
	
	// Unhealthy icon
	var unhealthyIcon = new GIcon(baseIcon);
	unhealthyIcon.image = "./images/marker_unhealthy_small.png";
	
	// No AQI icon
	var noaqiIcon = new GIcon(baseIcon);
	noaqiIcon.image = "./images/marker_noaqi_small.png";
	
	// Set the marker icon based on AQI parameter
	var markerOptions;
	if (aqi && aqi != "N/A") {
		if (aqi < 51) {
			markerOptions = { icon:goodIcon };
		} else if (aqi < 101) {
			markerOptions = { icon:moderateIcon };
		} else if (aqi < 151) {
			markerOptions = { icon:usgIcon };
		} else if (aqi < 201) {
			markerOptions = { icon:unhealthyIcon };
		}
	} else {
		markerOptions = { icon:noaqiIcon };
	}
	
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "mouseover", function() {
		marker.openInfoWindowHtml(html);
	});	
	GEvent.addListener(marker, "mouseout", function() {
		marker.closeInfoWindow();
	});
	map.addOverlay(marker);
}

function loadShape(index, fcst) {
	var county = WA_county_shapes[index];
	var color;
	if (fcst == "Good") {
		color = "#00E400";
	} else if (fcst == "Moderate") {
		color = "#FFFF00";
	} else if (fcst == "Unhealthy for Sensitive Groups") {
		color = "#FF7E00";
	} else if (fcst == "Unhealthy") {
		color = "#FF0000";
	} else if (fcst == "N/A") {
		color = "#C0C0C0";
	}
	
	var countyShape = new GPolygon.fromEncoded({polylines:[{color:"#A9A9A9", weight:1, opacity:1.0, points:county.encoded_pos,
																								 zoomFactor:32, levels:county.encoded_levels, numlevels:4}],
																		 						 fill:true, color:color, opacity:0.4, outline:true});
	return countyShape;
}

function addCountyShapes(shapes) {
	for (var i = 0, shape; shape = shapes[i++];) {
		map.addOverlay(shape);
	}
}

function removeCountyShapes(shapes) {
	for (var i = 0, shape; shape = shapes[i++];) {
		map.removeOverlay(shape);
	}
}

function showForecast() {
	chosen = "";
	len = document.frmFcst.radShowFcst.length;
	
	// Check each radio button to find the checked one
	for (var i = 0; i < len; i++) {
		if (document.frmFcst.radShowFcst[i].checked) {
			chosen = document.frmFcst.radShowFcst[i].value;
		}
	}
	
	if (chosen == "today") {
		removeCountyShapes(snohomishTomorrowShapes);
		removeCountyShapes(kingTomorrowShapes);
		removeCountyShapes(pierceTomorrowShapes);
		removeCountyShapes(kitsapTomorrowShapes);
		addCountyShapes(snohomishTodayShapes);
		addCountyShapes(kingTodayShapes);
		addCountyShapes(pierceTodayShapes);
		addCountyShapes(kitsapTodayShapes);
	} else if (chosen == "tomorrow") {
		removeCountyShapes(snohomishTodayShapes);
		removeCountyShapes(kingTodayShapes);
		removeCountyShapes(pierceTodayShapes);
		removeCountyShapes(kitsapTodayShapes);
		addCountyShapes(snohomishTomorrowShapes);
		addCountyShapes(kingTomorrowShapes);
		addCountyShapes(pierceTomorrowShapes);
		addCountyShapes(kitsapTomorrowShapes);
	} else if (chosen == "off") {
		removeCountyShapes(snohomishTodayShapes);
		removeCountyShapes(kingTodayShapes);
		removeCountyShapes(pierceTodayShapes);
		removeCountyShapes(kitsapTodayShapes);
		removeCountyShapes(snohomishTomorrowShapes);
		removeCountyShapes(kingTomorrowShapes);
		removeCountyShapes(pierceTomorrowShapes);
		removeCountyShapes(kitsapTomorrowShapes);
	}
}

function toggleLegend(chk) {
	if (chk.checked) {
		map.addControl(aqiLegend);
	} else {
		map.removeControl(aqiLegend);
	}
}

// Properties of the Station object
Station.prototype._stationCode;
Station.prototype._stationName;
Station.prototype._latitude;
Station.prototype._longitude;
Station.prototype._elevation;
Station.prototype._owner;
Station.prototype._pollutants;
Station.prototype._pmAqi;
Station.prototype._ozoneAqi;

// Methods of the Station object
Station.prototype.getStationCode = function() {
	return this._stationCode;
}
	
Station.prototype.setStationName = function(name) {
	this._stationName = name;
}

Station.prototype.getStationName = function() {
	return this._stationName;
}

Station.prototype.setStationLatitude = function(latitude) {
	this._latitude = latitude;
}

Station.prototype.getStationLatitude = function() {
	return this._latitude;
}

Station.prototype.setStationLongitude = function(longitude) {
	this._longitude = longitude;
}

Station.prototype.getStationLongitude = function() {
	return this._longitude;
}

Station.prototype.setStationElevation = function(elevation) {
	this._elevation = elevation;
}

Station.prototype.getStationElevation = function() {
	return this._elevation;
}

Station.prototype.setStationOwner = function(owner) {
	this._owner = owner;
}

Station.prototype.getStationOwner = function() {
	return this._owner;
}

Station.prototype.setStationPollutants = function(pollutants) {
	this._pollutants = pollutants;
}

Station.prototype.getStationPollutants = function() {
	return this._pollutants;
}

Station.prototype.setStationPmAqi = function(pmAqi) {
	this._pmAqi = pmAqi;
}

Station.prototype.getStationPmAqi = function() {
	return this._pmAqi;
}

Station.prototype.setStationOzoneAqi = function(ozoneAqi) {
	this._ozoneAqi = ozoneAqi;
}

Station.prototype.getStationOzoneAqi = function() {
	return this._ozoneAqi;
}

// Define the Station object
function Station(code) {
	this._stationCode = code;
}

// Properties of the Legend object
Legend.prototype._imgSrc;
Legend.prototype._imgWidth;
Legend.prototype._imgHeight;

// Define the Legend object
function Legend(imgSrc, imgWidth, imgHeight) {
	this._imgSrc = imgSrc;
	this._imgWidth = imgWidth;
	this._imgHeight = imgHeight;
}

Legend.prototype = new GControl();

// Implement methods of the GControl interface.
Legend.prototype.initialize = function(map) {
	// Initialize container to hold the image and click listener
	var container = document.createElement("div");
	container.style.cursor = "pointer";
	GEvent.addDomListener(container, "click", function() {
		window.open("/airq/basics/aqi.aspx", "aqiwin");
	});
	
	// Initialize the legend image itself and add to containing div
	var legendImage = document.createElement("img")
	legendImage.setAttribute("src", this._imgSrc);
	legendImage.setAttribute("width", this._imgWidth);
	legendImage.setAttribute("height", this._imgHeight);
	legendImage.setAttribute("border", "0");
	container.appendChild(legendImage);
	
	// Add the container div to the map container and return element
	map.getContainer().appendChild(container);
	return container;
}

Legend.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10));
}
