var TrailLine,Marker,PictureMarker,map;
var gdir;
var addressMarker;
var PictureMarkers;
var geocoder,countrycode,admincode;
var MapOverlays =[];
var inSlideShow;
var timeoutID;
var Pix;
var MapMode = {"EditTrail" : 0, "AddPictures" : 1, "View" : 2}; 
var TrailID;

function handleErrors()
{
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR){
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY){
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_BAD_KEY){
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	}
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST){
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	}
	else{
		alert("An unknown error occurred.");
	}
}


function addPicture(tripReport)
{
	if(tripReport == null)
	{
		tripReport = 0;
	}
	else
	{
		tripReport = 1;
	}
	
	if(Pix == null)
	{
		Pix = [];
	}
	var index = Pix.length;
	Pix[index] = [];
	Pix[index].Marker = new GMarker(map.getCenter(), {draggable: true});
	map.addOverlay(Pix[index].Marker);
	Pix[index].Marker.openInfoWindowHtml("This is your picture marker.<br />Drag it to the location that the picture was taken.");
	
	GEvent.addListener(Pix[index].Marker, "dragstart", function() {
		map.closeInfoWindow();
	});
	
	GEvent.addListener(Pix[index].Marker, "dragend", function() {
		Pix[index].Marker.openInfoWindowHtml(
		"<div style='margin: 5px;'>" +
			"<form action='/ImageUploads/upload.php' method='post' enctype='multipart/form-data' onsubmit=\"return AIM.submit(this, {'onLoad' : PicStartCallback, 'onComplete' : PicCompleteCallback})\">" +
			"<input type='file' name='file' id='file' /> <br />"+
			"<textarea cols='25' rows='3' name='description' id='description'>Picture Description</textarea><br />"+
			"<input type='hidden' name='lat' id='lat' value='"+Pix[index].Marker.getLatLng().lat()+"' />"+
			"<input type='hidden' name='lng' id='lng' value='"+Pix[index].Marker.getLatLng().lng()+"' />"+
			"<input type='hidden' name='tripReport' id='tripReport' value='"+tripReport+"' />"+
			"<input type='submit' name='submit' value='Upload' />"+
			"</form>" +
		"</div>");
	});
}

function PicStartCallback() {
	var index = Pix.length-1;
	var markup = "<div style='margin: 3px; text-align: center;'><img src='images/loading.gif' alt='' /><br /><strong>Loading</strong></div>";
	Pix[index].Marker.openInfoWindowHtml(markup);
    return true;
}

