var lat;
var lng;
var initialSearch;
//INITIAL PARAMETERS
// JavaScript Document
var gMap; // GMap
var gLocalSearch; // GlocalSearch
var gGeoCoder; // GClientGeocoder
var gCurrentResults; // Array
var centerMarker; // GMarker
var activeMarker; // GMarker
var userMarker; // GMarker
var addAddress; // String
var iconCenter; // gIcon
var iconDefault; // gIcon
var searchTerm = ""; // string
var circle; // GPolygon
var init; // Boolean
var resultset = new Array;
var searchType;
var directions;


// Create our center marker icon
var gCenterIcon = new GIcon();
gCenterIcon.image = "/img/marker_gear.png";
gCenterIcon.iconSize = new GSize(45, 45);
gCenterIcon.iconAnchor = new GPoint(22, 22);
	
// Create our location marker icon
var gLocationIcon = new GIcon();
gLocationIcon.image = "/img/marker_bike.png";
gLocationIcon.iconSize = new GSize(37, 25);
gLocationIcon.iconAnchor = new GPoint(18, 12);

// Create our location marker icon
var gUserIcon = new GIcon();
gUserIcon.image = "/img/marker_user.png";
gUserIcon.iconSize = new GSize(35, 35);
gUserIcon.iconAnchor = new GPoint(18, 18);

/* Called on page load */
$(document).ready(function() {
	$('#addlocation_clip').hide();
	$('input:checkbox:not([safari])').checkbox();

	if (!GBrowserIsCompatible()) {
		alert("Your browser is not compatible with google maps!");
		return;
	}
	
	//set the page heights
	var infoWinShell = document.createElement("div");
	infoWinShell.id = "infowindow_shell";

	// Create the map
	gMap = new GMap2(document.getElementById('map'));
	gMap.addControl(new GScaleControl());
	gMap.addControl(new GLargeMapControl(),  new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 30)));
	gMap.addControl(new GMapTypeControl());
	
	// Add map listeners
	GEvent.addListener(gMap, "move", onMapMove);
	GEvent.addListener(gMap, 'click', onMapClick);
	
	// Initialize the local searcher
	gLocalSearch = new GlocalSearch();
	gLocalSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
	gLocalSearch.setAddressLookupMode(gLocalSearch.ADDRESS_LOOKUP_DISABLED);
	gLocalSearch.setNoHtmlGeneration();
	gLocalSearch.setSearchCompleteCallback(null, onSearchLocal);
	
	//create the search geocoder
	gGeoCoder = new GClientGeocoder();
	
	
	//create the infoWindow holder
	$('#map').append(infoWinShell);
	
	//hide the window
	$('#infowindow_shell').css("visibility","hidden");
		
	// If we have an address set, run a geosearch
	if (address) {
		searchGeo(address);
		//if no address is set, use the Clif Bar default
	} else {
		address = "1610 5th St, Berkeley, CA";
		var point = (lat == null) ? new GLatLng(37.873665,-122.300708) : new GLatLng(lat,lng);
		
		setCenter(point);
		
		// Execute the initial search
		initSearch();
		setTimeout("showUserSubmissions()", 200);
	}
	
	addDestinationTimer = setTimeout("hideClip('addlocation_clip')", 300);
});

function showAddress(address) {
	searchGeo(address);
}
//http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=0&lstkp=0&rsz=large&hl=en&gss=.com&sig=5d50bdb54b756cb939d69ece0dadfd7b&q=food&sll=37.764202,-122.44887&gll=37732439,-122480633,37795964,-122417108&llsep=500,500&undefined&key=ABQIAAAATSEq6kwPXCW6lpyk_O6WwRSzGlpxI35j4AjbzZX5dePo0utbIhR8daT_zTcYzumy4IbuDoOuxeK-cA&v=1.0
function initSearch() {
	if (initialSearch) {
		searchTerm = initialSearch;
		initialSearch = null;
		gLocalSearch.setSearchCompleteCallback(null, function() { onSearchLocal("srch"); });
		gLocalSearch.execute(searchTerm);
	}
}

var count = 0;
function onWindowResize() {
	//setHeights();
	setTimeout("onMapMove()", 1);
}
function unsetResizing() {
	resizing = false;
}

function setHeights() {
}

