// Global variables used by the GPS Visualizer functions (1157614252):
var gv_api_version = 2;
var gv_maptypecontrol_style = 'menu';
var showMapButtons = false;
var gv_filter_map_types = true;
var gv_marker_icon = 'circle';  var gv_marker_color = 'yellow';
var gv_marker_link_target = '_blank';
var gv_marker_list_options = {map:'Edit.map',array:'wpts',colors:false,default_color:'#000000',icons:true,desc:false,toggle:false,center:false,zoom:false,info_window:true};
// end GPS Visualizer globals

var trackColor = "#f52520";
var trackWeight = 3;
var trackOpacity = 1.0;
var picDiv = document.getElementById('picDiv');
var GUIDE_ICON_URL = "/images/guideicon.png";
var GUIDE_ACTIVE_ICON_URL = "/images/guideicon.png"
var TRIP_ICON_URL = "/images/img_pin.png";
var TRIP_ACTIVE_ICON_URL = "/images/img_pin.pngg";

// track styling
var TRACK_OPACITY = 0.9;
var TRACK_OPACITY_DIM = 0.3;
var TRACK_OPACITY_STRONG = 1.0;

var TRACK_WEIGHT = 3;


function getTrackColor(index) {
	switch(index % 10) {
		case 0:
			return "#f52520"; // red
			break;
		case 1: 
			return "#e4ff00"; // vivid yellow
			break;
		case 2: 
			return "#90ff00"; // vivid green
			break;
		case 3:
			return "#fa7609"; // orange
			break;
		case 4: 
			return "#085397"; // blue
			break;
		case 5: 
			return "#00fcff"; // tiffany green
			break;
		case 6: 
			return "#d593c1"; // purple
			break;
		case 7: 
			return "#681c64"; // dark purple
			break;
		case 8: 
			return "#ff00de"; // pinkish red
			break;
		case 9: 
			return "#005948"; // green
			break;
		default:
			return trackColor;
			break;
	}

}




var pictureIcon = new GIcon();
pictureIcon.image = "/images/img_redpin.png";
pictureIcon.iconSize = new GSize(10,16);
pictureIcon.shadowSize = new GSize(0, 0);
pictureIcon.iconAnchor = new GPoint(5, 16);
pictureIcon.infoWindowAnchor = new GPoint(5, 5);

var videoIcon = new GIcon();
videoIcon.image = "/images/video_pin.png";
videoIcon.iconSize = new GSize(14,18);
videoIcon.shadowSize = new GSize(0, 0);
videoIcon.iconAnchor = new GPoint(7, 18);
videoIcon.infoWindowAnchor = new GPoint(5, 5);

var hiddenTripIcon = new GIcon();
hiddenTripIcon.image = "/images/img_purplecircle.png";
hiddenTripIcon.iconSize = new GSize(11, 11);
hiddenTripIcon.shadowSize = new GSize(0, 0);
hiddenTripIcon.iconAnchor = new GPoint(6, 6);
hiddenTripIcon.infoWindowAnchor = new GPoint(6, 6);

var activeTripIcon = new GIcon();
activeTripIcon.image = "/images/img_redcircle.png";
activeTripIcon.iconSize = new GSize(11, 11);
activeTripIcon.shadowSize = new GSize(0, 0);
activeTripIcon.iconAnchor = new GPoint(6, 6);
activeTripIcon.infoWindowAnchor = new GPoint(6, 6);

var activePictureIcon = new GIcon();
activePictureIcon.image = "/images/red_marker_pin_highlighted.png";
activePictureIcon.iconSize = new GSize(43, 49);
activePictureIcon.shadowSize = new GSize(0, 0);
activePictureIcon.iconAnchor = new GPoint(23, 38);
activePictureIcon.infoWindowAnchor = new GPoint(20, 19);


var trackStartIcon = new GIcon();
trackStartIcon.image = "/images/icon_go.png";
trackStartIcon.iconSize = new GSize(17, 24);
trackStartIcon.shadowSize = new GSize(17, 24);
trackStartIcon.iconAnchor = new GPoint(9, 24);
trackStartIcon.infoWindowAnchor = new GPoint(2, 12);

var trackEndIcon = new GIcon();
trackEndIcon.image = "/images/icon_end.png";
trackEndIcon.iconSize = new GSize(17, 24);
trackEndIcon.shadowSize = new GSize(17, 24);
trackEndIcon.iconAnchor = new GPoint(9, 24);
trackEndIcon.infoWindowAnchor = new GPoint(2, 12);

