// <![CDATA[
$(function() {
		   
	$('#brandCycle').cycle({ 
    	fx:     'fade', 
    	speed:   1000, 
    	timeout: 7000, 
    	//next:   '#brandCycle', 
		prevNextClick: null,
    	pause:   1,
		//random: 1,
		before:  onBefore, 
   		after:   onAfter		
	});
	
	$('.brandBannerBullets li a').click(function() { 
		var brandID = $(this).parents('li').attr('class');		
			brandID = parseFloat(brandID.replace(/item_/, "")) - 1;			
		$('#brandCycle').cycle(brandID);		
		return false; 
	}); 

	function onBefore() { 
   		//$('.slideInner').stop().animate(
		 //	{
		//		height: '0px'		 
		 //	}
		 //); 
		//$('.bestValue').stop().delay(250).animate(
		 //	{
		//		height: '0px'		 
		 //	}
		// );
	} 
	function onAfter() { 
		//$('.slideInner').stop().delay(500).animate(
//		 	{
//				height: '28px'		 
//		 	}
//	 	); 
//		$('.bestValue').stop().delay(750).animate(
//		 	{
//				height: '28px'		 
//		 	}
//	 	); 
	}
	
	$("#formSearch").bind({
		keyup: function() {
			if ($("#formSearch").val().length > 2){
				$.post( "/assets/ajax/mapSearch.php", {	
					searchString : $("#formSearch").val()
				},
				function(results) {
					$("#results").html(results);	 
					$("#formSearchWrap").show();																					 
				});
			} else {
				$("#formSearch").empty();
			}
			$("#formSearchType").val('');
			$('a.brandLogo').removeClass('current');
		},
		focus: function() {
			if ($("#formSearch").val().length > 2){
				$.post( "/assets/ajax/mapSearch.php", {	
					searchString : $("#formSearch").val()
				},
				function(results) {
					$("#results").html(results);	 
					$("#formSearchWrap").show();																					 
				});
			} else {
				$("#formSearch").empty();
			}
			$("#formSearchType").val('');
			$('a.brandLogo').removeClass('current');
		}
	});  
	
	$("#formSearchSubmit").click(function() {
		if($("#formSearchType").val() == "brandSearch") {
			loadBrand($("#formSearchRef").val());
		} else if ($("#formSearchType").val() == "motoSearch") {
			searchMoto($("#formSearch").val(), $("#formSearchRef").val());
		} else {
			searchLocations($("#formSearch").val());
		}
		$.post( "/assets/ajax/searchSave.php", {
			searchString : $("#formSearch").val(),
			searchType : "search"
		});
		return false;
	});                         

	$(".motoLink").live("click", function() {
		$("#formSearch").val($(this).html());
		$("#formSearchRef").val($(this).attr("rel"));
		$("#formSearchType").val('motoSearch');
		$("#formSearchWrap").hide();
		searchMoto($("#formSearch").val(), $("#formSearchRef").val());
		return false;
	});
	
	$(".brandLink").live("click", function() {
		$("#formSearch").val($(this).html().replace(/&amp;/, '&'));
		$("#formSearchRef").val($(this).attr("rel"));
		$("#formSearchType").val('brandSearch');
		$("#formSearchWrap").hide();
		loadBrand($("#formSearchRef").val());
		$('h3.collapsible:first').addClass('open').next('div').show();
		$('a#brand-'+$("#formSearchRef").val()).addClass('current');
		return false;
	});
	
	$(".resultsLink").live("click", function() {
		$("#formSearch").val($(this).html());
		$("#formSearchType").val('locationSearch');
		$("#formSearchWrap").hide();	
		searchLocations($(this).html());
		return false;
	});
	
	$('#closeSuggestions').live("click", function() {
		$("#formSearchWrap").slideUp("normal");
		return false;
	});
	
	$("#directionSubmit").click(function() {
		$("#directions").empty()
		setDirections($("#fromAddress").attr("value"), $("#toAddress").attr("value"), "en");
		$.post( "/assets/ajax/searchSave.php", {
			fromAddress : $("#fromAddress").val(),
			toAddress : $("#toAddress").val(),
			searchType : "routePlan"
		});
		if($("#stepDirectionsCheck").is(":checked")) {
			$("#directions").slideDown();
		} else {
			$("#directions").hide();
		}
		return false;
	});
	
	$('#stepDirectionsCheck').click(function() {
		if ($(this).is(':checked')) {
			$('#directions').slideDown();
		} else {
			$('#directions').slideUp();
		}
	});
	
	$("#motoNearby").live("click", function() {
		searchLocations($(this).attr("rel"));
		return false;
	});
	
	$(".brandLogo").click(function() {
		if($(this).hasClass('current')) {
			$(this).removeClass('current');
			loadBrand();
		} else {
			loadBrand($(this).attr('id').replace(/brand-/, '').toLowerCase());
			$('.brandLogo.current').removeClass('current');
			$(this).addClass('current');
		}
		return false;
	});
	
	$(".poiLogo").click(function() {
		if($(this).hasClass('current')) {
			$(this).removeClass('current');
			loadBrand();
		} else {
			loadBrand($(this).attr('id'));
			$('.poiLogo.current').removeClass('current');
			$(this).addClass('current');
		}
		return false;
	});
	
	$('#mapReset').click(function() {
		showMap();
		$("#formSearch").val('');
		$("#formSearchRef").val('');
		$("#formSearchType").val('');
		$('h3.open').removeClass('open').next('div').slideUp('normal');
		$('a.brandLogo.current').removeClass('current');
		$('a.poiLogo.current').removeClass('current');
		$("#fromAddress").val('');
		$("#toAddress").val('');
		$("#stepDirectionsCheck").attr('checked', 'checked');
		$('label.overlay').labelOver();
		$("#formSearchWrap").hide();
		$("#directions").empty().hide();
		return false;
	});
	
	$('h3.collapsible').click(function() {
		if($(this).hasClass('open')) {
			$('h3.open').removeClass('open').next('div').slideUp('normal');
		} else {
			$('h3.open').removeClass('open').next('div').slideUp('normal');
			$(this).addClass('open').next('div').slideDown('normal');
		}
		return false;
	});
	$('h4.collapsible:last').addClass('lastHeader').next('div').addClass('lastPanel');
	
	if (document.getElementsByTagName) {
		var inputElements = document.getElementsByTagName("input");
		for (i=0; inputElements[i]; i++) {
			if (inputElements[i].className && (inputElements[i].className.indexOf("disableAutoComplete") != -1)) {
				inputElements[i].setAttribute("autocomplete","off");
			}
		}
	}
	
//	$("#routeFromLocation").click(function routePlanFrom(latlng) {
//		$("#fromAddress").val(latlng);
//		if(!$("h3.collapsible:last").hasClass('open')) {
//			$('h3.open').removeClass('open').next('div').slideUp('normal');
//			$("h3.collapsible:last").addClass('open').next('div').slideDown('normal');
//		}
//	});
	$("#routeFromLocation").live("click", function routePlanFrom() {
		latlng = $(this).attr("rel");
		$("#fromAddress").val(latlng);
		if(!$("h3.collapsible:last").hasClass('open')) {
			$('h3.open').removeClass('open').next('div').slideUp('normal');
			$("h3.collapsible:last").addClass('open').next('div').slideDown('normal');
		}
		return false;
	});

//	$("#routeToLocation").click(function routePlanTo(latlng) {
//		alert(latlng);
//		$("#toAddress").val(latlng);
//		if(!$("h3.collapsible:last").hasClass('open')) {
//			$('h3.open').removeClass('open').next('div').slideUp('normal');
//			$("h3.collapsible:last").addClass('open').next('div').slideDown('normal');
//		}
//	});
	$("#routeToLocation").live("click", function routePlanTo() {
		latlng = $(this).attr("rel");
		$("#toAddress").val(latlng);
		if(!$("h3.collapsible:last").hasClass('open')) {
			$('h3.open').removeClass('open').next('div').slideUp('normal');
			$("h3.collapsible:last").addClass('open').next('div').slideDown('normal');
		}
		return false;
	});
	
	var base_url="/";
	var param_lat="-";
	var param_lng="-";
	var param_zoom="-";
	
	// arrays to hold copies of the markers and html used by the sidebar
	// because the function closure trick doesnt work there
	var gmarkers = [];
	var htmls = [];
	var i = 0;
	var b=0;
	
	// Global Variables
	var map;
	var ovcontrol;
	var ovmap;
	var theicon;
	var motosmall;
	var geocoder;
	var gdir;
	var addressMarker;
	var plotRoute;
	var markersArray = [];
	
	// Create our "motosmall" marker icon
	var motosmall = new GIcon();
	motosmall.image = '/development/map/map-small.png';
	motosmall.shadow = '/development/map/icons/shadow.png';
	motosmall.iconSize = new GSize(21,21);
	motosmall.shadowSize = new GSize(32,21);
	motosmall.iconAnchor = new GPoint(0,21);
	motosmall.infoWindowAnchor = new GPoint(11,0);
	motosmall.transparent = '/development/map/icons/transparent.png';
	
	var poiicon = new GIcon();
	poiicon.image = '/development/map/icons/brand_poi_small.png';
	poiicon.shadow = '/development/map/icons/shadow.png';
	poiicon.iconSize = new GSize(21,21);
	poiicon.shadowSize = new GSize(30,21);
	poiicon.iconAnchor = new GPoint(0,21);
	poiicon.infoWindowAnchor = new GPoint(11,0);
	poiicon.transparent = '/development/map/icons/transparent.png';
	
	var hereicon = new GIcon();
	hereicon.image = '/development/map/icons/here_small.png';
	hereicon.shadow = '/development/map/icons/shadow.png';
	hereicon.iconSize = new GSize(21,21);
	hereicon.shadowSize = new GSize(30,21);
	hereicon.iconAnchor = new GPoint(0,21);
	hereicon.infoWindowAnchor = new GPoint(11,0);
	hereicon.transparent = '/development/map/icons/transparent.png';
	
	
	// HISTORY FUNCTIONS
	
	function wheelevent(e){
		if (!e){
			e = window.event;
			}
		if (e.preventDefault){
			e.preventDefault();
			}
		e.returnValue = false;
	}
	
	function mapChangedListener(){
		//Get current map parameters
		param_lat=map.getCenter().lat();
		param_lng=map.getCenter().lng();
		param_zoom=map.getZoom();
		updateLinkToThisPage();
	}
	
	function updateLinkToThisPage() {
		//Save map view parameters to the URL
		var hash = "latitude/"+param_lat+"/longitude/"+param_lng+"/zoom/" + param_zoom;
		var currentHash = $.historyCurrentHash.replace(/^#/, '');
	
		if (hash != currentHash) $.historyLoad(hash);
	}
	
	function historyChange(newLocation){
		//Callback to set map view from URL parameters
		if(param_lat=="-") return;
	
		var place = newLocation.split("/");
	
		if(place.length==6){
			param_lat_new=parseFloat(place[1]);
			param_lng_new=parseFloat(place[3]);
			param_zoom_new=parseFloat(place[5]);
		}else if(place.length==4){
			param_lat_new=parseFloat(place[1]);
			param_lng_new=parseFloat(place[3]);
			param_zoom_new=parseFloat(17);
		}else{
			param_lat_new="-";
			param_lng_new="-";
			param_zoom_new="-";
		}
	
		if ((param_lat_new!="-") && (param_lng_new!="-") && ((param_lat_new!=map.getCenter().lat())||(param_lng_new!=map.getCenter().lng())||(param_zoom_new!=map.getZoom()))){
			map.setCenter(new GLatLng(param_lat_new, param_lng_new), param_zoom_new);
		}
	}
	
	
	// END HISTORY FUNCTIONS
	
	function icon(brand) {
		var useicon = new GIcon();
		useicon.image = '/development/map/icons/brand_' + brand + '_small.png';
		useicon.shadow = '/development/map/icons/shadow.png';
		useicon.iconSize = new GSize(21,21);
		useicon.shadowSize = new GSize(30,21);
		useicon.iconAnchor = new GPoint(0,21);
		useicon.infoWindowAnchor = new GPoint(11,0);
		useicon.transparent = '/development/map/icons/transparent.png';
		return useicon;
	}
	
	// Create large Moto icon for zoomed in view
	var motolarge = new GIcon();
	motolarge.image = '/development/map/map-small.png';
	motolarge.iconSize = new GSize(21,21);
	motolarge.shadowSize = new GSize(30,20);
	motolarge.iconAnchor = new GPoint(10,20);
	motolarge.infoWindowAnchor = new GPoint(10,0);
	
	function importanceOrder (marker,b) {
			return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000;
	}
	
	function createMarker(point, name, html, useicon, imp) {
		var markerOptions = {
			title: name,
			zIndexProcess: importanceOrder,
			icon: useicon
		}
	
		var marker = new GMarker(point, markerOptions);
		marker.importance = imp;
		GEvent.addListener(marker, "click", function() { 
			marker.openInfoWindowHtml(html); 
			var lat = point.lat();
			var long = point.lng();
			map.setCenter(new GLatLng(lat,long), 14);
		});
		return marker;
	}
	
	// This function picks up the click and opens the corresponding info window
	function clickToPlace(i) {
		gmarkers[i].openInfoWindowHtml(htmls[i]);
		map.panTo(gmarkers[i].getPoint());
	}
	
	// adds a point to the map - just testing at this stage
	function Clicks(overlay, point) {
		if (point) {
		  var marker = new GMarker(point);
		  map.addOverlay(marker);
		}
	} 
	
	function overviewMapPosition() 
	{
	  ovmap = document.getElementById("map_overview");
	  if(ovmap) 
	  {
		 ovmap.style.position = "absolute";
	
		 // == restyling ==
		 ovmap.firstChild.style.border = "1px solid gray";
		 ovmap.firstChild.firstChild.style.left="4px";
		 ovmap.firstChild.firstChild.style.top="4px";
		 
		 var mapdiv =document.getElementById("mappingMap");
		 mapdiv.appendChild(ovmap);
	   }
	}
	
	function overviewMapSetType()
	{
	  var ovmap2 = ovcontrol.getOverviewMap();
	  if(ovmap2) 
	  {
	   //  ======== change the overview map type AFTER the overview finishes initializing =====
		  ovmap2.setMapType(G_NORMAL_MAP);
		  ovmap2.addControl(new GSmallMapControl());
	   }
	}
	
	function setOverviewPos() 
	{
	   setTimeout("overviewMapPosition();", 5);
	   setTimeout("overviewMapSetType();",10);   
	}
	
	// search for location	   
	function searchLocations(address) {
		//var address = document.getElementById('formSearch').value;
		if (address == "Search (e.g. Town, Postcode)") {
	//			document.getElementById("mapInfo").innerHTML = "Please enter a town or postcode first";
				alert('Please enter a town or postcode first');
				return false;
		} else if (address.substring(0,8) == "latlng: ") {
			address = address.substring(8);
		} else {
			address = address + ", UK";
		}
		geocoder.getLatLng(address, function(latlng) {
			
			if (!latlng) {
				alert(address + ' not found');
			} else {
				var searchfor = new GLatLng(parseFloat(latlng.lat()), parseFloat(latlng.lng()));
				map.setCenter(searchfor, 9);
				var marker = createMarker(searchfor, address, searchfor, hereicon, 99);
				map.addOverlay(marker);
				// find the nearest motos
				searchLocationsNear(latlng, address, 40);
			}
		});
	}
		
	function searchLocationsNear(center, address, radius) {
		 var searchUrl = '/development/map/xml_locate.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
		 GDownloadUrl(searchUrl, function(data) {
		   var xml = GXml.parse(data);
		   var markers = xml.documentElement.getElementsByTagName('marker');
	
		   if (markers.length == 0) {
					searchLocationsNear(center, address, radius+40);
		   }
	
		   var bounds = new GLatLngBounds();
	
	// add the place we search for first to the bounds area
			var point = new GLatLng(center.lat(),center.lng());
			 bounds.extend(point);
	
		   for (var i = 0; i < markers.length; i++) {
				var name = markers[i].getAttribute('sitename');
				var address = markers[i].getAttribute('situation');
				var distance = parseFloat(markers[i].getAttribute('distance'));
				var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
										parseFloat(markers[i].getAttribute('lng')));
			 bounds.extend(point);
		   }
		   if (markers.length < 6) {
			$zoomLevel = map.getBoundsZoomLevel(bounds) - 1;
		   } else {
			$zoomLevel = map.getBoundsZoomLevel(bounds);
		   }
		   map.setCenter(bounds.getCenter(), $zoomLevel);
		 });
	}
	
	function handleErrors(){
		 if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		   alert("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.\nError code: " + gdir.getStatus().code);
		 else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		   alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
		 
		 else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		   alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
		
		 else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		   alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
		
		 else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		   alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
		  
		 else alert("An unknown error occurred.");
	}
	
	function setDirections(fromAddress, toAddress, locale) {
		gdir.load("from: " + fromAddress + " to: " + toAddress,
			{ "locale": locale });
	}
	
	function onGDirectionsLoad(){
			var poly=gdir.getPolyline();
			poly.color = "#FF0000";
			poly.redraw(true);
	}
	
	function loadBrand(brand) {
		map.clearOverlays();   // clears all overlays
		motoLocations(brand);
	}
	
	function searchMoto(name, latlng) {
		var ll = latlng;
		var temp = new Array();
		temp = ll.split(", ");
		map.setCenter(new GLatLng(temp[0],temp[1]), 14);
		//marker.openInfoWindowHtml(); 
	}
	
	function motoLocations(brand) {	
		url = "/development/rsslocations.xml";
		if (brand) {
			if (brand.match("poi")) {
				url = "/development/map/ajax_list.php?w=poi&q="+brand;
			} else if (brand.match("event")) {
				url = "/development/map/ajax_list.php?w=event&q="+brand;
			}
		}
		var b = 0;
		  // Read the data from rsslocations.xml
		  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");
			  
			  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);
	
				if (brand && (brand.match("poi") || brand.match("event"))) {
					var html = '<div id="infowindow"><h3>' + markers[i].getAttribute("sitename") + '</h3>';
					html = html + '<p><a href="http://www.google.co.uk/search?q=' + markers[i].getAttribute("label") + ' ' + markers[i].getAttribute("location") + '" target="_blank">Find out more information</a></p>';
					html = html + '<p><a href="#" id="motoNearby" title="Motos Near ' + markers[i].getAttribute("sitename") + '" rel="latlng: ' + markers[i].getAttribute("lat") + ', ' + markers[i].getAttribute("lng") + '">Find Motos nearby</a></p>';
					html = html +  '<p class="directionsLinks">Directions: <a href="#" id="routeToLocation" onclick="routePlanTo(\''+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'\'); return false;" rel="'+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'" title="Directions to '+markers[i].getAttribute("sitename")+'">To Here</a> | <a href="#" id="routeFromLocation" onclick="routePlanFrom(\''+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'\'); return false;" rel="'+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'"  title="Directions from '+markers[i].getAttribute("sitename")+'">From Here</a></p>';
					html = html + '</div>';
				} else {
					var html  = '<div id="infowindow">';
					html = html + '<h3>' + markers[i].getAttribute("sitename") +' '+ markers[i].getAttribute("direction") + '</h3>';
					html = html + '<p>' + markers[i].getAttribute("situation") + '</p>';
					html = html + '<p><strong>Postcode: </strong>' + markers[i].getAttribute("postcode") + '<br />';
					html = html + '<strong>Telephone:</strong>';
					if ((markers[i].getAttribute("sitetel1number") != null) && (markers[i].getAttribute("sitetel1number").length > 1)){
						html = html + ' ' + markers[i].getAttribute("sitetel1number");
					}
					if ((markers[i].getAttribute("sitetel1title") != null) && (markers[i].getAttribute("sitetel1title").length > 1)){
						html = html + ' ('+markers[i].getAttribute("sitetel1title")+')';
					}
					if ((markers[i].getAttribute("sitetel2number") != null) && (markers[i].getAttribute("sitetel2number").length > 1)){
						html = html + ', ' + markers[i].getAttribute("sitetel2number");
					}
					if ((markers[i].getAttribute("sitetel2title") != null) && (markers[i].getAttribute("sitetel2title").length > 1)){
						html = html + ' ('+markers[i].getAttribute("sitetel2title")+')';
					}
					if ((markers[i].getAttribute("sitetel3number") != null) && (markers[i].getAttribute("sitetel3number").length > 1)){
						html = html + ', ' + markers[i].getAttribute("sitetel3number");
					}
					if ((markers[i].getAttribute("sitetel3title") != null) && (markers[i].getAttribute("sitetel3title").length > 1)) {
						html = html + ' ('+markers[i].getAttribute("sitetel3title")+')';
					}
					
					//html = html + '<strong>Telephone: </strong>' + markers[i].getAttribute("sitetel1number") + '('+markers[i].getAttribute("sitetel1title")+') ' + markers[i].getAttribute("sitetel2number") + '('+markers[i].getAttribute("sitetel2title")+') ' + markers[i].getAttribute("sitetel3number") + '('+markers[i].getAttribute("sitetel3title")+')</p>';
	
					if (markers[i].getAttribute("shopping").match("m--s-simply-food")) {
						html = html +  '<p id="google-m--s-simply-food" class="brandLogo imgReplace"><span>Marks and Spencer</span></p>';
					}
					if (markers[i].getAttribute("shopping").match("costa")) {
						html = html +  '<p id="google-costa" class="brandLogo imgReplace"><span>Costa Coffee</span></p>';
					}
					if (markers[i].getAttribute("shopping").match("burger-king")) {
						html = html +  '<p id="google-burger-king" class="brandLogo imgReplace"><span>Burger King</span></p>';
					}
					if (markers[i].getAttribute("shopping").match("edc")) {
						html = html +  '<p id="google-edc" class="brandLogo imgReplace"><span>EDC</span></p>';
					}
					if (markers[i].getAttribute("shopping").match("whsmith")) {
						html = html +  '<p id="google-whsmith" class="brandLogo imgReplace"><span>WHSmith</span></p>';
					}
					if (markers[i].getAttribute("shopping").match("west-cornwall-pasty")) {
						html = html +  '<p id="google-west-cornwall-pasty" class="brandLogo imgReplace"><span>West Cornwall Pasty Co</span></p>';
					}
					if (markers[i].getAttribute("shopping").match("dominos")) {
						html = html +  '<p id="google-dominos" class="brandLogo imgReplace"><span>Dominos Pizza</span></p>';
					}
					if (markers[i].getAttribute("accommodation")) {
					html = html +  '<p id="google-' + markers[i].getAttribute("accommodation") + '" class="brandLogo imgReplace"><span>' + markers[i].getAttribute("accommodation") + '</span></p>';
					}
					html = html + '<div class="clear"></div>';
					html = html + '<p><a href="/location/' + markers[i].getAttribute("rewrite") + '" title="More information on ' + markers[i].getAttribute("sitename") +' '+ markers[i].getAttribute("direction") + '" class="icon info">More information on ' + markers[i].getAttribute("sitename") +' '+ markers[i].getAttribute("direction") + '</a></p>';
					/* 
					onclick="routePlanTo(\''+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'\'); return false;"
					onclick="routePlanFrom(\''+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'\'); return false;"
					*/
					html = html +  '<p class="directionsLinks"><strong>Directions:</strong> <a href="#" id="routeToLocation" rel="'+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'" title="Directions to '+markers[i].getAttribute("sitename")+'" >To Here</a> | <a href="#" id="routeFromLocation" rel="'+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'" title="Directions from '+markers[i].getAttribute("sitename")+'">From Here</a>';
					html = html + "</div>";
				}
				var label = markers[i].getAttribute("sitename");
				// show brand icon if it's selected
				if (brand && !brand.match("poi") && !brand.match("event")) {
					if ((markers[i].getAttribute("shopping").match(brand)) || (markers[i].getAttribute("accommodation").match(brand))) {
						var importance = 9999;
						b++;
						var useicon = icon(brand);
					} else { 
						var importance = 1;
						var useicon = motosmall;
					}
				} else if (brand && (brand.match("poi") || brand.match("event"))) {
						var importance = 99;
						b++;
						var useicon = poiicon;
				} else { 
					var importance = 1;
					var useicon = motosmall;
				}
				// create the marker
				var marker = createMarker(point, label, html, useicon, importance);
				map.addOverlay(marker);
			  }
			}
		  }
		  if (brand && (brand.match("poi") || brand.match("event"))) { motoLocations(); } // load the Moto locations over the POIs
		  request.send(null);
	}
	
	function setDir(which, latitude, longitude) {
		document.getElementById(which + "Address").value = latitude + ", " + longitude;
	}
	
	
	function showMap(brand)
	{
	   if (GBrowserIsCompatible()) 
	   {
			geocoder = new GClientGeocoder();
			map = new GMap2(document.getElementById("mappingMap"));
	
			$.historyInit(historyChange);
	
			if($.historyCurrentHash.replace(/^#/, '') != ""){
				var place = $.historyCurrentHash.replace(/^#/, '').split("/");
	
	
				if(place.length==6){
					param_lat=place[1];
					param_lng=place[3];
					param_zoom=place[5];
				}else if(place.length==4){
					param_lat=place[1];
					param_lng=place[3];
					param_zoom=17;
				}
	
			}
			
			// route planner
			gdir = new GDirections(map, document.getElementById("directions"));
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(gdir, "error", handleErrors);
	
	// ====== Restricting the range of Zoom Levels and Scroll area =====
		  // 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 5;}
			mt[i].getMaximumResolution = function() {return 17;}
		  }
	
		// Add a move listener to restrict the bounds range
			  GEvent.addListener(map, "move", function() {
				checkBounds();
			  });
		
			  // The allowed region which the whole map must be within
			  var allowedBounds = new GLatLngBounds(new GLatLng(49.5,-10), new GLatLng(59,2.6));
			  
			  // If the map position is out of range, move it back
			  function checkBounds() {
				// 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;}
				//alert ("Restricting "+Y+" "+X);
				map.setCenter(new GLatLng(Y,X));
			  }
	
		  map.addControl(new GLargeMapControl3D()); // not in v2.98
		  map.enableScrollWheelZoom();
		  map.addControl(new GScaleControl());
		  map.setMapType(G_NORMAL_MAP);
	
		  // move the copyright message
		  var MapDiv =document.getElementById("mappingMap");
		  var CopyrightDiv = MapDiv.firstChild.nextSibling;
	
		// load Moto locations
		  motoLocations(brand);
	
		// add traffic
		   map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		   
	
			if ((param_lat!="-") && (param_lng!="-")){
				if(param_zoom=="-") param_zoom=17; //Default zoom level
				map.setCenter(new GLatLng(parseFloat(param_lat), parseFloat(param_lng)), parseFloat(param_zoom));
			}else{
				//Default map values
				param_lat=53.77468884583577;
				param_lng=-2.197265625;
				param_zoom=6;
				map.setCenter(new GLatLng(53.77468884583577, -2.197265625), 6);
			}
			
			GEvent.addListener(map, 'moveend', function() {
				mapChangedListener();
			});
			
			//Disable mouse wheel page scroll
			GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
			map.getContainer().onmousewheel = wheelevent;
			
			updateLinkToThisPage();
		   
	   }
		else {
		  alert("Sorry, the Google Maps API is not compatible with this browser");
		}
	}
	
	// Initialise the map
	showMap();
	
});
// ]]>
