/**
 * @filename MapsUtil.js
 * 
 * @description Class to get form fields for activities
 * 
 * @author Michael Bina
 * @email michael.bina@garmin.com
 *
 * Copyright(c) 2008, Garmin International
 */

var MapsUtilConstants = {	
	mapMarkerPaths: {
		START: '/api/activity/component/images/map-marker-start.png',
		END: '/api/activity/component/images/map-marker-end.png'
	}
};

if(Garmin == null) var Garmin = {};
if(Garmin.map == null) Garmin.map = {};

 
Garmin.map.MapsUtil = {
    /** You can pass in the config parameters like so:
     * Garmin.map.MapsUtil.initializeMap('mapId', {showMoreButton: true, largeMap: false});
     * @param config.showMoreButton {Boolean} true if you want the more button, duh.
     * @param config.largeMap {Boolean} true if you want the large map, false for small. 
     */
	initializeMap: function(elementId, config) {
   		var mapContainer = $(elementId);
   		mapContainer.show();

    	var map = new GMap2(mapContainer);
		var mapControl;
		if(config.largeMap != null){
			mapControl = new GLargeMapControl();
		}else{
			mapControl = new GSmallMapControl();
		}
    	map.addControl(mapControl);
    	map.addControl(new GMapTypeControl());
    	if(config.showMoreButton == true){
			var moreButton = this.getMoreButton();
			map.addControl(moreButton);
    	}
		
    	map.addMapType(G_PHYSICAL_MAP);
    	var keyboardHandler = new GKeyboardHandler(map);
    	
    	return map;
	},
	
	    
    addEncodedPolylineToMap: function(gmapObject, polylineJson, details) {
    	gmapObject.clearOverlays();
    	var p = polylineJson.gPolyline;
    	var activityId = p.activityId;
    	if(p.numberOfPoints > 0) {
	    	var sw = new GLatLng(p.minLat, p.minLon);
	    	var ne = new GLatLng(p.maxLat, p.maxLon);
	    	var bounds = new GLatLngBounds(sw, ne);
	    	
	    	var startPoint = new GLatLng(p.startLat, p.startLon);
	    	var endPoint = new GLatLng(p.endLat, p.endLon);
	    	
	    	/* IE has issues with determining the bounds when the map container is hidden--checkResize fixes this.*/
	    	gmapObject.checkResize(); 
	    	gmapObject.setCenter(bounds.getCenter(), gmapObject.getBoundsZoomLevel(bounds));
    	
    		var encodedPolyline = new GPolyline.fromEncoded({
				color: "#ff0000",
				weight: 2,
				opacity: 0.8,
				points: p.encodedSamples,
				levels: p.encodedLevels,
				zoomFactor: 2,
				numLevels: 18
			});
			gmapObject.addOverlay(encodedPolyline);
			
			var startMarker = this.getStartMarker(startPoint, activityId);
			var endMarker = this.getEndMarker(endPoint);
			gmapObject.addOverlay(startMarker);
			gmapObject.addOverlay(endMarker);
			returnKey = true;
		}else if(details != null){
			$('noMapDataContainer').show();
			$('activityMapContainer').hide();
		}
    },
    	    
    getStartMarker: function(vertex, activityId) {
    	var startIcon = this.getIcon(MapsUtilConstants.mapMarkerPaths.START);
    		    	marker = new GMarker(vertex, {icon: startIcon, title: bundle_resource.player});
			GEvent.addListener(
				marker,
				'click',
				function(e){
					parent.window.location = '/player/'+activityId;
				}.bind(this)
			);
		return marker;
    },
    
    getEndMarker: function(vertex) {
    	var endIcon = this.getIcon(MapsUtilConstants.mapMarkerPaths.END);
    	return new GMarker(vertex, endIcon);
    },
    
	getIcon: function(iconPath) {
		var baseIcon = new GIcon();
		baseIcon.image = iconPath;
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
		return baseIcon;
	},
	
	getMoreButton: function(){
		var layers = [];
			layers[0] = new GLayer("com.panoramio.all");
		    layers[0].Visible = false;
		    layers[0].Added = false;
			layers[1] = new GLayer(this.getLocalizedWikiLayer(bundle_resource_locale));
//			layers[1] = new GLayer("org.wikipedia.en");
		    layers[1].Visible = false;
		    layers[1].Added = false;
	
		LayerControl.prototype = new GControl();
		var layerControl = new LayerControl([bundle_resource.more_photos, bundle_resource.more_wikipedia]);
		function LayerControl(opts) {
			this.opts = opts;
		}
		LayerControl.prototype.initialize = function(map) {
			var container = document.createElement("div");
			container.className = "mapMoreMenu";
			container.id = "layerControl";
			container.style.display = "none";
			var span = document.createElement("span");
			span.className = "mapMoreMenuInner";
			container.appendChild(span);
			
			for (var i=0; i<this.opts.length; i++) {
				var checkBox = document.createElement("input");
				Element.extend(checkBox);
				checkBox.id = "checkbox_"+i;
				checkBox.type = "checkbox";
				
				if (layers[i].Visible) {
					checkBox.selected = 'true';
				} else {
					checkBox.selected = 'false';
				}
				
				checkBox.onclick = function(i, map) {
					if (layers[i].Visible) {
					  layers[i].hide();
					} else {
					  if(layers[i].Added) {
						layers[i].show();
					  } else {
						map.addOverlay(layers[i]);
						layers[i].Added = true;
					  }
					}
					layers[i].Visible = !layers[i].Visible;
				}.bind(this, i, map);
				span.appendChild(checkBox);
				
				var node = document.createElement("span");
				node.innerHTML += "&nbsp;"+this.opts[i]+"<br>";
				span.appendChild(node);
			}
			map.getContainer().appendChild(container);
			
			GEvent.addDomListener(container, "mouseout", function() {
			  document.getElementById("mapMoreButton").className = "mapMoreButton";
			  document.getElementById("layerControl").style.display = 'none';
			});
			GEvent.addDomListener(container, "mouseover", function() {
		      document.getElementById("layerControl").style.display = 'block';
		      document.getElementById("mapMoreButton").className = "mapMoreButtonExpanded";
		    });
			
			return container;
		}

		function MoreControl() {};
		MoreControl.prototype = new GControl();
		MoreControl.prototype.initialize = function(map) {
			var container = document.createElement("div");
			container.className = "mapMoreButton";
			container.id = "mapMoreButton";
			var span = document.createElement("span");
			span.innerHTML = bundle_resource.more;
			container.appendChild(span);
		  
		    map.getContainer().appendChild(container);
		    map.addControl(layerControl);
			
		    GEvent.addDomListener(container, "mouseover", function() {
		      document.getElementById("mapMoreButton").className = "mapMoreButtonExpanded";
		      document.getElementById("layerControl").style.display = 'block';
		    });
		    return container;
		}
		return new MoreControl();
	},
	
	/**
	 * Returns the localized wiki layer namespace, if Google Maps and Connect supports it.
	 * For full list of public layers: http://spreadsheets.google.com/pub?key=p9pdwsai2hDN-cAocTLhnag
	 */
	getLocalizedWikiLayer: function(locale) {
	    var prefix = 'org.wikipedia.';
	    var namespace = '';
	    var english = 'en';  // overriding browser's default "en_US"
	    
	    switch(locale) {
	        case 'cs': 
	        case 'da': 
	        case 'nl': 
	        case 'es': 
	        case 'fr': 
	        case 'de': 
	        case 'it': 
	        case 'no': 
	        case 'pl': 
	        case 'pt': 
	        case 'ru': 
	        case 'sl': 
	        case 'sv': 
	           namespace = prefix + locale;
	           break;
	        default:
	           namespace = prefix + english;
	           break;
	    }
	    return namespace;
	}
}