/* Map Methods */
function onMapMove() {
	//if we have a visible infowindow
	if ($('#infowindow_shell').css('visibility') == "visible") {
		var marker = (activeMarker) ? activeMarker : centerMarker;
		var point=gMap.getCurrentMapType().getProjection().fromLatLngToPixel(gMap.getBounds().getSouthWest(),gMap.getZoom());
		var offset=gMap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),gMap.getZoom());
		var anchor=marker.getIcon().iconAnchor;
		var width=marker.getIcon().iconSize.width / 2;
		var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width - 50,- offset.y + point.y +anchor.y + 15)); 
		pos.apply(document.getElementById('infowindow_shell'));
	}
}
function onMapClick(m) {
	//if the map was clicked, and not on a marker, hide the infowindow
	if (m == null) hideInfoWindow();
}

function addMarker(marker, includeListeners) {
	var indx = 0
	while (resultset[indx]) indx++;
	//create a new object
	marker.indx = indx;
	
	//add listeners for the marker
	if (includeListeners) {
		GEvent.addListener(marker, "click", function() { selectLocation(this.indx); });
		GEvent.addListener(marker, "mouseover", function() { highlightLocation(this.indx); });
		GEvent.addListener(marker, "mouseout", function() { unHighlightLocation(this.indx); });	
	}
	
	//add the marker to the map
	gMap.addOverlay(marker);
	
	//add to the resultset
	resultset[indx] = marker;
	
	//return the index
	return indx;
}

/* Geo Search Methods */
function searchGeo(query) {
	$('#map_search').removeClass('map_search_off');
	$('#map_search').addClass('map_search_on');
	$('#map_search_overlay').css('display','none');
	$('#map_send').removeClass('map_send_off');
	$('#map_send').addClass('map_send_on');
	$('#map_send_overlay').css('display','none');
	//save the address
	address = query;
	//remove the search results
	clearSearch();
	//track("/searchGeo");
	//run a new location search
	gGeoCoder.getLocations(query, recenterMap);
}

function recenterMap(response) {
	if (!response) {
		alert(address + " not found!\nPlease try again.");
		return;
	} else if (response.Status.code != 200) {
		alert(address + " not found!\nPlease try again.");
		return;
	}
	// Retrieve the object
	place = response.Placemark[0];

	//grab the formatted address
	address = place.address;

	// Retrieve the latitude and longitude
	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	
	//set the new center
	setCenter(point);
	
	//set the address in the flash form
//	updateFlashAddress(address, place.Point.coordinates[0], place.Point.coordinates[1]);
	
	//check to see if we have an initial search to run
	initSearch();
	//show any user submisisons
	showUserSubmissions();
}

function setCenter(point) {
	if (centerMarker) {
		//remove the previous centerMarker
		gMap.removeOverlay(centerMarker);
	}
	//clear any previous results
	deactivateMarkers();
	clearSearch();
	removeResults();
	
	//create the center point
	gMap.setCenter(point, 13);
	centerMarker = new GMarker(point, gCenterIcon);
	gMap.addOverlay(centerMarker);
	GEvent.addListener(centerMarker, "click", function() { selectCenter(); });
	
	//draw the green circle
	drawCircle();

	//reset the local search center
	gLocalSearch.setCenterPoint(point);
	
	//open the info window
	showInfoWindow();
}

function drawCircle() {
	if (!centerMarker) return;
	var center = centerMarker.getPoint();
	var circleRadius = 2;
	var circlePoints = Array();
	var bounds = new GLatLngBounds();
	var txt = "";
	var lat = center.lat();
	var lon = center.lng();
	var latOffset = 0.01;
	var lonOffset = 0.01;
	with (Math) {
		var rLat = (circleRadius/3963.189) * (180/PI);
		var rLng = rLat/cos(center.lat() * (PI/180));

		for (var a = 0 ; a < 361 ; a+=2 ) {
			var aRad = a*(PI/180);
			var px = center.lng()*1 + (rLng * cos(aRad));
			var py = center.lat()*1 + (rLat * sin(aRad));
			var point = new GLatLng(parseFloat(py),parseFloat(px));
			bounds.extend(point);
			circlePoints.push(point);
		}
	}
	if (circle) gMap.removeOverlay(circle);
	circle = new GPolygon(circlePoints, false, 0, 0, "#009900", .2);
	gMap.addOverlay(circle);

}

function onSubmitLocal() {
	setTimeout("searchLocal()", 1);
	return false;
}

 /* Local Search Methods */
function searchLocal(srch) {
	//set the loading message
	//perform the search
	//track("/searchLocal");
	if (srch) {
		$('#search_results').fadeIn();
		searchTerm = srch;
	//	$('input_search').value = srch;
	//	setFlashSearch(srch);
	} else {
		//searchTerm = $('form_localsearch')['input_search'].value;
		//alert('setup search');
	}
	
	gLocalSearch.setSearchCompleteCallback(null, function() { onSearchLocal("srch"); });
	gLocalSearch.execute(searchTerm);
	return false;
}

