// The Map, Sidebar and the Geocoder need to be global
var map = null;
var geocoder = new GClientGeocoder();

// The map settings
var mapcenter_lat = 36.15896;
var mapcenter_lng =-115.13683;
var map_zoom = 11;
var map_zoom_add = 1;
var mapfiles_dir = "mapfiles";
var markerfile = ["markers.xml", "marker"];

var sidebar_html = "";
// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
var gmarkers = [];
var labels = [];
var i = 0;
// array to hold direction to variants of the lables
var to_labels = [];

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
// Breaking this into global allows to not have to contantly reset the standard
var baseIcon = new GIcon();
baseIcon.shadow = mapfiles_dir + "/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

function main() { // Is the MAIN!	
	if (GBrowserIsCompatible()) { // Make sure we are compatible before we continue
		// Draw our map
		drawMap(mapcenter_lat, mapcenter_lng, map_zoom);
		
		generateMarkers(mapfiles_dir, markerfile[0], markerfile[1]);
		
	} // Close comapt check
} //close main



function drawMap(lat, lng, zoom) { //This just draws the map and the controls
	map = new GMap2(document.getElementById("map"));
	map.enableContinuousZoom();
	map.enableDoubleClickZoom();
	map.addControl(new GLargeMapControl(),
		 new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10)));
	map.setCenter(new GLatLng(lat, lng), zoom);
} //Close drawMap



function generateMarkers(directory, xml_file, type) {
	GDownloadUrl(directory + "/" + xml_file, function(raw_xml, status) {
		if (status =! 404) {
			alert("Pulling the XML file failed... The map have no markers");
		} else {
			// This transforms it into stuff I can use from raw
			var xml = GXml.parse(raw_xml);
			
			//Put the master markers into a varible.
			var markers = xml.documentElement.getElementsByTagName(type);
						
			for (var i = 0; i < markers.length; i++) {
				// Start by pulling all the info for this user
				var lat = parseFloat(markers[i].getAttribute("lat"));
				var lng = parseFloat(markers[i].getAttribute("lng"));
				var icon = GXml.value(markers[i].getElementsByTagName("icon")[0]);
				//The info feilds
				var title = GXml.value(markers[i].getElementsByTagName("title")[0]);
				var street = GXml.value(markers[i].getElementsByTagName("street")[0]);
				var zipcode = GXml.value(markers[i].getElementsByTagName("zipcode")[0]);
				var extra = GXml.value(markers[i].getElementsByTagName("extra")[0]);
				
				// Build the point 
				var point = new GLatLng(lat, lng);
				
				// This is the construction of the info window contents
				// Extra should start with a break and have it's own html formatting
				var infowindow = title + "<br />" + street + ", " + zipcode + extra;
			
				// This will actually draw the marker
				map.addOverlay(createMarker(point, icon, title, infowindow));
				
				// put the assembled sidebar_html contents into the sidebar div
				document.getElementById("sidebar").innerHTML = sidebar_html;
				
			} //Close for loop
			
		} //Close error cheching if
	}); // Close the GDownloadUrl call and the enclosed function.
} // Close generate markers tag


// Create the marker and set up the event window
function createMarker(point, image, name, label) {
	//Build the icon
	var icon = new GIcon(baseIcon);
	icon.image = image;

	
	// store the inforamtion for the direction to varian of the info window
	to_labels[i] = label + '<br \><b>Directions to here</b>' +
		'<br \>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
		'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
		'<INPUT value="Get Directions" TYPE="SUBMIT">' +
		'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
		// "(" + name + ")" + 
		'"/>';
	
	// Append the inactive directions to the current label
    label += '<br \><a href="javascript:tohere('+i+')">Directions to here</a>';
	
	// Build the marker and add the info wondow
	var marker = new GMarker(point, {'icon': icon, 'title': name});
	GEvent.addListener(marker, "click", function() {
		map.setZoom(map_zoom + map_zoom_add);
		marker.openInfoWindowHtml(label);
	});
	
	// save the info we need to use later for the sidebar
	gmarkers[i] = marker;
	labels[i] = label;
	// add a line to the sidebar html
	sidebar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br \>';
	i++;
	
	return marker;
}


// This function picks up the sidebar clicks and opens the info window
function myclick(i) {
	map.setZoom(map_zoom + map_zoom_add);
	gmarkers[i].openInfoWindowHtml(labels[i]);
}

// This function activated the to directions window
function tohere(i) {
	map.setZoom(map_zoom + map_zoom_add);
	gmarkers[i].openInfoWindowHtml(to_labels[i]);
}

function showAddress(address) { // Geocoder function, called by inputbox
	if (geocoder) {
		geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				map.setCenter(point, 13);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(address + "<br />" + point.toString());
			} //Close ifElse
		} // Close function point
	); // close getLatLng
	} // Cose if geocoder
} // close function

main(); //Finnally... RUN THE CODE!!!