var trackStartEndIcon = new GIcon();
trackStartEndIcon.image = "/images/trackend.png";
trackStartEndIcon.iconSize = new GSize(16, 25);
trackStartEndIcon.shadowSize = new GSize(21, 31);
trackStartEndIcon.iconAnchor = new GPoint(11, 26);
trackStartEndIcon.infoWindowAnchor = new GPoint(8, 12);


var tripIcon = new GIcon();
tripIcon.image = "/images/img_pin.png";
tripIcon.iconSize = new GSize(11, 17);
tripIcon.shadowSize = new GSize(0, 0);
tripIcon.iconAnchor = new GPoint(6, 17);
tripIcon.infoWindowAnchor = new GPoint(6, 4);


var waypointIcon = new GIcon();
waypointIcon.image = "/images/red_pin.png";
waypointIcon.iconSize = new GSize(32, 28);
waypointIcon.shadowSize = new GSize(0, 0);
waypointIcon.iconAnchor = new GPoint(12, 26);
waypointIcon.infoWindowAnchor = new GPoint(9, 7);

var guideIcon = new GIcon();
guideIcon.image = GUIDE_ICON_URL;
guideIcon.iconSize = new GSize(13, 17);
guideIcon.shadowSize = new GSize(0, 0);
guideIcon.iconAnchor = new GPoint(7, 17);
guideIcon.infoWindowAnchor = new GPoint(7, 7);


var campgroundIcon = new GIcon();
campgroundIcon.image = "/images/campgroundIcon.png";
campgroundIcon.iconSize = new GSize(20, 20);
campgroundIcon.shadowSize = new GSize(20, 20);
campgroundIcon.iconAnchor = new GPoint(10, 10);
campgroundIcon.infoWindowAnchor = new GPoint(10, 10);

var trailheadIcon = new GIcon();
trailheadIcon.image = "/images/hikingIcon.png";
trailheadIcon.iconSize = new GSize(20, 20);
trailheadIcon.shadowSize = new GSize(20, 20);
trailheadIcon.iconAnchor = new GPoint(10, 10);
trailheadIcon.infoWindowAnchor = new GPoint(10, 10);

function getPoiIconUrl(index, isActive) {
	if(index == -1) {
		return "/images/POIicon_minor" + (isActive ? "_active" : "") + ".png"; 
	}
	
	if(index >= 40) {
		return "/images/POIicon_default" + (isActive ? "_active" : "") + ".png";
	}
	
	return "/images/POIicon_"+index + (isActive ? "_active" : "") + ".png";
}

function getPoiIcon(index, isActive) {
	var icon = new GIcon();
	icon.image = getPoiIconUrl(index, isActive);
	
	if(index == -1) {
		icon.iconSize = new GSize(10, 12);
		icon.shadowSize = new GSize(0, 0);
		icon.iconAnchor = new GPoint(6, 12);
		icon.infoWindowAnchor = new GPoint(6, 0);
		
	} else {
		icon.iconSize = new GSize(16, 18);
		icon.shadowSize = new GSize(0, 0);
		icon.iconAnchor = new GPoint(9, 18);
		icon.infoWindowAnchor = new GPoint(9, 0);
	}

	
	return icon;
}




function getMapFromName(name) {
   var mapType;
   if(name == "Topo") {
      mapType = USGS_TOPO_TILES;
   } else if(name == "Aerial") {
      mapType = USGS_AERIAL_TILES;
   } else if(name == "Terrain") {
      mapType = G_PHYSICAL_MAP;
   } else if(name == "Satellite") {
      mapType = G_SATELLITE_MAP;
   } else if(name == "Map") {
      mapType = G_NORMAL_MAP;
   } else if(name == "Hybrid") {
      mapType = G_HYBRID_MAP;
   } else if(name == "Earth") {
      mapType = G_SATELLITE_3D_MAP;
   } else {
      mapType = G_PHYSICAL_MAP;
   }
   return mapType;
}

function getMapFromMapName(name) {
	if(name == "G_NORMAL_MAP") return G_NORMAL_MAP;
	if(name == "G_SATELLITE_MAP") return G_SATELLITE_MAP;
	if(name == "G_HYBRID_MAP") return G_HYBRID_MAP;
	if(name == "USGS_TOPO_TILES") return USGS_TOPO_TILES;
	if(name == "USGS_AERIAL_TILES") return USGS_AERIAL_TILES;
	if(name == "G_PHYSICAL_MAP") return G_PHYSICAL_MAP;
      
	return G_HYBRID_MAP;
}

