// Javascript
//	SJGMaps.js
//		This version of htm & js has taken the 3d code of 1-May-2010 and retro-fitted it for using GMaps
//

// Global variables
var objMap; objMap = {};
var kmlpath = 'http://www.stjohnhistoricalsociety.org/KML/';
var htmlpath = 'kmlExtension/';
var moduleName = 'SJGMaps.js';

function gmapResize() {
	if (objMap && objMap.GMap2) {
		sjhs.consoleTrace.log("LOG", "gmap.checkResize()");
		objMap.GMap2.checkResize();
	}
}

// This function triggers the "click" event for the gMarker object which will open its info window
function placemarkClick(placeMark) {
	GEvent.trigger(placeMark, "click");
}
function tourClick(placeMark) {
	// Not supported in GMAPs
	sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "tourClick");	
}

// [uncluster marker,] click marker
function clusterMarkerClick(cluster, cIndex) {
	cluster.triggerClick(cIndex);
}

function addMapType_Satellite (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_Satellite", dtnode);	
		objMap.GMap2.addMapType(G_SATELLITE_MAP);
		mapType = G_SATELLITE_MAP;
	} catch (exception) {
	   sjhs.consoleTrace.log("ERROR", "Exception:	Module (%s), Procedure (%s), [%s - %s, lineNumber (%d) fileName (%s)]"
			, moduleName, "addMapType_Satellite", exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}

function addMapType_Earth (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_Earth", dtnode);	
		objMap.GMap2.addMapType(G_SATELLITE_3D_MAP);
		mapType = G_SATELLITE_3D_MAP;
	} catch (exception) {
	   sjhs.consoleTrace.log("ERROR", "Exception:	Module (%s), Procedure (%s), [%s - %s, lineNumber (%d) fileName (%s)]"
			, moduleName, "addMapType_Earth", exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}

// MapCruncher tile mapping function:  (x,y,zoom) --> tile url
function TileToQuadKey ( x, y, zoom){ 
	var quad = ""; 
	for (var i = zoom; i > 0; i--){
		var mask = 1 << (i - 1); 
		var cell = 0; 
		if ((x & mask) !== 0) {
			cell++; 
		};
		if ((y & mask) !== 0) {
			cell += 2; 
		};
		quad += cell; 
	} 
	return quad; 
}

// Functions to add mapTypes
function addMapType_Oxholm1780 (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_Oxholm1780", dtnode);	
		
		// Create the TileLayer
		var tilelayers = [new GTileLayer(new GCopyrightCollection("Map Data: Oxholm 1780"), 12, 14)];
		tilelayers[0].getTileUrl = function  (a,b) {
			var tileURL = "Maps/1780mc/Layer_NewLayer/" + TileToQuadKey(a.x,a.y,b) + ".png";  
			return tileURL; 
		};
	
		tilelayers[0].getCopyright = function(a,b) {
			return {prefix:"Map: ", copyrightTexts:["Oxholm 1780"]};
		};
		tilelayers[0].isPng = function() {return true;}; 
			
		// Create the MapType, copying most things from G_SATELLITE_MAP ==
		var mapType = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Oxholm 1780", {errorMessage: "data not available"});
			
		// Add the maptype to the map and map-controls
		objMap.GMap2.addMapType(mapType);
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "addMapType_Oxholm1780", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}


function addMapType_Oxholm1800 (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_Oxholm1800", dtnode);	
		
		// Create the TileLayer
		var tilelayers = [new GTileLayer(new GCopyrightCollection("Map Data: Oxholm 1800"), 12, 18)];
		tilelayers[0].getTileUrl = function  (a,b) {
			var tileURL = "Maps/1800mc/Layer_NewLayer/" + TileToQuadKey(a.x,a.y,b) + ".png";  
			return tileURL; 
		};
	
		tilelayers[0].getCopyright = function(a,b) {
			return {prefix:"Map: ", copyrightTexts:["Oxholm 1800"]};
		};
		tilelayers[0].isPng = function() {return true;}; 
			
		// Create the MapType, copying most things from G_SATELLITE_MAP ==
		var mapType = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Oxholm 1800", {errorMessage: "data not available"});
			
		// Add the maptype to the map and map-controls
		objMap.GMap2.addMapType(mapType);
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "addMapType_Oxholm1800",
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}

function addMapType_USCGS1934 (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_USCGS1934", dtnode);	

		var tilelayers = [new GTileLayer(new GCopyrightCollection("Map Image: US Coast + Geodetic Survey, 1934"), 12, 17)];
		tilelayers[0].getTileUrl = function  (a,b) {
			var tileURL = "Maps/1934mc/Layer_NewLayer/" + TileToQuadKey(a.x,a.y,b) + ".png";  
			return tileURL; 
		};
	
		tilelayers[0].getCopyright = function(a,b) {
			return {prefix:"Map: ", copyrightTexts:["USC+GS"]};
		};
		tilelayers[0].isPng = function() {return true;}; 
				
		// Create the MapType, copying most things from G_SATELLITE_MAP
		var mapType = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "USC+GS 1934", {errorMessage: "data not available"});
			
		// Add the maptype to the map and map-controls
		objMap.GMap2.addMapType(mapType);
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "addMapType_USCGS1934", 
						exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}

function addMapType_Aerial1947 (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_Aerial1947", dtnode);	
		
		var tilelayers = [new GTileLayer(new GCopyrightCollection("Map Image: William Stelzer"), 12, 17)];
		tilelayers[0].getTileUrl = function  (a,b) {
//			var tileURL = "Maps/STJ 1947 - abridged/Layer_NewLayer/" + TileToQuadKey(a.x,a.y,b) + ".png";  
			var tileURL = "Maps/1947mc/Layer_NewLayer/" + TileToQuadKey(a.x,a.y,b) + ".png";  
			return tileURL; 
		};
	
		tilelayers[0].getCopyright = function(a,b) {
			return {prefix:"Map: ", copyrightTexts:["William Stelzer"]};
		};
		tilelayers[0].isPng = function() {return true;}; 
			
		// Create the MapType, copying most things from G_SATELLITE_MAP
		var mapType = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "1947 Aerial photo", {errorMessage: "data not available"});
			
		// Add the maptype to the map and map-controls
		objMap.GMap2.addMapType(mapType);
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "addMapType_Aerial1947", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}

