// ------ Decide browser type and browser version
var isMac = (navigator.userAgent.indexOf("Mac") != -1);
var olOp = (navigator.userAgent.toLowerCase().indexOf('opera') > -1 && document.createTextNode);  // Opera 7
var olNs4 = (navigator.appName=='Netscape' && parseInt(navigator.appVersion) <= 4);
var olNs6 = (document.getElementById) ? true : false;
var olNsx = (navigator.appName == "Netscape");
var olKq = (olNs6 && /konqueror/i.test(navigator.userAgent));
var olIe4 = (document.all) ? true : false;
var olIe5 = false; 
var olIe55 = false; // Added additional variable to identify IE5.5+
var docRoot = 'document.body';

function EStyle(stemImage, stemSize, boxClass, boxOffset) {
	  this.stemImage = stemImage;
	  this.stemSize = stemSize;
	  this.boxClass = boxClass;
	  this.boxOffset = boxOffset;
	  this.fudge = 0;
}

var E_STYLE_1 = new EStyle(resPath+"/ewindow/stem1.png", new GSize(81,87),  "estyle1", new GPoint(-30,87-3));
var E_STYLE_2 = new EStyle(resPath+"/ewindow/stem2.png", new GSize(81,87),  "estyle2", new GPoint(-30,87-1));
var E_STYLE_3 = new EStyle(resPath+"/ewindow/stem3.png", new GSize(81,87),  "estyle3", new GPoint(-30,87-10));
var E_STYLE_4 = new EStyle(resPath+"/ewindow/stem3.png", new GSize(81,87),  "estyle4", new GPoint(-30,87-10));
var E_STYLE_5 = new EStyle(resPath+"/ewindow/stem1.png", new GSize(81,87),  "estyle5", new GPoint(-30,87-3));
var E_STYLE_6 = new EStyle(resPath+"/ewindow/stem6.png", new GSize(100,50), "estyle6", new GPoint(100-2,20));
var E_STYLE_7 = new EStyle(resPath+"/ewindow/stem7.png", new GSize(24,24),  "estyle2", new GPoint(-10,23));
var E_STYLE_8 = new EStyle(resPath+"/ewindow/stem7_light.png", new GSize(24,24),  "estyle2", new GPoint(-10,23));

function EWindow(map,estyle) {
	  // parameters
	  this.map=map;
	  this.estyle=estyle;
	  // internal variables
	  this.visible = false;
	  // browser - specific variables
	  this.ie = false;
	  var agent = navigator.userAgent.toLowerCase();
	  if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}
} 

EWindow.prototype = new GOverlay();

EWindow.prototype.initialize = function(map) {
	  var div1 = document.createElement("div");
	  div1.style.position = "absolute";
	  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div1);
	  var div2 = document.createElement("div");
	  div2.style.position = "absolute";
	  div2.style.width = this.estyle.stemSize.width+"px";
	  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div2);
	  this.div1 = div1;
	  this.div2 = div2;
}

EWindow.prototype.openOnMap = function(point, html, offset) {
	  this.offset = offset||new GPoint(0,0);
	  this.point = point;
	  this.div1.innerHTML = '<div class="' + this.estyle.boxClass + '"><nobr>' + html + '</nobr></div>';
	  if (this.ie && this.estyle.stemImage.toLowerCase().indexOf(".png")>-1) {
		var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.estyle.stemImage+"', sizingMethod='scale');";
		this.div2.innerHTML = '<div style="height:' +this.estyle.stemSize.height+ 'px; width:'+this.estyle.stemSize.width+'px; ' +loader+ '" ></div>';
	  } else {
		this.div2.innerHTML = '<img src="' + this.estyle.stemImage + '" width="' + this.estyle.stemSize.width +'" height="' + this.estyle.stemSize.height +'">';
	  }
	  var z = GOverlay.getZIndex(this.point.lat());
	  this.div1.style.zIndex = z;
	  this.div2.style.zIndex = z+1;
	  this.visible = true;
	  this.show();
	  this.redraw(true);
}
	
EWindow.prototype.openOnMarker = function(marker,html) {
	  var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
	  var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
	  this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
}
	
	
EWindow.prototype.redraw = function(force) {
	  if (!this.visible) {return;}
	  var p = this.map.fromLatLngToDivPixel(this.point);
	  this.div2.style.left   = (p.x + this.offset.x) + "px";
	  this.div2.style.bottom = (-p.y + this.offset.y -this.estyle.fudge) + "px";
	  this.div1.style.left   = (p.x + this.offset.x + this.estyle.boxOffset.x) + "px";
	  this.div1.style.bottom = (-p.y + this.offset.y + this.estyle.boxOffset.y) + "px";
}
	
