/**********************************************************************
 * HH400 Google Maps API Project
 * @File: hh400.maps.js
 * The base GMaps Script for the HH400 Map
 * Sets up the initial map; also handles the 3D transition via GE Plugin
 * Sets up several JS arrays that are used in conjunction with
 * hh400.map.helper.js and hh400.map.utilities.js
 * Version 1.0 | 05-04-2009
 * Developed by Cartosoft, LLC
 * http://www.cartosoft.com | info@cartosoft.com
 * Copyright 2009 Google, Inc. | http://www.google.com
**********************************************************************/

if (GBrowserIsCompatible()) {

//Set up some global variables
var fullscreen = 0;

var map; //Main map
var geocoder; //Google Geocoder
var sidebar_status = 'max'; //Initial sidebar status; it is maximized
var ini_point; //Initial map center
var ov_control = new GOverviewMapControl(); //Instantiate the Overview control outside of the loadmap function
var ini_window; //Global variable used later to determine initial map window state
var activeLayer; //Global variable used in various helper functions for a current layer
var activeOverlay; //Global variable used in various helper functions for a current historical map overlay (if any)

var svOverlay; //Street view overlay
var svClient; //Street view client
var lastMarkerLocation; //Last marker location; used by pre-canned street view functions for panorama display
var panorama; //Street View Panorama
var mapT; //Global vairable accessed for street view related functions
var streetMarker; //Street View Marker (yellow dude)
var streetMarkerEnd; //Global variable used to store last marker event listener
var streetMarkerClick; //Global variable used to determine last click event listener
var streetViewZoom; //Global variable used for street view zoom event listener
var streetViewChange; //Global variable used for street view change event listener
var sv_available = false; //Global variable used to store whether Street View is available for an extent

var ini_opacity = new Array(); //Global array for historical maps opacity settings

var polylineEncoder; //Global variable used later to instantiate PolylineEncoder Class

//The following global variables are used to keep track of clustered points for each theme
var illustrations_cluster;
var voyages_cluster = new Array();
var events_cluster;
var origins_cluster;
var water_cluster;
var sel_cluster;
var sel_cluster_marker;
var idx_cluster;
var cluster_bnds;

//Global array added to store IDs for markers that coincide in the same place; used to generate links list
var multiple_links_ids = new Array(); 

var overlays_tracker = 0; //Counter used to keep track of how many layers are currently visible
//Global variable used to keep track of last overlay that was added (*stores a string, not the overlay)
var mst_overlay;

var ge; //Global variable used to instantiate Google Earth (GE) Plugin
var sel_collada = new Array(); //Selected Collada/KML model to be displayed in GE Plugin
var colladas = new Array(); //Keep track of models that have been added; don't want to add the same one twice
var ge_buildings = 0; //Global var to keep track of building visibility in Google

var _eem_; //Shhhh...it's a secret!
var _eem_small;
//Global variable used by helper/utility functions to keep track of IE (for some browser-specific tweaks)
var ie_check; 

	function loadmap() {
		//Set up the map (make background same blue as the water)
		map = new GMap2(document.getElementById('map'), {backgroundColor:'#99b3cc'});
		
		//Set a listener to hide loading div and display intro div once map is ready
		//Prevents premature clicks and JS errors if map has not loaded
		GEvent.addListener(map, 'load', function() {
			$('ini-loading-div').toggle();
			$('intro-div').toggle();
		});
		
		//Instantiate the Street View control
		svClient = new GStreetviewClient();
		
		//Hack for IE6 and under; If NOT IE6, then use the "new" map controls
		//otherwise load the other controls
		//This is related to a bug with the "new" Google Maps Control and the GE Plugin
		var b_check = detectIeSix();
		if (!b_check) {
			map.setUIToDefault();
		}
		else {
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());
		}
		
		//Enable Google Earth Plugin
		map.addMapType(G_SATELLITE_3D_MAP);
		
		//Add the overview control that was instantiated outside of the function
		map.addControl(ov_control);
		ov_control.hide(true);
		
		//Set the map center and zoom
		ini_point = new GLatLng(40.7043266,-74.0142059);
		map.setCenter (ini_point, 3);
		
		//Add custom control for Street View
		if (document.getElementById("streetview-control")) {
			var addControl = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(68,20));
			document.getElementById("streetview-control").style.display="block";
			var st_control = document.getElementById("streetview-control");
			addControl.apply(st_control);
			map.getContainer().appendChild(st_control);
			GEvent.addDomListener(st_control, "click", function() {
				if (!svOverlay) { 
					svOverlay = new GStreetviewOverlay();
					map.addOverlay(svOverlay);
					st_control.innerHTML = '<img src="images/library/icons/icon-street-view-oval-on.png" alt="Street View" align="absmiddle" />';
					activateStreetView();
				}
				else {
					if (svOverlay.isHidden()) {
						svOverlay.show();
						st_control.innerHTML = '<img src="images/library/icons/icon-street-view-oval-on.png" alt="Street View" align="absmiddle" />';
						activateStreetView();
					}
					else {
						svOverlay.hide();
						st_control.innerHTML = '<img src="images/library/icons/icon-street-view-oval.png" alt="Street View" align="absmiddle" />';
						deActivateStreetView();
					}
				}
			});
		}
		
		//Add Other Non-Google Map Custom Controls
		addCustomControls();
		
		//Show the Initial Map Overlay (Vingboons North/South America)
		toggleMapLink(8,0);
		
		//Hmmm....wonder what this does?
		_ee_();
		
		//When toggling to GE Plugin, all controls are hidden
		//This event listener restores the controls (if needed) when map is changed back from GE
		GEvent.addListener(map, 'maptypechanged', function () {
		
			var mtype = map.getCurrentMapType() ;
			
			if (mtype != G_SATELLITE_3D_MAP) {
				$('streetview-control').setStyle({display:'block'});
				$('shortcuts-control').setStyle({display:'block'});
				$('topten-control').setStyle({display:'block'});
				$('ge-list-wrapper').setStyle({display:'none'});
				$('ge-list-toggle').setStyle({display:'none'});
				$('sidebar-content').setStyle({display:'block'});
			}
			else {
				_eem_.hide();
				_eem_small.hide();
				
				chkWindow();
			
				if ($('ge-list-wrapper').empty()) {
					getGeList();
					$('ge-list-wrapper').setStyle({display:'block'});
				}
				else {
					$('ge-list-wrapper').setStyle({display:'block'});
					$('sidebar-content').setStyle({display:'none'});
				}
				
			}
		
		});

	}
	
	
	/***
	Toggle GE Plugin and show a specific 3D model
	***/
	function toggleGE(collada_url, lat, lng) {
		sel_collada[0] = collada_url;
		sel_collada[1] = lat;
		sel_collada[2] = lng;
		
		map.closeInfoWindow();
		
		var mtype = map.getCurrentMapType() ;
			
		if (mtype != G_SATELLITE_3D_MAP) {
			map.setMapType(G_SATELLITE_3D_MAP);
		}
		
		map.getEarthInstance(getEarthInstanceCB);
	}
	
	var _lat, _lng;
	
	/***
	Instantiate Google Earth (via callback from previous function)
	and display 'base' models as well as the selected model
	***/
	function getEarthInstanceCB(object) {
	
		$('ge-status-div').setStyle({display:'block'});
		setTimeout(function(){$('ge-status-div').setStyle({display:'none'})}, 6000);
		
		//Work through some global variables
		collada_model = sel_collada[0];
		lat = sel_collada[1];
		lng = sel_collada[2];
		
		_lat = lat;
		_lng = lng;
		
		//Set up the GE Plugin
		if (!ge) {
			ge = object;
			ge.getOptions().setStatusBarVisibility(true);
			ge.getOptions().setScaleLegendVisibility(true);
			ge.getOptions().setFlyToSpeed(1);
			//Hide the buildings layer, as we are showing some of our own
			ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, false);
		}
		
		if (ge_buildings == 1) {
			ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
		}
		
		//Sanity check: if the 3D model has not yet been added...
		if (!colladas[collada_model]) {
		
			//Add the model to the array...
			colladas[collada_model] = collada_model;
			
			//And add a network link
			var networkLink = ge.createNetworkLink("");
			networkLink.setFlyToView(true); 
			
			// create a Link object
			var link = ge.createLink("");
			link.setHref(collada_model);
			
			// attach the Link to the NetworkLink
			networkLink.setLink(link); 
			
			// add the NetworkLink feature to Earth
			ge.getFeatures().appendChild(networkLink);
			
		}
		else if (colladas[collada_model]) {
			var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
			lookAt.setLatitude(lat+0.0003);
			lookAt.setLongitude(lng-0.0002);
			lookAt.setRange(110);
			lookAt.setTilt(85);
			lookAt.setAltitude(0);
			lookAt.setHeading(27);
			ge.getView().setAbstractView(lookAt);
		}
		
	}
	
	/***
	Function adds non-Google Maps specific controls
	***/
	function addCustomControls() {
		//The shortcuts control
		if (document.getElementById("shortcuts-control")) {
			function shortCutsControl() {}
		
			shortCutsControl.prototype = new GControl();
			shortCutsControl.prototype.initialize = function(map) {
				var addControl = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,28));
				document.getElementById("shortcuts-control").style.display="block";
				var st_control = document.getElementById("shortcuts-control");
				addControl.apply(st_control);
				map.getContainer().appendChild(st_control);
				return st_control;
			}
			map.addControl(new shortCutsControl());
		}
		
		//The Top Ten (now it's Top Five) control
		if (document.getElementById("topten-control")) {
			function topTenControl() {}
			
			topTenControl.prototype = new GControl();
			topTenControl.prototype.initialize = function(map) {
				var addControl = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(85,28));
				document.getElementById("topten-control").style.display="block";
				var st_control = document.getElementById("topten-control");
				addControl.apply(st_control);
				map.getContainer().appendChild(st_control);
				return st_control;
			}
			map.addControl(new topTenControl());
		}
	}
	
	/***
	Helper function closes the initial window if its still visible
	Called whenever a new theme is toggled on
	***/
	function chkWindow() {
		if (ini_window) {
			GEvent.removeListener(ini_maphelp);
			ini_window = false;
		}
		map.closeInfoWindow();
	}
	
	/***
	This function does not do anything!
	Or does it???
	***/
	var _ee_counter = 0;
	function _ee_() {
		var _eei_ = new GIcon();
			_eei_.image = 'images/library/misc/_ee_.png';
			_eei_.iconSize = new GSize(247,66);
			_eei_.iconAnchor = new GPoint(123,33);
			
		var _eei_small = new GIcon();
			_eei_small.image = 'images/library/misc/_ee_small.png';
			_eei_small.iconSize = new GSize(101,27);
			_eei_small.iconAnchor = new GPoint(50,13);
		
		var _eem_ll = new GLatLng(69.449842,43.945313);
		_eem_ = new GMarker(_eem_ll, {icon: _eei_});
		map.addOverlay(_eem_);
		_eem_.hide();
		
		_eem_small = new GMarker(_eem_ll, {icon: _eei_small});
		map.addOverlay(_eem_small);
		_eem_small.hide();
		
		GEvent.addListener(_eem_,'mouseover', function() {
			_eem_.setImage('images/library/misc/_ee_over.png');
			Sound.play('static/_ee_.mp3');
		});
		GEvent.addListener(_eem_,'mouseout', function() {
			_eem_.setImage('images/library/misc/_ee_.png');
		});
		
		GEvent.addListener(map,'zoomend', function() {
			var map_zoom = map.getZoom();
			if (map_zoom > 6) {
				_eem_.show();
			}
			else {
				_eem_.hide();
				if (_ee_counter < 7) {
					var map_bounds = map.getBounds();
				
					if (map_bounds.containsLatLng(_eem_small.getLatLng())) {
						_eem_small.show();
						setTimeout(function(){_eem_small.hide()}, 750);
						_ee_counter++;
					}
				}
			}
		});
	}


} //end GBrowserIsCompatible
else {
	alert("Sorry.  It appears that your browser is not compatible with the Google Maps API");
}