function addMapType_Topo (dtnode) {
	var mapType = null;
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s)", moduleName, "addMapType_Topo", dtnode);	
		
		// Create the TileLayer
		var tilelayers = [new GTileLayer(new GCopyrightCollection("Map Data: Topo"), 12, 17)];
		tilelayers[0].getTileUrl = function  (a,b) {
			var tileURL = "Maps/2007mc/Layer_NewLayer/" + TileToQuadKey(a.x,a.y,b) + ".png";  
			return tileURL; 
		};
	
		tilelayers[0].getCopyright = function(a,b) {
			return {prefix:"Map: ", copyrightTexts:["Robert Garrison"]};
		};
		tilelayers[0].isPng = function() {return true;}; 
			
		// Create the MapType, copying most things from G_SATELLITE_MAP ==
		var mapType = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Topo", {errorMessage: "data not available"});
			
		// Add the maptype to the map and map-controls
		objMap.GMap2.addMapType(mapType);
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "addMapType_Topo", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
		dtnode.data.mapType = mapType;
		return mapType;
	}
}

// load KmlExtension data for building balloons
function asyncLoadHtml(dtnode, urlHtml) {
	try {
		dtnode.data.overlayHtml = null;
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s) url (%s)", moduleName, "loadHtml", dtnode.data.title, urlHtml);	
		$.get(urlHtml, function (Html, status) {
			if (Html) {
				dtnode.data.overlayHtml = $(Html);	// Parse the Html text and store DOM Nodes in a JQuery object
			}
		});
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "loadHtml", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	}
}

// Add gMarker to SideBar Tree of maptypes and nodes
function addPlaceMarkNode(overlay, cluster, cmIndex) {
	try { 
		overlay.name = overlay.getTitle();	// Hack
		
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), Placemark (%s)", moduleName, "adding a Placemark to the Tree", overlay.name);	
		var dtnodes = $("#OverlayTree").dynatree("getSelectedNodes");	
		
		// Search list of Placemarks for "beforeNode"
		var beforeNode;
		dtnodes[0].visit( function(dtnode){
			if (dtnode.data.title > overlay.name) {
				if (!beforeNode) {
					beforeNode = dtnode;
				}
				return false;	// Doesn't seem to stop the recursive loop
			}
		 });
		
		// Call the DynaTreeNode.addChild() member function and pass options for the new "Placemark" node
		var childNode = dtnodes[0].addChild({
			title: overlay.name,
			//tooltip: "tootip = " + overlay.name,
			isFolder: false,
			hideCheckbox: true, 

			// Custom data
			placemark: overlay,
			cluster: cluster,
			cmIndex: cmIndex
		}, beforeNode );	
		overlay.Known = true;
		dtnodes[0].expand(true);

	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "onSelect", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	}

}