function PicCompleteCallback(response) {
	if(AIM.load != -1)
	{
		clearTimeout(AIM.load);
		AIM.load = -1;
	}

	var index = Pix.length-1;
	var PictureInfo = [];
	var markup;
	eval( "PictureInfo[index] = " + response);
	if(PictureInfo[index].length == 1)
	{
		markup = "<div style='margin: 3px; width: 200px;'><strong>"+PictureInfo[index].error+"</strong></div>";
		Pix[index].Marker.openInfoWindowHtml(markup);
		GEvent.clearListeners(Pix[index].Marker);
	}
	else
	{
		markup = "<div style='margin: 3px; height: 200px;'><strong>"+PictureInfo[index].name+"</strong><br /><img src='"+PictureInfo[index].url+"' alt='' /><br /><p>"+PictureInfo[index].description+"</p></div>";
	
		Pix[index].Marker.openInfoWindowHtml(markup);
		Pix[index].Marker.bindInfoWindowHtml(markup);
		
		GEvent.clearListeners(Pix[index].Marker);
		
		GEvent.addListener(Pix[index].Marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		
		GEvent.addListener(Pix[index].Marker, "dragend", function() {
			var xmlHttp=new XMLHttpRequest();
			var i;
			for(i=0;i<Pix.length;i++)
			{
				if(this == Pix[index].Marker)
				{
					break;
				}
			}
			xmlHttp.open("GET","DoMoveImage.php?number="+PictureInfo[index].id+"&lat="+this.getLatLng().lat()+"&lng="+this.getLatLng().lng());
			xmlHttp.send(null);
		});
	}
	
}

function addTrailHead()
{
	if(Marker != null)
	{
		map.removeOverlay(Marker);
		map.removeOverlay(TrailLine);
		Marker = null;
		TrailLine = null;
	}
	Marker = new GMarker(map.getCenter(), {draggable: true});
	map.addOverlay(Marker);
	Marker.openInfoWindowHtml('<div style="width: 300px;">This is your trailhead.<br/>Drag it to the correct location to begin setting a trail.</div>');

	GEvent.addListener(Marker, "dragstart", function() {
	  map.closeInfoWindow();
	});

	GEvent.addListener(Marker, "dragend", function() {

		if(TrailLine != null)
		{
			TrailLine.deleteVertex(0);
			TrailLine.insertVertex(0,Marker.getLatLng());
		}
		else
		{
			Marker.openInfoWindowHtml('<div style="width: 300px;">Click along the map to set waypoints for your trail. Click on the last node twice to finish.</div>');
			TrailLine = new GPolyline( [Marker.getLatLng()], "#FF1111",  5);
			map.addOverlay(TrailLine);
			TrailLine.enableDrawing({});
			TrailLine.enableEditing({onEvent: "mouseover"});
			TrailLine.disableEditing({onEvent: "mouseout"});
		
			GEvent.addListener(TrailLine, "endline", function() {
			Marker.openInfoWindowHtml('<div style="width: 300px;">Now that you have created a trail, fill in the description below and submit it.</div>');
			
			document.getElementById('Length').value = GetTrailLength();
			});
			
			GEvent.addListener(TrailLine, "lineupdated", function() {
				if(Marker.getLatLng() != TrailLine.getVertex(0) )
				{
					Marker.setLatLng(TrailLine.getVertex(0));
				}
				document.getElementById('Length').value = GetTrailLength()
			});
			
		}
	});
}

function GetTrailLength()
{
	var RoundTrip = 2;
	if(Math.sqrt(Math.pow(Math.abs(TrailLine.getVertex(0).lat() - TrailLine.getVertex(TrailLine.getVertexCount()-1).lat()),2) + 
	Math.pow(Math.abs(TrailLine.getVertex(0).lng() - TrailLine.getVertex(TrailLine.getVertexCount()-1).lng()),2)) <  0.00054)
	{
		RoundTrip = 1;
	}
	
	var len = TrailLine.getLength() * RoundTrip;
	return (Math.round((len*0.621371192) / 10) / 100);
}

function drawStringRoute(stringRoute)
{
	var bounds = new GLatLngBounds();
	var Marker;
	var route = stringRoute.split('|');
	var trail = [];
	for (var i=0;i<route.length;i++){
		var latlon = route[i].split(',');
		if(i===0)
		{
			Marker = new GMarker(map.getCenter(), {draggable: true});
		}
		trail[i] = new GLatLng(latlon[0], latlon[1]);
		bounds.extend(trail[i]);
	}
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
	
	TrailLine = new GPolyline( trail, "#FF1111",  10);
	map.addOverlay(TrailLine);

	TrailLine.enableEditing({onEvent: "mouseover"});
	TrailLine.disableEditing({onEvent: "mouseout"});

	GEvent.addListener(TrailLine, "lineupdated", function() {
		if(Marker.getLatLng() != TrailLine.getVertex(0) )
		{
			Marker.setLatLng(TrailLine.getVertex(0));
		}
		document.getElementById('Length').value = GetTrailLength();
	});
			
	var len = TrailLine.getLength();
	document.getElementById('Length').value = GetTrailLength();
	Marker.openInfoWindowHtml('<div style="width: 300px;">Now that you have created a trail, fill in the description below and submit it.</div>');
}

function GPXstartCallback() {
	return true;
}

function GPXcompleteCallback(response) {
	drawStringRoute(response);
	ToggleGPXForm();
}
		
AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },
	
	load : -1,

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onLoad) == 'function') {
			AIM.load = setTimeout(c.onLoad, 1000);
        }
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        } else {
            return true;
        }
    },

    loaded : function(id) {
		var d;
        var i = document.getElementById(id);
        if (i.contentDocument) {
            d = i.contentDocument;
        } else if (i.contentWindow) {
            d = i.contentWindow.document;
        } else {
            d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }

        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }
};