function getMapIndexFromType(type) {
	if(name == "USGS_TOPO_TILES") {
	     return 5;
   	} else if(name == "USGS_AERIAL_TILES") {
      	return 6;
   	} else if(name == "G_SATELLITE_MAP") {
      	return 1;
   	} else if(name == "G_NORMAL_MAP") {
      	return 0;
   	} else if(name == "G_HYBRID_MAP") {
      	return 2;
   	}  else if(name == "G_PHYSICAL_MAP") {
      	return 3;
   	}  else if(name == "Earth") {
      	return 4;
   	} else {
      	return 3;
   	}
}

function getMapTypeId(name) {
   var mapId;
   if(name == "Topo") {
      mapId = 5;
   } else if(name == "Aerial") {
      mapId = 6;
   } else if(name == "Satellite") {
      mapId = 1;
   } else if(name == "Map") {
      mapId = 0;
   } else if(name == "Hybrid") {
      mapId = 2;
   }  else if(name == "Terrain") {
      mapId = 3;
   }  else if(name == "Earth") {
      mapId = 4;
   } else {
      mapId =3;
   }
   return mapId;
}


function setMapType(type) {
	map.setMapType(eval(type));
}

function getMapIndexFromMapName(type) {
	return 0;
}

function changeMapType(map,type) {
	var mapType = getMapFromMapName(type);
	var mapId = getMapIndexFromMapName(type);
	var map_selector = document.getElementById('map_selector');
	
	if(map_selector) map_selector.selectedIndex = mapId;
	
	map.setMapType(mapType);
}

function makeTripMarker(map,latLng, title, tripId, picture) {

	var marker = new GMarker(latLng,{title:title,icon:tripIcon});

	GEvent.addListener(marker,"click",function() {
		var html = "<div class='trip-balloon'><A href=\"/view_trip.php?trip_id="+tripId+"\">"+title+"</a><br>";
         
		if(picture && picture != "") { 
			html += "<img src="+picture+" class='trip-balloon-picture'>"; 
		}
            
  		html+= "</div>";
        map.openInfoWindow(latLng,html);
	});
	return marker;
}


function getIconByName(name) {
	switch (name) {
		case "campgroundIcon":
		return campgroundIcon;
		break;
		
		case "trailheadIcon":
		return trailheadIcon;
		break;
		
		case "default":
		return G_DEFAULT_ICON;
		break;
		
		default:
		return waypointIcon;
	}
}

function addLoadingMessage(container, message, mapWidth, mapHeight) {

	

	statusDiv = document.createElement('div');
 	statusDiv.id = 'loading-container';

	messageWidth = 120;
	messageHeight = 20;

	mapWidth = mapWidth || container.style.width.replace('px','');
 	mapHeight = mapHeight || container.style.height.replace('px','');


	leftPos = (mapWidth-messageWidth)/2;
 	topPos = (mapHeight-messageHeight)/2;

	statusDiv.style.position = "absolute";
	statusDiv.style.zindex = 100;
	statusDiv.style.backgroundColor = "#FFFFFF";
	statusDiv.style.border = "2px solid #000000";
	statusDiv.style.left = leftPos+'px';
	statusDiv.style.top = topPos+'px';
	statusDiv.style.width = messageWidth + "px";
	statusDiv.style.height = messageHeight + "px";
	statusDiv.style.textAlign = "center";
	statusDiv.verticalAlign = "middle";

	statusDiv.innerHTML = "<font size=+0>"+message+"</font>";

	container.appendChild(statusDiv);
}

function removeLoadingMessage() {
	if(document.getElementById("loading-container")) {
		document.getElementById("loading-container").style.display = "none";
	}
}

function loadMap(container, mapType) {
	if (GBrowserIsCompatible()) {
       
		map = new GMap2(container);
		
		map.addControl(new GSmallMapControl());
		map.enableDoubleClickZoom();
 		//map.enableContinuousZoom();
		map.setCenter(new GLatLng(0,0),2);
		map.setMapType(mapType);
		
		if(picDiv) {
			
			GEvent.addListener(map, "move", function() {
				removeDivOnMap(map, picDiv);
			});
			
			GEvent.addListener(map, "zoomend", function() {
				removeDivOnMap(map, picDiv);
			});
			
			
		}
	}
	return map;
}


