//<![CDATA[

//list of markers
var mkrList= new Array();

function getElevation() {
	var ele = map.getCenter();
	getElevationAtLatLng( ele, "elevation");
}

//call locla USGS proxy (using REST)
function getElevationAtLatLng(latlng,elemName) {

	try {
	document.getElementById(elemName).value = "loading...";
	document.getElementById("getEle").disabled = true;

	this.ajaxObj = createAjaxObj();

	ajaxObj.onreadystatechange = function () {
	if (ajaxObj.readyState == 4) {
		if (ajaxObj.status==200 || ajaxObj.status==302 || ajaxObj.status==304)
		{ //if request was successful
			var xmldata=ajaxObj.responseXML;
							
			if (xmldata.getElementsByTagName("string").length==0)
			{
				document.getElementById(elemName).value="ERROR: "+ajaxObj.responseText;
			}
			else {
				var ele = xmldata.getElementsByTagName("string")[0].firstChild.nodeValue;
				if(ele < 0) { ele = "0.0"; } //sometimes usgs returns <0 (for valid lat/long)
				document.getElementById(elemName).value = parseInt(ele*footRatio);
				
			}
		}
		else {
			alert('There was a problem with the request: ' + ajaxObj.status);
			}	
		document.getElementById("getEle").disabled = false;
	} 
	
	} //end func;

	ajaxObj.open("GET", "/cgi-bin/get_elevation.cgi?latLong=" + latlng.lat().toFixed(6) + "," + latlng.lng().toFixed(6));
	ajaxObj.send(null);

	} catch(e) { alert("ERROR getting elevation: " + e); }
}

function doIconSizeChange(map,zoomLevel,zoomedIn) {
	return;
}

//as of gmap v2.65 19 is zoomed all the way in, 0 is all the way out
function getZoomIconMagicNum(lvl) {
	var factor = -16;
	if(lvl <= 9) {
		if(lvl <= 4) { factor = factor - 8; }
		//extra small
		factor = factor - 2;	
	}

	//we're zoomed in at
	return (factor + lvl);
}

//takes in a hashtable of addresses/links, creates markers out of them
function geoCodeTable(map, addrTable, iconType) {
	var latLonTable = getLatLongTable();
	var sizeChg = -5;
	var icon = new GIcon();
	if(iconType == 0) {
		icon.image = "/images/s_cam.png";

		icon.iconSize = new GSize(32+sizeChg,36+sizeChg);
		icon.infoWindowAnchor= new GPoint(32+sizeChg,36+sizeChg);
		//icon.shadow = "/images/s_cam_shadow.png";
	}
	else if(iconType == 1)
	{
		icon.image = "/images/warning.png";
		var defSize = 16;
		if((defSize + sizeChg > 2)) {
			icon.iconSize = new GSize(defSize+sizeChg,defSize+sizeChg);
			icon.infoWindowAnchor= new GPoint(defSize+sizeChg,defSize+sizeChg); //32,32
		}
		else 
		{ 
			icon.iconSize = new GSize(2,2);
			icon.infoWindowAnchor= new GPoint(2,2);
		}
	}
	else if(iconType == 2) {
		icon.image = "/images/cycle_hill.png";
		icon.iconSize = new GSize(30+sizeChg,30+sizeChg);
		icon.infoWindowAnchor= new GPoint(30+sizeChg,30+sizeChg);
	}
	else if(iconType == 3) {
		icon.image = "/images/slr_cam.png";
		icon.iconSize = new GSize(32+sizeChg,28+sizeChg);
		icon.infoWindowAnchor= new GPoint(32+sizeChg,28+sizeChg);
	}
	else if(iconType == 4) {
		icon.image = "/images/video.png";
		icon.iconSize = new GSize(35+sizeChg,25+sizeChg);
		icon.infoWindowAnchor= new GPoint(35+sizeChg,25+sizeChg);
	}
	else if(iconType == 5) { //high points
		icon.image = "/images/graph.png";
		icon.iconSize = new GSize(32+sizeChg,19+sizeChg);
		icon.infoWindowAnchor= new GPoint(32+sizeChg,19+sizeChg);
	}

	icon.iconAnchor = new GPoint(16,16);
	

	if(this.mkrList.length>0) {
		this.mkrList = new Array();
	}

	var marker;	
	for (var addr in addrTable) {
		
		marker = createWebCamMarker(latLonTable[addr], addr, addrTable[addr], icon, iconType);
		this.mkrList.push(marker);

		if(marker != null) {
			map.addOverlay(marker);
		}
	}
}

//clear overlays
function showHideMarkers() {
	if(this.markersShown) {
	this.map.clearOverlays();
	this.markersShown = false;
	}
	else {
	loadMarkers(); 
	}
}

