/* Script for displaying GoogleMap on Peakware.com
	Created by Terrill Thompson, http://www.mountbakermedia.com
	Last update: May 7, 2009
*/

var map;
var geocoder;
var debug=0; 
var arrow;
var pkMarker;

function updateMap(whichMap) { 
	//update map with data provided in HTML form fields
	var userLat = document.getElementById('latitude').value;
	var userLong = document.getElementById('longitude').value;	
	if (whichMap == 'addapeak') { 
		var userZoom = document.getElementById('zoom').value;
	}
	if (isset(userZoom)) { 
		map.setCenter(new GLatLng(userLat, userLong), userZoom);
	}
	else map.setCenter(new GLatLng(userLat, userLong),map.getZoom());
	//reposition marker in center of newly positioned map 
	var point = new GLatLng(userLat,userLong);	
	pkMarker.setLatLng(point);
}

function load(whichMap,latitude,longitude,zoom,homeTown){

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(latitude, longitude), zoom);
		map.addMapType(G_PHYSICAL_MAP); /* terrain */
		map.addMapType(G_SATELLITE_3D_MAP); /* Google Earth (requires plug-in) */
		
		if (whichMap == 'myConfig') { 
			geocoder = new GClientGeocoder();
			if (latitude && longitude) { 
				var point = new GLatLng(latitude,longitude);
				map.setCenter(point, 13);
			}
			else showAddress(latitude,longitude,homeTown);
		}
		else if (whichMap == 'route') { 
			var geoXml = new GGeoXml(kmlFile);
			var sw = new GLatLng(minLat,minLong);
			var ne = new GLatLng(maxLat,maxLong);
			//creating a bounding box
			var box = new GLatLngBounds(sw, ne);
			// Center map in the center of the bounding box  
			// and calculate the appropriate zoom level  
			map.setCenter(box.getCenter(), map.getBoundsZoomLevel(box)); 
			map.addOverlay(geoXml);
		}
		
		// Tile numbering function
		GetMyTopoTile=function(a,b,c) {
			var lURL=this.myBaseURL;
			lURL+=b;
			lURL+="/"+a.x;
			lURL+="/"+a.y+".png";
			return lURL;
		};

		// Set-up MyTopo tile layer
		var mytopoCopy = new GCopyright(1,new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)),0,'Topo maps (c) MyTopo.com'); 
		var mytopoc = new GCopyrightCollection(''); 
		mytopoc.addCopyright(mytopoCopy);
		var tileMytopo = new GTileLayer(mytopoc,1,15); 
		tileMytopo.myLayers='topoG'; 
		tileMytopo.myFormat='image/png';
		tileMytopo.myBaseURL='http://maps.mytopo.com/peakware/tilecache.py/1.0.0/topoG/';
		tileMytopo.getTileUrl=GetMyTopoTile;
		var mytopoLayer=[tileMytopo];
		var MYTOPO_MAP = new GMapType(mytopoLayer, G_SATELLITE_MAP.getProjection(), "MyTopo", G_PHYSICAL_MAP);
		
		//display MyTopo button if map falls within target scope
		var center = map.getCenter();
		var centerLat = center.lat();
		var centerLong = center.lng();
		var zoom = map.getZoom();
		if (zoom >= 9 && (centerLong >= -167 && centerLong <= -60 ) && 
			(centerLat <= 83 && centerLat >= 24 )){
			// Add tile layer to map object
			map.addMapType(MYTOPO_MAP);
			// Add 'Order a print of this topo map' link 
			if (map.getCurrentMapType() == MYTOPO_MAP) { 
				if (document.getElementById("printLink")) { 
					var topoUrl = 'http://www.mytopo.com/wildernet.cfm?pid=peakware&amp;lat=';
					topoUrl = topoUrl + centerLat + '&amp;lon=' + centerLong;
					var topoHTML = '<a href="' + topoUrl + '">';
					topoHTML = topoHTML + 'Order a print of this topo map</a>';
					document.getElementById("printLink").innerHTML = topoHTML.toString();
				}
			}
			else { 
				if (document.getElementById("printLink")) 
					document.getElementById("printLink").innerHTML = '';
			}
		}

		GEvent.addListener(map,"maptypechanged",function() {
			var mapType = map.getCurrentMapType();
			if (map.getCurrentMapType() == MYTOPO_MAP) { 
				if (document.getElementById("printLink")) { 
					center = map.getCenter();
					centerLat = center.lat();
					centerLong = center.lng();
					var topoUrl = 'http://www.mytopo.com/wildernet.cfm?pid=peakware&amp;lat=';
					topoUrl = topoUrl + centerLat + '&amp;lon=' + centerLong;
					var topoHTML = '<a href="' + topoUrl + '">';
					topoHTML = topoHTML + 'Order a print of this topo map</a>';
					document.getElementById("printLink").innerHTML = topoHTML.toString();
				}
			}
		});
		
		map.setMapType(G_PHYSICAL_MAP);
		var mapTypes = map.getMapTypes();
		var numTypes = mapTypes.length;
		if (iconSet == 2) {
			var arrowIcon = 'http://maps.google.com/mapfiles/kml/pal5/icon6.png';
			var arrowShadow = 'http://maps.google.com/mapfiles/kml/pal5/icon6s.png';
			//clear existing markers
			map.clearOverlays();
			//add marker for the current peak
			var pkIcon = new GIcon();
			pkIcon.iconSize=new GSize(32,32);
			pkIcon.shadowSize=new GSize(56,32);
			pkIcon.iconAnchor=new GPoint(16,32);
			pkIcon.infoWindowAnchor=new GPoint(16,0);			
			arrow = new GIcon(pkIcon,arrowIcon,null,arrowShadow);
		}
		
		GEvent.addListener(map,"moveend",function() {

			// gather data about current map
			var center = map.getCenter();
			var bounds = map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();
			var span = bounds.toSpan(); 
			var centerLat = center.lat();
			var centerLong = center.lng();
			var swLat = southWest.lat(); 
			var swLong = southWest.lng();
			var neLat = northEast.lat();
			var neLong = northEast.lng();
			var latSpan = span.lat();
			var longSpan = span.lng();
			var zoom = map.getZoom();

			if (whichMap != 'blank') { 
				showMarkers(whichMap,zoom,personId);
			}

			if (document.getElementById('msg')) { 
				var msg = '<ul>';
				msg = msg + '<li>Latitude: ' + centerLat + '</li>';
				msg = msg + '<li>Longitude: ' + centerLong + '</li>';
				msg = msg + '<li>Zoom Level: ' + zoom + '</li></ul>' + "\n";
				document.getElementById('msg').innerHTML = msg;
			}
			if (document.getElementById("zoom")) { 
				document.getElementById("zoom").value = zoom;
			}
			if (zoom >= 9 && (centerLong >= -167 && centerLong <= -60 ) && 
				(centerLat <= 83 && centerLat >= 24 )){
				// Add tile layer to map object
				map.addMapType(MYTOPO_MAP);
				// Add 'Order a print of this topo map' link 
				if (map.getCurrentMapType() == MYTOPO_MAP) { 
					if (document.getElementById("printLink")) { 
						var topoUrl = 'http://www.mytopo.com/wildernet.cfm?pid=peakware&amp;lat=';
						topoUrl = topoUrl + centerLat + '&amp;lon=' + centerLong;
						var topoHTML = '<a href="' + topoUrl + '">';
						topoHTML = topoHTML + 'Order a print of this topo map</a>';
						document.getElementById("printLink").innerHTML = topoHTML.toString();
					}
				}
				else { 
					if (document.getElementById("printLink")) 
						document.getElementById("printLink").innerHTML = '';
				}
			}
			else { 
				map.removeMapType(MYTOPO_MAP);
				// map.setMapType(G_PHYSICAL_MAP);
			}
			
		});
		if (iconSet == 2) {
			var point = new GLatLng(latitude,longitude);
			pkMarker = new GMarker(point, {draggable: true, icon: arrow});
			map.addOverlay(pkMarker);
			GEvent.addListener(pkMarker, "dragstart", function() {
				//map.closeInfoWindow();
			});
			GEvent.addListener(pkMarker, "dragend", function() {
				var pkCenter = pkMarker.getPoint();
				var pkLat = pkCenter.lat();		
				var pkLong = pkCenter.lng();
				//do we need to redraw the marker in the center? 
				//pkMarker.openInfoWindowHtml("some message here");
				if (whichMap == 'addapeak' || whichMap == 'review' || whichMap == 'myConfig') { 
					if (document.getElementById("latitude"))
						document.getElementById("latitude").value = pkLat;
					if (document.getElementById("longitude"))
						document.getElementById("longitude").value = pkLong;
					if (document.getElementById("zoom"))
						document.getElementById("zoom").value = map.getZoom();
				}
			});
		}

		if (whichMap != 'blank') { 
			showMarkers(whichMap,zoom,personId);
		}
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
	}
}

