// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];
var i = 0;
var map;
var popupName = "popWindow";
var popupOptions = "status=no,menubar=no,top=150,left=300,location=no" ;

// ==== first part of the select box ===
var select_html = "<select onChange=\"handleSelected(this)\">" + "<option selected> - Select a location - </option>";

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);
var newwindow, wheight = 0, wwidth = 0;
function popup(url, title, iwidth, iheight) {
	
	var pwidth, pheight;
	if (!newwindow || newwindow.closed) {
		pwidth = iwidth + 30;
		pheight = iheight + 30;
		newwindow = window.open("", popupName, "width=" + pwidth + ",height=" + pheight + "," + popupOptions);
		wheight = iheight;
		wwidth = iwidth;
	}
	if (wheight != iheight || wwidth != iwidth) {
		pwidth = iwidth + 30;
		pheight = iheight + 90;
		newwindow.resizeTo(pwidth, pheight);
		wheight = iheight;
		wwidth = iwidth;
	}
	if (window.focus) {newwindow.focus();}
}
function popupHTML(url, title, iwidth, iheight) {
	popup(url, title, iwidth, iheight);
	newwindow.location.href = url;
	newwindow.focus();
	return false;
}
function popupQT(url, title, iwidth, iheight) {
	// Create the popup
	var color = "white";
	var copyright = "All text and images copyright &copy; 2007 Randy Rogers.<br/> All rights reserved" ;
	popup(url, title, iwidth, iheight+ 120);
	var movie = QT_GenerateOBJECTText_XHTML(url, iwidth, iheight, "", "autoplay", "true", "emb#bgcolor", "black", "align", "middle", "controller", "true", "cache", "true");
	// Add the QT player
	newwindow.document.open();
	newwindow.document.writeln("<html> <head> <title>" + title + "</title> ") ;
	newwindow.document.writeln("<link rel=\"stylesheet\" type=\"text/css\" href=\"/map/map.css\" />");
	newwindow.document.writeln("</head> <body bgcolor= " + color + ">");
	newwindow.document.writeln(movie);
	newwindow.document.writeln("<div class=\"caption\">" + title + "<br/></div>") ;
	newwindow.document.writeln("<div class=\"copy\">" + copyright + "<br/><br/>") ;
	newwindow.document.writeln("<form><input type=\"button\" name=\"close_window\", value=\"Close\"");
	newwindow.document.writeln(" onclick=\"self.close()\">");
	newwindow.document.writeln("</form></div>");
	newwindow.document.writeln("</body> </html>");
	newwindow.document.close();
	newwindow.focus();
	return false;
}

// Routines to tidy up popup windows when page is left
// Call with an onUnload="closePopup()" in body tag
function closePopup() {
	if (newwindow && !newwindow.closed) {
		newwindow.close();
		newwindow = null ;
	}
}

//event listener for movement takes care of refreshing
function addMoveListener() {
	GEvent.addListener(map, "moveend", function () {
		var d = document.getElementById("longlat");
		if (d !== null) {
			var center = map.getCenter();
			var latLngStr = "Long/Lat of map center: ";
			latLngStr += "(" + Math.round(center.y * 10000) / 10000 + ", " + Math.round(center.x * 10000) / 10000 + ")";
			d.innerHTML = latLngStr;
		}
		d = document.getElementById("zoomlev");
		if (d !== null) {
			var zoomstring = "Zoom Level: ";
			zoomstring += map.getZoom();
			d.innerHTML = zoomstring;
		}
	});
}
function loadOn() {
	var a = document.getElementById("loading");
	a.innerHTML = "LOADING...";
	a.style.backgroundColor = "red";
}
function loadOff() {
	var a = document.getElementById("loading");
	a.innerHTML = "";
	a.style.backgroundColor = "white";
}
function changeLoad() {
	var a = document.getElementById("loading");
	if (a.innerHTML === "") {
		a.innerHTML = "LOADING...";
		a.style.backgroundColor = "red";
	} else {
		a.innerHTML = "";
		a.style.backgroundColor = "white";
	}
}

// ======= This function handles selections from the select box ====
// === If the dummy entry is selected, the info window is closed ==
function handleSelected(opt) {
	var i = opt.selectedIndex - 1;
	if (i > -1) {
		GEvent.trigger(gmarkers[i], "click");
	} else {
		map.closeInfoWindow();
	}
}
function node2string(xmlDocument) {
	var n = xmlDocument[0];
	var markup = "";
	for (var j = 0; j < n.childNodes.length; j++) {
		markup += getXMLNodeSerialisation(n.childNodes[j]);
		//GLog.write("m: " + markup);
	}
	return markup;
}