function showDivOnMap(point, offset, map, div) {
	var px1 = map.fromLatLngToDivPixel(point);
	var bounds = map.getBounds();
	var topLeft = new GLatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng());
	var px2 = map.fromLatLngToDivPixel(topLeft);
	var x = px1.x-px2.x;
	var y = px1.y-px2.y;
	var px = new GPoint(x,y);
	

	if(map.getBounds().containsLatLng(point)) {
		div.style.visibility = "visible";
	} else {
		div.style.visibility = "hidden";
	}
	div.style.top = px.y+ offset.y + 'px';
	div.style.left = px.x+ offset.x + 'px';
	return div;
}

function removeDivOnMap(map,div) {
	if(div) div.style.visibility = "hidden";
	
	//map.getContainer().removeChild(div);
}

function showThumbnailDiv(pt, thumb, map) {
	if(picDiv) removeDivOnMap(map,picDiv);
	
	picDiv = showDivOnMap(pt, new GPoint(-3,-75), map, picDiv);
	picDiv.innerHTML = showSquareImage('<img src="'+thumb+'" class="square-photo-image-small">',50,75);//"<img class='img100w img100h' src='"+thumb+"' style='max-width:100px;max-height:100px'>";
}

function makeSquareImage(img, size, thumbMax) {
	var offset = Math.floor((thumbMax - size) / 2) - 3;
	
	return "<div style='position: absolute; width:"+thumbMax+"px;height:"+thumbMax+"px; top:-"+offset+"px; left:-"+offset+"px;'>" +
	    "<table width=100% height=100% cellpadding=0 cellspacing=0><tr><td align=center valign=center class='middle center'>" +
	       img+
		"</td></tr></table></div>";
}

function showSquareImage(img, size, thumbMax) {
	return "<div style='height:"+size+"px; width:"+size+"px;' class='square-photo-container left'>" + 
				makeSquareImage(img, size, thumbMax) + 
	             "</div>";
}

function addPicture(title, lat, lon, thumb, full, doEnlarge) {
	var addToSlideshow = true;
	var pt = new GLatLng(lat,lon);
	var marker = new GMarker(pt, {icon:pictureIcon, zIndexProcess: function() { return 1;}});
	

	if(doEnlarge) {
		GEvent.addListener(marker, "click", function() {
			enlargePic(full);
		});
	}
         
	GEvent.addListener(marker, "mouseover", function() {
		showThumbnailDiv(pt,thumb,map);
	});
	GEvent.addListener(marker, "mouseout", function() {
		removeDivOnMap(map, picDiv);
	});
	
	pictures.push({"marker":marker,"title":title, "thumb":thumb, "full":full});

	map.addOverlay(marker);
	pictureMarkers.push(marker);
	if(addToSlideshow) {
	//	slideshowMap.addOverlay(marker);
	}
	
	return marker;
}





if (gv_api_version > 1) {
	var USGS_TOPO_TILES = WMSCreateMap('Topo','Topo maps by USGS via terraserver-usa.com','Topo maps unavailable',7,17,400,
                           'http://terraservice.net/ogcmap6.ashx?version=1.1.1&request=GetMap&styles=&srs=EPSG:4326&format=image/jpeg&bgcolor=0xCCCCCC&exceptions=INIMAGE&layers=DRG');
	var USGS_AERIAL_TILES = WMSCreateMap('Aerial','Imagery by USGS via terraserver-usa.com','USGS aerial imagery unavailable',7,18,400,
                           'http://terraservice.net/ogcmap6.ashx?version=1.1.1&request=GetMap&styles=&srs=EPSG:4326&format=image/jpeg&bgcolor=0xCCCCCC&exceptions=INIMAGE&layers=DOQ');
	var NRCAN_TOPO_TILES = WMSCreateMap('NRCan topo','Maps by NRCan.gc.ca','NRCan maps unavailable',8,18,600,
                          'http://wms.cits.rncan.gc.ca/cgi-bin/cubeserv.cgi?version=1.1.3&request=GetMap&format=image/png&bgcolor=0xFFFFFF&' +
                          'exceptions=application/vnd.ogc.se_inimage&srs=EPSG:4326&layers=PUB_50K:CARTES_MATRICIELLES/RASTER_MAPS');
	var BLUEMARBLE_TILES = WMSCreateMap('Blue Marble','Map by NASA','OnEarth server unavailable',3,8,128,
                          'http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&styles=&srs=EPSG:4326&format=image/jpeg&layers=modis');
	var DAILY_TERRA_TILES = WMSCreateMap('Daily "Terra"','Map by NASA','OnEarth server unavailable',3,10,256,
                           'http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&styles=&srs=EPSG:4326&format=image/jpeg&layers=daily_terra');
	var DAILY_AQUA_TILES = WMSCreateMap('Daily "Aqua"','Map by NASA','OnEarth server unavailable',3,10,256,
                          'http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&styles=&srs=EPSG:4326&format=image/jpeg&layers=daily_aqua');
}

