// 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_COLOR = "#F52520";
var TRACK_OPACITY = 0.8;
var TRACK_OPACITY_DIM = 0.3;
var TRACK_OPACITY_STRONG = 1.0;
var showCalloutDetails = false;

var TRACK_WEIGHT = 3;

var activeDestination;
var activeGuide;

var OSM_DIR = "http://localhost/maps";


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');
var CUSTOM_OSM = createOSMMapType(6,18, OSM_DIR);


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 destinationIcon = new GIcon();
destinationIcon.image = "/images/img_purplecircle.png";
destinationIcon.iconSize = new GSize(11, 11);
destinationIcon.shadowSize = new GSize(0, 0);
destinationIcon.iconAnchor = new GPoint(6, 6);
destinationIcon.infoWindowAnchor = new GPoint(6, 6);


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 > 80) {
		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()) {
       
		if(!mapType) mapType = G_PHYSICAL_MAP;
		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;
}


function createOSMMapType(minRes, maxRes, base) {
	var name = "ET OSM";
	var copyright = "everytrail.com";
	var errorMessage = "maps unavailable";
	var tileSize = 256;
	
	
	
	var tileLayer = new GTileLayer(new GCopyrightCollection(copyright),minRes,maxRes, {
	    tileUrlTemplate: base + '/{Z}/{X}/{Y}.png',
	 	//tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png',
	    isPng:true,      // /18/79323/96960.png
	    opacity:1.0
	  });
	

	var tileLayers = [tileLayer];
	
	return new GMapType(tileLayers,G_SATELLITE_MAP.getProjection(),name,{errorMessage:errorMessage,tileSize:tileSize});
}






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);
	
	// freedom trail
	
	//map.addMapType(CUSTOM_OSM);
	
	
	
	
	
	
}


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:'OSM)',type:'CUSTOM_OSM',title:'Custom OSM Map',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);
	
	
	try {
		if(poiIconMode == 0) {
			if(openMapId != null && openMapId == section.index) {
			} else {
				section.marker.setImage(iconUrl);
			}
		}

		
	} catch(e) {}
	
	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 addGuideTracks(guide) {
	// tracks
	if(guide.tracks && guide.tracks.length > 0) {
		for(var i=0; i<guide.tracks.length; i++) {
			
			// check for encoded polylines
			if(guide.tracks[i].encoded_polyline && guide.tracks[i].encoded_polyline.Points && guide.tracks[i].encoded_polyline.Levels) {
				
				if(guide.tracks[i].polyline) continue;
				
				guide.tracks[i].polyline = GPolyline.fromEncoded({
				    color: TRACK_COLOR,
				    weight: TRACK_WEIGHT,
					opacity: TRACK_OPACITY,
				    points: guide.tracks[i].encoded_polyline.Points,
				    levels: guide.tracks[i].encoded_polyline.Levels,
					zoomFactor: guide.tracks[i].encoded_polyline.ZoomFactor,
					numLevels: guide.tracks[i].encoded_polyline.NumLevels
				});
			
				map.addOverlay(guide.tracks[i].polyline);
				
				
				var lineBounds = guide.tracks[i].polyline.getBounds();
				if (mapBounds && lineBounds) {
					mapBounds.extend(lineBounds.getSouthWest());
					mapBounds.extend(lineBounds.getNorthEast());
				}
			
				GEvent.addListener(guide.tracks[i].polyline, "mouseover", function() {
					showGuide(guide);
				});

				GEvent.addListener(guide.tracks[i].polyline, "mouseout", function() {
					hideGuide(guide);
				});
				
				
			} else {
				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 addGuide(guide) {
	if(guide.lat == null || guide.lon == null) return;
	
	var lat = guide.lat['#text'] ? parseFloat(guide.lat['#text']) : guide.lat;
	var lon = guide.lon['#text'] ? parseFloat(guide.lon['#text']) : guide.lon;
	
//	alert(guide.url['#text']);
	
	
	var point = new GLatLng(lat, lon);
	var marker = new GMarker(point, {icon: guideIcon, zIndexProcess:orderGuideMarkers});
	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);
	
	
	addGuideTracks(guide);
}



function addDestination(destination) {
	if(destination.lat == null || destination.lon == null) return;
	
	var point = new GLatLng(parseFloat(destination.lat['#text']), parseFloat(destination.lon['#text']));
	

	var marker = new GMarker(point, {icon: destinationIcon});
	destination.marker = marker;
	
	GEvent.addListener(marker, "mouseover", function() {
		showDestination(destination);
	});
	
	GEvent.addListener(marker, "mouseout", function() {
		hideDestination(destination);
	});
	
	GEvent.addListener(marker, "click", function() {
		destinationClicked(destination);
	});
	
	if(mapBounds) mapBounds.extend(point);
	map.addOverlay(marker);
	
	
	
	
}



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);
		dimAllTrips();
	} catch(e) {}
}