//load all of the markers
function loadMarkers() {
	this.markersShown = true;
	geoCodeTable(map, getWebCamData(), 0);
	geoCodeTable(map, getWarningSites(), 1);
	geoCodeTable(map, getHills(), 2);	
	geoCodeTable(map, getInfoData(), 3);	
	geoCodeTable(map, getVideos(), 4);	
	geoCodeTable(map, getHighPoints(), 5);
}

//load special routes
function loadRoutes() {
	drawRoute(map,getNoGoRoutes(),badRouteColor,.75); 

	drawRoute(map, getTrails(),trailColor,1);
}

//from a |-delim string
function drawRoute(map, routeMap, color) {
	for(var i in routeMap) {
		loadRouteFromString(routeMap[i].toString().split("|"),color);
	}
}

//hide/show the info bar
function hideShowInfoBar() {
	
	if(this.infoBarShown == false) { //show
		
		this.infoBarShown=true;
		showInfoBar();
	}
	else { //hide
		this.infoBarShown=false;
		hideInfoBar();
	}
}

function showInfoBar() {
	var d = document.getElementById('infoBar');
	d.addChild(this.infoBarCopy);
}

function hideInfoBar() {
	var d = getElem('infoBar');
	var olddiv = getElem('childDiv');
	d.removeChild(olddiv);
	getElem("map").style.left="2px";
	getElem("map").style.width="100%";

}

//toggle's local search
function toggleLocalSearch() {
	this.localSearch = !this.localSearch;
}

//create a marker for the lat/long and fill in the link, add evt listener
function createWebCamMarker(latLong, name, link, icon, iconType) {
		if(latLong == null || latLong == 'null')
		{ return null; }

		var str;
		//link to page or image?
		if(iconType < 2 && imgRegex.test(link)) {
			str = '<HTML><IMG HEIGHT="300" WIDTH="320" SRC="' + link + '"></IMG></HTML>';
		}
		else if(iconType ==0) //link of some kind
		{
			str = '<HTML><A TARGET="about:blank" HREF="' + link + '">' + name + '</A>&nbsp;&nbsp;</HTML>';
		}
		else if(iconType == 1 || iconType == 4 || iconType == 5) { //warning
			str = '<HTML>' + link + '</HTML>';
		}
		else if(iconType == 2 || iconType == 3) {
			str = '<HTML>' + link + '&nbsp;&nbsp;</HTML>';
		}
		
		var marker = new GMarker(latLong, icon);
					
		//add event handler
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(str); 
		});
		return marker
} //end func


//show/hide king county bike map
function showKCMap() {

	var photo = new TPhoto();
	photo.id = 'king_county_bike_map';

	if(this.kcmap) {
	this.kcmap = false;
	document.getElementById("kcmap").value = "show";
	map.removeTPhoto(photo);
	}
	else {

	map.clearOverlays();

	photo.src = 'http://veloroutes.googlepages.com/King_County_North.jpg';

	photo.percentOpacity = 65;
	photo.anchorTopLeft = new GLatLng(47.782481174472856, -122.4814224243164);
	photo.anchorBottomRight = new GLatLng(47.38858773975688, -121.63169860839844);
		
	map.addTPhoto(photo);

	document.getElementById("kcmap").value = "hide";	
	this.kcmap = true;
	}
} //end showKCmap

//show/hide puget speed map
function showPugetSpeedMap() {

	var photo = new TPhoto();
	photo.id = 'speed_map';

	if(this.speedmap) {
	this.speedmap = false;
	document.getElementById("speedmap").value = "show";
	map.removeTPhoto(photo);
	}
	else {

	photo.src = '/bikemaps/tiles/pugetspeed.png';
	photo.percentOpacity = 75;
	
	var pnt = new GLatLng(47.883197, -122.096558);
	panToSite(pnt, 10);
	
	photo.anchorTopLeft = new GLatLng(48.24525380784484, -122.50648498535156);
	photo.anchorBottomRight = new GLatLng(47.469878, -121.661224);
	map.addTPhoto(photo);

	document.getElementById("speedmap").value = "hide";	
	this.speedmap = true;
	}
} //end showPugetSpeedMap