function updateCoords(newField,newValue) { 

	if (newField == 'city') { 
		var newCity = newValue;
		var newState = document.getElementById('state').value;
		var newCountry = document.getElementById('country').value;
	}
	else 	if (newField == 'state') { 
		var newCity = document.getElementById('city').value;
		var newState = newValue;
		var newCountry = document.getElementById('country').value;
	}
	else 	if (newField == 'country') { 
		var newCity = document.getElementById('city').value;
		var newState = document.getElementById('state').value;
		var newCountry = newValue;
	}
	var newLocation = newCity + ', ' + newState + ', ' + newCountry;
	//	 (newLocation);
	// showAddress(newLocation);
}

function showAddress(latitude,longitude,hometown) {

	if (latitude && longitude) { 
		var point = new GLatLng(latitude,longitude);
		map.setCenter(point, 13);
		pkMarker = new GMarker(point,{title: homeTown});
		map.addOverlay(pkMarker);
	}
	else { 
		geocoder.getLatLng(
			homeTown,
			function(point) {
				if (!point) {
					alert(homeTown + " not found");
				} 
				else {
					map.setCenter(point, 13);
					marker = new GMarker(point,{title: homeTown});
					map.addOverlay(marker);
				}
				var htLat = point.lat();
				var htLong = point.lng();
				if (document.getElementById('latitude'))
					document.getElementById('latitude').value=htLat;
				if (document.getElementById('longitude'))
					document.getElementById('longitude').value=htLong;
			}
		);
	}
}