function setFlashSearch(str) {
	//TODO - Plug into Flash
	var _sidebar = getSidebar();
}

function onSearchLocal(queryType, resultsArray) {
	if (resultsArray == null) resultsArray = gLocalSearch.results;
	//remove all results
	removeResults(queryType);
	//hide the loading message
	//$('sidebar_loading').setStyle({ display: "none" });
	if (queryType == 'srch') {
		clearSearch();
	}	
	
	//add the new markers
	for (var i=0; i<resultsArray.length; i++) {
		//if (!resultsArray[i]) return;
		addSearchResult(queryType, resultsArray[i]);
	}
}

function clearSearch() {
	$('#sidebarFlash').clearSearch();
}

function addSearchResult(queryType, result) {
	//create the marker
	var p = new GPoint(parseFloat(result.lng), parseFloat(result.lat));
	var marker = (queryType == "user") ? new GMarker(p, gUserIcon) : new GMarker(p, gLocationIcon);
	
	//add the marker to the list
	marker.queryType = queryType;
	marker.result = result;
	
	//add the marker to the resultset
	var indx = addMarker(marker, true);
	
	//set the deault values for the marker
	marker.title = marker.result.title;
	if (queryType == "user") {
		marker.address = (marker.result.address != "undefined") ? marker.result.address : "";
		marker.phone = (marker.result.phone != "undefined") ? marker.result.phone : "";
	} else {
		marker.address = marker.result.streetAddress;
		if (marker.result.city) marker.address += ", " + marker.result.city;
		if (marker.result.region) marker.address += ", " + marker.result.region;
		marker.phone = (marker.result.phoneNumbers) ? marker.result.phoneNumbers[0].number : "";
	}
	$('#searchwell').fadeIn('fast');
	$('#searchTerms').fadeOut('fast');
	
	var searchResult = 	document.createElement("div");
	searchResult.id = "result" + indx;
	searchResult.queryType = queryType;
	searchResult.indx = indx;
	searchResult.className = "location";
	//searchResult.innerHTML = "Result " + indx;
	searchResult.innerHTML = getResultHTML(indx);
	searchResult.onmouseover = function() { highlightLocation(this.indx); };
	searchResult.onmouseout = function() { unHighlightLocation(this.indx); };
	searchResult.onmouseup = function() { selectLocation(this.indx); };
	
	if ($('#searchwell').children().length > 0) $('#searchwell').append(searchResult);
	else $('#searchwell').append(searchResult);


}

function addLocalSearchResult(obj) {
	var _sidebar = getSidebar();
	
}

function getSidebar() {
	return $('#sidebarFlash');
}



function clearSearch() {
//	searchTerm = "";
//	removeResults("srch");
}

function removeResults(queryType) {
	$('#searchwell').fadeOut('fast');
	$('#searchTerms').fadeIn('fast');
	var newset = Array();
	if (!queryType) queryType = "removeall";
	//remove all previous markers
	for (var i in resultset) {
		if (resultset[i].queryType == queryType || queryType == "removeall") {
			if (resultset[i] == activeMarker) {
				hideInfoWindow();
			}
			gMap.removeOverlay(resultset[i]);
			var res = $("#result" + i);
			if (res) res.remove();
		} else {
			newset[i] = resultset[i];
		}
	}
	//if (newset.length == 0) $('search_clear').setStyle({ visibility: "hidden" });	
	if (newset.length == 0) {
	//	clearSearch();
	}
	//create the new resultset
	resultset = new Array();
	for (var i in newset) resultset[i] = newset[i];
}

function onCheckCategory(checkbox) {
	if (!checkbox.checked) {
		removeResults(checkbox.value);
		return;
	}
	searchType = checkbox.value;
	gLocalSearch.setSearchCompleteCallback(null, function() { onSearchLocal(searchType); });
	gLocalSearch.execute(checkbox.value);
}