function GV_Add_Custom_Layers(map) {
	map.addMapType(USGS_TOPO_TILES);
	map.addMapType(USGS_AERIAL_TILES);
	map.addMapType(NRCAN_TOPO_TILES);
	map.addMapType(BLUEMARBLE_TILES);
	map.addMapType(DAILY_TERRA_TILES);
	map.addMapType(DAILY_AQUA_TILES);
}


function WMSCreateMap(name,copyright,errorMessage,minResolution,maxResolution,tileSize,baseUrl) {
	var tileLayer = new GTileLayer(new GCopyrightCollection(copyright),minResolution,maxResolution);
	tileLayer.baseUrl = baseUrl;
	tileLayer.tileSize = tileSize;
	tileLayer.getTileUrl = WMSGetTileUrl;
	tileLayer.getCopyright = function() { return { prefix:'',copyrightTexts:[copyright]}; };
	var tileLayers = [tileLayer];
	return new GMapType(tileLayers,G_SATELLITE_MAP.getProjection(),name,{errorMessage:errorMessage,tileSize:tileSize});
}


function WMSGetTileUrl(tile,zoom) {
	var southWestPixel = new GPoint(tile.x*this.tileSize,(tile.y+1)*this.tileSize);
	var northEastPixel = new GPoint((tile.x+1)*this.tileSize,tile.y*this.tileSize);
	var southWestCoords = G_SATELLITE_MAP.getProjection().fromPixelToLatLng(southWestPixel,zoom);
	var northEastCoords = G_SATELLITE_MAP.getProjection().fromPixelToLatLng(northEastPixel,zoom);
	var bbox = southWestCoords.lng()+','+southWestCoords.lat()+','+northEastCoords.lng()+','+northEastCoords.lat();
	return this.baseUrl+'&bbox='+bbox+'&width='+this.tileSize+'&height='+this.tileSize;
}


/**************************************************
 * Custom map-type control:
 * more or less from Google's own documentation
 **************************************************/
function GV_MapTypeControl(selectorName) {
   this.selectorName = selectorName; 
}


var map_types = [
	{ label:'Google map',type:'G_NORMAL_MAP',title:'Google street map',bounds:[-180,-90,180,90],excluded:[] }
	,{ label:'Google satellite',type:'G_SATELLITE_MAP',title:'Google satellite map',bounds:[-180,-90,180,90],excluded:[] }
	,{ label:'Google hybrid',type:'G_HYBRID_MAP',title:'Google "hybrid" map',bounds:[-180,-90,180,90],excluded:[] }
	,{ label:'Google terrain',type:'G_PHYSICAL_MAP',title:'Google terrain map',bounds:[-180,-90,180,90],excluded:[] }
	,{ label:'Google Earth (3D)',type:'G_SATELLITE_3D_MAP',title:'Google earth map',bounds:[-180,-90,180,90],excluded:[] }
	,{ label:'USGS topo (US only)',type:'USGS_TOPO_TILES',title:'USGS topographic map',bounds:[-169,18,-66,72],excluded:[] }
	,{ label:'USGS satellite (US only)',type:'USGS_AERIAL_TILES',title:'USGS aerial photos (black/white)',bounds:[-152,17,-65,65],excluded:[] }
//	,{ label:'Canada topo',type:'NRCAN_TOPO_TILES',title:'NRCan/Toporama maps with contour lines',bounds:[-141,41.7,-52,85],excluded:[-141,41.7,-86,48] }
//	,{ label:'Blue Marble',type:'BLUEMARBLE_TILES',title:'NASA "Visible Earth" image',bounds:[-180,-90,180,90],excluded:[] }
//	,{ label:'Daily "Terra"',type:'DAILY_TERRA_TILES',title:'Daily imagery from "Terra" satellite',bounds:[-180,-90,180,90],excluded:[] }
//	,{ label:'Daily "Aqua"',type:'DAILY_AQUA_TILES',title:'Daily imagery from "Aqua" satellite',bounds:[-180,-90,180,90],excluded:[] }
];