EWindow.prototype.remove = function() {
	  this.div1.parentNode.removeChild(this.div1);
	  this.div2.parentNode.removeChild(this.div2);
	  this.visible = false;
}
	
EWindow.prototype.copy = function() {
	  return new EWindow(this.map, this.estyle);
}
	
EWindow.prototype.show = function() {
	  this.div1.style.display="";
	  this.div2.style.display="";
	  this.visible = true;
}
	
EWindow.prototype.hide = function() {
	  this.div1.style.display="none";
	  this.div2.style.display="none";
	  this.visible = false;
}
	
EWindow.prototype.isHidden = function() {
	  return !this.visible;
}
	
EWindow.prototype.supportsHide = function() {
	  return true;
}
	
// Create the marker and corresponding information window
function createInfoMarker(icon, ew, point, file, text, exifDate) {
		var marker = new GMarker(point, icon);
		var img = file;
		var thumb = "thumbs/"+file;
		var slide = file.substring(0, file.indexOf('.'));
		var style = '';
		if (file == "" && text != "") {
			style = ' style=\"background-color:#FFFFFF;border:1px solid black;float:left;\"';
		}
		var info = '<table border="0" cellpadding="0" cellspacing="0" class="gmap_infowindow"' + style + '>';
		if (text != "") {
			info = info + '<tr><td width="100%" nowrap>' + text + '</td></tr>';
		}
		if (file != "") {
			info += '<tr><td nowrap><img src="'+thumb+'" align="middle"></td></tr>';
		}
		info += '</table>';
	
		// ========== Open the EWindow instead of a Google Info Window ==========
		GEvent.addListener(marker, "mouseover", function() {
		  ew.openOnMarker(marker, info);
		});
	
		// ========== Close the EWindow if theres a map click ==========
		GEvent.addListener(marker, "mouseout", function() {
			ew.hide();
		});
		
		// ========== Open the EWindow instead of a Google Info Window ==========
		GEvent.addListener(marker, "click",
		function() {
			window.location = "slides/" + slide + ".html";
		});
	
		return marker;
}
	
	var markers = null;
	var bounds = new GLatLngBounds();
	var markerskeyIndex = new Array();
	var markersHashTable = new Object();
	var trackkeyIndex = new Array();
	var trackHashTable = new Object();
	var map = null;
	
	var ge;
	var ew;

function getEarthInstanceCB(object) {
	ge = object; // You can now manipulate ge using the full Google Earth API.
}