function showUserSubmissions() {
	if (!$('#showusersubmissions').attr('checked')) {
		removeResults('user');
		return;
	}
	
	var radius = 4;
	var pt = centerMarker.getPoint();

	$.ajax({
		url: "/scripts/map/getuserlocations.php",
		type: "POST",
		data: "lat="+pt.lat()+"&lng="+pt.lng()+"&radius=4",
		success: function(responseText){
			//deserialize the object
			var results = eval(responseText);
			if (results.length == 0) {
				var msg = "No user submissions found within " + radius + " miles of your location.\n\n";
				msg += "Want to add a destination in your area?";
				if ($('#addlocation_container').panelopen) {
					msg += "\nFill out the \"Add a Location\" form, preview, and submit.";
					alert(msg);
				} else {
					if (confirm(msg)) showAddDestination(true);
				}
				checkbox.checked = false;
			} else {
				onSearchLocal("user", results)
			}
		},
		error: function(responseText){
			alert("Error in update: " + responseText);
		}
	
	});
}


/* Loction display */

function highlightLocation(result) {
	if (!$('#result' + result)) return;
	$('#result' + result).addClass("location_over");
}

function unHighlightLocation(result) {
	if (!resultset[result]) return;
	if (!$('#result' + result)) return;
	if (activeMarker != resultset[result]) $('#result' + result).addClass("location");
}

function addBorder(r) {
	r.css("border","none");
}

function deactivateMarkers() {
	if (!activeMarker) return;
	var loc = $('#result' + activeMarker.indx)
	if (loc) loc.addClass("location");
	activeMarker = null;
}

function selectCenter() {
	
	//remove any active marker
	deactivateMarkers();
	
	//move to the radius center
	gMap.panTo(centerMarker.getPoint());
	
	//show the info window
	showInfoWindow();
	
	drawCircle();
}

function selectLocation(indx) {

	//deactivate all the markers
	deactivateMarkers();
	
	//set the active marker
	activeMarker = resultset[indx];
	highlightLocation(indx);
	directionsPanel = document.getElementById("directionsPanel");

	
	//move to the active marker
	gMap.panTo(activeMarker.getPoint());
	directions = new GDirections(gMap, directionsPanel);
	directions.clear();
	directions.load("from: "+address+" to: "+activeMarker.getLatLng(), {travelMode:G_TRAVEL_MODE_WALKING});
	$('#directionsPanel').hide();

	
	//show the info window
	showInfoWindow(indx);
}

function showInfoWindow(indx) {
	//clear out the infoWindow
	$('#infowindow_shell').html("");
	
	//add the infowindow content container
	var infoWindowContainer = document.createElement("div");
	infoWindowContainer.id = "infowindow";
	
	//add the close button
	var infoWindowClose = document.createElement("div");
	infoWindowClose.id = "infowindow_close";
	infoWindowClose.className = "close";
	infoWindowClose.innerHTML = "<a href='javascript:closeInfoWindow(" + indx + ")'><img src='/img/map/infowindow_x.gif' alt='x' style=\"padding-right:5px; padding-top:5px;\" border='0' /></a>";
	infoWindowContainer.appendChild(infoWindowClose);
	
	//add the content node to the container
	var infoContent = document.createElement("div");
	infoContent.className = "content";
	infoContent.id = "infowindow_content";
	if (indx == null) {
		infoContent.innerHTML = "<div style=\"clear:both\"></div>" + getCenterHTML();
	} else if (resultset[indx] == userMarker) {
		infoContent.innerHTML = getUserHTML();
	} else {
		infoContent.innerHTML = getInfowindowHTML(indx);
	}
	
	infoWindowContainer.appendChild(infoContent);
	$('#infowindow_shell').append(infoWindowContainer);
	
	//add the infoPointer node to the container
	infoPointer = document.createElement("div");
	infoPointer.id = "infopointer";
	infoPointer.innerHTML = "<img src='/img/map/infowindow_pointer.png' />";
	$('#infowindow_shell').append(infoPointer);
	
	//append the container
	infoWindowContainer.appendChild(infoContent);

	//make visible and position
	$('#infowindow_shell').css("visibility","visible");
	$('#infowindow_shell').css("clear","both");
	
	//cleanImage($('#infopointer').childNodes[0]);
	onMapMove();
}

function getCenterHTML() {
	var txt = "<img src=\"/img/map/your2miles.gif\"/>";
	txt += "<img src='/img/map/hr.gif' style='width:100%; height:2px; padding-top:5px; padding-bottom:5px;'/>";
	txt += "<h6>" + address + "<br />&nbsp;</h6>";
	txt == "</div>";
	return txt;
}

