//define map as a global var so it doesn't need passing around
		var map = null;
		
	
		var lowIcon = new GIcon();
      	lowIcon.image = "images/marker_low.png";
		lowIcon.iconSize = new GSize(31, 40);
		lowIcon.iconAnchor = new GPoint(15, 40);
		lowIcon.infoWindowAnchor = new GPoint(15, 1);
		
		var mediumIcon = new GIcon();
      	mediumIcon.image = "images/marker_medium.png";
		mediumIcon.iconSize = new GSize(31, 40);
		mediumIcon.iconAnchor = new GPoint(15, 40);
		mediumIcon.infoWindowAnchor = new GPoint(15, 1);
		
		var highIcon = new GIcon();
      	highIcon.image = "images/marker_high.png";
		highIcon.iconSize = new GSize(31, 40);
		highIcon.iconAnchor = new GPoint(15, 40);
		highIcon.infoWindowAnchor = new GPoint(15, 1);
		
		function load() {
			  //show the streesearch button if script is loaded
			  $('btnStreetSearch').style.display = "block";
			  $('legend').style.display = "block";
			  $('howto').style.display = "block";
		
		      if (GBrowserIsCompatible()) {
		      	map = new GMap2(document.getElementById("googleMap"));
				map.enableScrollWheelZoom();
		      	/*map.addControl(new GLargeMapControl());*/
				map.addControl(new GSmallZoomControl());
		      	map.addControl(new GMapTypeControl());
				map.addControl(new GScaleControl());
		      	map.setCenter(new GLatLng(53.459335, -2.702293), 12);
				
		        
				//add the dragend event, this reloads the markers when the map has been moved
		      	GEvent.addListener(map, "dragend", function() {
					
          		  	var bounds = map.getBounds();
       				var southWest = bounds.getSouthWest();
        			var northEast = bounds.getNorthEast();
					
					//load the data based on the map that is in the viewport
					getViewportData(southWest,northEast);
        			
        	  	});
			
				//add the zoomend event, this reloads the markers when the map has been zoomed
				GEvent.addListener(map, "zoomend", function() {
					
					
					//load the data based on the map that is in the viewport
					getViewportData();
        			
				});
		           
		      }
		 }
		 
		 /*
		 	calls the url to get the point data for the map
			after getting the data from the filters
		 */
		 function getViewportData(){
		 	var bounds = map.getBounds();
       		var southWest = bounds.getSouthWest();
        	var northEast = bounds.getNorthEast();
			
		 	var paramsHash = filterMap();
			
			//add the coordinate data to the paramsHash
			paramsHash.set('southwest',southWest);
			paramsHash.set('northeast',northEast);
				
			
			new Ajax.Request('loadviewportdata.do?' + paramsHash.toQueryString(), {
  				method: 'get',
				onComplete: function(transport){
     				processJson(transport.responseText);
    			}
  			});
			
		 }
		 
		 /**
		 	function that handles the Json response
		 **/
		 function processJson(json){
		 	//clear the map
		 	map.clearOverlays()
			
			var data = json.evalJSON();
			var noResults = data.noResults;
			
			if(noResults <= 50){
				//get the marker data from the json
				var result = data.result
				$('counter').innerHTML = "Showing " + noResults + " streetworks in current view"
				//loop through the array and output a marker
				for(var i = 0; i < result.length ;i++ ){
					var streetwork = result[i];
					
					createMarker(streetwork);
					
					//there is more than 1 point show a 
					if(streetwork.points.length > 1){
						if(map.getZoom() > 14){
							createPoly(streetwork);
						}
					}
					
				}
			}else{
				$('counter').innerHTML = noResults + " streetworks found in current view. You will only be shown markers when less than 50 are found."
			}
			
		 }
		 
		 /**
		 Function that creates a gMarker with the appropriate icon and
		 info window
		 **/
		 function createMarker(streetwork){
		 	markerOptions = { icon:highIcon };
			if(streetwork.impact == "LOW"){
				markerOptions = { icon:lowIcon };
			}else if(streetwork.impact == "MEDIUM"){
				markerOptions = { icon:mediumIcon };
			}
			
			var marker = new GMarker(new GLatLng(streetwork.points[0].split(":")[0],streetwork.points[0].split(":")[1]), markerOptions)
			
		 	//var marker = new GMarker(new GLatLng(streetwork.latitude, streetwork.longitude), markerOptions);
			
			
			GEvent.addListener(marker, "click", function() {
			
				var html = "<ul>";
				 	html = html + "<li><b>Works Reference:</b> " + streetwork.worksRef + "</li>";
					html = html + "<li><b>Address:</b> " + streetwork.address + ", " + streetwork.locality + "</li>";
					html = html + "<li><b>Location:</b> " + streetwork.location + "</li>";
					html = html + "<li><b>Promoter: </b> " + streetwork.promName + "</li>";
					html = html + "<li><b>Telephone No.:</b> " + streetwork.telephone + "</li>";
					html = html + "<li><b>Proposed Start Date:</b> " + streetwork.planStart + "</li>";
					html = html + "<li><b>Proposed End Date: </b> " + streetwork.planEnd + "</li>";
					html = html + "</ul>";
					
				var tabs = [
      				new GInfoWindowTab("Info", html),
      				new GInfoWindowTab("Description", streetwork.description),
					new GInfoWindowTab("Traffic Control", streetwork.trafficman)
    			];
					
         		 	marker.openInfoWindowTabsHtml(tabs,{maxWidth:300});
				});
					
			map.addOverlay(marker);
		 }
		 
		 
		 /**
		 Function that creates a gPolyLine 
		 **/
		 function createPoly(streetwork){
			//loop through the array and convert each element into gLatLng
			
			var newArr = new Array();
			
			for(var i = 0; i < streetwork.points.length ;i++ ){
			
				var pnt = streetwork.points[i];	
				newArr[newArr.length] = new GLatLng(pnt.split(":")[0],pnt.split(":")[1]);
			}
			
			var color = "";
			
			color = '#DD2223';
			if(streetwork.impact == "LOW"){
				color = '#85B655' ;
			}else if(streetwork.impact == "MEDIUM"){
				color = '#F89C06';
			}
			
		 	var line = new GPolyline(newArr,color,5,1);
			map.addOverlay(line);
		 }
			
			
		 /**
		 Function that retruns a string containg the values of the filters
		 **/
		 function filterMap(){
			var filterHash = new Hash();
			var retData = "";
			//check the filter fields
			//impact
			
			var proposed = $F('proposed');
			var inprogress = $F('inprogress');
			var low = $F('low');
			var medium = $F('medium');
			var high = $F('high');
			
			if(proposed == "true") {
				filterHash.set('proposed','true');
			}else{
				filterHash.set('proposed','false');
			}
			
			if(inprogress == "true") {
				filterHash.set('inprogress','true');
			}else{
				filterHash.set('inprogress','false');
			}
			
			if(low == "true"){
				filterHash.set('low', 'true');
			}else{
				filterHash.set('low', 'false');
			}
			
			if(medium == "true"){
				filterHash.set('medium', 'true');
			}else{
				filterHash.set('medium', 'false');
			}
			
			if(high == "true"){
				filterHash.set('high', 'true');
			}else{
				filterHash.set('high', 'false');
			}
			
			return filterHash;			
			
		 }
		 
		 
		 /**
		 function that returns the street details where the user can 
		 select the correct street.
		 **/
		 function streetSearch(){
		 	var street  = $F('street');
		 
			if(street.length < 1){
				alert("You must enter a street to search for");
			}else{
				//carry on processing
				new Ajax.Request('streetsearch.do?street=' + street, {
  				method: 'get',
				onComplete: function(transport){
     				var data = transport.responseText.evalJSON();
					var streets = data.streets;
					
					var html = '';
					
					if(streets.length > 0){	
						html = html + '<div><b>Select a street to show it on the map.</b></div>';
						html = html + '<ul>';
						for(var i = 0; i < streets.length ;i++ ){
							var street = streets[i];
							var start = street.start;
							start = start.replace("(", "").replace(")","");
							
							var end = street.end;
							end = end.replace("(", "").replace(")","");

							html = html + '<li><a href="#" onclick="gotoStreet(' + start + ',' + end + ')" >' + street.streetName + ', ' + street.locality + '</a></li>';
						}
						html = html + '</ul>';
					}else{
						 html = "<b>No Street could be found.</b>";						
					}
					
					$('streetsearchresults').innerHTML = html;
    			}
  			});	
			}
		 }
		 
		 
		 /*
		 zoom to the street selected
		 */
		 function gotoStreet(startx, starty, endx, endy){
		 	map.setZoom(16);
		 	map.setCenter(new GLatLng(startx, starty));
			getViewportData();
		 }
