 google.load("maps", "2");


		// === if URL contains target map view values, these values are assigned to variables; if not, they are set to defaults ===


		var zoomthresh = 16; // Sets zoom level at which all markers within the map view will be displayed
 
 		

		// === more variables to declare

		var map = null;
    	var geocoder = null;
		var mgr = null;

		var lettersarray = new Array('A','B','C','D','E','F','G','H','I','J','K','L');
   		var supressloadmarkers = 0;
   
   
		// = Function to load the map
    	function initialize() {


     
      			map = new google.maps.Map2(document.getElementById("map_canvas"));
           		map.setCenter(new google.maps.LatLng(targetlat,targetlng),targetzoom); // set map view based on target values
           		
           		mgrOptions = { borderPadding: 50, maxZoom: 22};

				mm = new MarkerManager(map, mgrOptions);
				smm = new MarkerManager(map, mgrOptions);
				
				
							

           		geocoder = new google.maps.ClientGeocoder();
				
				map.setUIToDefault();
				
				google.maps.Event.addListener(map, "dragend",  loadMarkers); // calls marker loading function when the map is dragged to reload makers
				
				google.maps.Event.addListener(map, "zoomend", function(){loadMarkers(); mm.clearMarkers();}); // calls marker loading function when the map is zoomed to reload markers
					
					
				
					
					

					
				loadMarkers(); // calls marker loading function for the first time
				
   		 }
   		 

    
 
    	// == Reloads markers within the map view by loading a dynamically generated xml file with the map view specified in the url. If the current map view zoom is greater than the specified zoom threshold, one xml file is loaded, if not a different xml file is loaded.
		function loadMarkers(){
			
			if (supressloadmarkers == 1){ return;}
			
			zoom = map.getZoom(); // detects current zoom level

			if(zoom >= zoomthresh){ // tests whether zoom level exceeds threshold
			
				


				//   == if zoom level does exceed threshold load all markers in the map view == 
				
				// detect the latitudes and longditudes that bound the current map view
				var bounds = map.getBounds();
				var southWest = bounds.getSouthWest();
				var northEast = bounds.getNorthEast();
				var south = southWest.lat();
				var north = northEast.lat();
				var east = northEast.lng();
				var west = southWest.lng();
		

				
				var xmlurl = "loadallmarkers.php?north=" + north + "&south=" + south + "&east=" + east + "&west=" + west ; // URL of php file that generates xml with marker data for the current map view. Current map view is specified in the URL.
				
   				google.maps.DownloadUrl(xmlurl, function(data) { // download xml from URL and parse data
  					var xml = google.maps.Xml.parse(data);
  					var markers = xml.documentElement.getElementsByTagName("marker");
  					
  				batch = [];
  				mm.clearMarkers();  // clear all currently displayed markers once xml has been downloaded, but before new markers are created and displayed

  
  					for (var i = 0; i < markers.length; i++) { // iterates through xml nodes, passing data to the createMarker function for each marker
    					var id = markers[i].getAttribute("ID");
    					var title = markers[i].getAttribute("title");
    					var address = markers[i].getAttribute("address");
    					var info = markers[i].getAttribute("info");
    					var modificationdate = markers[i].getAttribute("modificationdate");
    				
    					var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
    					var commentcount = markers[i].getAttribute("commentcount");
    					
    					var comments = [];
    					    					
    					if(commentcount > 0){
    					
    						for (var j = 0; j < commentcount; j++){
    						
    							comments.push('<div id="markercomment">' + markers[i].childNodes[j].getAttribute("date") + '<br><br>' + markers[i].childNodes[j].getAttribute("commenttext") + '</div>');
    						}
    					
    						
    					
    					}
    					
    					
    					comments = comments.join("<br\>");
    					
    					
    					var marker = createMarker(point, id, title, address, info, modificationdate,commentcount,comments); // calls createMarker for each maker
    					
    					mm.addMarker(marker,0); // displays the marker just created by createMarker
						
   					}
   					
   					
				});


			} else { 
			
				//   == if zoom level does NOT exceed threshold load some markers in the map view == 

				// detect the latitudes and longditudes that bound the current map view
				var bounds = map.getBounds();
				var southWest = bounds.getSouthWest();
				var northEast = bounds.getNorthEast();
				var south = southWest.lat();
				var north = northEast.lat();
				var east = northEast.lng();
				var west = southWest.lng();
				

				
				var size = map.getSize();
				
				var xmlurl = "loadsomemarkers.php?north=" + north + "&south=" + south + "&east=" + east + "&west=" + west + "&size=" + size;// URL of php file that generates xml with SOME marker data for the current map view. Current map view is specified in the URL. This file divides the current map view into a number of regions and gives 1 marker to represent all markers in that region. Because these markers represent clusters, only the id, lng, and lat of these markers are retreived.
				
  				google.maps.DownloadUrl(xmlurl, function(data) {
  					var xml = google.maps.Xml.parse(data);
 					var markers = xml.documentElement.getElementsByTagName("marker");
  
  
  					batch = [];
  					mm.clearMarkers(); // clear all currently displayed markers once xml has been downloaded, but before new markers are created and displayed


  
 					for (var i = 0; i < markers.length; i++) { // iterates through xml nodes, passing data to the createMarker function for each marker
    					var id = markers[i].getAttribute("ID");
    					var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
    					var count = markers[i].getAttribute("count");
    					
    					var sth = markers[i].getAttribute("s");
    					var nth = markers[i].getAttribute("n");
    					var est = markers[i].getAttribute("e");
    					var wst = markers[i].getAttribute("w");
    					
    					clusterbounds = new google.maps.LatLngBounds();
    					clusterbounds.extend(new google.maps.LatLng(nth,est));
    					clusterbounds.extend(new google.maps.LatLng(sth,wst));
    					

    					var marker = createClusterMarker(point, id, count, clusterbounds); // calls createClusterMarker for each maker
    					
    					mm.addMarker(marker,0);
					
   						
					}
					
					
				});

			}

		}

		function replaceURLWithHTMLLinks(text) {
   			 var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  			  return text.replace(exp,"<a href='$1'>$1</a>"); 
		}







		// == creates regular markers ==
		function createMarker(point, id, title, address, info, modificationdate, commentcount, comments, newmarker) {
		
	
		
  			var marker = new google.maps.Marker(point, {title: title, zIndexProcess:setLowZIndex});
  			
  			info = replaceURLWithHTMLLinks(info);
 			var infohtml = '<DIV STYLE=overflow:auto;max-width:400;max-height:500px><b>' + title +'</b><br>' + address + '<br><br><div id="markerinfo">' + info + '</div><div id="disclaimer">Information is contributed and edited by users of this site, and may be inaccurate or out of date.</div><br><i>Last Updated: ' + modificationdate + '</i><br><br> <a href="editmarker.php?id=' + id + '">Edit this marker</a> | <a href="marker.php?id=' + id + '">Permalink</a></div>';
 			
 			commenthtml = '<DIV STYLE=overflow:auto;max-width:400;max-height:500px><a href="newcomment.php?id=' + id + '"> Add a comment</a><br><br>' + comments + '</div>';
 			
 			google.maps.Event.addListener(marker, 'click', function() {
    			marker.openInfoWindowTabsHtml([new google.maps.InfoWindowTab('Info', infohtml), new google.maps.InfoWindowTab('Comments (' + commentcount +')', commenthtml)]);
 			});
  			
  			return marker;
  
		}

		// == creates Searched markers ==
		function createSearchedMarker(point, id, title, address, info, modificationdate, commentcount, comments, type, i) {

		
			if (type == 1){
			var markercolour = "#E75D56";
			resultcolour = "red";
			
			
			} else if (type == 2){
			var markercolour = "#5893FB";
			resultcolour = "blue";
			}

		
			var searchedMarkerIcon = MapIconMaker.createLabeledMarkerIcon({label: lettersarray[i] , primaryColor: markercolour});
		
  			var marker = new google.maps.Marker(point, {title: title, icon: searchedMarkerIcon, zIndexProcess:setHighZIndex});
  			
  						if (type == 1){
			info = replaceURLWithHTMLLinks(info);
 			var infohtml = '<DIV STYLE=overflow:auto;max-width:400;max-height:500px><b>' + title +'</b><br>' + address + '<br><br><div id="markerinfo">' + info + '</div><br><i>Last Updated: ' + modificationdate + '</i><br><br> <a href="editmarker.php?id=' + id + '">Edit this marker</a> | <a href="marker.php?id=' + id + '">Permalink</a></div>';
 			
 			commenthtml = '<DIV STYLE=overflow:auto;max-width:400;max-height:500px><a href="newcomment.php?id=' + id + '"> Add a comment</a><br><br>' + comments + '</div>';
 			


 			
 			google.maps.Event.addListener(marker, 'click', function() {
 			

 						 			zoom = map.getZoom();
		
		 
			if(zoom <= zoomthresh){ 
						map.setCenter(point, 18);}
 			          var iwAnchor = marker.getIcon().infoWindowAnchor;
          var iconAnchor = marker.getIcon().iconAnchor;
          var offset = new google.maps.Size(iwAnchor.x-iconAnchor.x,iwAnchor.y-iconAnchor.y);
    			map.openInfoWindowTabsHtml(marker.getLatLng(),[new google.maps.InfoWindowTab('Info', infohtml), new google.maps.InfoWindowTab('Comments (' + commentcount +')', commenthtml)],{pixelOffset:offset});
 			});
			
			
			} else if (type == 2){
			
	
 			
			var infohtml = '<div align="center"><br>' + title + '<br>'+ address + '<br><br><a href="newmarker.php?latLng=' + point + '&address=' + address + '&title=' + title +  '">Enter new access info for this location</a><br><br>(Note: co-ordinates of this marker are only approximate.<br>You may need to create a new marker at the correct co-ordinates.)</div>';
			
			 			google.maps.Event.addListener(marker, 'click', function() {
			 			zoom = map.getZoom();
		
		 
			if(zoom <= zoomthresh){ 
						map.setCenter(point, 18);}
						
			 			 			          var iwAnchor = marker.getIcon().infoWindowAnchor;
          var iconAnchor = marker.getIcon().iconAnchor;
          var offset = new google.maps.Size(iwAnchor.x-iconAnchor.x,iwAnchor.y-iconAnchor.y);
    			map.openInfoWindowHtml(marker.getLatLng(),infohtml,{pixelOffset:offset});
 			});
			}
  			
  			
  			
			gmarkers.push(marker);
			
			    					resultdiv = document.createElement("div");
    					
    					resultdiv.className = "result";
    					
    					resultdiv.id = "result"+i;
    					
    					resultdiv.innerHTML =  '<img src="MarkerImages/'+resultcolour+ '_Marker'+ lettersarray[i]+ '.png" align="left" ><a href="javascript:myclick('+i+');"><div class="title">' + title + '</div></a><div class="address">'+address+'</div><br>'
    					
    					document.getElementById("searchresults").appendChild(resultdiv);
  			
  			return marker;
  
		}


