function addLoadListener(fn)
{
  if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener != 'undefined') {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onload', fn);
  }
  else {
    var oldfn = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = fn;
    }
    else {
      window.onload = function() {
        oldfn();
        fn();
      };
    }
  }
}

// Restrict the map to certain bounds.
// Hat-tip: http://econym.googlepages.com/range.htm

// The allowed region which the whole map must be within
var allowedBounds = new GLatLngBounds(new GLatLng(50.5,-14), new GLatLng(57,-5));

// If the map position is out of range, move it back
function checkBounds(map) {
  // Perform the check and return if OK
  if (allowedBounds.containsLatLng(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));
}

function initialise() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));

    // Restrict the range of zoom levels
    G_PHYSICAL_MAP.getMinimumResolution = function() { return 7; }
    G_PHYSICAL_MAP.getMaximumResolution = function() { return 12; }

    // Add the controls for the map
    map.setCenter(new GLatLng(53.618579,-7.668457), 7);
    map.setUIToDefault();

    // Add custom overlay
    var tilelayer = new GTileLayer(new GCopyrightCollection(), 7, 12);
    tilelayer.getTileUrl = function(tile, zoom) {
      return "tiles/" + zoom + "/x" + tile.x + "_y" + tile.y + ".png";
    };
    tilelayer.getOpacity = function() {return 0.33;}
    map.addOverlay(new GTileLayerOverlay(tilelayer));

    // Add a move listener to restrict the bounds range
    GEvent.addListener(map, "move", function() {
      checkBounds(map);
    });
  }
}

addLoadListener(initialise);

