<!-- ============================================================================== -->
<!-- Google Maps API V2                                              -->
<!-- ============================================================================== -->

document.write('<script type="text/javascript" src="map/textualZoomControl.js" ></script>');

// Google map.
var _map=null;

// markers to display on map, populated from XML files
var _markers = null;

// lacation data for markers
var _locations = null;

// current tooltip to display
var _tooltip = document.createElement("div");

// text to display on infowindow
var _text = '';

var _timescale = '';
//alert("timescale at top of gmaps is " + _timescale);

var _URL_HOST_SITE = "/cdmf-webserver/map/";

var _minimumZoomLevel = 10; //the minimum level the user can zoom out to. (i.e. out the way)

//Get the state of the checkboxes for toggling events before automatically loading the icons
//so as to restrict what are loaded if they were toggled off before a refresh

<!-- ============================================================-->
<!-- initMap                                                     -->
<!-- this is called by the edinburghMap.jsp to show the map. 	     -->   
<!-- if ID is null it is an overview map showing ALL events, if  -->
<!-- ID is not null we are displaying an event on the map	     -->
<!-- ============================================================-->
function initMap(doc, lat, lon, zoom, id, timescale) 
{
    _markers = new Array();
    _locations = new Array();
    
    // show the map
    _map = new GMap2(doc.getElementById("map"));

    _map.addControl(new GLargeMapControl());
    _map.addControl(new GScaleControl());

	_timescale = parseInt(timescale);
	//alert("timescale in initMap of gmaps is " + _timescale);

	var zoomInt = parseInt(zoom);
	var longInt = parseFloat(lon);
	var latInt = parseFloat(lat);
	  
	_map.setCenter(new GLatLng(latInt, longInt), zoomInt);

 	restrictZoomLevel();

    _map.addControl(new GOverviewMapControl(new GSize(150,150)));
    _map.addControl(new TextualZoomControl());
	_map.enableDoubleClickZoom();
	
	loadMarkers(id);
	
    // add a boundry polyline
    addBoundry();
    
    // Add a move listener to restrict the bounds range
    GEvent.addListener(_map, "move", function() 
    {
        checkBounds();
    });      
}

<!-- ====================================-->
<!-- removeEvents                        -->
<!-- Removes events on the map           -->
<!-- ====================================-->
function removeEvents(typeOfEvent)
{
	_map.closeInfoWindow();

	// first remove all the event markers
	for (var i=0; i <_markers.length; i++) 
	{	
		if (_markers[i].type == typeOfEvent)
		{
			_map.removeOverlay(_markers[i] );
			_markers[i].isVisible=false;
		}
	}
}

<!-- ====================================-->
<!-- removeEvents                        -->
<!-- Removes events on the map           -->
<!-- ====================================-->
function removeAllEvents()
{
	_map.closeInfoWindow();

	// first remove all the event markers
	for (var i=0; i <_markers.length; i++) 
	{	

		_map.removeOverlay(_markers[i] );
		_markers[i].isVisible=false;
	}
}

<!-- ==================================-->
<!-- addEvents                         -->
<!-- Adds events to the map            -->
<!-- ==================================-->
function addEvents(typeOfEvent)
{	
	removeEvents(typeOfEvent);
	
	var timescale = document.timescale.timescalelist.options[document.timescale.timescalelist.selectedIndex].value
		
	for (var i=0; i <_markers.length; i++) 
	{	
		var markerTimescaleDays = parseInt(_markers[i].timescale);
		var timescaleDays = parseInt(timescale);
	
		_markers[i].isVisible=false;
	
		if (_markers[i].type == typeOfEvent && markerTimescaleDays <= timescaleDays)
		{
			_map.addOverlay(_markers[i] );
			_markers[i].isVisible=true;
		}
	}
}