function getResultHTML(indx) {
	var txt = "<div class=\"";
	if (resultset[indx].queryType == 'user') {
		txt += "inner_user";
	} else {
		txt += "inner";
	}
	txt += "\"><h2>";
	txt += resultset[indx].title + "</h2>";
	txt += "<h6>" + resultset[indx].address;
	if (resultset[indx].phone) txt += "<br />" + resultset[indx].phone;
	txt += "</h6>";
	
	//calculate the distance
	var dist = Math.round( 100 * centerMarker.getPoint().distanceFrom(resultset[indx].getPoint()) / 1609.344 ) / 100;
	txt += "<h5>Distance: " + dist + " miles | <a href=\"javascript:selectLocation(" + indx + ");\">View</a></h5>";
	txt += "</div>";
	return txt;
}

function getInfowindowHTML(indx) {
if (indx == undefined) {
		indx = '';
	}
	
	var txt = "<h2>" + resultset[indx].title + "</h2>";
	txt += "<img src='/img/map/hr.gif' style='width:100%; height:2px; padding-top:5px; padding-bottom:5px;'/>";
	txt += "<h6>" + resultset[indx].address;
	if (resultset[indx].phone) txt += "<br />" + resultset[indx].phone;
	txt += "</h6>";
	
	//calculate the distance
	var dist = Math.round( 100 * centerMarker.getPoint().distanceFrom(resultset[indx].getPoint()) / 1609.344 ) / 100;
	txt += "<h5>Distance: " + dist + " miles <div id=\"infowindow_links\"> | <a href=\"javascript:readReviews(false);\">Read Reviews</a>";
	txt += " | <a href=\"javascript:readReviews(true);\">Add A Review</a>";
	txt += "</div>";
	txt += "<div id=\"infowindow_addanother\"><strong>Thank you!</strong> <a href=\"javascript:tweenToReviewForm();\">Add Another Review</a></div>";
	txt += "<br />&nbsp;</h5>";
//	txt += "<h5>Distance: " + dist + " miles | <a href=\"javascript:saveLocation(" + indx + ");\">Save</a></h5>";
	return txt;
}

function getUserHTML() {
	var txt = "<div class=\"inner\"><h2>" + userMarker.locationname + "</h2>";
	txt += "<h6>" + userMarker.locationaddress + "</h6>";
	var dist = Math.round( 100 * centerMarker.getPoint().distanceFrom(userMarker.getPoint()) / 1609.344 ) / 100;
	txt += "<h5>Distance: " + dist + " miles<br />&nbsp;</h5>";
	txt += "</div>";
	return txt;
}

function closeInfoWindow(indx) {
	//if we have an active marker, pan back to the marker
	if (activeMarker) gMap.panTo(activeMarker.getPoint());
	hideInfoWindow();
	unHighlightLocation(indx);
}

function hideInfoWindow() {
	//recenter the map
	$('#infowindow_shell').css("visibility","hidden");
	activeMarker = null;
}



/* USER LOCATIONS */
var addDestinationTimer;
function showAddDestination(openOnly) {
	
	var panel = $('#addlocation_clip');

	//if (panel.is(':visible')) {
	if (openOnly) {
		if (!panel.is(':visible')) {
			panel.show("slide", { direction: "left" }, 500);
		}
	} else {
		panel.toggle("slide", { direction: "left" }, 500);
	}
	//} else {
	//	panel.show();
	//}
//	if (panel.effect) panel.effect.cancel();
	
//	var left = panel.css('left');
//	if (left) left = left.sub('px', '');
//	else left = 0;
	
//	if (openOnly && panel.panelopen) return;
	
//	if (panel.panelopen) {
//		addDestinationTimer = setTimeout("hideClip('addlocation_clip')", 300);
//		panel.effect = new Effect.MoveBy(panel, 0, -230 - left, {duration: .3});
//		panel.panelopen = false;
//	} else {
//		if (addDestinationTimer != null) clearTimeout(addDestinationTimer);
//		showClip('addlocation_clip');
		//panel.effect = new Effect.MoveBy(panel, 0, -1 - left, {duration: .3});
//		panel.effect = new Effect.MoveBy(panel, 0, 227, {duration: .3});
//		panel.panelopen = true;
//	}
	
}


function showClip(id) {
	$(id).css("left","250px");
	$(id).css("display","block");
}

function hideClip(id) {
	$(id).css("display","none");
}



