// Javascript
//	SJGEarth.js
//  29-Apr-2010
//

// Global variables
var ge;
var gex;
var kmlpath = 'http://www.stjohnhistoricalsociety.org/KML/';
var htmlpath = 'kmlExtension/';
var moduleName = 'SJGEarth.js';

function gmapResize(container) {
	;
}

function openHtmlBalloon(kmlObject) {
	var balloon = ge.createHtmlStringBalloon('');
	balloon.setFeature(kmlObject);
	balloon.setMaxWidth(550);
	balloon.setMinWidth(550);
	balloon.setMaxHeight(400);
	
/*
For x.02, skip kml - extension stuff...

	// Process KML description, creating/cloning html balloon
	// If "a.ajaxBalloon" defined
	// then create a Html balloon which 
	//		displays a "loading...gif", loads the Ajax content, and on completion, initializes the flow player...
	// else
	//	just clone the static kml description
	t0 = '<div>' + kmlObject.getDescription() + '</div>';
	var htmUrl = $("a.ajaxBalloon", $(t0)).attr("href");
	if (htmUrl && htmUrl.length) {
		try {
			var strHtml = '<div id="balloonWindow" style="min-width:500px; min-height:400px;"><img src="CSS/flowplayer/assets/loading.gif" alt="loading..." onload="$(\'#balloonWindow\').load(\'HTMLURL\', function (responseText, textStatus, XMLHttpRequest) { $(\'#tabs\').tabs(); $(\'a.myPlayer\').flowplayer(\'flowplayer/flowplayer-3.1.5.swf\'); });" /></div>';
			var re = /HTMLURL/;
			strHtml = strHtml.replace(re, htmUrl);
			
			balloon.setContentString(strHtml);
		} catch (exception) {
			sjhs.console.Trace.log("ERROR", 'Exception: ', exception);
		}
	} else {

		// Fix <a target="_blank">
		$(t0).find("a.href_more").each (function () { this.attr(target, "_blank"); });
		balloon.setContentString(kmlObject.getDescription());
	}
*/

	balloon.setContentString(kmlObject.getDescription());
	// open the html balloon
	ge.setBalloon(balloon);
}

function placemarkClick(pm) {
	openHtmlBalloon(pm);
	
	/*
	 var balloon = ge.createFeatureBalloon('');
	  balloon.setMaxWidth(500);
	  balloon.setFeature(pm);
	  ge.setBalloon(balloon);
	  */
}

function tourClick(pm) {
	ge.getTourPlayer().setTour(pm);
}

