	
	var markers;
	var searchTimerId = 0;  
	
	// this variable will collect the html which will eventually be placed in the side_bar div
	var side_bar_html = "";
	
	// arrays to hold copies of the markers used by the side_bar
	var gmarkers = [];
	var ii = 0;

	// arrays to hold variants of the info window html with get direction forms open
    var to_htmls = [];
    var from_htmls = [];
	var directions = [];
	var dircontent

	// setup custom pushpin icon
	var baseicon = new GIcon();
	baseicon.image = "images/mm_20_red.png";
	baseicon.shadow = "images/mm_20_shadow.png";
	baseicon.iconSize = new GSize(12, 20);
	baseicon.shadowSize = new GSize(22, 20);
	baseicon.iconAnchor = new GPoint(6, 20);
	baseicon.infoWindowAnchor = new GPoint(5, 1);
	
	// ====== A function to create the marker and set up the event window ======
	function createMarker(point,name,description,images,buildings,moreinfo) {
		// assign images to a variable and, if there is a picture, create it
		var picture = images;
		if (!picture){
			picture = "";
		}
		else{
			picture = "<img src='images/buildings/" + images + ".jpg' class='picture' />";
		}
		
		var info = moreinfo;
		if (!info){
			info = "";
		}
		else{
			info = "<p><a href='" + moreinfo + "' target='_blank'>(more info...)</a></p>";
		}
		
		var marker = new GMarker(point,baseicon);
		side_bar_html += "<li><a href='javascript:myclick(" + ii + ")' onmouseover='mymouseover(" + ii + ")' onmouseout='mymouseout()'>" + name + "</a></li>";

		// The info window version with the "to here" form open
        to_htmls[ii] = directions + '<h1>' + name + '</h1><p id="infodirections">Get directions: <b>To here<\/b> - <a href="javascript:fromhere(' + ii + ')">From here<\/a></p>' +
           '<form action="javascript:getDirections()"><p>Start address</p>' +
           '<input type="text" size=40 maxlength=40 name="saddr" id="saddr" value="" />' +
           '<input value="Go" type="submit" id="submit" />' +
           //'<div id="walking">Walking Directions <input type="checkbox" name="walk" id="walk" /></div>' +
		   '<div id="mode_select"><select id="d_mode"><option value="d">By car</option><option value="w">Walking</option></div>' +
           '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/></form>';
        // The info window version with the "from here" form open
        from_htmls[ii] = directions + '<h1>' + name + '</h1><p id="infodirections">Get directions: <a href="javascript:tohere(' + ii + ')">To here<\/a> - <b>From here<\/b></p>' +
           '<form action="javascript:getDirections()"><p>End address</p>' +
           '<input type="text" size=40 maxlength=40 name="daddr" id="daddr" value="" />' +
           '<input value="Go" type="submit" id="submit" />' +
           //'<div id="mode_select">Walking Directions <input type="checkbox" name="walk" id="walk" /></div>' +
		   '<div id="mode_select"><select id="d_mode"><option value="d">By car</option><option value="w">Walking</option></div>' +
           '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/></form>';
		 
		 var direction_links = '<p>Directions: <a href="javascript:tohere('+ ii +')">To here<\/a> - <a href="javascript:fromhere('+ ii +')">From here<\/a></p>';
		
		// if a building # is not read from the XML file, store the info for bus routes, otherwise campus buildings
		var tooltip_building;
		var info_building;
		tooltip_building = "(" + buildings + ")";
		info_building = "<h2>Building ID: " + buildings + "</h2>";
		
		// create pop-up tooltip for hovering over marker and links
		marker.tooltip = "<div class='tooltip'><nobr>" + name + "</nobr> " + tooltip_building + "</div>";
		// when the marker is clicked, show event window
		GEvent.addListener(marker, "click", function() {
		  marker.openInfoWindowHtml("<div class='infowindow'><h1>" + name + "</h1>" + info_building + "<p>" + description + "</p>" + info + direction_links + "</div>" + picture);
		});
		
		// save the info we need to use later for the side_bar
		gmarkers[ii] = marker;

		ii++;

		// ======  The new marker "mouseover" and "mouseout" listeners  ======
		GEvent.addListener(marker,"mouseover", function() {
			showTooltip(marker);
		});        
		GEvent.addListener(marker,"mouseout", function() {
			tooltip.style.visibility="hidden"
		});        

	return marker;
	}

	// ====== This function displays the tooltip ======
	function showTooltip(marker) {
		tooltip.innerHTML = marker.tooltip;
		var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
		var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
		var anchor=marker.getIcon().iconAnchor;
		var width=marker.getIcon().iconSize.width;
		var height=tooltip.clientHeight;
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
		pos.apply(tooltip);
		tooltip.style.visibility="visible";
	}

	// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
	// It launches the tooltip on the icon      
	function mymouseover(i) {
		showTooltip(gmarkers[i])
	}
	// ===== This function is invoked when the mouse leaves an entry in the side_bar =====
	// It hides the tooltip      
	function mymouseout() {
		tooltip.style.visibility="hidden";
	}
	
	// This function picks up the click and opens the corresponding info window
	function myclick(i) {
		GEvent.trigger(gmarkers[i], "click");
		window.location.hash = "#map";
	}
	
	// ===== request the directions =====
	function getDirections() {
		// ==== Set up the walk option ====
		var opts = {};
		if (document.getElementById("d_mode").value == "d") {
		   opts.travelMode = G_TRAVEL_MODE_DRIVING;
		}
		else if(document.getElementById("d_mode").value == "w"){
		   opts.travelMode = G_TRAVEL_MODE_WALKING;
		}
		// ==== set the start and end locations ====
		var saddr = document.getElementById("saddr").value
		var daddr = document.getElementById("daddr").value
		gdir.load("from: " + saddr + " to: " + daddr, opts);
		
		dircontent = document.getElementById('directions');
		dircontent.innerHTML = "<p><a href='#' onClick='clearDirections();'>Clear Directions</a></p><p><strong>Please Note</strong>:  Due to recent construction on campus, certain streets in Google Maps may not be accurate.  Please use the directions below as a guideline to your destination.</p>";

	}
	// functions that open the directions forms
	function tohere(i) {
		gmarkers[i].openInfoWindowHtml("<div class='infowindow'>" + to_htmls[i] + "</div>");
	}
	function fromhere(i) {
		gmarkers[i].openInfoWindowHtml("<div class='infowindow'>" + from_htmls[i] + "</div>");
	}

	// Display Google Maps with some controls 
	var map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.enableScrollWheelZoom();

	// ====== set up marker mouseover tooltip div ======
	var tooltip = document.createElement("div");
	map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
	tooltip.style.visibility="hidden";

	// ============================================================
	// ====== Create a copyright entry =====
	/*var copyright = new GCopyright(1,
	new GLatLngBounds(new GLatLng(-89.98758536807179, -180),new GLatLng(85.0511287798066, 180) ),0, "The University of Alabama");
			
	// ============================================================
	// ====== Create a copyright collection and add the copyright to it =====
	var copyrightCollection = new GCopyrightCollection('Map Data:');
	copyrightCollection.addCopyright(copyright);*/
	
	function initialize() {
		//if (GBrowserIsCompatible()) {
			// add our custom map and center it
			var dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer("http://mudman.landmgt.ua.edu/arcgis/rest/services/ltlg/Camp_Bldg_LL_DS/MapServer", null, 0.75, dynmapcallback);
			map.setCenter(new GLatLng(33.211655052789496, -87.53979206085205),15);
		
			map.addControl(new GMapTypeControl());
		//} //close if browser compatible
	}
	
	function dynmapcallback(mapservicelayer) {
		map.addOverlay(mapservicelayer);
	}


	function readMap(url) {
		// ============================================================
		// ===== Read the data from xml files =====
		var buildings;
		var label;
		document.getElementById('searchresults').innerHTML = "";
		GDownloadUrl(url, function(data, responseCode){
			if (responseCode == 200) {
			var xmlDoc = GXml.parse(data);
			// obtain the array of markers and loop through it
			markers = xmlDoc.documentElement.getElementsByTagName("marker");

			//map.clearOverlays();          
			gmarkers = [];
			ii = 0;
			side_bar_html = "";
			
				for (var i = 0; i < markers.length; i++) {
				// obtain the attribues of each marker
				var lat = parseFloat(markers[i].getAttribute("lat"));
				var lng = parseFloat(markers[i].getAttribute("lng"));
				var point = new GLatLng(lat,lng);
				var description = markers[i].getAttribute("html");
				//method to use child nodes in XML var description = GXml.value(markers[i].getElementsByTagName("html")[0]);
				label = markers[i].getAttribute("label");
				var images = markers[i].getAttribute("image");
				buildings = markers[i].getAttribute("building");
				var infolinks = markers[i].getAttribute("moreinfo");
				// pass attributes to function and create the marker
				var marker = createMarker(point,label,description,images,buildings,infolinks);
				map.addOverlay(marker);
				}
			// put the assembled side_bar_html contents into the side_bar div
			document.getElementById("side_bar").innerHTML = "<ul class='main'>" + side_bar_html + "</ul>";
			
			}
			else if (responseCode == -1) {
			alert("Data request timed out.  Please try later.");
			}
			else{
			alert("Request resulted in error.  Check XML file is retrieveable.");
			}

		});
	}

	// When initially loaded, use the data from main XML file
	readMap("buildings.xml");



	// === create a GDirections Object ===
	var gdir = new GDirections(map, document.getElementById("directions"));

	
	// === Array for decoding the failure codes ===
	var reasons=[];
	//reasons[G_GEO_SUCCESS]            = "Success";
	//reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "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.";
	//reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "The given key is either invalid or does not match the domain for which it was given.";
	reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
	//reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.";
	reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
	//reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
	
	// === catch Directions errors ===
	GEvent.addListener(gdir, "error", function() {
		var code = gdir.getStatus().code;
		var reason = "Code " + code;
		if (reasons[code]) {
			reason = reasons[code]
		} 
	
		alert(reason);
	});
	
	function clearDirections() {
		gdir.clear();
		dircontent.innerHTML = "";
		map.setCenter(new GLatLng(33.211655052789496, -87.53979206085205),15);
		return false;
	}
	


	// ============================================================
	// == Search function
	
	function searchIt(searchString) {	
		clearTimeout(searchTimerId);
		searchTimerId = setTimeout("search2('" + searchString + "')", 150);
	}
	
	function search2(searchString) {
		var content = document.getElementById('searchresults');
		content.innerHTML = "";
		if (searchString.length > 1){
			content.style.display = "block";
			content.innerHTML = "<h3>Search Results</h3>";
			var objRegex = new RegExp("^" + searchString + "| *?" + searchString + "| " + searchString ,"i");
			var foundMatch = false;

			for(var i = 0; i < markers.length; i++){
					if(markers[i].getAttribute("label").match(objRegex) != null)
					{
						content.innerHTML += "<p><a href='javascript:myclick(" + i + ")' onmouseover='mymouseover(" + i + ")' onmouseout='mymouseout()'>" + markers[i].getAttribute("label") + "</a></p>";

						foundMatch = true;
					}
			}
			if(!foundMatch){
				content.innerHTML += "<p>No matches found</p>";
			}
			
		}
		else{	 
		content.style.display = "none";
		content.innerHTML = "";
		}
	}