function ToggleMapType()
{
	var MapType = map.getCurrentMapType();
	if(MapType == G_PHYSICAL_MAP)
		map.setMapType(G_NORMAL_MAP);
	else if(MapType == G_NORMAL_MAP)
		map.setMapType(G_SATELLITE_MAP);
	else
		map.setMapType(G_PHYSICAL_MAP);
}

function ToggleGPXForm()
{
	var form = document.getElementById("GPXUploadForm");

	if(form.style.display == "none")
		form.style.display = "block";
	else
		form.style.display = "none";

	//Stupid hack to make IE correctly collapse the div.
	var mainDiv = document.getElementById("content");
	mainDiv.style.display = "none";
	mainDiv.style.display = "block";
	//End stupid hack
}

//var MapMode = {"EditTrail" : 0, "AddPictures" : 1, "View" : 2}; 
function MapControl(mode) 
{
	this.MapMode = mode;
}

MapControl.prototype = new GControl();
MapControl.prototype.initialize = function(map) {
	var outerContainer = document.createElement("div");
	var leftLoc;

	if(this.MapMode == MapMode.View)
	{
		leftLoc = "90px";
		outerContainer.style.width = "20%";
	}
	else if(this.MapMode == MapMode.AddPictures)
	{
		leftLoc = "180px";
		outerContainer.style.width = "28%";
	}
	else
	{
		leftLoc = "500px";
		outerContainer.style.width = "70%";
	}
	var left = document.createElement("img");
	left.src = "images/LeftWhiteEndCap.png";
	left.style.left = "-24px";
	left.style.position = "absolute";
	outerContainer.appendChild(left);
	
	var right = document.createElement("img");
	right.src = "images/RightWhiteEndCap.png";
	right.style.left = leftLoc;
	right.style.position = "absolute";
	outerContainer.appendChild(right);

	var container = document.createElement("div");
	container.style.backgroundImage = "url(images/ToolbarBackground.png)";
	container.style.backgroundRepeat = "repeat-x";
	container.style.height = "24px";
	container.style.width = leftLoc;
	outerContainer.appendChild(container);

	if(this.MapMode == MapMode.EditTrail)
	{
		var resetDiv = document.createElement("span");
		this.setButtonStyle_(resetDiv);
		container.appendChild(resetDiv);
		resetDiv.appendChild(document.createTextNode("Reset Map"));
		GEvent.addDomListener(resetDiv, "click", function() {
			if(TrailID == null)
				map.clearOverlays();
			else
				loadTrail(TrailID,MapMode.EditTrail,null);
		});

		var createDiv = document.createElement("span");
		this.setButtonStyle_(createDiv);
		container.appendChild(createDiv);
		createDiv.appendChild(document.createTextNode("Create New Trailhead"));
		GEvent.addDomListener(createDiv, "click", function() {
			addTrailHead();
		});

		var GpxDiv = document.createElement("span");
		this.setButtonStyle_(GpxDiv);
		container.appendChild(GpxDiv);
		GpxDiv.appendChild(document.createTextNode("Load GPX"));
		GEvent.addDomListener(GpxDiv, "click", function() {
			ToggleGPXForm();
		});

		var pictureDiv = document.createElement("span");
		this.setButtonStyle_(pictureDiv);
		container.appendChild(pictureDiv);
		pictureDiv.appendChild(document.createTextNode("Add Picture"));
		GEvent.addDomListener(pictureDiv, "click", function() {
			addPicture();
		});
	}
	else if(this.MapMode == MapMode.AddPictures)
	{
		var pictureDiv = document.createElement("span");
		this.setButtonStyle_(pictureDiv);
		container.appendChild(pictureDiv);
		pictureDiv.appendChild(document.createTextNode("Add Picture"));
		GEvent.addDomListener(pictureDiv, "click", function() {
			addPicture(1);
		});
	}
	var TypeDiv = document.createElement("span");
	this.setButtonStyle_(TypeDiv);
	container.appendChild(TypeDiv);
	TypeDiv.appendChild(document.createTextNode("Map Type"));
	GEvent.addDomListener(TypeDiv, "click", function() {
		ToggleMapType();
	});
	
	map.getContainer().appendChild(outerContainer);
	return outerContainer;
};

MapControl.prototype.getDefaultPosition = function() {

  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 10));

};