function setHighZIndex(marker){
return google.maps.Overlay.getZIndex(marker.getPoint().lat())+10000000;


}

function setLowZIndex(marker){
return google.maps.Overlay.getZIndex(marker.getPoint().lat())-10000000;


}

		// == creates 'cluster' markers == 
		function createClusterMarker(point, id, count, clusterbounds) {
		
	    


		var clusterIcon = MapIconMaker.createFlatIcon({width: 23, height: 23, label: count, primaryColor: "#E59393"});

    		var marker = new google.maps.Marker(point, {title: count + ' marker(s). Click to zoom', icon: clusterIcon});
		
		
	   		
    		google.maps.Event.addListener(marker, 'click', function() { 
    			
    			map.setCenter(point,map.getBoundsZoomLevel(clusterbounds));
    		 	
    			
  			});
  			
  			return marker;
		}







	




		// == places new marker at center of map view ==
		function dropNewMarker(){

			zoom = map.getZoom();
			if(zoom >= zoomthresh){ // tests whether current zoom level exceeds zoom threshold. If so, new dragable marker is created at the map center.

				var bounds = map.getBounds();
				var center = bounds.getCenter();
				var marker = new google.maps.Marker(center, {draggable: true});

				google.maps.Event.addListener(marker, "dragstart", function() { // close info window on drag start
  					map.closeInfoWindow();
 		 		});
	
				google.maps.Event.addListener(marker, "dragend", function() { // on drag end, call function which opens info window 
 					displayNewMarkerOptions(marker);
  				});

				google.maps.Event.addListener(marker, "click", function() { // when marker is clicked, call function which opens info window 
  					displayNewMarkerOptions(marker);
 		 		});


   				map.addOverlay(marker); // display the marker
    			displayNewMarkerOptions(marker); // call
    	
    		} else { // if zoom level does not exceed zoom threshold, display alert. 
    		alert('You must zoom in to street level before you can create a new marker');
    		
    		}
    
		}



		// == opens an info window for a new marker and displays lng/lat and a link to enter new information == 

		function displayNewMarkerOptions(marker){ 
			latLng = marker.getLatLng();

			text = '<div align="center"><b>New Marker</b><br>Lat/Lng: ' + latLng + '<br><br><a href="newmarker.php?latLng=' + latLng + '">Enter new access info for this location</a><br><br>(Drag this marker to reposition it)</div>';
			marker.openInfoWindowHtml(text);
		}    
    