<!-- =======================================================-->
<!-- showEvents                                             -->
<!-- Shows events on the map by using the overlay           -->
<!-- =======================================================-->
function showEvents(timescale)
{
	_map.closeInfoWindow();
	
	if (timescale == 'Now')
	{
		timescale = 0;
	}

	// first remove all the event markers
	for (var i=0; i <_markers.length; i++) 
	{	
		_map.removeOverlay(_markers[i] );
		_markers[i].isVisible=false;
	}

	for (var i=0; i <_markers.length; i++) 
	{

		//alert('Marker is |' + _markers[i].type + '| timescale is |' + timescale + '|');
		var markerTimescaleDays = parseInt(_markers[i].timescale);
		var timescaleDays = parseInt(timescale);

		_markers[i].isVisible=false;

		//alert("marker at i type is " + _markers[i].type);

		if (markerTimescaleDays <= timescaleDays)
		{	
			if((_markers[i].type == 'Carparks') && (document.getElementById("carpark").checked==true))
			{
				_map.addOverlay(_markers[i] );
				_markers[i].isVisible=true;
				//alert("car parks was ticked and should be displayed");
			}		
			if((_markers[i].type == 'Vms') && (document.getElementById("vms").checked==true))
			{
				_map.addOverlay(_markers[i] );
				_markers[i].isVisible=true;
				//alert("vms was ticked and should be displayed");
			}
			//temporarily comment this out because we don't want to display incidents for now
			// JIRA issue http://ukglasas02:8080/browse/EDINCPG-127
			//if((_markers[i].type == 'Incidents') && (document.getElementById("incident").checked==true))
			//{
				
				//_map.addOverlay(_markers[i] );
				//_markers[i].isVisible=true;
				//alert("incidents was ticked and should be displayed");
			//}
			//temporarily comment this out because we don't want to display roadworks for now
			// JIRA issue http://ukglasas02:8080/browse/EDINCPG-127
			//if((_markers[i].type == 'Roadworks') && (document.getElementById("roadwork").checked==true))
			//{
				
				//_map.addOverlay(_markers[i] );
				//_markers[i].isVisible=true;
				//alert("roadworks was ticked and should be displayed");
			//}
			//temporarily comment this out because we don't want to display accidents for now
			// JIRA issue http://ukglasas02:8080/browse/EDINCPG-127
			//if((_markers[i].type == 'Accidents') && (document.getElementById("accident").checked==true))
			//{
				
				//_map.addOverlay(_markers[i] );
				//_markers[i].isVisible=true;
				//alert("accidents was ticked and should be displayed");
			//}
			if((_markers[i].type == 'Events') && (document.getElementById("event").checked==true))
			{
				_map.addOverlay(_markers[i] );
				_markers[i].isVisible=true;
				//alert("events was ticked and should be displayed");
			}

		}
	}
}

<!-- ============================================================-->
<!-- restrictZoomLevel                                           -->
<!-- Restricts the user from zooming out to far                  -->
<!-- ============================================================-->
function restrictZoomLevel()	
{
	// ====== Restricting the range of Zoom Levels =====
    // Get the list of map types      
    var mt = _map.getMapTypes();
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i=0; i<mt.length; i++) {
        mt[i].getMinimumResolution = function() {return _minimumZoomLevel;}
    }
}

<!-- ============================================================-->
<!-- loadMarkers                                                -->
<!-- Load the map markers into memory from the XML files         -->
<!-- ============================================================-->
function loadMarkers(id)
{
	
    // load all the markers
    loadMapXML(_URL_HOST_SITE+"/data/carParks.xml", _map, id, 'Carparks');
    loadMapXML(_URL_HOST_SITE+"/data/accidents.xml", _map, id, 'Accidents');
    loadMapXML(_URL_HOST_SITE+"/data/roadworks.xml", _map, id, 'Roadworks');
    loadMapXML(_URL_HOST_SITE+"/data/events.xml", _map, id, 'Events');
    loadMapXML(_URL_HOST_SITE+"/data/vms.xml", _map, id, 'Vms');
    loadMapXML(_URL_HOST_SITE+"/data/incidents.xml", _map, id, 'Incidents');	
    
}