MapControl.prototype.setButtonStyle_ = function(button) {
	button.style.textDecoration = "none";
	button.style.color = "#6688cc";
	//button.style.font = "Tahoma";
	button.style.fontSize = "12px";
	button.style.marginRight = "5px";
	button.style.marginLeft = "20px";
	button.style.marginTop = "0px";
	button.style.marginBottom = "0px";
	button.style.padding = "0px";
	button.style.textAlign = "center";
	button.style.verticalAlign = "middle";
	button.style.cursor = "pointer";
};

function updateRegions()
{		
	var xmlHttp=new XMLHttpRequest();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			eval(xmlHttp.responseText);
			document.getElementById("RegionSpan").innerHTML = shittles["Links"];
			 var i;
		/*	 for(i=0;i<MapOverlays.length;i++)
			 {
				map.removeOverlay(MapOverlays[i]);
			 }
			*/ 
			if( (typeof markerCluster) == 'object')
			{
			markerCluster.clearMarkers();
			}

			MapOverlays = [];
			for(i=0;i<shittles.Markers.length;i++)
			{
				var wtf = new GLatLng(shittles.Markers[i]["lat"], shittles.Markers[i]["lon"]);
				var icon = new GIcon(G_DEFAULT_ICON);
				icon.image = "/images/TrailHead.png";//"http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,6688cc,000000&ext=.png";
				icon.iconSize  = new GSize(33,38);
				icon.iconAnchor  = new GPoint(26,38);
				icon.imageMap = [0,3, 0,38, 33,38, 33,3];

				var dammit = new GMarker(wtf, { title: shittles.Markers[i]["name"], icon: icon });
				var markup = "<div><strong><a href='ViewHike.php?id="+shittles.Markers[i]["id"]+"&amp;name="+escape(shittles.Markers[i]["name"])+"'>"+shittles.Markers[i]["name"]+"</a></strong><p>"+shittles.Markers[i]["length"]+" Miles</p></div>";
				dammit.bindInfoWindowHtml(markup);
				//map.addOverlay(dammit); 
				MapOverlays[i] = dammit;
				
			}
			var style = [{
							url: '/images/Hicon.png',
							height: 38,
							width: 37,
							opt_anchor: [0,20],
							opt_textColor: '#6688cc',
							opt_title: 'Click to Expand'
						}];
			var mcOptions = {gridSize: 40, maxZoom: 12, styles: style};
			markerCluster = new MarkerClusterer(map, MapOverlays, mcOptions);
		}
	};
	
	var RegionFilter = "";
	if(countrycode)
	{
		RegionFilter = "&country="+countrycode;
	}
	else if (admincode)
	{
		RegionFilter = "&region="+admincode;
	}
	
	var sw = map.getBounds().getSouthWest();
	var ne = map.getBounds().getNorthEast();
	xmlHttp.open("GET","FindHikesHelper.php?n="+ne.lat()+"&e="+ne.lng()+"&s="+sw.lat()+"&w="+sw.lng()+RegionFilter,true);
	xmlHttp.send(null);
}

function AddHikeHere()
{
	window.location = "AddHike.php?lat="+map.getCenter().lat()+"&lon="+map.getCenter().lng()+"&zoom="+map.getZoom();
}

function loadSearch(address,country,region)
{
	countrycode = country;
	admincode = region;
	if (GBrowserIsCompatible() === true) 
	{
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(37, -95), 2); //default to US
		map.setMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl3D() );
		
		map.addControl(new MapControl(MapMode.View));
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
	
		geocoder = new GClientGeocoder();

		geocoder.getLocations(
		  address,
		  function(response) {
			if (!response) {
			  alert("Address not found");
			} else {
			  place = response.Placemark[0];

			  point = new GLatLng(place.Point.coordinates[1],
								  place.Point.coordinates[0]);

			  map.setCenter(point, map.getBoundsZoomLevel( new GLatLngBounds( new GLatLng (place.ExtendedData.LatLonBox.south, place.ExtendedData.LatLonBox.west) , 
														new GLatLng(place.ExtendedData.LatLonBox.north, place.ExtendedData.LatLonBox.east))));
			}
		  }
		);
		
		GEvent.addListener(map, "moveend", updateRegions);
	}
}