function guideClicked(guide) {
	var url = guide.url['#text'] ? guide.url['#text'] : guide.url;
	
	top.location.href="/guide/" + url;
}

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

function showGuideDiv(guide) {
	return _showGuideDiv(guide);
}

function _showGuideDiv(guide) {
	if(!guide.marker) return;
	
	var bounds = map.getBounds();
	
	if(!bounds.containsLatLng(guide.marker.getPoint())) return;
	
	
	var divWidth = 0;
	guideDiv.innerHTML = "";
	var title = guide.title['#text'] ? guide.title['#text'] : guide.title;
	if(showCalloutDetails) {
		var divWidth = 300;
		var html = "";
		if(guide.picture) {
			var thumb = guide.picture.thumbnail['#text'];
		
			var picDiv = '<div style="margin-right:6px;" class="left">'+ squareThumbnail(thumb, 75, 130, "", null)  +'</div>';
			html = picDiv;
		}

		html += "<div style='overflow:hidden'>";
		
		html += '<div class="title">'+title+'</div>';
		if(guide.num_reviews) {
			var avgVote = parseFloat(guide.avg_review['#text']);
			var numVotes = parseInt(guide.num_reviews['#text']);
	
			if(avgVote > 0) html += "<div class='left' style='height:17px'>"+ ratingHTML(avgVote) + "</div>";
			if(numVotes > 0) html += '<div class="num-reviews" style="height:17px">'+ numVotes + " " + (numVotes == 1 ? "review" : "reviews") +'</div>';
			html += "<div style='clear:right'></div>";
		}
		
		
		if(guide.difficulty || guide.distance) {
			html += "<div>";
			
			var difficulty = guide.difficulty['#text'];
			if(difficulty != "unknown") {
				html += difficulty;
			} else {
				difficulty = null;
			}
		
			
			var length = parseFloat(guide.distance['#text']);
			if(length && difficulty) html += ", ";
			
			if(length) {
				html += distanceString(length, units);
			}
			
			html += "</div>";
		}	
		html += "</div>";
		html += "<div class='clear'></div>";
		guideDiv.innerHTML = html;
	} else {
		guideDiv.innerHTML = "<b>" + title + "</b>";
	}
	
	
	// position div
	var topLeft = new GLatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng());
	var bottomRight = new GLatLng(bounds.getSouthWest().lat(), bounds.getNorthEast().lng());
	var px1 = map.fromLatLngToDivPixel(guide.marker.getPoint());
	var px2 = map.fromLatLngToDivPixel(topLeft);
	var brPx = map.fromLatLngToDivPixel(bottomRight);
	
	var offset = new GPoint(2,0);
	var x = px1.x-px2.x + offset.x; // difference from left to point
	var y = px1.y-px2.y + offset.y; // difference from top to point
	
	
	if(guideDiv.style.minWidth) divWidth = guideDiv.style.minWidth.replace("px", "");
	if(guideDiv.style.width) divWidth = guideDiv.style.width.replace("px", "");
	if(x + divWidth > brPx.x - px2.x) {
		
		x = brPx.x - px2.x- divWidth;
	}



	guideDiv.style.visibility = "visible";
	guideDiv.style.top = y + 'px';
	guideDiv.style.left = x + 'px';
}

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


// trips