function getXMLNodeSerialisation(xmlNode) {
  var text = false;
  try {
    // Gecko-based browsers, Safari, Opera.
    var serializer = new XMLSerializer();
    text = serializer.serializeToString(xmlNode);
  }
  catch (e) {
    try {
      // Internet Explorer.
      text = xmlNode.xml;
    }
    catch (e) {}
  }
  return text;
}
// A function to create the marker and set up the event window
function createMarker(lat, lng, name, html) {

  // Create a lettered icon for this point using our icon class
  var index = i + 1 ;

	var letter = String.fromCharCode("A".charCodeAt(0) + i);
	var icon = new GIcon(baseIcon);
	icon.image = "/images/gicons/iconr" + index + ".png";

  // FF 1.5 fix
  //html = '<div style="white-space:nowrap;">' + html + '</div>';
	var markerOptions = {title:name, icon:icon};
	var marker = new GMarker(new GPoint(lng, lat), markerOptions);
	var info = [];
	for (var j = 0; j < html.length; j = j + 1) {
		info.push(new GInfoWindowTab(html[j].title, html[j].html));
	}
	GEvent.addListener(marker, "click", function () {
		marker.openInfoWindowTabsHtml(info);
		map.panTo(new GLatLng(lat, lng));
	});
	gmarkers[i] = marker;
	htmls[i] = html;
  // add a line for the select box
	select_html += "<option> " + index + ". " + name + "</option>";
	i = i + 1;
        
  //  map.addOverlay(marker);
	var topElement = marker.iconImage;
	if (marker.transparentIcon) {
		topElement = marker.transparentIcon;
	}
	if (marker.imageMap) {
		topElement = marker.imageMap;
	}
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}
function initMap(xmlfile) {
	if (GBrowserIsCompatible()) {
		loadOn();

    // Read the data from the xml file
		var rand = Math.random();
		GDownloadUrl(xmlfile + "?" + rand, function (data, responseCode) {
			var xmlDoc = GXml.parse(data);
			var i = 0;
			var lat, lng, zoom;
		   // create the map
			var mapdata = xmlDoc.documentElement.getElementsByTagName("map");
			for (i = 0; i < mapdata.length; i++) {
				lat = parseFloat(mapdata[i].getAttribute("lat"));
				lng = parseFloat(mapdata[i].getAttribute("lng"));
				zoom = parseFloat(mapdata[i].getAttribute("zoom"));
			}
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(lat, lng), zoom);

		   // get general information
			var pop = xmlDoc.documentElement.getElementsByTagName("popup");
			for (i = 0; i < pop.length; i++) {
				popupName = pop[i].getAttribute("name");
				popupOptions = pop[i].getAttribute("options");
			}

		   // obtain the array of markers and loop through it
			var markers = xmlDoc.documentElement.getElementsByTagName("marker");
			for (i = 0; i < markers.length; i = i + 1) {
		     // obtain the attribues of each marker
				lat = parseFloat(markers[i].getAttribute("lat"));
				lng = parseFloat(markers[i].getAttribute("lng"));
				var tooltip = markers[i].getAttribute("tooltip");
				var html = [];
				var tabs = markers[i].getElementsByTagName("tab");
				for (var j = 0; j < tabs.length; j++) {
					var t = tabs[j].getAttribute("title");
					var a = tabs[j].getElementsByTagName("embed");
					var h = node2string(a);
					if (tabs.length > 2) {
						var ohtml = h;
						h = "<center>";
						if (j === 0) {
							h += "<div style=\"width:" + tabs.length * 88 + "px\">" + ohtml + "</div></center>";
						} else {
							h += ohtml + "</center>";
						}
					}
					html.push({title:t, html:h});
				}

		     // create the marker
				createMarker(lat, lng, tooltip, html);
			}
		   // put the assembled select contents into the sidebar div
		   // ===== final part of the select box =====
			select_html += "</select>";
			a = document.getElementById("selection");
			a.innerHTML = select_html;
			var mgrOptions = {borderPadding:50, maxZoom:15, trackMarkers:true};
			var mgr = new GMarkerManager(map, mgrOptions);
			mgr.addMarkers(gmarkers, 0, 15);
			mgr.refresh();
			addMoveListener();
			loadOff();
		});
	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
}
window.onunload = "GUnload()";