function loadMarkerFeed(urlstem){

	// detect the latitudes and longditudes that bound the current map view
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var south = Math.round(southWest.lat()*1000000)/1000000;
	var north = Math.round(northEast.lat()*1000000)/1000000;
	var east = Math.round(northEast.lng()*1000000)/1000000;
	var west = Math.round(southWest.lng()*1000000)/1000000;
	
	window.location = urlstem + "?north=" + north + "&south=" + south + "&east=" + east + "&west=" + west;
}

function loadURLForView(){

	// detect the latitudes and longditudes that bound the current map view
	var bounds = map.getBounds();
	zoom = map.getZoom(); // detects current zoom level
	center = bounds.getCenter();
	alert("http://www.accessibilitymapr.com/index.php?lat=" + center.lat() + "&lng=" + center.lng() + "&zoom=" + zoom);
	window.location = "index.php?lat=" + center.lat() + "&lng=" + center.lng() + "&zoom=" + zoom;
}

function doSearch(q){

q = q.replace(' ','+');


var bounds = map.getBounds();
var center = bounds.getCenter();
sspn = bounds.toSpan().toUrlValue();

var xmlurl = "mapsearchresults.php?lat="+center.lat()+"&lng="+center.lng()+"&search="+q+"&sspn="+sspn;



    					document.getElementById("searchcontainer").removeChild(document.getElementById("searchresults"));
    					    					
    					    					
    					    					div = document.createElement("div");
    					
   					
    					div.id = "searchresults";
    					
    					document.getElementById("searchcontainer").appendChild(div);
    					
    					
   				google.maps.DownloadUrl(xmlurl, function(data) { // download xml from URL and parse data
  					var xml = google.maps.Xml.parse(data);
  					var markers = xml.documentElement.getElementsByTagName("marker");
  					
  					
  					gmarkers = Array();
  					
  						if(markers.length == 0) { 	
    							resultdiv = document.createElement("div");
    					
    					    					
    					resultdiv.id = "noresults";
    					
    					resultdiv.innerHTML =  'No results for current map view<br><br>(try zooming the map or using different search terms)';
    					
    					document.getElementById("searchresults").appendChild(resultdiv);
    					
    					} else {
    					
    					resultdiv = document.createElement("div");
    					
    					    					
    					resultdiv.id = "resultsheader";
    					
    					resultdiv.innerHTML =  'Top results for current map view <br>(<a href="javascript: clearSearchResults();">clear results</a>)<br><br>';
    					
    					document.getElementById("searchresults").appendChild(resultdiv);
    					
    					
    					resultdiv = document.createElement("div");
    					
    					    					
 
    					


    					
    					}
    					
				var bounds = new GLatLngBounds();
  				
  				smm.clearMarkers();  // clear all currently displayed markers once xml has been downloaded, but before new markers are created and displayed

  
  					for (var i = 0; i < markers.length; i++) { // iterates through xml nodes, passing data to the createMarker function for each marker
  						var type = markers[i].getAttribute("type");
    					var id = markers[i].getAttribute("ID");
    					var title = markers[i].getAttribute("title");
    					var address = markers[i].getAttribute("address");
    					var info = markers[i].getAttribute("info");
    					var modificationdate = markers[i].getAttribute("modificationdate");
    				
    					var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
    					var commentcount = markers[i].getAttribute("commentcount");
    					
    					var comments = [];
    					    					
    					if(commentcount > 0){
    					
    						for (var j = 0; j < commentcount; j++){
    						
    							comments.push('<div id="markercomment">' + markers[i].childNodes[j].getAttribute("date") + '<br><br>' + markers[i].childNodes[j].getAttribute("commenttext") + '</div>');
    						}
    					
    						
    					
    					}
    					
    					
    					comments = comments.join("<br\>");
    					
			
    					
    					var marker = createSearchedMarker(point, id, title, address, info, modificationdate,commentcount,comments,type,i); // calls createMarker for each maker
    					
    					
    					
    					smm.addMarker(marker,0,19); // displays the marker just created by createMarker
    					
						bounds.extend(point);
						
   					}
   					
   								    					
    			if(markers.length != 0) { 		
    			
    					

    					
    					   					 map.setZoom(map.getBoundsZoomLevel(bounds)-1);			
	   map.setCenter(bounds.getCenter());	
				}
   					

   					
				});
				
				
		
	
}

      function myclick(i) {
     	
		zoom = map.getZoom();
		
		 
			if(zoom <= zoomthresh){ // tests whether zoom level exceeds threshold
       map.setCenter(gmarkers[i].getLatLng(),18);
     
          
       }
       

       
       google.maps.Event.trigger(gmarkers[i], "click");
	
      }


function clearSearchResults(){

smm.clearMarkers(); document.getElementById("searchcontainer").removeChild(document.getElementById("searchresults"));
    					    					div = document.createElement("div");
    					
   					
    					div.id = "searchresults";
    					
    					document.getElementById("searchcontainer").appendChild(div);
}


function loadaddControl() {
function addControl() {
};

    addControl.prototype = new google.maps.Control();

	addControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var buttonDiv = document.createElement("div");
  this.setButtonStyle_(buttonDiv);
  container.appendChild(buttonDiv);
  buttonDiv.appendChild(document.createTextNode("Create new marker"));
  google.maps.Event.addDomListener(buttonDiv, "click", function() {
    dropNewMarker();
  });



  map.getContainer().appendChild(container);
  return container;
}
addControl.prototype.getDefaultPosition = function() {
  return new google.maps.ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(70, 12));
}
addControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "11em";
  button.style.cursor = "pointer";
}
map.addControl(new addControl());

}


function setHeight(){
var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
document.getElementById("mapcontainer").style.height=(windowHeight-87);
document.getElementById("map_canvas").style.height=(windowHeight-117);
document.getElementById("sidebarscrolldiv").style.height=(windowHeight-95);
}


google.setOnLoadCallback(initialize);
