var CurrentPopup = null;

var CoML = {
	KmlPath: "projects_map/projects_markers.kml",
	IconWidth: 50,
	IconHeight: 16,
	MaxWidth: 300,
	Projects: [],
	GlobalProjects: [],
	LegendColumns: 2,

	load: function (googleMap, LegendLocalDiv, LegendGlobalDiv) {
		this.map = googleMap;
		this.LegendLocalDiv = LegendLocalDiv;
		this.LegendGlobalDiv = LegendGlobalDiv;
		this.LabelsOn = true;

		var url = this.KmlPath;
		// Add random parameter, so the KML contents are not cached by browser
		var random_parm = (new Date()).format('mmddyyyyhhnnss');

		if (navigator.userAgent.toLowerCase().indexOf('netscape') > 0) {
			GDownloadUrl("http://seamap.env.duke.edu/coml/projects_map/projects_markers.kml", this.parseKml.bind(CoML));
		} else {
			GDownloadUrl(url + "?" + random_parm,  this.parseKml.bind(CoML));
		}
	},

	parseKml: function (xml_text, readyState) {
		if (readyState == 200){
			var data = GXml.parse(xml_text);

			placemarks = data.documentElement.getElementsByTagName("Placemark");

			var projects = $A(placemarks).collect(function (placemark) {
				var project = {
					name: getXmlNodeValue(placemark, 'name'),
					lon: getXmlNodeValue(placemark, 'coordinates').split(',')[0],
					lat: getXmlNodeValue(placemark, 'coordinates').split(',')[1],
					desc: getXmlNodeValue(placemark, 'description'),
					icon_href: getXmlNodeValue(placemark, 'href'),
					color: getXmlNodeValue(placemark, 'color'),
					icon_width: getXmlNodeValue(placemark, 'width')
				}

				return project;
			});
			this.addProjects(projects);
		}
	},

	addProjects: function (projects) {
		var legendDiv = $(this.LegendDiv);

		/*
		var table = $(document.createElement('TABLE'));
		var tbody = $(document.createElement('TBODY'));
		legendDiv.appendChild(table);
		table.appendChild(tbody);
		*/
		var tbody_local = $(this.LegendLocalDiv);
		var tbody_global = $(this.LegendGlobalDiv);
		var num_local = -1;

		for (var i = 0; i < projects.length; i++) {
			// Add project to list
			var project = projects[i];
			var project_name = project.name;
			var project_id = project_name.replace(/(-|:|#|\s)/g, "_");

			var global_proj = (project.lat == 0 && project.lon == 0);
			if (global_proj) {
				var tbody = tbody_global;
			} else {
				var tbody = tbody_local;
				num_local++;
			}

			// Add it to Legend
			if (project_name.indexOf("NO_LEGEND") == -1) {
				if (global_proj || (!global_proj && num_local % this.LegendColumns == 0)) {
					var tr = $(document.createElement('TR'));
					tbody.appendChild(tr);
				}

				var td = $(document.createElement('TD'));

				if (project.icon_width == "") {
					var icon_width = this.IconWidth;	// Default
				} else {
					var icon_width = project.icon_width;	// If specified in KML <width>
				}
				switch (project_name) {
					case "ICOMM":
						var legend_mark = "<img src='http://seamap.env.duke.edu/coml/projects_map/purple.gif' border='0' height='8'> <img src='projects_map/bullet_blue.gif' border='0' height='8'>";
						td.update(legend_mark);
						break;
					case "CenSeam":
						var legend_mark = "<img src='http://seamap.env.duke.edu/coml/projects_map/circle_ccff99.png' border='0'>";
						var color = "#" + project.color.substr(6,2) + project.color.substr(4,2) + project.color.substr(2,2);
						td.setStyle({"background-color": color, width: '24px'});
						td.update(legend_mark);
						break;
					case "CMarZ":
						var legend_mark = "<img src='http://seamap.env.duke.edu/coml/projects_map/circle_29a4bc_small.png' border='0'>";
						var color = "#" + project.color.substr(6,2) + project.color.substr(4,2) + project.color.substr(2,2);
						td.setStyle({"background-color": color, width: '24px', 'text-align': 'center'});
						td.update(legend_mark);
						break;
					case "CReefs":
						var legend_mark = "<img src='http://seamap.env.duke.edu/coml/projects_map/point_australia_marker.png' border='0'>";
						var color = "#" + project.color.substr(6,2) + project.color.substr(4,2) + project.color.substr(2,2);
						td.setStyle({"background-color": color, width: '24px', 'text-align': 'center'});
						td.update(legend_mark);
						break;
					case "HMAP (FB)":
						var legend_mark = "<img src='http://seamap.env.duke.edu/coml/projects_map/fishbones.png' border='0'>";
						td.update(legend_mark);
						break;
					case "HMAP (WWP)":
						var legend_mark = "<img src='http://seamap.env.duke.edu/coml/projects_map/whaling_trackline.png' border='0'>";
						td.update(legend_mark);
						break;
					default:
						var color = "#" + project.color.substr(6,2) + project.color.substr(4,2) + project.color.substr(2,2);
						td.setStyle({"background-color": color, width: '24px'});
				}
				tr.appendChild(td);

				var td = $(document.createElement('TD'));
				td.setStyle({'padding-right': "5px"});
				var aA = this.creatLink(project_id, project_name, global_proj);
				$(aA).addClassName('legend_label');
				td.appendChild(aA);
				tr.appendChild(td);
			} else {
				num_local--;
			}

			// Add project label marker to Google Map as an overlay
			if (!global_proj) {
				var point = new GLatLng(project.lat, project.lon);
				var icon = this.pointIcon(project.icon_href, icon_width, this.IconHeight);	// Added by Ei
				var opt = this.map.getInfoWindow();
				opt.maxWidth = this.MaxWidth;
				var marker = this.createMarker(point, project.desc, icon, opt);

				this.map.addOverlay(marker);

				// Add to a global array
				this.Projects[project_id] = marker;
			} else {
				this.GlobalProjects[project_id] = project.desc;
			}
		}
	},

	creatLink: function (project_id, project_name, global_proj) {
		var aA = document.createElement("A");
		aA.href = "javascript: void(0);";

		if (global_proj) {
			aA.onclick = function () {CoML.selectGlobalProject(project_id);};
		} else {
			aA.onclick = function () {CoML.selectProject(project_id);};
		}
		aA.innerHTML = project_name;
		aA.style.display = 'block';
		return aA;
	},

	createMarker: function (point, desc, icon, opt){
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(desc, opt);
		});
		return marker;
	},

	pointIcon: function  (icon_href, width, height) {
		var icon = new GIcon();

		if (icon_href != "") {
			icon.image = icon_href;
		} else {
			// Default icon
			icon.image = "http://seamap.env.duke.edu/icons/ball_ge.png";
		}

		if (width == 0)  {
			width = gIconWidth;
		}
		if (height == 0)  {
			height = gIconHeight;
		}
		icon.iconSize = new GSize(width, height);
		icon.iconAnchor = new GPoint(width / 2, height / 2);
		icon.infoWindowAnchor = new GPoint(width / 2, height / 2);
		return icon;
	},

	selectProject: function (project_id) {
		if ($('global_project')) {
			CurrentPopup.close();
			CurrentPopup = null;
		}
		var marker = this.Projects[project_id];
		GEvent.trigger(marker, "click");
	},

	selectGlobalProject: function (project_id) {
		var desc = this.GlobalProjects[project_id];
		var map_obj = $('map');
		var pos = Position.cumulativeOffset(map_obj);
		var height = parseInt(map_obj.getStyle('height')) - 35;
		var width = parseInt(map_obj.getStyle('width')) - 50;
		width = Math.min(width, 500);
		height = Math.min(height, 320);

		map.closeInfoWindow();
		if ($('global_project')) {
			CurrentPopup.close();
			CurrentPopup = null;
		}
		CurrentPopup = new PopupWindow("global_project", "global_popup",
				{width: width + "px", height: height + "px", left: (pos[0] + 10) + "px", top: (pos[1] + 10) + "px"});
		CurrentPopup.show("TEST", desc);

	},

	labelsOnOff: function (label_div) {
		if (this.LabelsOn) {
			var new_label = "Show labels";
		} else {
			var new_label = "Hide labels";
		}

		$(label_div).update(new_label);

		for (var project_id in this.Projects) {
			if (typeof(this.Projects[project_id]) == "object") {
				var project = this.Projects[project_id];
				if (this.LabelsOn) {
					this.map.removeOverlay(project);
				} else {
					this.map.addOverlay(project);
				}
			}
		}

		this.LabelsOn = !this.LabelsOn;
	}
}


/***** XML Utility *****/
function getXmlNodeValue(xml, node_name) {
	if (xml.getElementsByTagName(node_name).length > 0) {
		var value = xml.getElementsByTagName(node_name)[0].childNodes[0].nodeValue;
	} else {
		var value = "";
	}

	return value;
}