function load(lat,lon,zoom,showControls) 
{
	if (GBrowserIsCompatible() === true) 
	{
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(lat, lon), zoom);
		map.setMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl3D() );
		if(showControls === true)
		{
			map.addControl(new MapControl(MapMode.EditTrail));
		}

		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
	}
}

function ShowToolTip(object)
{
	if(object == document.getElementById('closebutton'))
	{
		document.getElementById('text').innerHTML="Close full screen mode";
	}
	else if(object == document.getElementById('leftarrow'))
	{
		document.getElementById('text').innerHTML="Show the previous image";
	}
	else if(object == document.getElementById('playbutton'))
	{
		if(inSlideShow)
		{ 
			document.getElementById('text').innerHTML="Stop the slideshow";
		}
		else
		{
			document.getElementById('text').innerHTML="Start a slideshow";
		}
	}
	else if(object == document.getElementById('rightarrow'))
	{
		document.getElementById('text').innerHTML="Show the next image";
	}
}



function ClearToolTip(index)
{
	document.getElementById('text').innerHTML=Pix[index].description;
}

function show(theImg) 
{
	theImg.style.left = ((document.body.clientWidth - theImg.width) / 2) + "px";
	theImg.style.top = (((document.body.clientHeight - theImg.height) / 2)+ document.documentElement.scrollTop) + "px";
	if(theImg.id == "loading")
	{
		theImg.style.zIndex = 5;
	}
	else
	{
		theImg.style.zIndex = 6;
	}
		
}


function hide() 
{
	document.getElementById("mainContent").style.display = "block";
	document.getElementById('ImageViewer').innerHTML="";
	window.clearTimeout(timeoutID);
	inSlideShow = false;
}

function ShowFullPicture(index)
{	
	document.getElementById("mainContent").style.display = "none";
	var playzindex = 7;
	var pausezindex = 3;
    var prevIndex = (index === 0) ? Pix.length - 1 : index - 1;
	var nextIndex = (index == Pix.length - 1) ? 0 : index + 1;
	if(inSlideShow)	
	{
		prevIndex = index;
		index = nextIndex;
		nextIndex = (index == Pix.length - 1) ? 0 : nextIndex + 1;
		timeoutID = window.setTimeout("ShowFullPicture("+index+")",4000);
		playzindex = 3;
		pausezindex = 7;
	}

	var ButtonSource =  "images/PlayButton.png";
	if(inSlideShow)
	{ 
		ButtonSource =  "images/PauseButton.png";
	}
	
    var width = document.body.clientWidth;
	var height = document.body.clientHeight;
	document.getElementById('ImageViewer').innerHTML=
		'<img src="/ImageUploads/upload/'+Pix[nextIndex].number + '.' + Pix[nextIndex].type+'" style="width:100px;height:100px;z-index:2;position:absolute;left:0px;top:0px;">' + //cache next image
		'<img src="/ImageUploads/upload/'+Pix[index].number + '.' + Pix[index].type+'" style="max-height: '+height+'px;max-width: '+width+'px; width: expression(this.width >' +width+ '?'+width+': true);position:absolute;left:0px;top:0px;z-index:3;" onclick="hide()" onLoad="show(this)">' +
		'<img src="images/overlay.GIF" style="position:absolute;left:0px;top:0px;width:' + document.body.clientWidth + 'px;height:' + height + 'px;z-index:4;" id="dimmer" onclick="hide()" />'+
		'<img src="images/loading.gif" style="position:absolute;left:0px;top:0px;z-index:3;" id="loading" onclick="hide()" onLoad="show(this)" />'+
		'<span style="position:absolute;width:'+width+'px;left:0px;text-align:center;top:0px;z-index:7;"><div style="width: 170px;margin: 3px auto 0px auto;background-image: url(\'/images/Overlay.png\');background-repeat: repeat;z-index:7;">' +
		'<img id="leftarrow" onMouseOut="ClearToolTip('+index+')" onMouseOver="ShowToolTip(this)" src="images/PreviousButton.png" onclick="ShowFullPicture('+prevIndex+')" style="margin: 4px;" />'+
		'<img id="closebutton" onMouseOut="ClearToolTip('+index+')"  onclick="hide()" onMouseOver="ShowToolTip(this)" src="images/CloseButton.png" style="margin: 4px;" />'+
		'<img id="playbutton" onMouseOut="ClearToolTip('+index+')"  onclick="ToggleSlideShow('+index+')" onMouseOver="ShowToolTip(this)" src="'+ButtonSource+'" style="margin: 4px;" />'+
		'<img id="rightarrow" onMouseOut="ClearToolTip('+index+')"  onMouseOver="ShowToolTip(this)" src="images/NextButton.png" onclick="ShowFullPicture('+nextIndex+')" style="margin: 4px;" />'+
		'</div></span>' +
		'<span style="color:#ffffff;position:absolute;width:'+width+'px;left:0px;text-align:center;top:'+(height - 30)+'px;z-index:7;"><span id="text" style="padding: 5px;background-image: url(\'/images/Overlay.png\'); background-repeat: repeat;">'+Pix[index].description+'</span></span>';
}

