// TODO: Should I geocode the directory entries to save the visitor time?

// Load the version of the API we require - this doesn't like being in an onload event, it moaned.
var gLocalSearch;
var myMarkers = [];
google.load("maps", "2.x");
google.load("search", "1");
google.setOnLoadCallback(initializeGoogleMap);


// -----------------------------------------------------------------------------

function clickSpecificMapMarker(eventID) {
	for (var i = 0; i < myMarkers.length; i++ ) {
		if (myMarkers[i].value == eventID) {
			handleMarkerClick(myMarkers[i]);
			break;
		}
	}
}

// -----------------------------------------------------------------------------

function handleMarkerClick(marker) {
	// Reset all the images to be unselected
	for (var i = 0; i < myMarkers.length; i++ ) {
		//myMarkers[i].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
		myMarkers[i].setImage("../images/maps/map-marker-green.png");
	}
	
	// Change the icon of the given (selected) marker
	marker.setImage("../images/maps/map-marker-red.png");
	
	// Now go and fetch the XML file containing the markup for this single event
	GDownloadUrl("/feeds/get_events.asp?id=" + marker.value, function(data) {
		marker.openInfoWindowHtml(data);

//		document.getElementById("mapOneEventContent").innerHTML = data;
	});
}

// -----------------------------------------------------------------------------

function createMarker(APoint, AID) {
	// Create our custom icon (just use a Google one for now)
	var iconOurMarker = new GIcon(G_DEFAULT_ICON);
	iconOurMarker.image = "../images/maps/map-marker-green.png";
	iconOurMarker.iconSize = new GSize(32, 32);	                

	// Set up our GMarkerOptions object
	markerOptions = {icon:iconOurMarker};

	var marker = new GMarker(APoint, markerOptions);
	marker.value = AID;

	// Quick hack, I don't want the ability to click a marker when we're on the product profile page
	// TODO: Do this more elegantly
	if (!document.getElementById("mapDirMember")) {
		GEvent.addListener(marker, "click", function() {
			handleMarkerClick(marker);
		});
	}

	return marker;
}

// -----------------------------------------------------------------------------

	// Called when search results are returned
	function OnLocalSearch() {
		if (gLocalSearch.results[0]) {
			// For some reason, it doesn't like it when I set this up outside this function
			var map = new google.maps.Map2(document.getElementById("mapDirMember"));
			map.addControl(new GLargeMapControl());	// Add zoom and positioning buttons
			map.addControl(new GMapTypeControl());	// Add "Map/Satellite/Hybrid" buttons

			// Add a marker for the first result
			var point = new GLatLng(gLocalSearch.results[0].lat, gLocalSearch.results[0].lng);
			map.setCenter(point, 15, G_NORMAL_MAP);
			map.addOverlay(createMarker(point, "Map"));

			// Change the class on the map so that the styling will all work
			document.getElementById("mapDirMember").className = "mapYes";
		}
    }
	
// -----------------------------------------------------------------------------

	function initializeGoogleMap() {
	// TODO: One initialisation for both maps

	// The events map
	if (document.getElementById("mapEventsMap")) {
        // Setup the map
		var map = new google.maps.Map2(document.getElementById("mapEventsMap"));
		map.addControl(new GLargeMapControl());	// Add zoom and positioning buttons
		map.addControl(new GMapTypeControl());	// Add "Map/Satellite/Hybrid" buttons

		map.setCenter(new google.maps.LatLng(40, -100), 1);		// Just a test long and lat, can change if needed

		// Now go and fetch the XML file containing all the events
		GDownloadUrl("/feeds/get_events.asp?type=2&year=" + getValueFromURL("year"), function(data) {
			var xml = GXml.parse(data);
			var arEvents = xml.documentElement.getElementsByTagName("event");
			for (var i = 0; i < arEvents.length; i++) {
				var point = new GLatLng(arEvents[i].getElementsByTagName("event_latitude")[0].firstChild.nodeValue, arEvents[i].getElementsByTagName("event_longitude")[0].firstChild.nodeValue);
				var marker=createMarker(point, arEvents[i].getElementsByTagName("event_id")[0].firstChild.nodeValue)
				map.addOverlay(marker);
				myMarkers.push(marker);
			}

			// Select the first marker
//			if (myMarkers.length > 0) {
//				handleMarkerClick(myMarkers[0]);
//			}

		});
	}
	
	// A directory members map, make sure we have both elements we need for this
	if (document.getElementById("mapDirMember")) {
		var bTryAddress = false;

		if ((document.getElementById("mapLongitude")) && (document.getElementById("mapLatitude"))) {
			// Longitude and latitude field found, so use that to display the map
	        // Setup the map
			if ((document.getElementById("mapLongitude").value != "0") && (document.getElementById("mapLatitude").value != "0") && (document.getElementById("mapLongitude").value != "") && (document.getElementById("mapLatitude").value != "")) {
				var map = new google.maps.Map2(document.getElementById("mapDirMember"));
				map.addControl(new GLargeMapControl());	// Add zoom and positioning buttons
				map.addControl(new GMapTypeControl());	// Add "Map/Satellite/Hybrid" buttons

				var point = new GLatLng(document.getElementById("mapLatitude").value, document.getElementById("mapLongitude").value);
				map.setCenter(point, 15, G_NORMAL_MAP);
				map.addOverlay(createMarker(point, "Map"));
	
				// Change the class on the map so that the styling will all work
				document.getElementById("mapDirMember").className = "mapYes";
			} else
				bTryAddress = true;
		} else
			bTryAddress = true;


		// The longitude and latitude is not on there or empty, so try the address
		if (bTryAddress) {
			// Search for the mapAddress for the map
			if (document.getElementById("mapAddress")) {
				if (document.getElementById("mapAddress").value != "") {
			      	// Initialize the local search
			      	gLocalSearch = new GlocalSearch();
			      	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
					gLocalSearch.execute(document.getElementById("mapAddress").value);
				}
			}
		}
	}	

}

// -----------------------------------------------------------------------------