// Enhance gmarker infoWindow
function enhanceInfoWindow(overlay) {
	try { 
		overlay.name = overlay.getTitle();	// Hack

sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), Placemark (%s)", moduleName, "enancing InfoWindow", overlay.name);	
		var dtnodes = $("#OverlayTree").dynatree("getSelectedNodes");	
		
		// Create the tabbed balloon, by combining the kml description and the kmlExtension data (html description).
		var tabs = [];
		tabs.push (new GInfoWindowTab("Main", "<h1>" + overlay.name + "</h1>" + overlay.description));
		var htmlData = objMap.rootNode.data.currentChild.data.overlayHtml;	// This html text has already been parsed into a JQuery object
		if (htmlData) {
			var selector = "." + overlay.name;									// Match .classname with overlay name
			var html = $(selector, htmlData);	// Select named division  -- why doesn't this work?  Work-around: Added another magic <div> wrapper
			var html2 = '<script>try { sjhs.consoleTrace.log("LOG", "trying..."); $("a.myPlayer").flowplayer("flowplayer/flowplayer-3.1.5.swf"); sjhs.consoleTrace.log("LOG", "Player should be activated"); $f("*").each(function() { sjhs.consoleTrace.log("LOG", this.getVersion()); });} catch(exception) { } </script>'	;				
			if (html.length) {
				tabs.push (new GInfoWindowTab("Stories", "<h1>" + overlay.name + "</h1>" + $(html).html() + html2));	// code to install and activate Flowplayer
				sjhs.consoleTrace.log("LOG", "Adding an InfoWindowTab for (%s)", overlay.name);
			}
		}
		overlay.bindInfoWindowTabs(tabs);

	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "onSelect", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	}
}
// Load Kml, return handle to markerClusterer
function loadKml(dtnode, urlKml) {
	try {
		
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), dtnode (%s) url (%s)", moduleName, "loadKml", dtnode.data.title, urlKml);	

		// use an empty addmarker function because we want to let ClusterMarker do the actual adding
		var geoXml = new EGeoXml("geoXml", objMap.GMap2, urlKml, {iwwidth:450
			, iwoptions:{autoScroll:true}, addmarker:function(){}}
			);

		// When kml parsing completed...
		// == listen for the parsing to finish, then load the array into the ClusterMarker ==
		hEventListener = GEvent.addListener(geoXml, "parsed", function() {

			try {
				GEvent.removeListener(hEventListener);		// stop listening for "parsed" event
	/*	
				// Use MarkerClusterer
				var markerCluster = new MarkerClusterer(objMap.GMap2, geoXml.gmarkers, {gridSize:100, maxZoom:15});
				markerCluster.clearMarkers();
				markerCluster.addMarkers(geoXml.gmarkers);
	*/		  
				// Use ClusterMarker
				var markerCluster = new ClusterMarker(objMap.GMap2, { markers:geoXml.gmarkers });
				markerCluster.refresh(true);
			  
			  // PHB Now add gMarkers to the sidebar, enhance balloon content
				for (var i=0; i<geoXml.gmarkers.length; i++) {
					addPlaceMarkNode(geoXml.gmarkers[i], markerCluster, i);
					// enhanceInfoWindow(geoXml.gmarkers[i]);
				}
				rootNode.data.currentChild.data.overlayKml.push(markerCluster);	// save handles to markerClusterer
				
				// If all KML files for this mapType have been loaded, then update the SideBar and flyTo
				if (dtnode.data.overlayKml.length == dtnode.data.urlKml.length) {
					sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), kml (%s)", "SJGMap.js", "all kml processed", urlKml);
					// Expand child node
					dtnode.expand(true);
					dtnode.focus();
					
					// flyTo		
					if ((sjhs.bFlyTo) && (sjhs.urlVariables.lat) && (sjhs.urlVariables.long) && (sjhs.urlVariables.zoomlevel)) {
					//	objMap.GMap2.zoomIn(new GLatLng(sjhs.urlVariables.lat, sjhs.urlVariables.long), true, true);
					//	markerCluster.refresh(true);
					}
					//sjhs.bFlyTo = false;
				}
			}
			catch (exception) {
				sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "loadKml-parsed", 
					exception.name, exception.message, exception.lineNumber, exception.fileName);
			} finally {
			}
				  
				
		});
		
		geoXml.parse();

		}
	catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "loadKml", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	} finally {
	}
}

