      
var map;
var gdir;
var branches = new Array;
var mapPoints = new Array;
var lsResIndicator = new Array;


/** 
* @param {Function} func the callback function 
* @param {Object} opts an object literal with the following 
* properties (all optional): 
* bind: the object to bind the function to (what the "this" keyword will refer to) 
* args: an array of arguments to pass to the function when it is called, these will be 
* appended after any arguments passed by the caller 
* suppressArgs: boolean, whether to supress the arguments passed 
* by the caller. This default is false. 
*/ 

// takesCallback(callback(myFunction,{scope:myObject,args:[myArgOne,myArgTwo],suppressArgs:true})); 
// or 
// takesCallback(myObject.myMethod,{scope:myObject,args:[myArgOne]});


function addDirectionsOptions()
{
  var dirSelect = document.getElementById("branch_directions_to");
  for(var i=0; i<branches.length;i++)
  {
    var optn = document.createElement("option");
    optn.text = branches[i]['locatorname'];
    optn.value = branches[i]['gdir'];
    dirSelect.options.add(optn);
  }
}

function getPointsFromPostcodes()
{
  for(var i=0; i<branches.length;i++)
  {
    if(branches[i]['lat'] == "" && branches[i]['lng'] == "")
    {
      localSearch.setSearchCompleteCallback(null, handleSearchResult );
      lsResIndicator[branches[i]['postcode']] = i;
      localSearch.execute(branches[i]['postcode'] + ", UK");
    }
  }
}

function handleSearchResult()
{
  if(localSearch.results[0])
  {    
    var resultLat = localSearch.results[0].lat;
    var resultLng = localSearch.results[0].lng;
    
    var point = new GLatLng(resultLat,resultLng);
    savePoint(point);
    var markerLabel = "";
    for(var postcode in lsResIndicator)
    {
      if( localSearch.results[0].addressLines[0].indexOf(postcode) != -1 )
        var markerLabel = ""+(parseInt(lsResIndicator[postcode])+1);
    }
    placeMarkerAtPoint(point, markerLabel ,false);
    fitMap();
  }
  else
  {
    alert("Postcode not found!");
  }
}

function placeKnownMarkers()
{
  for(var i=0; i<branches.length;i++)
  {
    if(branches[i]['lat'] != "" && branches[i]['lng'] != "")
    {
      var point = new GLatLng(branches[i]['lat'],branches[i]['lng']);
      var markerLabel = ""+(parseInt(i)+1);
      savePoint(point);
      placeMarkerAtPoint(point, markerLabel ,branches[i]['warning']);
    }
  }
  fitMap();
}

function savePoint(point)
{
  mapPoints.push(point);
}

function placeMarkerAtPoint(point,label,warning)
{
  var iconOptions = {};
      iconOptions.label = label;
      iconOptions.primaryColor = "#FF0000";
      iconOptions.strokeColor = "#000000";
      iconOptions.labelColor = "#000000";
      if(warning != "")
      {
        iconOptions.addStar = true;
        iconOptions.starPrimaryColor = "#FFFF00";
        iconOptions.starStrokeColor = "#0000FF";
        var html = $("#branchDirectionsWarnings").html()
        $("#branchDirectionsWarnings").html(html+label+": "+warning+"<br>");
      }
  var newIcon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
	var marker = new GMarker(point,newIcon);
	map.addOverlay(marker);

}

function fitMap()
{
   var bounds = new GLatLngBounds();
   for (var i=0; i< mapPoints.length; i++)
   {
      bounds.extend(mapPoints[i]);
   }
   map.setZoom(map.getBoundsZoomLevel(bounds)-1);
   map.setCenter(bounds.getCenter());
}

function getDirections()
{
  var saddr = document.getElementById("branch_directions_from").value + ", UK";
  var daddr = document.getElementById("branch_directions_to").value;
  var dirWalking = document.getElementById("dir_type_walking").checked;
  if(dirWalking)
    gdir.load("from: "+saddr+" to: "+daddr ,{travelMode:G_TRAVEL_MODE_WALKING,locale:'en_UK'});
  else
    gdir.load("from: "+saddr+" to: "+daddr ,{travelMode:G_TRAVEL_MODE_DRIVING,locale:'en_UK'});
  return false;
}

// Call this function when the page has been loaded
function initialize()
{
  addDirectionsOptions();
  var mapDiv = document.getElementById("branchDirectionsMap");
  map = new GMap2(mapDiv);
  map.addControl(new GSmallMapControl());
  map.setCenter(new GLatLng(54.622978,-2.592773), 5 );
    gdir = new GDirections(map, document.getElementById("directions"));
    var reasons=[];
    reasons[G_GEO_SUCCESS]            = "Success";
    reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
    reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
    reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
    
    GEvent.addListener(gdir, "error", function() {
      var code = gdir.getStatus().code;
      var reason="Code "+code;
      if (reasons[code]) {
        reason = reasons[code]
      } 
    
      alert("Failed to obtain directions, "+reason);
    });
  placeKnownMarkers();
  getPointsFromPostcodes();
  
}
 