if (gv_api_version > 1) {
	GV_MapTypeControl.prototype = new GControl();
	GV_MapTypeControl.prototype.initialize = function(map) {
		if(showMapButtons) {
               GV_Add_Custom_Layers(map);
  }
		
	//	var center_lat = map.getCenter().lat();
//		var center_lng = map.getCenter().lng();

		if (gv_maptypecontrol_style == 'menu') {
			var map_selector = document.createElement("select");
			if(this.selectorName) {
                  map_selector.id = this.selectorName;
               } else {
			   map_selector.id = 'map_selector';
			}
			
			map_selector.name = "mapType";
			map_selector.style.font = '10px Verdana';
			map_selector.style.backgroundColor = '#FFFFFF';

			for (j=0; j<map_types.length; j++) {
			/*	if (!gv_filter_map_types || gv_filter_map_types < 0 ||
                       ( (center_lng >= map_types[j]['bounds'][0] && center_lat >= map_types[j]['bounds'][1] && center_lng <= map_types[j]['bounds'][2] && 
                          center_lat <= map_types[j]['bounds'][3]) && !(center_lng >= map_types[j]['excluded'][0] && center_lat >= map_types[j]['excluded'][1] && 
                          center_lng <= map_types[j]['excluded'][2] && center_lat <= map_types[j]['excluded'][3]) 
                        ) ) {
               */
					var opt = document.createElement("option");
					opt.value = map_types[j]['type'];
					opt.appendChild(document.createTextNode(map_types[j]['label']));
					map_selector.appendChild(opt);
					if (map.getCurrentMapType() == eval(opt.value)) { map_selector.selectedIndex = map_selector.length - 1; }
			//	}
			}
			GEvent.addDomListener(map_selector, "change", function(){map.setMapType(eval(this.value));} );
		
              // typeTitle = document.createElement('div');
             //  typeTitle.innerHTML = "Map Type";



              // map.getContainer().appendChild(typeTitle)
          	map.getContainer().appendChild(map_selector);           
			return map_selector;
		} else {
			var map_type_container = document.createElement("div");
			for (j=0; j<map_types.length; j++) {
				if (!gv_filter_map_types || gv_filter_map_types < 0 || ( (center_lng >= map_types[j]['bounds'][0] && center_lat >= map_types[j]['bounds'][1] && center_lng <= map_types[j]['bounds'][2] && center_lat <= map_types[j]['bounds'][3]) && !(center_lng >= map_types[j]['excluded'][0] && center_lat >= map_types[j]['excluded'][1] && center_lng <= map_types[j]['excluded'][2] && center_lat <= map_types[j]['excluded'][3]) ) ) {
					var maplink = document.createElement("div");
					maplink.className = 'gv_maptypelink';
					if (self.gv_maptypecontrol && map.getCurrentMapType() == eval(map_types[j]['type'])) {
						maplink.className = 'gv_maptypelink gv_maptypelink_selected';
					}
					maplink.title = map_types[j]['title'];
					maplink.type = map_types[j]['type'];
					map_type_container.appendChild(maplink);
					maplink.appendChild(document.createTextNode(map_types[j]['label']));
					GEvent.addDomListener(maplink, "click", function(){
						map.setMapType(eval(this.type));
						if (self.gv_maptypecontrol) {
							map.removeControl(gv_maptypecontrol);
							map.addControl(gv_maptypecontrol);
						}
					} );
				}
			}
			map.getContainer().appendChild(map_type_container);
			return map_type_container;
		}
	}
	GV_MapTypeControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,7));
	}
}


function centerAndZoom(map, bounds, padding) {

	if(padding) {
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		
		var h = ne.lat() - sw.lat();
		var w = ne.lng() - sw.lng();
		
		var newNe = new GLatLng( ne.lat() + padding*h, ne.lng() + padding*w   );
		var newSw = new GLatLng( sw.lat() - padding*h, sw.lng() - padding*w   );
		
		bounds.extend(newNe);
		bounds.extend(newSw);
	}
	
	
	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}




/////



function showSection(section) {
	if(activePoi) hideSection(activePoi);
	if(activeGuide) hideGuide(activeGuide);
	
	showSectionDiv(section);
	// change pin
	
	if(!section.marker) return;
	var iconUrl = section.level == 1 ? getPoiIconUrl(-1, true) : getPoiIconUrl(section.index+1, true);
	
	if(poiIconMode == 0) section.marker.setImage(iconUrl);
	activePoi = section;
}

function hideSection(section) {
	hideSectionDiv();
	// change pin
	
	if(!section.marker) return;
	var iconUrl = section.level == 1 ? getPoiIconUrl(-1, false) : getPoiIconUrl(section.index+1, false);
	
	if(openMapId != section.index && poiIconMode == 0) section.marker.setImage(iconUrl);
	
	
	activePoi = null;
}

