var map;  // The google map
var theChosenMarker;  // Will contain a reference to the "chosen" marker
var mCount = 0;            // How many markers are on the screen
var mArray = new Array();  // An array of references to markers
var noPhoto = "none.png";  // The photo used when no photo is available
var isCurrentNoPhoto = false;  // Changes whenever a new marker is selected
var currentID = 0;  // The ID of the last marker selected
// longitude is negative because Tacoma roughly 122.5ºW, or -122.5ºE
downtownTacomaLatitude = 47.24730;
downtownTacomaLongitude = -122.44400;
downtownTacomaZoom = 13;

tacomaLatitude = 47.25569;
tacomaLongitude = -122.47112;
tacomaZoom = 12;

southSoundLatitude = 47.10939;
southSoundLongitude = -122.39593;
southSoundZoom = 9;

homeLatitude = tacomaLatitude;
homeLongitude = tacomaLongitude;
homeZoom = tacomaZoom;

// Define how the generic marker appears
var iconMarker;
iconMarker = new GIcon();
iconMarker.image = "marker.png";
iconMarker.iconSize = new GSize(20, 34);
iconMarker.shadow = "shadow.png";
iconMarker.printImage = "markerie.gif";
iconMarker.printShadow = "shadowie.gif";
iconMarker.mozPrintImage = "markerff.gif";
iconMarker.mozPrintShadow = "shadowff.gif";
iconMarker.shadowSize = new GSize(37, 34);
iconMarker.iconAnchor = new GPoint(9, 34);
iconMarker.infoWindowAnchor = new GPoint(5, 1);

// Define how the highlighted marker appears
var iconChosen;
iconChosen = new GIcon();
iconChosen.image = "chosen.png";
iconChosen.iconSize = new GSize(20, 34);
iconChosen.iconAnchor = new GPoint(9, 34);
iconChosen.infoWindowAnchor = new GPoint(5, 1);

function load() {
  if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.setCenter(new GLatLng(homeLatitude, homeLongitude), homeZoom);
	
	// Report the bounds, will overwrite hotspot info when map moved
	// Comment out when not using to determine where to point map
	//GEvent.addListener(map, "moveend", function () { gps(); });
	
	GEvent.addListener(map, "click", function(marker, point) {
		if (marker) {
			newwin = window.open("hotspot.php?id="+currentID, 'name', 'width=400, height=500, resizable=0, scrollbars=1');
		}
	});
	
	updateMarkers();
  }
}

function gps() {
	var center = map.getCenter();
	var bounds = map.getBounds();
	var zoom = map.getZoom();
	document.getElementById("result").innerHTML =
		"<i>" + 
		"Center at " + center.toString() + "<br />" +
		"Zoom: " + zoom + "<br />" +
		"SW = " + bounds.getSouthWest() + "<br />" +
		"NE = " + bounds.getNorthEast() + "</i>"
		;
}

function zoomDowntownTacoma() {
	map.setCenter(new GLatLng(downtownTacomaLatitude, downtownTacomaLongitude), downtownTacomaZoom);
}

function zoomTacoma() {
	map.setCenter(new GLatLng(tacomaLatitude, tacomaLongitude), tacomaZoom);
}

function zoomSouthSound() {
	map.setCenter(new GLatLng(southSoundLatitude, southSoundLongitude), southSoundZoom);
}

function createMarker(point, data) {
	
	var marker = new GMarker(point, {icon: iconMarker});
	
	GEvent.addListener(marker, "mouseover", function() {
		
		if (theChosenMarker == null) {
			theChosenMarker = new GMarker(marker.getPoint(), {icon: iconChosen});
		}
		
		// These two lines essentially bring the chosen icon image to the front
		// of the map, overlapping the marker and appearing highlighted.
		map.removeOverlay(theChosenMarker);
		map.addOverlay(theChosenMarker);
		theChosenMarker.setPoint(marker.getPoint());
		
		// Display the hidden marker's message
		document.getElementById("result").innerHTML = makeHTML(data);
		
		var photo = data[9];
		isCurrentNoPhoto = false;
		
		if (!photo) {
			photo = noPhoto;
			isCurrentNoPhoto = true;
		}
		
		currentID = data[10];
		
		document.getElementById("storefront").src = "photos/" + photo;
	});
	
	return marker;
}