//show/hide wa speed map
function showWASpeedMap() {

	var photo = new TPhoto();
	photo.id = 'waspeed_map';

	if(this.waspeedmap) {
	this.waspeedmap = false;
	document.getElementById("waspeedmap").value = "show";
	map.removeTPhoto(photo);
	}
	else {

	photo.src = '/bikemaps/tiles/wa_speed_map.png';
	photo.percentOpacity = 55;
	
	//zoom out a bit
	var pnt = new GLatLng(47.234490, -120.509033);
	panToSite(pnt, 7);

	photo.anchorTopLeft = new GLatLng(49.048670, -124.881592);
	photo.anchorBottomRight = new GLatLng(45.269088, -116.820374);
		
	map.addTPhoto(photo);

	document.getElementById("waspeedmap").value = "hide";	
	this.waspeedmap = true;
	}
} //end showWASpeedMap

//show/hide snohomish county bike map
function showSnohomishMap() {

	var photo = new TPhoto();
	photo.id = 'sno_county_bike_map';

	if(this.snomap) {
	this.snomap = false;
	document.getElementById("snomap").value = "show";
	map.removeTPhoto(photo);
	}
	else {

	photo.src = 'http://veloroutes.googlepages.com/snohomish_county.jpg';
	photo.percentOpacity = 75;
	photo.anchorTopLeft = new GLatLng(48.263884, -122.401257);
	photo.anchorBottomRight = new GLatLng(47.79286140021344, -121.91116333007812);
	panToSite(new GLatLng(48.04595573996009, -122.15423583984375), 11);
	map.addTPhoto(photo);
	document.getElementById("snomap").value = "hide";	
	this.snomap = true;
	}
} //end showSnomap


//add bike-map layer
function addExtraMaps(map) {
	map.addMapType(WMS_TOPO_MAP);
	map.addMapType(WMS_NEXRAD_MAP);
	
	map.addControl(new RoutesControl());

}

//from acme.com
function WMSGetTileUrl(tile,zoom)
{
	var southWestPixel=new GPoint(tile.x*256,(tile.y+1)*256);
	var northEastPixel=new GPoint((tile.x+1)*256,tile.y*256);
	var southWestCoords=G_NORMAL_MAP.getProjection().fromPixelToLatLng(southWestPixel,zoom);
	var northEastCoords=G_NORMAL_MAP.getProjection().fromPixelToLatLng(northEastPixel,zoom);
	var bbox=southWestCoords.lng()+','+southWestCoords.lat()+','+northEastCoords.lng()+','+northEastCoords.lat();
	var transparency=this.transparent?'&TRANSPARENT=TRUE':'';
	return this.baseUrl+'?VERSION=1.1.1&REQUEST=GetMap&LAYERS='+this.layer+'&STYLES=&SRS=EPSG:4326&BBOX='+bbox+'&WIDTH=256&HEIGHT=256&FORMAT='+this.format+'&BGCOLOR=0xCCCCCC&EXCEPTIONS=INIMAGE'+transparency;
}

	var WMS_TOPO_MAP=CreateMap('Elevation','Images by USGS / Service by TerraServer','http://www.terraserver-usa.com/ogcmap6.ashx','DRG','image/jpeg',false,4,17,[],'o');
	var WMS_NEXRAD_MAP=CreateMap('Radar','Data by NWS / Service by Iowa U. Ag. Dept.','http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi','nexrad-n0r','image/png',true,4,10,G_SATELLITE_MAP.getTileLayers(),'n');//HYBRID
	
function CreateMap(name,copyright,baseUrl,layer,format,transparent,minResolution,maxResolution,extraTileLayers,urlArg)
{
var tileLayer=new GTileLayer(new GCopyrightCollection(copyright),minResolution,maxResolution);
tileLayer.baseUrl=baseUrl;tileLayer.layer=layer;tileLayer.format=format;tileLayer.transparent=transparent;
tileLayer.getTileUrl=WMSGetTileUrl;
tileLayer.getCopyright=function(){return{prefix:'',copyrightTexts:[copyright]};};
var tileLayers=[];
for(var i in extraTileLayers) {tileLayers.push(extraTileLayers[i]);}
tileLayers.push(tileLayer);
var _mMapError=false;//for 2.94
return new GMapType(tileLayers,G_SATELLITE_MAP.getProjection(),name,{errorMessage:_mMapError,urlArg:urlArg});
}
//end from acme.com


function RoutesControl() {
}
RoutesControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
RoutesControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var routesDiv = document.createElement("div");
  this.setButtonStyle_(routesDiv);
  container.appendChild(routesDiv);
  routesDiv.appendChild(document.createTextNode("Routes"));
  GEvent.addDomListener(routesDiv, "click", function() {
    map.clearOverlays();
     var geoXml = new GGeoXml("http://veloroutes.org/rss/?n=100&l=1");

     map.addOverlay(geoXml);
  });

  
  map.getContainer().appendChild(container);
  return container;
}

RoutesControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 37));
}

// Sets the proper CSS for the given button element.
RoutesControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "2px";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
}




//]]>