function ToggleSlideShow(index)
{
	if(inSlideShow)
	{ 
		window.clearTimeout(timeoutID);
		inSlideShow = false;
		document.getElementById('playbutton').src = "images/PlayButton.png";
	}
	else
	{
		inSlideShow = true;
		timeoutID = window.setTimeout("ShowFullPicture("+index+")",4000);
		document.getElementById('playbutton').src = "images/PauseButton.png";
	}
}

function ShowThumbs(index)
{
	var numberToShow = (Pix.length > 4) ? 4 : Pix.length;
					
	var prevIndex = (index === 0) ? Pix.length - 1 : index - 1;
	var nextIndex = (index == Pix.length - 1) ? 0 : index + 1;
	var markup = "";
	
	if(Pix.length > 4) {
		markup += '<img src="/images/PreviousButton.png" onclick="javascript:ShowThumbs(' + prevIndex + ');" alt="Previous" />';
	}
	
	for(var i=0; i<numberToShow; i++,index++)
	{
		if(index==Pix.length)
		{
			index=0;
		}
		
		var thumbURL = Pix[index].number + "t." + Pix[index].type;
		markup += "<img onMouseOut=\"javascript:hideMarker(" + index + ");\" onMouseOver=\"javascript:showMarker(" + index + ");\" onclick=\"javascript:ShowFullPicture(" + index + ");\"  src=\"/ImageUploads/upload/" + thumbURL + "\" alt=\"\" />&nbsp;";
	}
	if(Pix.length > 4) {
		markup += '<img src="/images/NextButton.png" onclick="javascript:ShowThumbs(' +nextIndex+ ');" alt="Next" />';
	}
	
	markup += '<br /><span id="desc">Mouse over images to see where they were taken.  Click on them to view full size.</span>';
	document.getElementById('ImageGallery').innerHTML = markup;
}

function initReport(TrailId)
{
	loadTrail(TrailId,MapMode.AddPictures,-1);
	document.getElementById("ReportForm").style.display = "block";
}

function loadTrail(id,mode,reportId)
{
	TrailID = id;
	//alert(TrailID);
	var xmlHttp=new XMLHttpRequest();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{

			eval("var TailPoints = " + xmlHttp.responseText + ";");
			
			var bounds = new GLatLngBounds();
			var trail = [];
			var i;
			for (i=0;i<TailPoints.length;i++)
			{
				trail[i] = new GLatLng(TailPoints[i][0], TailPoints[i][1]);
				bounds.extend(trail[i]);
			}

			map = new GMap2(document.getElementById("map")); 
			map.setMapType(G_PHYSICAL_MAP);
			map.enableContinuousZoom();
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			map.addControl(new GLargeMapControl3D() );

			TrailLine = new GPolyline( trail, "#FF1111",  5);
			map.addOverlay(TrailLine);
			map.addControl(new MapControl(mode));
			if(mode == MapMode.EditTrail)
			{
				map.enableScrollWheelZoom();
				TrailLine.enableDrawing({});
				TrailLine.enableEditing({onEvent: "mouseover"});
				TrailLine.disableEditing({onEvent: "mouseout"});
				TrailLine.disableEditing();
				
				GEvent.addListener(TrailLine, "lineupdated", function() {
					document.getElementById('Length').value = GetTrailLength()
				});
			}
			if(reportId != -1)
			{
				loadTrailPictures(reportId,mode);
			}
		}
	};

	xmlHttp.open("GET","GetTrailHelper.php?id="+id,true);
	xmlHttp.send(null);
}

