		var lastMoveEndLat=51.5094995;
		var lastMoveEndLng=-0.08171422;
		
		// this variable will collect the html which will eventually be placed in the side_bar/results
		var side_bar_html = "";
		
		// arrays to hold copies of the markers and html used by the side_bar
		// because the function closure trick doesnt work there
		var gmarkers = [];
		
		//This boolean flags whether to do a reload when the map is moved. It should be false
		//when an info window is opened otherwise the map moves, data reloads and overlays are cleared!
		var doLoad = true;
		
    function initialize() {
      if (GBrowserIsCompatible()) {
				map = new GMap2(document.getElementById("map_canvas"));
				map.setCenter(new GLatLng(51.5094995,-0.08171422), 13);
				map.setUIToDefault();
				geocoder = new GClientGeocoder();

				GEvent.addListener(map, "dragend", function() {
					doLoad = true;
				});     

				GEvent.addListener(map, "moveend", function() {
						var curPoint = map.getCenter();
						if((curPoint.lat() == lastMoveEndLat) && ((curPoint.lng() == lastMoveEndLng))) {
							//deal with stupid first call before the move actually starts
						}
						else {
							if(doLoad) {
								side_bar_html = "";
								document.getElementById("results_canvas").innerHTML = side_bar_html;
								lastMoveEndLat = curPoint.lat();
								lastMoveEndLng = curPoint.lng();
								loadMap();
							}
						}
				});

      }
    }
    function panTo() {
    	side_bar_html="";
    	document.getElementById("results_canvas").innerHTML = side_bar_html;
			var address = document.form.address.value;

    	doLoad = true;
    	var current = map.getCenter();
    	map.setCenter(current);
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            }
            else {
			  			map.panTo(point);
			  			srcLat = point.lat();
			  			srcLng = point.lng();
            }
          }
        );
      }
    }
    
		function createTabbedMarker(point, htmls, name) {
			var labels = ["Info", "Directions"];
			var marker = new GMarker(point);
			GEvent.addListener(marker, "click", function() {
				doLoad = false;
				// adjust the width so that the info window is large enough for this many tabs
				if (htmls.length > 2) {
					htmls[0] = '<div style="width:'+htmls.length*88+'px">' + htmls[0] + '</div>';
				}
				var tabs = [];
				for (var i=0; i<htmls.length; i++) {
					tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
				}
				marker.openInfoWindowTabsHtml(tabs);
			});
			
			// save the info we need to use later for the side_bar
			gmarkers.push(marker);
			// add a line to the side_bar html
			side_bar_html += '<ul>'
			side_bar_html += '<li><a title="'+ name +'" href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a></li>';
			side_bar_html += '</ul>'			
			return marker;
		}
    
    
		function createMarker(point,html, name) {
			var marker = new GMarker(point);
			GEvent.addListener(marker, "click", function() {
				doLoad = false;
				marker.openInfoWindowHtml(html);
			});
			
			// save the info we need to use later for the side_bar
			gmarkers.push(marker);
			// add a line to the side_bar html
			side_bar_html += '<ul>'
			side_bar_html += '<li><a title="'+ name +'" href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a></li>';
			side_bar_html += '</ul>'
			return marker;
		}
		
		// This function picks up the click and opens the corresponding info window
		function myclick(i) {
			doLoad = false;
			GEvent.trigger(gmarkers[i], "click");
		}		
		
		function makeHtml(mosqueId, name) {
			var html = "<div class='mosquePopup'><h2><a href='show_mosque.php?id=" + mosqueId + "' title='"+ name +"'>"+ name +"</a></h2><div class='floatL'><a href='show_mosque.php?id=" + mosqueId + "'><img class='gimage' width='70' height='65' src='/images/mosques/thumb_msq_" + mosqueId + ".jpg' title='"+ name +"' /></a></div><div class='floatR'><a href='show_mosque.php?id=" + mosqueId + "'>More Info</a></div></div>";
			return html;
		}
		
		function makeTabbedHtml(mosqueId, name, imgExists) {
			//tab1 html
			var tab1html = "<div class='mosquePopup'><h2><a href='show_mosque.php?id=" + mosqueId + "' title='"+ name +"'>"+ name +"</a></h2><a href='show_mosque.php?id=" + mosqueId + "'>";
			
			if(imgExists == "y") {
				tab1html += "<div class='floatL'><img class='gimage' width='70' height='65' src='/images/mosques/thumb_msq_" + mosqueId + ".jpg' ";
			}
			else {
				tab1html += "<div class='floatL'><img class='gimage' width='70' height='65' src='/images/mosques/no_image_thumb.jpg'";
			}
			
			tab1html += "title='"+ name +"' /></a></div><div class='floatR'> <br /><a href='show_mosque.php?id=" + mosqueId + "'>Click here for more mosque info</a> </div></div><div class='popupDirections'><h3>Get Directions</h3><form method='post' action='get_directions.php'> From: <input type='text' name='start' /><input type='hidden' name='mosque_id' value='" + mosqueId + "' /><br /><input type='radio' name='method' VALUE='walk' checked>On foot&nbsp;<input type='radio' name='method' VALUE='car'>By car<input type='submit' value='Show me!'></form>";
			//add directions tab html
			/*var directionsHtml = "<h2>Get to this mosque</h2>Type in your start location then we'll <br/> direct you how to get to this mosque:<p/>";
			directionsHtml += "<form method='post' action='get_directions.php'>"
			directionsHtml += "From: <input type='text' name='start' /><p/><br/><input type='hidden' name='mosque_id' value='" + mosqueId + "' />";
			directionsHtml += "<input type='radio' name='method' VALUE='walk' checked>On foot&nbsp;<input type='radio' name='method' VALUE='car'>By car &nbsp;&nbsp;";
			directionsHtml += "<input type='submit' value='Show me!'>";
			directionsHtml += "</form>";
			return [tab1html, directionsHtml];*/
			return [tab1html];
		}		
		
		function loadMap() {
			var curSpot = map.getCenter();
			side_bar_html = "";
						
			var selected_index = document.form.elements["distance"].selectedIndex;
			var radius=document.form.elements["distance"].options[selected_index].value;
			
			//var url=("mosque_loader.php?lng=" + curSpot.lng() + "&lat=" + curSpot.lat() + "&r=" + radius);
			var url=("mosque_loader.php?lng=" + curSpot.lng() + "&lat=" + curSpot.lat());
			var request = GXmlHttp.create();
			request.open("GET", url, true);
			request.onreadystatechange = function() {

				if (request.readyState == 4) {
					var xmlDoc = request.responseXML;
					// obtain the array of markers and loop through it
					var markers = xmlDoc.documentElement.getElementsByTagName("marker");
					// hide the info window, otherwise it still stays open where the removed marker used to be
					//map.getInfoWindow().hide();
					map.clearOverlays();
					// empty the array
					gmarkers = [];
					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 nm = markers[i].getAttribute("name");
						var msqId = markers[i].getAttribute("mosque_id");
						var imgExists = markers[i].getAttribute("img");
						var point = new GLatLng(lat,lng);
						// create the marker
						//var marker = createMarker(point, makeHtml(msqId, nm), nm);				
						var marker = createTabbedMarker(point, makeTabbedHtml(msqId, nm, imgExists), nm);
						map.addOverlay(marker);
					}
					// put the assembled side_bar_html contents into the side_bar div
					document.getElementById("results_canvas").innerHTML = side_bar_html;
				}
			}
			request.send(null);
		}
		