/* variable "data" is an array containing information in the order
 * displayed on spots.php and returns that information formatted for HTML. */
function makeHTML(data) {
	var name = data[0];
	var address = data[1];
	var city = data[2];
	var state = "WA";
	var zipcode = data[3];
	var phone = data[4];
	var url = data[5];
	var urlshort = makeShort(url);
	var buzz = data[6];
	
	var result = "<font size=3><b>"+name+"</b></font><br /><font size=2>"+address+", "+city+", "+state+" "+zipcode+" </font>";
	
	if (url != "")
		result += "<br />&#8226; <b>URL:</b> <a href=\""+httpFront(url)+"\" target=blank>"+urlshort+"</a>";
	else
		result += "<br />&#8226; <b>URL:</b> ";
	result += "<br />&#8226; <b>Phone:</b> "+phone;
	
	result += "</p>";
	result += '<p><a href="javascript:void(window.open(\'hotspot.php?id=\'+currentID, \'name\', \'width=400, height=500, resizable=0, scrollbars=1\'));">Make a Comment</a></p>';
	
	return result;
}

/* Determine what markers to display on the map, based on what the user can see.
 * Information about GXmlHttp, which the Google API says simply creates an XmlHttpRequest
 * can be found around half way down the page, at the title "Object Properties" at...
 *    http://developer.apple.com/internet/webcontent/xmlhttpreq.html
 */
function updateMarkers() {
	
	var bounds = map.getBounds();
	var url = "spots.php";
	
	// Now add new markers
	var request = GXmlHttp.create();
	
	request.open("GET", url);
	
	request.onreadystatechange = function() {
		
		// if (request.readyState == "completed") {
		if (request.readyState == 4) {
			
			// Delete the old markers first
			while (mArray.length > 0) {
				GEvent.clearListeners(mArray[mArray.length-1],'mouseover');
				mArray.pop();
			}
			if (theChosenMarker != null)
				map.removeOverlay(theChosenMarker);
			
			mCount = 0;
			
			map.clearOverlays();
			
			// Display new markers
			var response = request.responseText;
			var rows = response.split("\n");
			for (var i=0; i<rows.length-1; i++) {
				var record = rows[i];
				var data = record.split("|");
				if (data.length == 11) {
					var point = new GLatLng(data[7],data[8]);
					var marker = createMarker(point, data);
					map.addOverlay(marker);
					mArray[mCount++] = marker;
				}
			}
			
			// Redisplay the chosen marker again, if it's on the screen
			if (theChosenMarker != null) {
				var chosenPoint = theChosenMarker.getPoint();
				/*
				if (bounds.getSouthWest().lat() < chosenPoint.lat() &&
					bounds.getNorthEast().lat() > chosenPoint.lat() &&
					bounds.getSouthWest().lng() < chosenPoint.lng() &&
					bounds.getNorthEast().lng() > chosenPoint.lng()) {
					*/
					map.addOverlay(theChosenMarker);
				//}
			}
		}
	};
	
	request.send(null);
	
}

function submitPhoto() {
	if (isCurrentNoPhoto) {
		window.open("photo.php?id="+currentID, 'name', 'width=360, height=430, resizable=1');
	}
}

/* Return a shorter version of the URL for display purposes */
function makeShort(url) {
	
	var results = url;
	
	var httpslashes = url.indexOf("//");
	if (httpslashes > 0) {
		results = results.substring(httpslashes+2);
	}
	
	var nextslash = results.indexOf("/");
	if (nextslash == -1) {
		return results;
	} else {
		return results.substring(0, nextslash);
	}
}

/* Put "http://" in front of a URL if necessary */
function httpFront(url) {
	
	if (url.indexOf("http://") == 0) {
		return url;
	} else {
		return "http://" + url;
	}
}