function load() {
	  if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(0, 0), 0);
		map.addMapType(G_PHYSICAL_MAP);

		map.addMapType(G_SATELLITE_3D_MAP);
		map.getEarthInstance(getEarthInstanceCB);

		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
	
		// Create our "tiny" marker icon
		var icon = new GIcon();
		icon.image = resPath+"/mymarker_red.png";
		icon.iconSize = new GSize(16, 28);
		icon.shadowSize = new GSize(16, 28);
		icon.iconAnchor = new GPoint(8, 28);
		icon.infoWindowAnchor = new GPoint(5, 1);
		
		var icon2 = new GIcon();
		icon2.image = resPath+"/clearpixel.png";
		icon2.iconSize = new GSize(1, 1);
		icon2.shadowSize = new GSize(1, 1);
		icon2.iconAnchor = new GPoint(1, 1);
		icon2.infoWindowAnchor = new GPoint(1, 1);
		
		var icon3 = new GIcon();
		icon3.image = resPath+"/marker-pushpin-yellow.png";
		icon3.iconSize = new GSize(32, 32);
		icon3.shadowSize = new GSize(59, 32);
		icon3.iconAnchor = new GPoint(10, 32);
		icon3.infoWindowAnchor = new GPoint(1, 1);
		
				// Create an EWindow
		ew = new EWindow(map, E_STYLE_8);      
		map.addOverlay(ew);
		
		GDownloadUrl("gmapMarkers.xml", function(data, responseCode) {
			var xml = GXml.parse(data);
			 markers = xml.documentElement.getElementsByTagName("marker");
	
			for (var i = 0; i < markers.length; i++) {
				var file = markers[i].getAttribute("file");
				var text = markers[i].getAttribute("text");
				var name = markers[i].getAttribute("name");
				var exifDate = markers[i].getAttribute("date");
				var displayDate = markers[i].getAttribute("dateDisplay");
				var showAsMarker = markers[i].getAttribute("marker");
				var showAsTrackPoint = markers[i].getAttribute("trackPoint");
				var showAsWayPoint = markers[i].getAttribute("wayPoint");

				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
									parseFloat(markers[i].getAttribute("lng")));

				bounds.extend(point);
			
				if (showAsMarker == "true") {
					if (file == "null") {
						var marker = createInfoMarker(icon3, ew, point, "", name, displayDate);
					} else {
						var marker = createInfoMarker(icon, ew, point, file, "", displayDate);
					}
					map.addOverlay(marker);
					markersHashTable[exifDate] = marker;
					markerskeyIndex.push(exifDate);
				}
				if (showAsTrackPoint == "true" || showAsTrackPoint == "start") {
					trackPoint = new Object();
					trackPoint.point = point;
					trackPoint.start = showAsTrackPoint;
					trackPoint.name = name;
					trackPoint.text = text;
					trackHashTable[exifDate] = trackPoint;
					trackkeyIndex.push(exifDate);
				}
			}
	
			map.setZoom(map.getBoundsZoomLevel(bounds));
			var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
			var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
			map.setCenter(new GLatLng(clat,clng));
	
			if (geoMaptype == "sat") {
				map.setMapType(G_SATELLITE_MAP);
			} else if (geoMaptype == "hyb") {
				map.setMapType(G_HYBRID_MAP);
			} else {
				map.setMapType(G_NORMAL_MAP);
			}
			
			var startmarker = (markersHashTable[ markerskeyIndex[0] ]);
			// startmarker.setImage(resPath+"/mymarker_yellow.png");
			var endmarker = (markersHashTable[ markerskeyIndex[markerskeyIndex.length - 1] ]);
			// endmarker.setImage(resPath+"/mymarker_green.png");
	
			if (showTrack == "images") {
				markerskeyIndex.sort();
				var i;
				var polyPoints = new Array();
				for (i in markerskeyIndex) {
					polyPoints.push((markersHashTable[ markerskeyIndex[i] ]).getPoint());
				}
				
				var polyline = new GPolyline(polyPoints, "#0099ff", 3, 1);
				map.addOverlay(polyline);
			} else if (showTrack == "gps") {
				// trackkeyIndex.sort();
				var i;
				var polyPoints = new Array();
				var firstPoint = true;
				trackNum = 1;

				for (i in trackkeyIndex) {
					if (!firstPoint && trackHashTable[ trackkeyIndex[i] ].start == "start") {
						trackNum++;
						var polyline = createPolyLine(ew, polyPoints, "#0099ff", 3, 1, trackInfo, "", marker);
						var polyPoints = new Array();
						map.addOverlay(polyline);
					}
					polyPoints.push((trackHashTable[ trackkeyIndex[i] ].point));
					firstPoint = false;
					if (trackHashTable[ trackkeyIndex[i] ].start == "start") {
						var trackInfo = "<b>" + trackHashTable[ trackkeyIndex[i] ].name + "</b><br>" + trackHashTable[ trackkeyIndex[i] ].text;
						var marker = createTextInfoMarker(icon2, ew, trackHashTable[ trackkeyIndex[i] ].point, "", "");
						map.addOverlay(marker);
						marker.hide();
					}
				}
				
				var polyline = createPolyLine(ew, polyPoints, "#0099ff", 3, 1, trackInfo, "", marker);
				map.addOverlay(polyline);
			}
			range = Math.abs(bounds.getNorthEast().lat() - bounds.getSouthWest().lat()) * 111;
			loadgeonames(clat, clng, range, 150);
		});
	  }
}	  