function poiClicked(poi) {
	// default: do nothing
}

function addSection(section, enlargePics) {
	
	var enlargePics = enlargePics || false;
	if(section.lat == null || section.lon == null) return;
	
	var point = new GLatLng(section.lat, section.lon);

	var icon = section.level == 1 ? getPoiIcon(-1) : getPoiIcon(section.index+1);

	var marker = new GMarker(point, {icon:icon, zIndexProcess:orderSectionMarkers});
	section.marker = marker;
	
	GEvent.addListener(marker, "mouseover", function() {
		showSection(section);
	});
	
	GEvent.addListener(marker, "mouseout", function() {
		hideSection(section);
	});
	
	
	GEvent.addListener(marker, "click", function() {
		poiClicked(section);
	});
	
	for(var i=0; i<section.media.length; i++) {
	//	section.media[i].marker = new GMarker(new GLatLng(section.media[i].lat, section.media[i].lon), {icon:pictureIcon});
		
		
		section.media[i].marker = addPicture("", section.media[i].lat, section.media[i].lon, section.media[i].thumb, section.media[i].full, enlargePics);
		
		
	//	map.addOverlay(section.media[i].marker);
		section.media[i].marker.hide();
	}
	
	mapBounds.extend(point);
	
	map.addOverlay(marker);
}


function changePoiIcons(showNumbers) {
	poiIconMode = showNumbers ? 0 : 1;
	var poi; 
	
	for(var i=0; i<pois.length; i++) {
		poi = pois[i];
		
		
		if(poi.marker) {
			if(showNumbers) {
				var iconUrl = poi.level == 1 ? getPoiIconUrl(-1, activePoi && activePoi.index == poi.index) : getPoiIconUrl(poi.index+1, activePoi && activePoi.index == poi.index);
				poi.marker.setImage(iconUrl);
			} else {
				if(poi.type) {
					poi.marker.setImage(poi.type.mapIcon);	
				} else {
					poi.marker.setImage("/images/poipin_default.png");	
				}
			}
		}
		
	}

	
	var span = document.getElementById("poi-type-span");
	if(span) {
		if(showNumbers) {
			span.innerHTML = 'POIs: numbers | <a href="javascript:changePoiIcons(false);">icons</a>';
		} else {
			span.innerHTML = 'POIs: <a href="javascript:changePoiIcons(true);">numbers</a> | icons';
		}
		
	}
}


// mapping functions


function addGuide(guide) {
	if(guide.lat == null || guide.lon == null) return;
	
	var point = new GLatLng(guide.lat, guide.lon);
	var marker = new GMarker(point, {icon: guideIcon});
	guide.marker = marker;
	
	GEvent.addListener(marker, "mouseover", function() {
		showGuide(guide);
	});
	
	GEvent.addListener(marker, "mouseout", function() {
		hideGuide(guide);
	});
	
	GEvent.addListener(marker, "click", function() {
		guideClicked(guide);
	});
	
	mapBounds.extend(point);
	map.addOverlay(marker);
	
	// tracks
	if(guide.tracks && guide.tracks.length > 0) {
		for(var i=0; i<guide.tracks.length; i++) {
			for(var j=0; j<guide.tracks[i]['trksegs'].length; j++) {
				var trackColor = getTrackColor(guide.index);
				
				guide.tracks[i]['trksegs'][j].polyline = new GPolyline(guide.tracks[i]['trksegs'][j]['points'], trackColor, TRACK_WEIGHT,TRACK_OPACITY);
		        map.addOverlay(guide.tracks[i]['trksegs'][j].polyline);

				var lineBounds = guide.tracks[i]['trksegs'][j].polyline.getBounds();
				if (mapBounds && lineBounds) {
					mapBounds.extend(lineBounds.getSouthWest());
					mapBounds.extend(lineBounds.getNorthEast());
				}
				
				GEvent.addListener(guide.tracks[i]['trksegs'][j].polyline, "mouseover", function() {
					showGuide(guide);
				});

				GEvent.addListener(guide.tracks[i]['trksegs'][j].polyline, "mouseout", function() {
					hideGuide(guide);
				});
				
			
			}	
		}
	}
	
	
}

function showGuide(guide) {
	try { 
		if(activePoi) hideSection(activePoi);
	} catch(e) {}
	
	if(activeGuide) hideGuide(activeGuide);
	showGuideDiv(guide);

	// change pin
	if(guide.marker) guide.marker.setImage(GUIDE_ACTIVE_ICON_URL);
	activeGuide = guide;
	
	// change tracks
	try {
		showGuideTracks(guide);
		dimAllGuides(guide);
	} catch(e) {}
}