<!-- ============================================================-->
<!-- loadMapXML                                                 -->
<!-- Load the map markers into memory from the XML files         -->
<!-- ============================================================-->
function loadMapXML(url, ctrl, id, type) 
{
    // IE is caching the xml file instead of reloading it.  
    // add random numbers to the url, to force IE to reload.
    GDownloadUrl(url + "?r=" + Math.random(), function(data, responseCode) 
    {   
		if(responseCode == 200)
		{
			var xml = GXml.parse(data);
	        processMapXML(xml, ctrl, type)
			showMarker(id)
		}
		else
		{
			alert("Failed to load map XML.");
		}
    });
}

<!-- ============================================================-->
<!-- showMarker                                                  -->
<!-- Show a marker on the map         							 -->
<!-- ============================================================-->
function showMarker(id)
{
    var found = false;
    var index = 0;
    
    // find the ID in the list of markers
    while (!found && index<_markers.length)
    {
    	// does the ID exist in the location XML
        if (_locations[index].getAttribute("id")==id)
        {			
        	_markers[index].id = id;
        	
        	if (_markers[index].isVisible)
        	{
	        	// yes, display the info window for this ID
				GEvent.trigger(_markers[index],'click');        	    		
			}
			found = true;
        }
        index++;
    }
}

<!-- =============================================================-->
<!-- processMapXML                                                -->
<!-- Creates the markers and adds them to the map        		  -->
<!-- =============================================================-->
function processMapXML(xmlDoc, ctrl, type)
{   
    var locations = xmlDoc.documentElement.getElementsByTagName("location");

    if (locations == null)
    {
		return;
    }
  
    var amount = _markers.length;
    
    for (var i=0; i <locations.length; i++) 
    {
        var marker = createMarker( locations[i], i,type );

	 	var markerTimescaleDays = parseInt(marker.timescale);
	 	var timescaleDays = parseInt(_timescale);

		marker.isVisible=false;
		
        if (markerTimescaleDays <= timescaleDays)
	  	{
           if((marker.type == 'Carparks') && (document.getElementById("carpark").checked==true))
			{
				ctrl.addOverlay( marker );
           		marker.isVisible=true;
				//alert("car parks was ticked and should be displayed");
			}		
			if((marker.type == 'Vms') && (document.getElementById("vms").checked==true))
			{
				ctrl.addOverlay( marker );
           		marker.isVisible=true;
				//alert("vms was ticked and should be displayed");
			}
			/* temporarily commented out because we don't want incidents displayed at present
			// JIRA issue http://ukglasas02:8080/browse/EDINCPG-127
			if((marker.type == 'Incidents') && (document.getElementById("incident").checked==true))
			{
				ctrl.addOverlay( marker );
           		marker.isVisible=true;
				//alert("incidents was ticked and should be displayed");
			}
			*/
			/* temporarily commented out because we don't want roadworks displayed at present
			// JIRA issue http://ukglasas02:8080/browse/EDINCPG-127
			if((marker.type == 'Roadworks') && (document.getElementById("roadwork").checked==true))
			{
				ctrl.addOverlay( marker );
           		marker.isVisible=true;
				//alert("roadworks was ticked and should be displayed");
			}
			*/
			/* temporarily commented out because we don't want accidents displayed at present
			// JIRA issue http://ukglasas02:8080/browse/EDINCPG-127
			if((marker.type == 'Accidents') && (document.getElementById("accident").checked==true))
			{
				ctrl.addOverlay( marker );
           		marker.isVisible=true;
				//alert("accidents was ticked and should be displayed");
			}
			*/
			if((marker.type == 'Events') && (document.getElementById("event").checked==true))
			{
				ctrl.addOverlay( marker );
           		marker.isVisible=true;
				//alert("events was ticked and should be displayed");
			}
           
           
           //ctrl.addOverlay( marker );
           //marker.isVisible=true;
	  	}        	       
        
        _markers[amount] = marker;
        _locations[amount] = locations[i];
		amount++;
    }
}