function loadSlideMap(fileName, geoMaptypeSlide) {
  if (GBrowserIsCompatible()) {
  	var info = "";
  	var lat, lng, elev;
  	var latStr, lngStr;
  	var UTMstring;
  	
	map = new GMap2(document.getElementById("slidemap"));
	map.setCenter(new GLatLng(0, 0), 0);
	map.addMapType(G_PHYSICAL_MAP);
	map.addControl(new GSmallZoomControl());
	map.addControl(new GMapTypeControl());

	// Create our "tiny" marker icon
	var icon = new GIcon();
	icon.image = resPath+"/mymarker_red.png";
	icon.iconSize = new GSize(16, 28);
	icon.shadowSize = new GSize(16, 28);
	icon.iconAnchor = new GPoint(8, 28);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	// Create an EWindow
	ew = new EWindow(map, E_STYLE_8);      
	map.addOverlay(ew);
	
	GDownloadUrl("../gmapMarkers.xml", 
	function(data, responseCode) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");

		for (var i = 0; i < markers.length; i++) {
			var file = markers[i].getAttribute("file");
			if (file == fileName) {
				
				lat = parseFloat(markers[i].getAttribute("lat"));
				lng = parseFloat(markers[i].getAttribute("lng"));
				if (lat > 0)	latStr = lat + " N";
				else		latStr = (lat * -1) + " S";
				if (lng > 0)	lngStr = lng + " E";
				else		lngStr = (lng * -1) + " W";
				
				elev = markers[i].getAttribute("altitude");
				
				UTMstring = cvLatLngToUTM(lat, lng); // gUTM.js			
				var point = new GLatLng(lat, lng);
				info =	"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"gmap_infowindow\" style=\"background-color:#FFFFFF;border:1px solid black;float:left;\">";
				info +=		"<tr><td colspan='2' nowrap align='center'><b>" + fileName + "</b></td></tr>";
				info +=		"<tr><td nowrap align='left'>UTM: </td><td nowrap align='left'> " + UTMstring + "</td></tr>";
				info +=		"<tr><td nowrap align='left'>lat: <br>lng:</td><td nowrap align='left'> " + latStr + "<br> " + lngStr + "</td></tr>";
				if (elev != 0)
				info +=		"<tr><td nowrap align='left'>elev: </td><td nowrap align='left'> " + elev + " metres</td></tr>";
				info +=		"<tr><td nowrap align='left'>taken:</td><td nowrap align='left'>" + markers[i].getAttribute("dateDisplay") + "</td></tr>";
				info +=		"</table>";
		
				var marker = createTextInfoMarker(icon, ew, point, info, "");
				map.addOverlay(marker);
				map.setZoom(13); // 16
				map.setCenter(point);

				break;
			}
		}
		if (geoMaptypeSlide == "sat") {
			map.setMapType(G_SATELLITE_MAP);
		} else if (geoMaptypeSlide == "hyb") {
			map.setMapType(G_HYBRID_MAP);
		} else {
			map.setMapType(G_NORMAL_MAP);
		}
		
	});
  }
}

function createTextInfoMarker(icon, ew, point, info, popupurl) {
		var marker = new GMarker(point, icon);

		if (info && info != "") {
			// ========== Open the EWindow instead of a Google Info Window ==========
			GEvent.addListener(marker, "mouseover", function() {
				ew.openOnMarker(marker, info);
			});

			// ========== Close the EWindow if theres a map click ==========
			GEvent.addListener(marker, "mouseout", function() {
				ew.hide();
			});
		}

		if (popupurl && popupurl!="") {
			// ========== Close the EWindow if theres a map click ==========
			GEvent.addListener(marker, "click", function() {
				window.open(popupurl);
			});
		}

		return marker;
}

function createPolyLine(ew, polyPoints, linecolor, lineweight, opacity, textinfo, popupurl, marker) {
	var pLine = new GPolyline(polyPoints, linecolor, lineweight, opacity);

	if (textinfo && textinfo != "") {
		textinfo =	"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"gmap_infowindow\" style=\"background-color:#FFFFFF;border:1px solid black;float:left;\">" +
		"<tr><td nowrap align='left'>" +
		textinfo +
		"</td></tr>"
		"</table>";

		// ========== Open the EWindow instead of a Google Info Window ==========
		GEvent.addListener(pLine, "mouseover", function() {
			pLine.setStrokeStyle({color: "#ed4400"});
			marker.show();
			ew.openOnMarker(marker, textinfo);
		});

		// ========== Close the EWindow if theres a map click ==========
		GEvent.addListener(pLine, "mouseout", function() {
			pLine.setStrokeStyle({color: "#0099ff"});
			marker.hide();
			ew.hide();
		});
	}

	// if (popupurl && popupurl!="") {
		// ========== Close the EWindow if theres a map click ==========
	//	GEvent.addListener(pLine, "click", function() {
	//		window.open(popupurl);
	//	});
	// }

	return pLine;
}