// When the container is ready...
function mapLoad() {
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s)", moduleName, "Loading the map");	

		if (GBrowserIsCompatible()) {
			objMap.GMap2 = new GMap2(document.getElementById("map3d"), {mapTypes:[]});
			objMap.GMap2.addControl(new GLargeMapControl());
			objMap.GMap2.addControl(new GScaleControl());  
			objMap.GMap2.enableScrollWheelZoom();
			objMap.GMap2.enableDoubleClickZoom();
			objMap.GMap2.enableContinuousZoom();
		} else {
			// tbd - $("#map3d").html('Your browser does not support Google Maps API');
			sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s):  Browser not supported by GMaps", moduleName, "Loading the map");
			return;
		}
		
		sjhs.bFlyTo = (sjhs.urlVariables.maptype) ? true : false;
		
		// Build the tree of maps.  Select the default map.
		sjhs.overlayTree = $("#OverlayTree").dynatree({
			checkbox: true,
			clickFolderMode: 2,
			// Override class name for checkbox icon:
			classNames: {checkbox: "ui-dynatree-radio"}, 
			selectMode: 1,
			fx: { height: "toggle", duration: 600 },
			autoFocus: true, // Set focus to first child, when expanding or lazy-loading.
			
			// Custom data: current selected child 
			currentChild: null,
			
			//Handlers
			onClick: function(dtnode) {
				if ( 'placemark' in dtnode.data ) {
					// placemarkClick(dtnode.data.placemark);
					clusterMarkerClick(dtnode.data.cluster, dtnode.data.cmIndex);
					sjhs.consoleTrace.log("LOG", "Map3d: placemarkClick: %s", dtnode.data.title);
					return false;
				} else if ( 'tour' in dtnode.data ) {
					tourClick(dtnode.data.tour);
					sjhs.consoleTrace.log("LOG", "Map3d: tourClick: %s", dtnode.data.title);
					return false;
				} else {
					return;
				}
			},
	
			onDblClick: function(dtnode) {
				if ( 'placemark' in dtnode.data ) {
					sjhs.consoleTrace.log("LOG", "Map3d: onDblClick: %s", dtnode.data.title);
					// if GM
					objMap.GMap2.zoomIn(dtnode.data.placemark.getLatLng(), true, true);
					/* if GE
					ge.getOptions().setFlyToSpeed(1.0);
					gex.util.flyToObject(dtnode.data.placemark, { defaultRange:4000 } );
					*/
					return false;
				}
			},
			
			onKeydown: function(dtnode, event) {
				switch (event.which) {
					case 13:	// <enter>
						if (dtnode.data.isFolder) {
							$("#OverlayTree").dynatree("getTree").selectKey(dtnode.data.key);
							return false;
						};
				}
			},
			
			// Do not allow user to de-select radio button
			onQuerySelect: function(flag, dtnode) {
				if ((dtnode.data.isFolder) && (!flag)) {
					return false;
				}
			},

			// MapOverlay selected (radioBox is checked)
			onSelect: function(flag, dtnode) {
				try {
					sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), flag (%s), dtnode.data.title (%s)", moduleName, "onSelect", flag, dtnode.data.title);	

					if (flag) {
						rootNode = $("#OverlayTree").dynatree("getRoot");
						
						// if node currently selected, then de-select node
						if (rootNode.data.currentChild) {

							// Remove map overlays
							objMap.GMap2.clearOverlays();

							prevcurKmlChild = rootNode.data.currentChild;
							while (prevcurKmlChild.data.overlayKml.length) {
								overlayKml = prevcurKmlChild.data.overlayKml.pop();
								if (overlayKml) {
									overlayKml.removeMarkers();
									overlayKml._removeClusterMarkers();
								}
							}
							prevcurKmlChild.removeChildren();
						}
						
						// Select node.  
						rootNode.data.currentChild = dtnode;

						// update map title
						$("#mapContainer .n").html("<em>Selected map</em>:  " + dtnode.data.tooltip);

						// Set the mapType now
						// Url variables, map switching and interception placemarks
						if (!objMap.GMap2.isLoaded()) {
							if (!sjhs.bFlyTo) {
								objMap.GMap2.setCenter(new GLatLng(18.337727, -64.740383), (12), dtnode.data.mapType);
							} else {
								var t = {};
								t.lat = (sjhs.urlVariables.lat) ? (sjhs.urlVariables.lat) : (18.337727);
								t.long = (sjhs.urlVariables.long) ? (sjhs.urlVariables.long) : (-64.740383);
								t.zl = (sjhs.urlVariables.zoomlevel) ? (sjhs.urlVariables.zoomlevel) : (12);
								
								objMap.GMap2.setCenter(new GLatLng(t.lat, t.long), parseInt(t.zl,10), dtnode.data.mapType);
								sjhs.bFlyTo = false;
							}
//							objMap.GMap2.addControl(new GOverviewMapControl());
						} else {
							objMap.GMap2.setMapType(dtnode.data.mapType);
						}

						// load kml-extension data
						asyncLoadHtml( dtnode, htmlpath + dtnode.data.urlHtml + "?" + Math.random() );
						
						// load kml data
						rootNode.data.currentChild.data.overlayKml = [];
						
						if (dtnode.data.urlKml instanceof Array) {
							for (var ai=0;ai < dtnode.data.urlKml.length; ai++){
								//loadKml( dtnode, kmlpath + dtnode.data.urlKml[ai] + "?" + Math.random());
								loadKml( dtnode, kmlpath + dtnode.data.urlKml[ai]);
							}
						}

					} else {
						sjhs.consoleTrace.log("LOG", "Map3D: Unexpected node collapse event");
						// Our radio box rules:  If the set of maps types is not null, then one must be selected.
						// Thus we do not allow the user to "deselect" this map-type.
						dtnode.select();
					}
				} catch (exception) {
					sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "onSelect", 
						exception.name, exception.message, exception.lineNumber, exception.fileName);
				}
			},
			
			// Process child nodes, adding mapTypes to the tree
			onPostInit: function (isReloading, isError) {
				try {
					sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), isReloading (%s), isError (%s)", moduleName, "onPostInit", isReloading, isError);	
					if (!isError) {
						
						// Process body of maptype children, adding mapTypes to GM
						objMap.rootNode = this.getRoot();
						for (var i=0; i<objMap.rootNode.childList.length; i++) {
							dtnode = objMap.rootNode.childList[i];
							dtnode.data.addMapType(dtnode);	
							sjhs.consoleTrace.log("LOG", "dtnode (%s)", dtnode.data.title);
						}
						
						// Process query parms.
						// if "explorer=1" then create mouse-tracking display
						// if "map type and lat-long & zoom specified, then set center
						// Else use default mapType
						if (sjhs.bFlyTo) {
							$("#OverlayTree").dynatree("getTree").selectKey(sjhs.urlVariables.maptype);
						} else {
							$("#OverlayTree").dynatree("getTree").selectKey("Aerial1947");	// Select default map type for GE
						}
						
						// If Explorer, then reveal the lat/long of the mouse cursor
						if (sjhs.urlVariables.explorer == "1") {
							// Add Mousemove event listener -> Display Latitude/Longitude of cursor
							GEvent.addListener(objMap.GMap2, "mousemove", function(point){
								var zoomLevel = objMap.GMap2.getZoom();
								var latLngStr6 = point.y.toFixed(6) + ', ' + point.x.toFixed(6);
								$("#mapCursor").text( latLngStr6 + " " + zoomLevel );
							});
							
							$("#mapCursorDiv").removeClass("NotSelected");
						}
					}
				} catch (exception) {
					sjhs.consoleTrace.log("ERROR", "Exception:      Module (%s), Procedure (%s), exception (%s)", moduleName, "onPostInit", 
						exception.name, exception.message, exception.lineNumber, exception.fileName);
				}
			},
			
			debugLevel: 1, // 0:quiet, 1:normal, 2:debug
	
			// Maps of St John in ascending time order:  tbd-add Oxholm 1780, USC+GS 1934
			// Children with additional custom attributes: addMapType, urlKml, overlayKml, urlHtml(kmlExtension data)
			//	Note:  Within KML url replace "space char" with %20
			children: [
//				  { title: 'Oxholm 1780', key: 'Oxholm1780', isFolder: true, tooltip: 'Oxholm 1780 map with the estates and their tax records'
//				  	, addMapType: addMapType_Oxholm1780,  urlKml: 'STJ%201800%20Placemarks.kml', overlayKml : null  }
				 { title: 'Oxholm 1800', key: 'Oxholm1800', isFolder: true, tooltip: 'Oxholm Map of 1800 with Taxable Estate markers'
				  	, addMapType: addMapType_Oxholm1800,  urlKml: ['STJ%201800%20Placemarks,%20x.03.kml'], overlayKml : []  }
				, { title: 'USC&amp;GS 1934', key: 'USCGS1934', isFolder: true, tooltip: 'US Coast &amp; Geodetic Survey Map of 1934 with Place-Names of 1840s-1940s'
					, addMapType: addMapType_USCGS1934, urlKml: ['STJ Place-names, x.03.kml'], overlayKml : []  }
				, { title: 'Aerial photo 1947', key: 'Aerial1947', isFolder: true
					, tooltip: '1947 Aerial photo mosiac, assembled by William Stelzer, with PlaceNames of 1840s-1940s'
					, addMapType: addMapType_Aerial1947, urlKml: ['STJ Place-names, x.03.kml'], urlHtml: 'Placemarks.htm', overlayKml : []  }
				, { title: 'Topographic', isFolder: true, tooltip: 'Topographic Map of 2007 with Roads and Trails'
					, addMapType: addMapType_Topo,  urlKml: null, overlayKml : []  }
				, { title: 'Satellite', key: 'Satellite', isFolder: true, tooltip: 'Satellite images of St. John'
					,  addMapType: addMapType_Satellite, urlKml: null, overlayKml : [] }
				, { title: 'Earth', isFolder: true, tooltip: 'Earth images of St. John'
					, addMapType: addMapType_Earth,  urlKml: null, overlayKml : []  }
				]
		});
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Exception:	Module (%s), Procedure (%s), exception (%s)", moduleName, "loading the map", 
			exception.name, exception.message, exception.lineNumber, exception.fileName);
	}

}