function previewDestination() {
	//validate the form
	var form = $('#form_addlocation');
	var locationAddress = $("input[name='locationaddress']").val();
	var locationName = $("input[name='locationname']").val();
	
	var errors = "";
	if (locationAddress == "") errors += "\nPlease include an address.";
	if (locationName == "") errors += "\nPlease include a name for the location.";
	if (errors != "") {
		alert("The form is incomplete!\n" + errors + "\n\nPlease complete and preview again");
		return false;
	}
	
	//remove any previous usermarker
	if (userMarker) gMap.removeOverlay(userMarker);
	userMarker = new Object;
	userMarker.locationaddress = locationAddress;
	
	//hide the preview button and show the loading button
	$('#addlocation_preview').css("display","none");
	$('#addlocation_searching').css("display","block");
	$('#addlocation_submit').css("display","none");
	
	//perform the search
	gGeoCoder.getLocations(locationAddress, onPreviewDestination);
	
}

function onPreviewDestination(response) {
	
	if (!response) {
		//show the address not found message
		alert(userMarker.locationaddress + " not found!\nPlease try again.");
		//update the buttons
		$('#addlocation_preview').css("display","block");
		$('#addlocation_searching').css("display","none");
		$('#addlocation_submit').css("display","none");
		return;
	} else if (response.Status.code != 200) {
		//show the address not found message
		alert(userMarker.locationaddress + " not found!\nPlease try again.");
		//update the buttons
		$('#addlocation_preview').css("display","block");
		$('#addlocation_searching').css("display","none");
		$('#addlocation_submit').css("display","none");
		return;
	}
	
	//grab the form
	var form = $('#form_addlocation');
	
	// Retrieve the object
	var previewPlacemark = response.Placemark[0];

	//set the form value
	$("input[name='locationaddress']").val(previewPlacemark.address);

	// Retrieve the latitude and longitude
	var previewPoint = new GLatLng(previewPlacemark.Point.coordinates[1], previewPlacemark.Point.coordinates[0]);
	
	//show the preview and submit butons
	$('#addlocation_preview').css("display","block");
	$('#addlocation_searching').css("display","none");
	$('#addlocation_submit').css("display","block");
	
	//clear any previous results
	deactivateMarkers();
	
	//create the marker and recenter
	if (userMarker) gMap.removeOverlay(userMarker);
	delete userMarker;
	userMarker = new GMarker(previewPoint, gUserIcon);
	gMap.addOverlay(userMarker);
	
	//add the form information
	userMarker.locationaddress = $("input[name='locationaddress']").val();
	userMarker.locationname = $("input[name='locationname']").val();
	userMarker.yourname = $("input[name='yourname']").val();
	userMarker.youremail = $("input[name='youremail']").val();
	userMarker.subject = $("input[name='subject']").val();
	userMarker.review = $("textarea[name='review']").val();

	//add the marker to the list
	addMarker(userMarker, false);
	
	//add the listener
	GEvent.addListener(userMarker, "click", function() { selectLocation(this.indx); });
	
	//highlight the user marker
	selectLocation(userMarker.indx);
	
}

function addDestination() {
	
	//if the location is different, preview again
	if ($("input[name='locationaddress']").val() != userMarker.locationaddress) {
		
		$('#addlocation_preview').css("display","block");
		$('#addlocation_searching').css("display","none");
		$('#addlocation_submit').css("display","none");
		
		if ($("input[name='locationname']").val() == "") {
			alert('You must enter address information.\nPlease enter and re-submit');
		} else if (confirm("The address entered has changed!\nAnother preview will be provided before continuing.")) {
			previewDestination();
		}
		return;
	}
	
	var errors = "";
	if ($("input[name='subject']").val() == "") errors += "You must include a subject.\n";
	if ($("textarea[name='review']").val() == "") errors += "You must include a review.\n";
	if (errors != "") {
		errors = "The form is incomplete!\n" + errors + "\nPlease complete the form and resubmit.";
		alert(errors);
		return false;
	}
	
	//add the form information
	var name = $("input[name='locationname']").val();
	var addr = $("input[name='locationaddress']").val();
	var phone = "";
	var username = $("input[name='yourname']").val();
	if (username == "") username = "anonymous";
	var useremail = $("input[name='youremail']").val();
	var subject = $("input[name='subject']").val();
	var review = $("textarea[name='review']").val();
	var tags = "";
	var pt = userMarker.getPoint();
	var lat = pt.lat();
	var lng = pt.lng();
	
	$.ajax({
		url: "/scripts/map/addreview.php",
		type: "POST",
		data: "name="+escape(name)+"&address="+escape(addr)+"&phone="+escape(phone)+"&lat="+lat+"&lng="+lng+"&username="+escape(username)+"&useremail="+escape(useremail)+"&subject="+escape(subject)+"&tags="+escape(tags)+"&review="+escape(review)+"&user_submission=1",
		success: function(responseText){
			
			//add the destination to the search well
			addSearchResult("user", {lat : lat, lng: lng, title: name, address: addr, phone: phone, user_submission: 1});
			//clear out the search title, address, subject, and review
			var form = $('#form_addlocation');
			var locationAddress = $("input[name='locationaddress']").val("");
			var locationName = $("input[name='locationname']").val("");
			var locationSubject = $("input[name='subject']").val("");
			var locationReview = $("textarea[name='review']").val("");
			
			//notify and ask if the user would like to create another?
			if (confirm("Success!\n\nYour location is now in the 2 Mile Challenge.\nWould you like to add another?\n")) {
				showAddDestination(true);
			} else {
				if ($('#addlocation_container').panelopen) showAddDestination();
			}	
		},
		error: function(responseText){
			alert("Error in update: " + responseText);
		}
	
	});
}
 
