//<![CDATA[

// 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';

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');
	}
}

function routePlanTo(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');
	}
}

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*1000000;
}

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 setDirections(fromAddress, toAddress, locale) {
	gdir.load("from: " + fromAddress + " to: " + toAddress,
		{ "locale": locale });
}

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 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>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>' + markers[i].getAttribute("sitetelno") + '</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("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>';
				html = html +  '<p><strong>Directions:</strong> <a href="" id="routeToLocation" rel="'+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'" title="Directions to '+markers[i].getAttribute("sitename")+'" onclick="routePlanTo(\''+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'\'); return false;">To Here</a> | <a href="#" id="routeFromLocation" rel="'+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'" title="Directions from '+markers[i].getAttribute("sitename")+'" onclick="routePlanFrom(\''+markers[i].getAttribute("lat")+', '+markers[i].getAttribute("lng")+'\'); return false;">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")) {
				var importance = 999;
				if ((markers[i].getAttribute("shopping").match(brand)) || (markers[i].getAttribute("accommodation").match(brand))) {
					b++;
					var useicon = icon(brand);
				} else { 
					var useicon = motosmall;
				}
			} else if (brand && (brand.match("poi") || brand.match("event"))) {
					var importance = 99;
					b++;
					var useicon = poiicon;
			} else { 
				var importance = 50;
				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"));
		
		// 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.setCenter(new GLatLng(53.77468884583577, -2.197265625), 6);
	  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}));
	   
   }
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}
//]]>