// When document is ready...
$(document).ready(function () {
	try {
		var tl = (typeof sjhs.urlVariables.trace != "undefined") ? parseInt(sjhs.urlVariables.trace) : WARNING;	// ?trace=0
		sjhs.consoleTrace = new consoleTrace(tl);	// Reporting severity threshold filter:  0=log, 1=info, 2=warning, 3=error
		sjhs.consoleTrace.log("LOG", "$(document).ready");
		
		// Initialize menu
		var MainMenuBar = new Spry.Widget.MenuBar("MainMenuBar", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});

		// Write footer information
		if (document.lastModified) {		// Not supported by Safari 3.2
			$("#LastModified").html("Page last modified " + document.lastModified);
		}

		// Build the container for the Google map division and the dynaTree division
		$("#mapContainer").buildContainers({ 
			containment:"document"
			, elementsPath:"Includes/mb.containerPlus.2.4.8/elements/"
			, onResize:function(container){
				switch (this.resizeState++) {
					case 0:
						// if GM
						mapLoad(); 
						
						/* if GE
						google.earth.createInstance('map3d', initCallback, failureCallback);
						*/
						break;
					default:
						break;
				}
			}
			, resizeState: 0
			, onClose:function(o){}
			, onCollapse:function(o){gmapResize();}
			, onIconize:function(o){gmapResize();}
			, onLoad:function(o){
				// If iconized, then restore												 
				if ($("#mapContainer").mb_getState("iconized")) {
					$("#mapContainer").mb_iconize(); 
				}
				window.setTimeout ( function() {
					// Re-position mapContainer
					$("#mapContainer").mb_setPosition(147, 10);
					
					window.setTimeout ( function() {
						// Enlarge mapContainerWrapper division
						var vpWidth = $(window).width();
						var vpHeight = $(window).height();
						
						var h = vpHeight - parseInt($("#header").height()) - parseInt($("#footer").height());
						$("#mapContainerWrapper").height(h - 45);
		
						var w = vpWidth - 40;
						var h = vpHeight - parseInt($("#header").height()) - parseInt($("#footer").height()) -45;

						// Resize mapContainer	
						// onResize - load google earth plugin
						$('#mapContainer').mb_resizeTo(h, w, true);
					}, 0.5*1000);
				}, 2*1000);
			} 
		}); 

   } catch (exception) {
	   sjhs.consoleTrace.log("ERROR", "Exception:	Module (%s), Procedure (%s), [%s - %s, lineNumber (%d) fileName (%s)]"
			, moduleName, "initCallback", exception.name, exception.message, exception.lineNumber, exception.fileName);
   }
 });

// Release memory
$(window).unload(GUnload);

// end of maps.js
