﻿var _map = null;
var _geocoder = null;
var _dealers = new Array();
var _markers = new Array();
var _markerManager = null;
var _dealerMarkerOptions = null;
var _userMarkerOptions = null;

var _defaultZoom = 5;

var _userAddress = "";
var _userCountry = "United Kingdom";
var _userLatitude = null;
var _userLongitude = null;
var _userMarker = null;

var _allowedBounds = null;

var _page = 1;
var _pageSize = 10;

var _minZoom = 5;
var _maxZoom = 14;


function Dealer(id, name, street, city, state, postcode, telephone, email, lat, lng, url, marker)
{
  this.id = id;
  this.name = name;
  this.street = street;
  this.city = city;
  this.state = state;
  this.country = "";
  this.postcode = formatPostcode(postcode);
  this.telephone = telephone;
  this.email = email;
  this.lat = lat;
  this.lng = lng;
  this.url = url;
  this.marker = marker;
}

function load(page, pageSize, address, country, latitude, longitude) 
{
  if (GBrowserIsCompatible()) 
  {
    _page = page;
    _pageSize = pageSize;
    _userCountry = country;
    _userLatitude = latitude;
    _userLongitude = longitude;
    // call init routine
    init();
  }
}

function init()
{
  // init _map
  _map = new GMap2(document.getElementById("map"));
  // event listener to restrict map movement to UK only
  _allowedBounds = new GLatLngBounds(new GLatLng(49.5, -10), new GLatLng(59, 2.6));
  var mapTypes = _map.getMapTypes();
  for (var i = 0; i < mapTypes.length; i++) {
    mapTypes[i].getMinimumResolution = function() {return _minZoom;}
    mapTypes[i].getMaximumResolution = function() {return _maxZoom;}
  }
  GEvent.addListener(_map, "move", function() { checkBounds(); });
  // set up a few map parameters
  _map.enableContinuousZoom();
  _map.enableScrollWheelZoom();
  // init icons
  var logo = new GIcon(G_DEFAULT_ICON);
  logo.image = "/_images/map-marker.png";
  logo.iconSize = new GSize(20, 20);
  logo.shadow = "";
  logo.iconAnchor = new GPoint(10, 20);
  _dealerMarkerOptions = { icon: logo }; 
  var marker = new GIcon(G_DEFAULT_ICON);
  marker.image = "/_images/user-map-marker.png";
  marker.iconSize = new GSize(20, 20);
  marker.shadow = "";
  marker.iconAnchor = new GPoint(10, 20);
  _userMarkerOptions = { icon: marker, zIndexProcess:zIndexHack };
  // init geocoder
  _geocoder = new GClientGeocoder();
  // set map center
  resetMap();
  // allow map to load (otherwise nothing works!)
  waitForLoad();
}

function resetMap()
{
  setCentre(_userCountry, _defaultZoom);
}

function waitForLoad()
{
  if(_map.isLoaded()) 
  {
    moreInit();
  }
  else
  {
    window.setTimeout("waitForLoad();", 50);
  }
}

function zIndexHack(marker, b)
{
  return -9999999;
}

function moreInit()
{
  // init marker manager
  _markerManager = new GMarkerManager(_map);
  // create marker for user (if location known)
  if(_userLatitude != null && _userLongitude != null)
  {
    _userMarker = new GMarker(new GLatLng(_userLatitude, _userLongitude), _userMarkerOptions);
    _markerManager.addMarker(_userMarker, _minZoom, _maxZoom);
  }
  // create markers for dealers
  for(i = 0; i < _dealers.length; i++) addDealer(i);
  // stick the dealers on the map
  _markerManager.addMarkers(_markers, _minZoom, _maxZoom); // all zoom levels
  _markerManager.refresh();
  if (_userLatitude != null && _userLongitude != null) {
  	window.setTimeout("setCentrePoint(" + _userLatitude + ", " + _userLongitude + ", 10); dealerClick(0);", 500);
  }
  else {
  	window.setTimeout("zoomToAll();", 500);
  }
}

function setCentre(address, zoom) 
{
  if (_geocoder) {
    _geocoder.getLatLng(
      address,
      function(point) {
        if (point) 
        {
          _map.setCenter(point, zoom);
        }
      }
    );
  }
}

function setCentrePoint(lat, lng, zoom)
{
  _map.setCenter(new GLatLng(lat, lng), zoom);
}

function addDealer(i)
{
  var dealer = _dealers[i];
  if(dealer.lat != null && dealer.lng != null)
  {
    var marker = new GMarker(new GLatLng(dealer.lat, dealer.lng), _dealerMarkerOptions);
    GEvent.addListener(marker, "click", GEvent.callbackArgs(this, dealerClick, i.toString()));
    _markers[_markers.length] = marker;
  }
}

function dealerClick(i)
{
  var dealer = _dealers[i];
  var marker = _markers[i];
  var address = dealer.street.replace(/\,/g, ",<br/>");
  if(dealer.city != "")
  {
    if(address != "") address += ",<br/>";
    address += dealer.city;
  }
  if(dealer.state != "")
  {
    if(address != "") address += ",<br/>";
    address += dealer.state;
  }
  if(dealer.country != "")
  {
    if(address != "") address += ",<br/>";
    address += dealer.country;
  }
  address += "<br/>" + dealer.postcode + "<br/>";
  if(dealer.telephone != "")
  {
    address += "<br/>Tel: " + dealer.telephone;
  }
  if(dealer.email != "")
  {
    address += "<br/>Email: <a href=\"mailto:" + dealer.email + "\">" + dealer.email + "</a>";
  }
  var html = "<table><tr><td rowspan=\"2\" style=\"padding-right: 15px;\"><img src=\"/_images/map-marker.png\"></td><td style=\"text-align: left; padding-right: 20px;\"><strong><a href=\"" + dealer.url + "\">" + dealer.name + "</a></strong></td></tr><tr><td style=\"text-align: left;\">" + address + "<br/>";
  marker.openInfoWindowHtml(html + "</td></tr></table>");
}

function zoomToAll()
{
  // zoom in so that all dealers are visible (e.g. as close as possible)
  if(_markers.length > 0)
  {
    var bounds = new GLatLngBounds();
    for(var i = 0; i < _markers.length; i++)
    {
      var latlng = _markers[i].getLatLng();
      bounds.extend(latlng);
    }
    // pan and zoom to show points
    var zoom = _map.getBoundsZoomLevel(bounds) - 1;   // minus one because the speech bubble can get in the way
    var point = bounds.getCenter();
    if(zoom < _minZoom) zoom = _minZoom;
    if(zoom > _maxZoom) zoom = _maxZoom;
    _map.setZoom(zoom);
    _map.setCenter(point);
    return;
  }
  resetMap();
}

function getDirections(i)
{
  if(_userAddress != null)
  {
    _directions.load(_userAddress + " to " + dealers[i].street + ", " + dealers[i].city + ", " + dealers[i].state + ", " + dealers[i].country + ", " + dealers[i].postcode);
  }
}

function formatPostcode(pc)
{
  pc = pc.toUpperCase().replace(' ', '');
  if(pc.length >= 5)
  {
    pc = pc.substr(0, pc.length-3) + ' ' + pc.substr(pc.length-3, 3);
  }
  return pc;
}

function findDealer(id)
{
  for(var i = 0; i < _dealers.length; i++)
  {
    if(_dealers[i].id == id)
    {
      setCentrePoint(_dealers[i].lat, _dealers[i].lng, 10);
      window.setTimeout("dealerClick(" + i + ");", 50);
      return;
    }
  }
}

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;

  _map.setCenter(new GLatLng(Y,X));
}