function loadgeonames(lat, lng, geonamesradius, maxResults) {
	var geonameswebservice = "findNearby"; // countryCode, countrySubdivision, findNearbyPostalCodes, findNearbyPlaceName, findNearbyStreets, findNearByWeather, findNearbyWikipedia, findNearestAddress, findNearestIntersection, findNearby, neighbourhood, srtm3, gtopo30, timezone
	var script = document.createElement('script');
	document.body.appendChild(script);
	script.src = 'http://ws.geonames.org/' + geonameswebservice + 'JSON?lat=' + lat + '&lng=' + lng + '&radius=' + geonamesradius + '&maxRows=' + maxResults + '&style=FULL&callback=loadJSON';
}

function loadllgeonames(fileName, radius, maxResults) {
	GDownloadUrl("../gmapMarkers.xml", 
	function(data, responseCode) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");

		for (var i = 0; i < markers.length; i++) {
			var file = markers[i].getAttribute("file");
			if (file == fileName) {
				loadgeonames(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), radius, maxResults);
				break;
			}
		}

		
	});
}

function loadJSON(result) {
	// Create our "tiny" marker icon
	var divOut = "";
	var info;
	var exturl;
	var UTMstring;
	var lat, lng;
	var latlng = new Object();
	var icon = new GIcon();
	icon.iconSize = new GSize(10, 17);
	icon.shadowSize = new GSize(10, 17);
	icon.iconAnchor = new GPoint(10, 17);
	icon.infoWindowAnchor = new GPoint(5, 1);
	if (result && result.geonames && result.geonames.length > 0) {
		for (var i = 0; i < result.geonames.length; i++) {
			icon.image = resPath+"/marker-" + result.geonames[i].fcl + "-10.png";
			lat = parseFloat(result.geonames[i].lat);
			lng = parseFloat(result.geonames[i].lng);
			latlng.y = lat;
			latlng.x = lng;
			UTMstring = cvLatLngToUTM(lat, lng); // gUTM.js		
			var point = new GLatLng(lat, lng);

			info =	"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"gmap_infowindow\" style=\"background-color:#FFFFFF;border:1px solid black;float:left;\">";
			info +=		"<tr><td colspan='2' nowrap align='center'><b>" + result.geonames[i].name + "</b></td></tr>";
			info +=		"<tr><td nowrap align='left'>UTM: </td><td nowrap align='left'> " + UTMstring + "</td></tr>";
			info +=		"<tr><td nowrap align='left'>lat: <br>lng:</td><td nowrap align='left'> " + lat + "<br> " + lng + "</td></tr>";
			if (parseFloat(result.geonames[i].elevation) > 0)
			info +=		"<tr><td nowrap align='left'>elev: </td><td nowrap align='left'> " + result.geonames[i].elevation + " m</td></tr>";
			info += 	"<tr><td nowrap align='left'>type: </td><td nowrap align='left'> " + result.geonames[i].fcodeName + "</td></tr>";
			info +=		"</table>";

			exturl = "http://www.geonames.org/" + result.geonames[i].geonameId;
			var marker = createTextInfoMarker(icon, ew, point, info, exturl);
			map.addOverlay(marker);

			divOut += info;
		}
		// writeHTMLtoDiv('geoOut', divOut);
		// writeHTMLtoDiv('geoOut', JSON.stringify(result).replace(/{/g, "<br><br>{").replace(/}/g, "}<br><br>"));
	}
}

function getAjaxRequest(url, divName) {
	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try	{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e)	{
			try
			{
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request)	{
		// alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = function() { alertContents(http_request, divName); };
	http_request.open('GET', url, true);
	http_request.send(null);
}

function alertContents(http_request, divName) {
	var retStr = "";
	if (http_request.readyState == 4) {
		if (http_request.status == 200)	{
			retStr = innerHTML=http_request.responseText;
		} else {
			;
		}
		writeHTMLtoDiv(divName, retStr);
	}
}

function writeHTMLtoDiv(divName, txt) {
	var divObj = getDOMObject(divName);
	txt += "";
	if (typeof divObj.innerHTML != 'undefined') {
		if (olIe5 && isMac) divObj.innerHTML = '';
		divObj.innerHTML = txt;
	} else	if (olNs4) {
		var lyr = document.layers[divName].document;
		lyr.write(txt);
		lyr.close();
	}
}

function readHTMLfromDiv(divName) {
	var divObj = getDOMObject(divName);
	var divHTML = "";
	if (typeof divObj.innerHTML != 'undefined') {
		divHTML = divObj.innerHTML;
	} else	if (olNs4) {
		var lyr = document.layers[divName].document;
		lyr.read(divHTML);
		lyr.close();
	}
	return divHTML;
}
