var map
var gdir

function setDirections(fromAddress, toAddress) 
{	
	if(gdir == null)
	{
		gdir = new GDirections(map, $(".googleDirectionsDiv")[0]);
		GEvent.addListener(gdir, "error", handleErrors);
  	 	GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // Triggers marker swap, Esa
	}
	
	gdir.load("from: " + fromAddress + " to: " + toAddress,
	{ "locale": "en_US" , "getSteps":true});
}

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.");
}

var newMarkers = [];
var latLngs = [];
var icons = [];


function onGDirectionsAddOverlay(){ 
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }

  // Loop through the markers and create draggable copies
  for (var i=0; i<=gdir.getNumRoutes(); i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
    map.addOverlay(newMarkers[i]);

    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
    GEvent.addListener(newMarkers[i], "dragend", function(){
      var points = [];
      for (var i=0; i<newMarkers.length; i++){
        points[i]= newMarkers[i].getLatLng();
      }
      gdir.loadFromWaypoints(points);
    });

    //Bind 'click' event to original markers 'click' event
    copyClick(newMarkers[i],originalMarker);

    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
  }

  function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      GEvent.trigger(oldMarker,'click');
    });
  }
}

function createBaseIcon()
{
	//Create a base icon
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(15, 15);
	baseIcon.iconAnchor = new GPoint(15, 15);
	baseIcon.infoWindowAnchor = new GPoint(15, 0);
	return baseIcon;
}

function createIcon(baseIcon, iconPath)
{

	// Create a new marker icon
	var icon = new GIcon(baseIcon);
	icon.image = iconPath;
	return icon;
}

function createMarker(point, baseIcon, iconPath, infoText) 
{

	//Create a marker for mapped points
	var icon = createIcon(baseIcon, iconPath);
	var marker = new GMarker(point, icon);
	
	//Add an event listener
    GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(infoText);});
    return marker;
}

var gmap;
//Add markers based on the xml file
function createLocationsMapSingleMarker(lat, lng, zoomLevel, infoText) 
{
    
	if (GBrowserIsCompatible()) 
	{
		//Create the map with the controls we want
		map = new GMap2($(".googleMapDiv")[0]);
		map.addControl(new GSmallMapControl());
		//map.addControl(new GMapTypeControl());

		//Centre the map on the current location
        map.setCenter(new GLatLng(lat, lng), zoomLevel);
		
		//Create the icon
		var baseIcon = createBaseIcon();
		var iconPath = "favicon.ico";
		
		//Now add a marker to the map for this location
		var point = new GLatLng(lat, lng);
		var marker = createMarker(point, baseIcon, iconPath, infoText);
		map.addOverlay(marker);		
		
    //Open the info window that relates to the current item
		marker.openInfoWindowHtml(infoText);
        
	}
	else
	{

		//Do something different as their browser doesnt support google maps
		//TODO Customise
            
	}
	var gmap = map;
}

function changeLocation(centreLat, centreLng)
{

	map = new GMap2($('.googleMapDiv')[0])
	map.setCenter(new GLatLng(centreLat,centreLng), 11);	
}

var namedMarkers = {};
var globalMapCenter;
function createLocationsMapFromXml(centreLat, centreLng, zoomLevel, xmlFileName)
{   
   
	if (GBrowserIsCompatible()) 
	{
		  
         
      //Create the map with the controls we want
		map = new GMap2($(".googleMapDiv")[0]);
		map.addControl(new GSmallMapControl());
		//map.addControl(new GMapTypeControl());
		
		//Create the base icon
		var baseIcon = createBaseIcon();
		
		//Centre the map on the current location
		map.setCenter(new GLatLng(centreLat, centreLng), zoomLevel);
	    
	    var currentMarker;
	    var currentInfo;
		
	    globalMapCenter = {latitude : centreLat, longitude : centreLng};
		//Create pointers for the map from the xml file
		GDownloadUrl(xmlFileName, function(data, responseCode) 
		{
		   
			//Parse the xml file
			var xml = GXml.parse(data);
			
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) 
			{
			 
				//Add a new marker for each element
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
										parseFloat(markers[i].getAttribute("lng")));
				
				var iconPath = "favicon.ico";
				var infoText = markers[i].getAttribute("info");
				var detailedInfoText = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
				if (detailedInfoText!="")
				{
					infoText = detailedInfoText;
				}
			
				var marker = createMarker(point, baseIcon, iconPath, infoText);
				map.addOverlay(marker);
				
				namedMarkers['branch'+markers[i].getAttribute("id")] = marker;
				

			}
			$nearestLocationControl = $('.googleMarkerControl:first');
			if($nearestLocationControl.length){
				namedMarkers[$nearestLocationControl.attr('id')].openInfoWindowHtml($nearestLocationControl.html());   
			}
			
		}); 
		var gmap = map;
		return map;
	}
	else
	{

		//Do something different as their browser doesnt support google maps
		//TODO Customise
            
	}
}