function loadKml(dtnode, urlKml) {
	
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), kml (%s)", moduleName, "loadKml", urlKml);
		google.earth.fetchKml(ge, urlKml, function(kmlObject) {
												   
			try {												   
				// Save current Kml child dtnode (for toggle)
				$("#OverlayTree").dynatree("getRoot").data.currentChild = dtnode;
				dtnode.data.domKml.push(kmlObject);
	
				if (!kmlObject) {
				  // wrap alerts in API callbacks and event handlers in a setTimeout to prevent deadlock in some browsers
				  setTimeout(function() {
					alert('Bad or null KML: ' + urlKml);
				  }, 0 );
				  return;
				}
				
				// Show the entire KML file in Google Earth plugin.
				ge.getFeatures().appendChild(kmlObject);
			
				// If all KML files for this mapType have been loaded, then update the SideBar and flyTo
				if (dtnode.data.domKml.length == dtnode.data.urlKml.length) {
					// Select "KmlPlacemarks" from Kmlobject, producing dynamic tree and sidebar
					sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s), kml (%s)", moduleName, "loadKml-gex.dom.walk", urlKml);
					gex.dom.walk({
						rootObject: ge,
						visitCallback: function() {
							var childNode;
								
							// Add a child to the dtnode
							if (this.getType() == "KmlPlacemark") {
							
								if ('getName' in this) {
									name = this.getName();
								} else {
									name = "Placemark 0";
								}
		
								var dtnodes = $("#OverlayTree").dynatree("getSelectedNodes");	
								
								// Search list of Placemarks for "beforeNode"
								var beforeNode=null;
								dtnodes[0].visit( function(dtnode){
									if (dtnode.data.title > 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
								childNode = dtnodes[0].addChild({
									title: name,
									// tooltip: "tootip = " + overlay.name,
									isFolder: false,
									hideCheckbox: true, 
						
									// Custom data
									placemark: this
								}, beforeNode );	
		
								// Enhance kml feature balloon
								google.earth.addEventListener(this, 'click', function(event) {
								   event.preventDefault();
								   openHtmlBalloon(event.getTarget());
								});
								
								sjhs.consoleTrace.log("LOG", "%s: Placemark: %s", moduleName, name);
							} else if (this.getType() == "KmlTour") {
								if ('getName' in this) {
									name = "(tour) " + this.getName();
								} else {
									name = "(tour) " + "Tour 0";
								}
								// Call the DynaTreeNode.addChild() member function and pass options for the new "Tour" node
								var dtnodes = $("#OverlayTree").dynatree("getSelectedNodes");	
								
								// Search list of Placemarks for "beforeNode"
								var beforeNode=null;
								dtnodes[0].visit( function(dtnode){
									if (dtnode.data.title > 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
								childNode = dtnodes[0].addChild({
									title: name,
									// tooltip: "tootip = " + overlay.name,
									isFolder: false,
									hideCheckbox: true, 
						
									// Custom data
									tour: this
								}, beforeNode );	
		
								sjhs.consoleTrace.log("LOG", "%s: Tour: %s", name);
							}
						}
					});
		
					// Expand child node?
					dtnode.expand(false);
					dtnode.focus();
					
					// fly to St John, VI
					setTimeout(function() {
						try {									  
							ge.getOptions().setFlyToSpeed(0.1);
							var la = ge.createLookAt('');
							la.set(18.35159564576041, -64.73474988356682,
								0, // altitude
								ge.ALTITUDE_RELATIVE_TO_GROUND,
								0, // heading
								0, // straight-down tilt
								20000 // range (inverse of zoom)
							);
							ge.getView().setAbstractView(la);
						
						} catch (exception) {
							sjhs.consoleTrace.log("ERROR", "Module (%s), Procedure (%s), error (%s)", moduleName, "loadKml-LookAt function", exception);
						}
					}, 5*1000);
				}
			} catch (exception) {
				sjhs.consoleTrace.log("ERROR", "Module (%s), Procedure (%s), error (%s)", moduleName, "loadKml-callback function", exception);
			}
			
		});
	} catch (exception) {
		sjhs.consoleTrace.log("ERROR", "Module (%s), Procedure (%s), error (%s)", moduleName, "loadKml", exception);
	}
 }	

	
    
function initCallback(instance) {
	try {
		sjhs.consoleTrace.log("LOG", "Module (%s), Procedure (%s)", moduleName, "initCallback");
		ge = instance;
		ge.getWindow().setVisibility(true);
	
		// add a navigation control
		ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
		
		// load Google Earth Extensions
		gex = new GEarthExtensions(ge);

		// 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);
					sjhs.consoleTrace.log("LOG", "%s: placemarkClick: %s", dtnode.data.title);
					return false;
				} else if ( 'tour' in dtnode.data ) {
					tourClick(dtnode.data.tour);
					sjhs.consoleTrace.log("LOG", "%s: tourClick: %s", dtnode.data.title);
					return false;
				} else {
					return;
				}
			},
	
			onDblClick: function(dtnode) {
				if ( 'placemark' in dtnode.data ) {
					sjhs.consoleTrace.log("LOG", "%s: 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;
				}
			},

			// When user selects a mapType... 
			onSelect: function(flag, dtnode) {
				sjhs.consoleTrace.log("LOG", "%s: Selected: %s", dtnode.data.title);
				if (dtnode.data.isFolder) {
					if (flag) {
						rootNode = $("#OverlayTree").dynatree("getRoot");
						if (rootNode.data.currentChild) {

							ge.setBalloon(null);
							
							prevcurKmlChild = rootNode.data.currentChild;
							while (prevcurKmlChild.data.domKml.length) {
								domKml = prevcurKmlChild.data.domKml.pop();
								if (domKml) {
									ge.getFeatures().removeChild(domKml);
								}
							}
							//prevcurKmlChild.data.domKml = null;
							prevcurKmlChild.removeChildren();
						}
						
						rootNode.data.currentChild = dtnode;
						// update map title
						$("#mapContainer .n").html("<em>Selected map</em>:  " + dtnode.data.tooltip);
						
						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("WARN", "%s: Unexpected node collapse event");
					}
				} else {
						sjhs.consoleTrace.log("LOG", "%s: Document selected: %s", dtnode.data.urlKml);
				}
			},
			
			// 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) {
						// Select default node
						$("#OverlayTree").dynatree("getTree").selectKey("USCGS1934");		// default map type for GE
						//$("#OverlayTree").dynatree("getTree").selectKey("Aerial1947");	// default map type for GM
					}
				} catch (exception) {
				   sjhs.consoleTrace.log("ERROR", "Exception:	Module (%s), Procedure (%s), [%s - %s, lineNumber (%d) fileName (%s)]"
						, moduleName, "onPostInit", exception.name, exception.message, exception.lineNumber, exception.fileName);
				}
			},
			
			debugLevel: 1, // 0:quiet, 1:normal, 2:debug
	
			// Children with additional custom attributes: urlKml, domKml
			children: [
				// { title: 'Oxholm 1780', isFolder: true, key: 'Oxholm1780', urlKml: '1780SO.kml', domKml: [] }, 
				{ title: 'Oxholm 1800', isFolder: true, key: 'Oxholm1800',  
					tooltip: 'Oxholm Map of 1800 with Taxable Estate markers', urlKml: ['1800SO.kml', 'STJ%201800%20Placemarks,%20x.03.kml'], domKml: [] }
				, { title: 'USC+GS 1934', isFolder: true, key: 'USCGS1934', 
					tooltip: 'US Coast &amp; Geodetic Survey Map of 1934 with Place-Names of 1840s-1940s', urlKml: ['1934SO.kml', 'STJ Place-names, x.03.kml'], domKml: [] }
				, { title: 'Aerial Photos 1947', isFolder: true, key: 'Aerial1947', 
					tooltip: '1947 Aerial photo mosiac, assembled by William Stelzer, with PlaceNames of 1840s-1940s', urlKml: ['1947SO.kml', 'STJ Place-names, x.03.kml'], domKml: [] }
				, { title: 'Topographic 2007', isFolder: true, key: 'Topo', 
					tooltip: 'Topographic Map of 2007 with Roads and Trails', urlKml: ['2007SO.kml'], domKml: [] }
				]
		});
		
   } 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);
   }
}
    
function failureCallback(errMsg) {
	 sjhs.consoleTrace.log("ERROR", "Module (%s), Procedure (%s), [%s]", moduleName, "failureCallback", errMsg);
}

// 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:
						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);
   }
 });
// end of SJGEarth.js