/* USER REVIEWS */

function getReviewsForm() {
	var txt = '<form name="reviews_form" id="reviews_form" method="post" action="" onsubmit="postReview(this); return false;">';
	txt += '<h5 style="margin-bottom: 5px;"><b>Submit Your Review</b></h5>';
	txt += '<div style="float: left; padding-right: 10px; ">';
	txt += 'Your Name<br /><input type="text" name="yourname" id="ReviewsFormYourname" class="medium" />';
	txt += '</div><div style="float: left; ">';
	txt += 'Your Email<br /><input type="text" name="youremail" id="ReviewsFormYouremail" class="medium" />';
	txt += '</div><div class="clear"></div>';
	txt += 'Subject<br /><input type="text" name="subject" id="ReviewsFormSubject" class="long" /><br />';
	txt += 'Write Your Review<br /><textarea name="review" id="ReviewsFormReview" cols="45" rows="3" class="long"></textarea>';
	txt += '<br /><input type="submit" name="submit" id="ReviewsFormSubmit" value="Post Review" class="button" />';
	txt += '<input type="button" name="submitting" id="ReviewsFormSubmitting" value="Submitting..." style="display: none;" /></form>';
	txt += '<div id="reviews_submitted" style="display: none;"><h4>Thank you!</h4><p>Your review has been added.<br />';
	txt += '<a href="#" onmouseup="showReviewsForm();">Post another review</a></div>';
	return txt;
}

function readReviews(startWithAdd) {
	//hide the reviews links
	$('#infowindow_links').css("display","none");
	//save the current map position
//	gMap.savePosition()
	
	var pt = activeMarker.getPoint();
	var xpos = 250;
	var ypos = 512;
	
	//find the corners
	var proj = gMap.getCurrentMapType().getProjection();
	var bounds = gMap.getBounds();
	var zoom = gMap.getZoom();
	var trPos = proj.fromLatLngToPixel( bounds.getNorthEast(), zoom);
	var blPos = proj.fromLatLngToPixel( bounds.getSouthWest(), zoom);
	var height = blPos.y - trPos.y; 
	var width = trPos.x - blPos.x; 
	//find the current location of the marker
	var markerPos = proj.fromLatLngToPixel(pt, zoom);
	
	//find the distances to move
	xpos -= (markerPos.x - blPos.x);
	ypos -= (markerPos.y - trPos.y);
	
	//move that distance
	gMap.panDirection(3*xpos/width, 3*ypos/height)
	
	//expand the info window
	var w = $('#infowindow');
	w.css("width","530px");
	//grab the height
	var h = (w.offsetHeight) ? w.offsetHeight : w.pixelHeight;
	w.css("height","390px");
	//add in the reviews
	var scroller = document.createElement("div");
	scroller.id = "infowindow_scrolling";
	var reviews = document.createElement("div");
	reviews.id = "infowindow_reviews";
	reviews.innerHTML = "<div class=\"review\"><h4>Loading...</h4></div>";
	var reviewsForm = document.createElement("div");
	reviewsForm.id = "infowindow_form";
	reviewsForm.innerHTML = getReviewsForm();

	//grab the reviews
	$.ajax({
		url: "/scripts/map/getreviews.php",
		type: "POST",
		data: "lat="+pt.lat()+"&lng="+pt.lng(),
		success: function(responseText){
			//alert("Gotten!");
			if (responseText == "") {
				$('#infowindow_reviews').html("<div class=\"review bottom\"><h4>Be the first to review this location!</h4></div>");
			} else {
				$('#infowindow_reviews').html(responseText);
			}
			//make sure we're scrolled to the proper position
			if (startWithAdd) {
				//alert("startWithAdd: " + $('infowindow_scrolling').scrollHeight);
				$('#infowindow_scrolling').animate({scrollTop: $('#infowindow_scrolling')[0].scrollHeight}, 500);
			} else {
				$('#infowindow_scrolling').animate({scrollTop: 0}, 500);
			}
		},
		error: function(responseText){
			alert("Error in update: " + responseText);
		}
	
	});

	scroller.appendChild(reviews);
	scroller.appendChild(reviewsForm);
	$('#infowindow_content').append(scroller);
	$('#infowindow_scrolling').css("height",(390 - h) + "px");

}