function guideClicked(guide) {
	top.location.href="/guide/" + guide.url;
}

function hideGuide(guide) {
	hideGuideDiv();
	// change pin
	
	if(!guide.marker) return;
	guide.marker.setImage(GUIDE_ICON_URL);
	activeGuide = null;
	
	try {
		resetGuideColors();
	} catch(e) {}
}

function showGuideDiv(guide) {
	if(!guide.marker) return;
	
	guideDiv.style.visibility = "visible";
	guideDiv.innerHTML = "<b>" + guide.title + "</b>";

	var px1 = map.fromLatLngToDivPixel(guide.marker.getPoint());
	var bounds = map.getBounds();
	var topLeft = new GLatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng());
	var px2 = map.fromLatLngToDivPixel(topLeft);
	var x = px1.x-px2.x;
	var y = px1.y-px2.y;
	var px = new GPoint(x,y);
	var offset = new GPoint(2,0);
	

	guideDiv.style.top = px.y + offset.y + 'px';
	guideDiv.style.left = px.x + offset.x + 'px';
}

function hideGuideDiv() {
	guideDiv.style.visibility = "hidden";
}



// trips
function addTrip(trip) {
	if(trip.lat == null || trip.lon == null) return;
	
	var point = new GLatLng(trip.lat, trip.lon);
	var marker = new GMarker(point, {icon: tripIcon});
	trip.marker = marker;
	
	GEvent.addListener(marker, "mouseover", function() {
		showTrip(trip);
	});
	
	GEvent.addListener(marker, "mouseout", function() {
		hideTrip(trip);
	});
	
	GEvent.addListener(marker, "click", function() {
		tripClicked(trip);
	});
	
	mapBounds.extend(point);
	map.addOverlay(marker);
	
	// tracks
	/*
	if(trip.tracks && trip.tracks.length > 0) {
		for(var i=0; i<guide.tracks.length; i++) {
			for(var j=0; j<guide.tracks[i]['trksegs'].length; j++) {
				var trackColor = getTrackColor(guide.index);
				
				guide.tracks[i]['trksegs'][j].polyline = new GPolyline(guide.tracks[i]['trksegs'][j]['points'], trackColor, TRACK_WEIGHT,TRACK_OPACITY);
		        map.addOverlay(guide.tracks[i]['trksegs'][j].polyline);

				var lineBounds = guide.tracks[i]['trksegs'][j].polyline.getBounds();
				if (mapBounds && lineBounds) {
					mapBounds.extend(lineBounds.getSouthWest());
					mapBounds.extend(lineBounds.getNorthEast());
				}
				
				GEvent.addListener(guide.tracks[i]['trksegs'][j].polyline, "mouseover", function() {
					showGuide(guide);
				});

				GEvent.addListener(guide.tracks[i]['trksegs'][j].polyline, "mouseout", function() {
					hideGuide(guide);
				});
				
			
			}	
		}
	}
	*/
}


function showTrip(trip) {
	if(activeGuide) hideGuide(activeGuide);
	if(activeTrip) hideTrip(activeTrip);
	
	showTripDiv(trip);

	// change pin
	if(trip.marker) trip.marker.setImage(TRIP_ACTIVE_ICON_URL);
	activeTrip = trip;
}

function tripClicked(trip) {
	top.location.href="/view_trip.php?trip_id=" + trip.tripId;
}

function hideTrip(trip) {
	hideTripDiv();
	// change pin
	
	if(!trip.marker) return;
	trip.marker.setImage(TRIP_ICON_URL);
	activeTrip = null;
}

function showTripDiv(trip) {
	if(!trip.marker) return;
	
	tripDiv.style.visibility = "visible";
	tripDiv.innerHTML = "<b>" + trip.name + "</b>";

	var px1 = map.fromLatLngToDivPixel(trip.marker.getPoint());
	var bounds = map.getBounds();
	var topLeft = new GLatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng());
	var px2 = map.fromLatLngToDivPixel(topLeft);
	var x = px1.x-px2.x;
	var y = px1.y-px2.y;
	var px = new GPoint(x,y);
	var offset = new GPoint(2,0);
	

	tripDiv.style.top = px.y + offset.y + 'px';
	tripDiv.style.left = px.x + offset.x + 'px';
}

function hideTripDiv() {
	tripDiv.style.visibility = "hidden";
}