function showMarkers(whichMap,zoom,personId) { 
	var url;
	if (whichMap == 'person') map.clearOverlays();
	if (whichMap == 'default') { 
		if (zoom >= 3) { 
			//retrieve markers for this map from database
			url = createUrl(whichMap,zoom);
		}
		else { 
			url = 'data/sevensummits.xml';
		}
	}
	else { 
		url = createUrl(whichMap,zoom,personId); 
	}
	GDownloadUrl(url, function(data, responseCode) {
		var xml = GXml.parse(data);
		if (xml) { 
			var markers = xml.getElementsByTagName("marker");
			if (markers) { 
				var numMarkers = markers.length;
				for (var i = 0; i < numMarkers; i++) {
					var matchId = markers[i].getAttribute("id");
					//var matchType = parseFloat(markers[i].getAttribute("type"));
					var matchType = markers[i].getAttribute("type");
					var matchName = markers[i].getAttribute("name");
					var matchLat = parseFloat(markers[i].getAttribute("lat"));
					var matchLong = parseFloat(markers[i].getAttribute("long"));
					if (matchLat && matchLong) { 
						var point = new GLatLng(matchLat,matchLong); 
						// map.addOverlay((point,matchId,matchType,matchName));
						map.addOverlay(createMarker(point,matchId,matchType,matchName));
					}
				}
			}
		}
	});
}

function createMarker(point,markerId,markerType,markerName) {

	var marker = new GMarker(point, {title: markerName});
	GEvent.addListener(marker, "click", function() {
		if (markerType == 'peak') var link = 'peaks.html?pk=';
		else if (markerType = 'photo') var link = 'photos.html?photo=';
		else if (markerType = 'log') var link = 'logs.html?log=';
		else if (markerType = 'route') var link = 'routes.html?route=';
		else if (markerType = 'person') var link = 'people.html?person=';
		link = link + markerId; 
		document.location.href = link;
	});
	return marker;
} 

function createUrl(whichMap,zoom,personId) { //previously old zoom was third param, not used

	//alert ('Your zoom level is ' + zoom);
	var url = 'data/getmarkers.php?map=' + whichMap;
	
	if (whichMap == 'person') { 
		url = url + '&personId=' + personId;
		if (document.getElementsByName('mapChoice')) {
			var mapChoices = document.getElementsByName('mapChoice');
			for(var i = 0; i < mapChoices.length; i++) {
				if (mapChoices[i].checked == true) { 
					var mapChoice = mapChoices[i].value;
					url = url + '&mapChoice=' + mapChoice;
				}
			}
		}
	}
	else if (whichMap == 'default' || whichMap == 'addapeak' || whichMap == 'people' || 
		whichMap == 'peak') { 
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var span = bounds.toSpan(); 
		var swLat = southWest.lat(); 
		var swLong = southWest.lng();
		var neLat = northEast.lat();
		var neLong = northEast.lng();
		var latSpan = span.lat();
		var longSpan = span.lng();
		url = url + "&swLat=" + swLat;
		url = url + "&swLong=" + swLong;
		url = url + "&neLat=" + neLat;
		url = url + "&neLong=" + neLong;
		url = url + "&longSpan=" + longSpan;
		url = url + "&latSpan=" + latSpan;
		url = url + "&zoom=" + zoom;
	}
	return url;
}

function plotCorners () { 
	/* This is for debugging only. Put a marker in two opposite corners of the map. */
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var span = bounds.toSpan(); 
	var swLat = southWest.lat(); 
	var swLong = southWest.lng();
	var neLat = northEast.lat();
	var neLong = northEast.lng();
	var zoom = map.getZoom();
	/* southwest */
	var point = new GLatLng(swLat,swLong);
	map.addOverlay(createMarker(point,1,'','Southwest'));
	/* northeast */
	var point = new GLatLng(neLat,neLong);
	map.addOverlay(createMarker(point,2,'','Northeast'));
}	

function isset(varname)  {
  if(typeof( window[ varname ] ) != "undefined") return true;
  else return false;
}