function postReview(form) {
	var errors = "";
	if (form.subject.value == "") errors += "You must include a subject.\n";
	if (form.review.value == "") errors += "You must include a review.\n";
	if (errors != "") {
		errors = "The form is incomplete!\n" + errors + "\nPlease complete the form and resubmit.";
		alert(errors);
		return false;
	}
	var result = resultset[activeMarker.indx].result;
	var name = result.title;
	var addr = result.streetAddress
	if (result.city) addr += ", " + result.city;
	if (result.region) addr += ", " + result.region;
	var phone = (result.phoneNumbers) ? result.phoneNumbers[0].number : "";
	var lat = result.lat;
	var lng = result.lng;
	var username = form.yourname.value;
	if (username == "") username = "anonymous";
	var useremail = form.youremail.value;
	var subject = form.subject.value;
	var tags = "";
	var review = form.review.value;
	onPostReview(form, activeMarker.indx, name, addr, phone, lat, lng, username, useremail, subject, tags, review);
	
	$('#ReviewsFormSubmit').css("display","none");
	$('#ReviewsFormSubmitting').css("display","block");
	
	return false;
}

function tweenToReviewForm() {
	$('#infowindow_scrolling').animate({scrollTop: $('#infowindow_scrolling')[0].scrollHeight}, 500);
}

function onPostReview(form, indx, name, addr, phone, lat, lng, username, useremail, subject, tags, review) {
	$.ajax({
		url: "/scripts/map/addreview.php",
		type: "POST",
		data: "name="+escape(name)+"&address="+escape(addr)+"&phone="+escape(phone)+"&lat="+lat+"&lng="+lng+"&username="+escape(username)+"&useremail="+escape(useremail)+"&subject="+escape(subject)+"&tags="+escape(tags)+"&review="+escape(review),
		success: function(responseText){
			
			//add the submission to the bottom of the list
			var updatedreviews = String($('#infowindow_reviews').html());
			updatedreviews = responseText + updatedreviews;
			$('#infowindow_reviews').html(updatedreviews);
			
			//show the form buttons.
			$('#ReviewsFormSubmit').css("display","block");
			$('#ReviewsFormSubmitting').css("display","none");
			
			//show the thanks/add another
			$('#infowindow_addanother').css("display","block");
			
			//scroll the reviews window to the top
			$('#infowindow_scrolling').animate({scrollTop: 0}, 500);
		},
		error: function(responseText){
			alert("Error in update: " + responseText);
		}
	
	});
	
}

function showReviewsForm() {
	if ($('#reviews_form') == null) return;
	
	//reset the submission form
	$("#ReviewsFormSubject").val("");
	$("#ReviewsFormReview").val("");
	$('#ReviewsFormSubmit').css("display","block");
	$('#ReviewsFormSubmitting').css("display","none");
	
	//show the form
	$('#reviews_form').css("display","block");
	$('#reviews_submitted').css("display","none");
	
}

//FLASH EXTERNAL INTERFACE
function updateFlashAddress(txt, lon, lat) {
	var _sidebar = getSidebar();
	_sidebar.updateLocation(txt, lon, lat);
}

function sendEmailToFriend() {
	if ($('#STFEmail').val() != 'Email sent') {
		var pt = centerMarker.getPoint();
		$.ajax({
			url: "/scripts/map/map_email.php",
			type: "POST",
			data: "email="+escape($('#STFEmail').val())+"&address="+escape(address)+"&latitude="+pt.lat()+"&longitude="+pt.lng()+"&updates="+$('#STFJoin').attr('checked')+"&clifnews="+$('#STFInformed').attr('checked'),
			success: function(responseText){
				$('#STFEmail').val('Email sent')
			},
			error: function(responseText){
				alert("Error in update: " + responseText);
			}
		
		});
	}
}

//function thisMovie(movieName) {
//    if (navigator.appName.indexOf("Microsoft") != -1) {
//        return window[movieName]
//    }
//    else {
//        return document[movieName]
//    }
//}