function loadTrailPictures(id,mode)
{
	var xmlHttp=new XMLHttpRequest();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			eval("Pix = " + xmlHttp.responseText + ";");
			if(Pix != null && Pix.length > 0) 
			{
				for(i=0;i<Pix.length;i++) 
				{
					Pix[i].Marker = new GMarker(new GLatLng(Pix[i].lat, Pix[i].lng), {draggable: true});
					
					if(mode == MapMode.EditTrail || mode == MapMode.AddPictures)
					{
						var markup = "<div style='margin: 3px; height: 200px;'><img src='/ImageUploads/upload/"+Pix[i].number + "t." + Pix[i].type+"' alt='' /><br /><p>"+Pix[i].description+"</p></div>";
						map.addOverlay(Pix[i].Marker);
						
						Pix[i].Marker.bindInfoWindowHtml(markup);

						GEvent.addListener(Pix[i].Marker, "dragstart", function() {
							map.closeInfoWindow();
						});
						
						GEvent.addListener(Pix[i].Marker, "dragend", function() {
							var xmlHttp=new XMLHttpRequest();
							var i;
							for(i=0;i<Pix.length;i++)//for(i=0;i<Pix[i].Marker.length;i++)
							{
								if(this == Pix[i].Marker)
									break;
							}
							var page = "DoMoveImage.php?number="+Pix[i].number+"&lat="+this.getLatLng().lat()+"&lng="+this.getLatLng().lng();
							//alert(page);
							xmlHttp.open("GET",page);
							xmlHttp.send(null);
						});
					}
				}
				if(mode == MapMode.View)
				{
					ShowThumbs(0);
				}
			}
		}
	};

	if(id == null)
	{
		var sw = map.getBounds().getSouthWest();
		var ne = map.getBounds().getNorthEast();
		xmlHttp.open("GET","FindPicturesHelper.php?n="+ne.lat()+"&e="+ne.lng()+"&s="+sw.lat()+"&w="+sw.lng(),true);
	}
	else
	{
		xmlHttp.open("GET","FindPicturesHelper.php?id="+id,true);
	}
	xmlHttp.send(null);
}

function pageResized()
{
	hide();
}

function hideMarker(index)
{
	map.removeOverlay(Pix[index].Marker);
	document.getElementById('desc').innerHTML="Mouse over images to see where they were taken.  Click on them to view full size.";
}

function showMarker(index)
{
	map.addOverlay(Pix[index].Marker);
	document.getElementById('desc').innerHTML=Pix[index].description;
}

function checkRegistration()
{
	if(	document.getElementById('SignupEmail').value == "" ||
		document.getElementById('SignupUser').value == "" ||
		document.getElementById('SignupPass').value == "" )
	{
		alert("You must complete all fields of the registration form");
		return false;
	}
		document.getElementById('RegistrationForm').submit();
}

function getRoute()
{
	if(TrailLine == null)
	{
		alert("Please set a trail.  Click 'Create New Trailhead' to begin.");
		return false;
	}
	
	if(isNaN(document.getElementById('Length').value))
	{
		alert("Invalid Trail Length");
		return false;
	}
	
	if(isNaN(document.getElementById('Gain').value))
	{
		alert("Invalid Trail Elevation Gain");
		return false;
	}
	
	var wayPoints = [];
	for( var i = 0; i < TrailLine.getVertexCount(); i++){
		wayPoints[i] = TrailLine.getVertex(i).lat()+','+TrailLine.getVertex(i).lng();
	}

	document.getElementById('Route').value = wayPoints.join(";");
	document.getElementById('HikeCreationForm').submit();
}

function drawRoute(route)
{
	var trail = [];
	for (var i=0;i<route.length;i++){
		trail[i] = new GLatLng(route[i][0], route[i][1]);
	}
	
	var fucker = new GPolyline( trail, "#FF1111",  5);
	map.addOverlay(fucker);
}

function initialize(lat,lon) 
{
    if (GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(lat,lon), 10);
        map.setUIToDefault();
		gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "error", handleErrors);
    }
}

function setDirections(fromAddress, toAddress, locale) 
{
	var DirDiv = document.getElementById('directions');
	DirDiv.innerHTML = '';
    gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}