<!-- ===============================================================-->
<!-- showTooltip                                               		-->
<!-- Dsiplays a tooltip for a given marker       		  			-->
<!-- ===============================================================-->
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";
	_tooltip.style.backgroundColor="white";
}

<!-- ===============================================================-->
<!-- createMarker                                              		-->
<!-- Creates and returns a marker.			     		  			-->
<!-- ===============================================================-->
function createMarker(location, i, type) 
{    
    var line1 = '';
    var line2 = '';
    var line3 = '';
    var line4 = '';
    var message = '';

    var divLine = '';

    nodes = location.getElementsByTagName("line1");
    if (nodes != null && nodes[0] != null)
    {
    	/*
    	Note that we replace the '~' character with a line break
    	due to the updates for CVP 29 - Dynamic Data on SVMS
    	*/
        line1 = nodes[0].firstChild.nodeValue;
        line1 = line1.replace(/~/g,"<br/>");
		divLine = "<div style=\"text-align:left;width:300px\"><FONT SIZE=2>"+line1+"</font><br>";
    }

    nodes = location.getElementsByTagName("line2");
    if (nodes != null && nodes[0] != null)
    {
        line2 = nodes[0].firstChild.nodeValue;
		divLine += line2+"<br>";
    }

    nodes = location.getElementsByTagName("line3");
    if (nodes != null && nodes[0] != null)
    {
        line3 = nodes[0].firstChild.nodeValue;
        if (line3 != 'No Contact Details')
        {
	    	divLine += line3+"<br>";
        }
    }

    nodes = location.getElementsByTagName("line4");
    if (nodes != null && nodes[0] != null)
    {
        line4 = nodes[0].firstChild.nodeValue;
		divLine += line4+"<br>";
    }
    nodes = location.getElementsByTagName("message");
    if (nodes != null && nodes[0] != null)
    {
        message = nodes[0].firstChild.nodeValue;
		divLine += message+"<br>";
    }

    divLine += "</div>";
	
    var timescale = 0;
    nodes = location.getElementsByTagName("timescale");

    if (nodes != null && nodes[0] != null)
    {
		timescale = nodes[0].firstChild.nodeValue;
    }

	// get the xml for the infoWindow
    var tablenodes = location.getElementsByTagName("table");    

    // depending on the browser, get the xml from the tablenodes node.
    var markup = '';

    if (navigator.appName.indexOf('Microsoft') != -1)
    {
		var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
		xmlDocument.appendChild(tablenodes[0]);
		// serialize
    	markup = xmlDocument.xml;
    }
    else
    {
		var xmlSerializer = new XMLSerializer();
      	markup = xmlSerializer.serializeToString(tablenodes[0]);
    }

    // --------------------       
    var points = location.getElementsByTagName("point");
    var lng = parseFloat( points[0].getAttribute( "lng" ));
    var lat = parseFloat( points[0].getAttribute( "lat" ));
    var point = new GPoint( lng, lat );
    
    var icon = location.getElementsByTagName("icon");
    var iconImage = icon[0].getAttribute("image");
    
    var icon = new GIcon( baseIcon );
    icon.image = _URL_HOST_SITE+iconImage;
    var marker = new GMarker( point, icon );
    marker.type = type;
    marker.timescale = timescale;
    marker.isVisible = false;

    marker.tooltip = '<div class="tooltip">'+divLine+'</div>';

    _map.getPane(G_MAP_FLOAT_PANE).appendChild(_tooltip);
    

    GEvent.addListener( marker, "click", function() 
    {
        //detailmap.setCenter(point , 13); 
        
        marker.openInfoWindowHtml(markup);	
        	    	
    });

    GEvent.addListener(marker,"mouseover", function() 
    {
        showTooltip(marker);
    }); 
       
    GEvent.addListener(marker,"mouseout", function() 
    {
		_tooltip.style.visibility="hidden"
    });
   
    return marker;
}

   
<!-- ===============================================================-->
<!-- checkBounds                                             		-->
<!-- If the map position is out of range, move it back		     	-->
<!-- ===============================================================-->
function checkBounds() 
{
	// The allowed region which the whole map must be within												
	var _allowedBounds = new GLatLngBounds(new GLatLng(55.448560,-4.254552), new GLatLng(56.258432,-2.623037)); //bottom left, top right
	
    // Perform the check and return if OK
    if (_allowedBounds.contains(_map.getCenter())) 
    {
      return;
    }

    // It`s not OK, so find the nearest allowed point and move there
    var C = _map.getCenter();
    var X = C.lng();
    var Y = C.lat();

    var AmaxX = _allowedBounds.getNorthEast().lng();
    var AmaxY = _allowedBounds.getNorthEast().lat();
    var AminX = _allowedBounds.getSouthWest().lng();
    var AminY = _allowedBounds.getSouthWest().lat();

    if (X < AminX) {X = AminX;}
    if (X > AmaxX) {X = AmaxX;}
    if (Y < AminY) {Y = AminY;}
    if (Y > AmaxY) {Y = AmaxY;}

    _map.setCenter(new GLatLng(Y,X));
}