function addTripTracks(trip) {
	// tracks
	if(trip.tracks && trip.tracks.length > 0) {
		for(var i=0; i<trip.tracks.length; i++) {
			
			// check for encoded polylines
			if(trip.tracks[i].encoded_polyline && trip.tracks[i].encoded_polyline.Points && trip.tracks[i].encoded_polyline.Levels) {
				
				if(trip.tracks[i].polyline) continue;
				
				trip.tracks[i].polyline = GPolyline.fromEncoded({
				    color: TRACK_COLOR,
				    weight: TRACK_WEIGHT,
					opacity: TRACK_OPACITY,
				    points: trip.tracks[i].encoded_polyline.Points,
				    levels: trip.tracks[i].encoded_polyline.Levels,
					zoomFactor: trip.tracks[i].encoded_polyline.ZoomFactor,
					numLevels: trip.tracks[i].encoded_polyline.NumLevels
				});
			
				map.addOverlay(trip.tracks[i].polyline);
				
				
				var lineBounds = trip.tracks[i].polyline.getBounds();
				if (mapBounds && lineBounds) {
					mapBounds.extend(lineBounds.getSouthWest());
					mapBounds.extend(lineBounds.getNorthEast());
				}
			
				GEvent.addListener(trip.tracks[i].polyline, "mouseover", function() {
					showTrip(trip);
				});

				GEvent.addListener(trip.tracks[i].polyline, "mouseout", function() {
					hideTrip(trip);
				});
			
			}
		}
	}
}




function addTrip(trip) {
	if(trip.lat == null || trip.lon == null) return;
	
	var lat = trip.lat['#text'] !== undefined && trip.lat['#text'] !== null ? parseFloat(trip.lat['#text']) : trip.lat;
	var lon = trip.lon['#text'] !== undefined && trip.lon['#text'] !== null ? parseFloat(trip.lon['#text']) : trip.lon;
	
	var point = new GLatLng(lat, lon);
	
	var marker = new GMarker(point, {icon: tripIcon, zIndexProcess:orderTripMarkers});
	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);

}


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;
	
	// change tracks
	try {
		showTripTracks(trip);
		dimAllGuides();
		dimAllTrips(trip);
	} catch(e) {}
}

function tripClicked(trip) {
	var tripId = trip['@id'] ? trip['@id'] : trip.tripId;
	
	top.location.href="/view_trip.php?trip_id=" + tripId;
}

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