<!-- ===============================================================-->
<!-- process_it                                             		-->
<!-- Reads the region boundry values from a text file.		     	-->
<!-- ===============================================================-->
process_it = function(doc, responseCode) {
    // === split the document into lines ===
    lines = doc.split("\n");
	var polpoints = [] ;

	if(responseCode == 200)
	{
		for (var i=0; i<lines.length; i++) 
		{
	      	if (lines[i].length > 1) 
	  		{
	            // === split each line into parts separated by "|" and use the contents ===
	            parts = lines[i].split(",");
	            var lat = parseFloat(parts[0]);
	            var lng = parseFloat(parts[1]);
	
	   	    	polpoints.push(new GLatLng(lat, lng)) ;
	      	}
	    }
	
	    _map.addOverlay( new GPolyline(polpoints,"#FFFF00", 10, 0) ) ; 
	    //_map.addControl(new GxMagnifierControl());   
	}
	else
	{
		alert("Failed to initialise boundary box values.");
	}
}          
          
<!-- ===============================================================-->
<!-- addBoundry                                             		-->
<!-- Adds a boundry to the map. The boundry points are read from    -->
<!-- a text file west_sussex_boundary_points.txt		     	    -->
<!-- ===============================================================-->
function addBoundry()
{
	GDownloadUrl(_URL_HOST_SITE + "edinburgh_boundary_points.txt", process_it);
}

<!-- ===============================================================-->
<!-- zoomTo                                            				-->
<!-- Zooms to an area on the map									-->
<!-- ===============================================================-->
function zoomTo(lon, lat, zoom) 
{
	_map.setCenter(new GLatLng(lat, lon), zoom);
}

////////////////////////////////////////////////////////////////////////////////
// Show events on the map. The events show will either be the information
// parameter passed in or the current selected value in the information drop down
////////////////////////////////////////////////////////////////////////////////
function disp_text()
{
   //var selected_timescale = '0'; 

   var selected_timescale = _timescale; 
   //alert("current timescale is " + selected_timescale);	
	
   if (document.timescale.timescalelist != null)
   {
		var w = document.timescale.timescalelist.selectedIndex;
		selected_timescale = document.timescale.timescalelist.options[w].value;
   }
   
   //if(trafficInfoTimescale != null)
   //{
   //		set the selected timescale from traffic info into the map
   //}
   	
   //showEvents('30');
   showEvents(selected_timescale);
   
   _timescale = selected_timescale;
   
   //Perhaps put in some code here to only show evetns that are toggled on in the map
   //document.getElementById("carpark").checked="true";
   //document.getElementById("roadwork").checked="true";
   //document.getElementById("event").checked="true";
   //document.getElementById("accident").checked="true";
   //document.getElementById("incident").checked="true";
   //document.getElementById("vms").checked="true";
}