/*
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 showTripDiv(t) {
	if(!t.marker) return;
	
	var bounds = map.getBounds();
	if(!bounds.containsLatLng(t.marker.getPoint())) return;


	var html = "";
	tripDiv.innerHTML = "";
	var title = t.name['#text'] ? t.name['#text'] : t.name;
	
	
	var divWidth = 0;
	if(showCalloutDetails) {
		var divWidth = 300;
		if(t.picture) {
			var thumb = t.picture.thumbnail['#text'];
		
			var picDiv = '<div style="margin-right:6px" class="left">'+ squareThumbnail(thumb, 75, 130, "", null)  +'</div>';
			html = picDiv;
		}
		
		html += '<div style="overflow:hidden">';
		html += '<div class="title">'+title+'</div>';
		if(t.num_votes) {
			var avgVote = parseFloat(t.avg_vote['#text']);
			var numVotes = parseInt(t.num_votes['#text']);
			
			if(avgVote > 0) html += "<div class='left' style='height:17px'>"+ ratingHTML(avgVote) + "</div>";
			if(numVotes > 0) html += '<div class="num-reviews" style="height:17px">'+ numVotes + " " + (numVotes == 1 ? "vote" : "votes") +'</div>';
			html += "<div style='clear:right'></div>";
		}
		
		
		if(t.distance) {
			html += "<div>";
			var length = parseFloat(t.distance['#text']);
			if(length) {
				html += distanceString(length, units);
			}
			html += "</div>";
		}
		html += "</div>";
		html += "<div class='clear'></div>";
	} else {
		html = "<b>" + title + "</b>";
	}
	
	tripDiv.innerHTML = html;
	
	
	// position div

	
	var topLeft = new GLatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng());
	var bottomRight = new GLatLng(bounds.getSouthWest().lat(), bounds.getNorthEast().lng());
	var px1 = map.fromLatLngToDivPixel(t.marker.getPoint());
	var px2 = map.fromLatLngToDivPixel(topLeft);
	var brPx = map.fromLatLngToDivPixel(bottomRight);
	var x = px1.x-px2.x; // difference from left to point
	var y = px1.y-px2.y; // difference from top to point
	
	
	if(tripDiv.style.minWidth) divWidth = tripDiv.style.minWidth.replace("px", "");
	if(tripDiv.style.width) divWidth = tripDiv.style.width.replace("px", "");
	if(x + divWidth > brPx.x) {
		x = brPx.x - divWidth;
	}
	
	var offset = new GPoint(2,0);
	tripDiv.style.visibility = "visible";
	tripDiv.style.top = y + offset.y + 'px';
	tripDiv.style.left = x + offset.x + 'px';
}






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


function showSectionDiv(section) {
	if(!section.marker) return;
	
	sectionDiv.style.visibility = "visible";
	var html = "";
	if(section.type) {
		html += '<img src="'+ section.type.icon +'" title="'+ section.type.name +'" align="left" style="vertical-align:top; margin-right: 4px">';
	}
	
	html += "<b>" + section.title + "</b>";

	sectionDiv.innerHTML = html;

	var px1 = map.fromLatLngToDivPixel(section.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);

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


function orderGuideMarkers(marker) {
	return 5;
}

function orderDestinationMarkers(marker) {
	
}

function orderTripMarkers(marker) {
	return 1;
}

function orderSectionMarkers(marker) {
	return 1;
}

function hideSectionDiv() {
	sectionDiv.style.visibility = "hidden";
}



// destinations
function showDestination(d) {
	if(activeDestination) hideDestination(d);
	showDestinationDiv(d);

	// change pin
	activeDestination = d;
}

function destinationClicked(d) {
	top.location.href="/destination/" + d.url['#text'];
}

function hideDestination(d) {
	hideDestinationDiv();
	// change pin
}

function showDestinationDiv(d) {
	if(!d.marker) return;
	
	var bounds = map.getBounds();
	if(!bounds.containsLatLng(d.marker.getPoint())) return;
	

	var html = "";
	destinationDiv.innerHTML = "";
	var title = d.title['#text'] ? d.title['#text'] : d.title;
	
	
	var divWidth = 0;
	if(showCalloutDetails) {
		var divWidth = 300;
		if(d.picture) {
			var thumb = d.picture.thumbnail['#text'];
		
			var picDiv = '<div style="margin-right:6px" class="left">'+ squareThumbnail(thumb, 75, 130, "", null)  +'</div>';
			html = picDiv;
		}
		
		html += '<div class="title">'+title+'</div>';
		if(d.num_reviews) {
			var avgVote = parseFloat(d.avg_review['#text']);
			var numVotes = parseInt(d.num_reviews['#text']);
			
			if(avgVote > 0) html += "<div class='left' style='height:17px'>"+ ratingHTML(avgVote) + "</div>";
			if(numVotes > 0) html += '<div class="num-reviews" style="height:17px">'+ numVotes + " " + (numVotes == 1 ? "review" : "reviews") +'</div>';
			html += "<div style='clear:right'></div>";
		}
		
		
		if(d.num_guides || d.num_trips) {
			html += "<div>";
			var num_guides = parseInt(d.num_guides['#text']);
			var num_trips = parseInt(d.num_trips['#text']);
			
			if(num_guides) html += num_guides + " " + (num_guides == 1 ? "Guide" : "Guides");
			if(num_guides && num_trips) html += ", ";
			if(num_trips) html += num_trips +  " " + (num_trips == 1 ? "Community Trip" : "Community Trips");
		
			html.innerHTML += "</div>";
		}
		
		html += "<div class='clear'></div>";
	} else {
		html = "<b>" + title + "</b>";
	}
	
	destinationDiv.innerHTML = html;
	
	
	// position div

	
	var topLeft = new GLatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng());
	var bottomRight = new GLatLng(bounds.getSouthWest().lat(), bounds.getNorthEast().lng());
	var px1 = map.fromLatLngToDivPixel(d.marker.getPoint());
	var px2 = map.fromLatLngToDivPixel(topLeft);
	var brPx = map.fromLatLngToDivPixel(bottomRight);
	var x = px1.x-px2.x; // difference from left to point
	var y = px1.y-px2.y; // difference from top to point
	
	
	if(destinationDiv.style.minWidth) divWidth = destinationDiv.style.minWidth.replace("px", "");
	if(destinationDiv.style.width) divWidth = destinationDiv.style.width.replace("px", "");
	if(x + divWidth > brPx.x) {
		x = brPx.x - divWidth;
	}
	
	var offset = new GPoint(2,0);
	destinationDiv.style.visibility = "visible";
	destinationDiv.style.top = y + offset.y + 'px';
	destinationDiv.style.left = x + offset.x + 'px';
}

function hideDestinationDiv() {
	destinationDiv.style.visibility = "hidden";
}




function resetGuideOpacity(guide) {
	if(guide.tracks == null) return;
	
	for(var i=0; i<guide.tracks.length; i++) {
		if(guide.tracks[i].polyline) {
			guide.tracks[i].polyline.setStrokeStyle({"opacity":TRACK_OPACITY});
		} else {
			for(var j=0; j<guide.tracks[i]['trksegs'].length; j++) {
				if(guide.tracks[i]['trksegs'][j].polyline) {
					guide.tracks[i]['trksegs'][j].polyline.setStrokeStyle({"opacity":TRACK_OPACITY});
				}
			}
		}
	}
}

function showGuideTracks(guide) {
	if(guide.tracks == null) return;
	
	
	for(var i=0; i<guide.tracks.length; i++) {
		
		if(guide.tracks[i].polyline) {
			guide.tracks[i].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_STRONG});
		} else {
			for(var j=0; j<guide.tracks[i]['trksegs'].length; j++) {
				if(guide.tracks[i]['trksegs'][j].polyline) {
					guide.tracks[i]['trksegs'][j].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_STRONG});
				}
			}
		}
	}
}

function dimGuideTracks(guide) {
	if(guide.tracks == null) return;
	
	for(var i=0; i<guide.tracks.length; i++) {
		if(guide.tracks[i].polyline) {
			guide.tracks[i].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_DIM});
		} else {
			for(var j=0; j<guide.tracks[i]['trksegs'].length; j++) {
				if(guide.tracks[i]['trksegs'][j].polyline) {
					guide.tracks[i]['trksegs'][j].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_DIM});
				}
			}
		}
	}
}

function dimAllGuides(exception) {
	for(var i=0; i<guides.length; i++) {
		if(exception && exception.index == guides[i].index && exception.url == guides[i].url) continue;
		
		dimGuideTracks(guides[i]);
	}
}

function resetGuideColors() {
	for(var i=0; i<guides.length; i++) {
		resetGuideOpacity(guides[i]);
	}
}



// trip tracks
function resetTripOpacity(trip) {
	if(trip.tracks == null) return;
	
	for(var i=0; i<trip.tracks.length; i++) {
		if(trip.tracks[i].polyline) {
			trip.tracks[i].polyline.setStrokeStyle({"opacity":TRACK_OPACITY});
		} else {
			for(var j=0; j<trip.tracks[i]['trksegs'].length; j++) {
				if(trip.tracks[i]['trksegs'][j].polyline) {
					trip.tracks[i]['trksegs'][j].polyline.setStrokeStyle({"opacity":TRACK_OPACITY});
				}
			}
		}
	}
}

function showTripTracks(trip) {
	if(trip.tracks == null) return;
	
	
	for(var i=0; i<trip.tracks.length; i++) {
		
		if(trip.tracks[i].polyline) {
			trip.tracks[i].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_STRONG});
		} else {
			for(var j=0; j<trip.tracks[i]['trksegs'].length; j++) {
				if(trip.tracks[i]['trksegs'][j].polyline) {
					trip.tracks[i]['trksegs'][j].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_STRONG});
				}
			}
		}
	}
}

function dimTripTracks(trip) {
	if(trip.tracks == null) return;
	
	for(var i=0; i<trip.tracks.length; i++) {
		if(trip.tracks[i].polyline) {
			trip.tracks[i].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_DIM});
		} else {
			for(var j=0; j<trip.tracks[i]['trksegs'].length; j++) {
				if(trip.tracks[i]['trksegs'][j].polyline) {
					trip.tracks[i]['trksegs'][j].polyline.setStrokeStyle({"opacity":TRACK_OPACITY_DIM});
				}
			}
		}
	}
}

function dimAllTrips(exception) {
	
	for(var i=0; i<trips.length; i++) {		
		if(exception && exception['@id'] == trips[i]['@id']) continue;
		
		dimTripTracks(trips[i]);
	}
}

function resetTripColors() {
	for(var i=0; i<trips.length; i++) {
		resetTripOpacity(trips[i]);
	}
}