var roadworks="on";
var events="on";
var accidents="on";
var incidents="on";
var bbc="on";
var trains="on";
var airports="on";
var parking="on";
var vms="on";

function switchRoadworksOn()
{
	roadworks="on";
	addEvents('Roadworks');	
}

function toggleRoadworksOnMap()
{   
	if (roadworks.valueOf() == 'on')
	{
		roadworks="off";
		removeEvents('Roadworks');
	}
	else
	{
		switchRoadworksOn();	
	}
}

function switchEventsOn()
{
	events="on";
	addEvents('Events');	
}

function toggleEventsOnMap()
{
	if (events.valueOf() == 'on')
	{
		events="off";
		removeEvents('Events');
	}
	else
	{
		switchEventsOn();	
	}
}

function switchAccidentsOn()
{
	accidents="on";
	addEvents('Accidents');
}

function toggleAccidentsOnMap()
{
	if (accidents.valueOf() == 'on')
	{
		accidents="off";
		removeEvents('Accidents');
	}
	else
	{
		switchAccidentsOn();	
	}
}

function switchIncidentsOn()
{
	incidents="on";
	addEvents('Incidents');	
}

function toggleIncidentsOnMap()
{
	if (incidents.valueOf() == 'on')
	{
		incidents="off";
		removeEvents('Incidents');
	}
	else
	{
		switchIncidentsOn();	
	}
	return true;
}

function switchTrainsOn()
{
	trains="on";
	document.getElementById('trainButton').src='../images/infinite-eye/b-rail.gif';
	document.getElementById('trainButton').title='Train Stations On';
	addEvents('Trains');
}

function toggleTrainsOnMap()
{
	if (trains.valueOf() == 'on')
	{
		trains="off";
		document.getElementById('trainButton').src='../images/infinite-eye/b-rail-over.gif';
		document.getElementById('trainButton').title='Trains Off';
		removeEvents('Trains');
		
	}
	else
	{
		switchTrainsOn();	
	}
}

function switchAirportsOn()
{
	airports="on";
	document.getElementById('airportButton').src='../images/infinite-eye/b-airports.gif';
	document.getElementById('airportButton').title='Airports On';
	addEvents('Airports');
}

function toggleAirportsOnMap()
{
	if (airports.valueOf() == 'on')
	{
		airports="off";
		document.getElementById('airportButton').src='../images/infinite-eye/b-airports-over.gif';
		document.getElementById('airportButton').title='Airports Off';
		removeEvents('Airports');
	}
	else
	{
		switchAirportsOn();	
	}
}

function switchParkingOn()
{
	parking="on";
	addEvents('Carparks');
}

function toggleParkingOnMap()
{
	if (parking.valueOf() == "on")
	{
		parking="off";
		removeEvents('Carparks');
	}
	else
	{
		switchParkingOn();
	}
	
	return true;
}

function switchVmsOn()
{
	vms="on";
	addEvents('Vms');
}

function toggleVmsOnMap()
{
	if (vms.valueOf() == "on")
	{
		vms="off";
		removeEvents('Vms');
	}
	else
	{
		switchVmsOn();
	}
	
	return true;
}




if (GBrowserIsCompatible()) 
{
    // Create a base icon for all of our markers that specifies the shadow, icon
    // dimensions, etc.
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/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);
}
else 
{	
    document.getElementById("map").innerHTML="<p>The map functionality is currently not available.</p><p>Please select another option.</p>";
}
    
