// JavaScript Document

function loadGoogleMap() {
/*
  // custom icon setup
	var customIcon = new GIcon();
	customIcon.image = 'images/elements/google_map_icon.png';
	customIcon.iconSize = new GSize(50, 58);
	customIcon.iconAnchor = new GPoint(15, 50);
	customIcon.infoWindowAnchor = new GPoint(20, 25);
*/

  // default zoom
  var gZoom = 15;
  
  // html for popup
  var myHtml = address.replace(/,/g, ',<br />') + '<br />';

  /* HELPER FUNCTIONS */

  // zooms and centers map
  var centerMap = function (map, point, gZoom) {
    var centerPoint = new GLatLng(point.lat() + 0.002, point.lng() + 0.002); // Offset to allow for the overlay height
    map.setCenter(centerPoint, gZoom);
  }
  
  // adds a marker
  var addMarker = function(map, point, customIcon) {
    var marker = (customIcon != null ? new GMarker(point, {icon: customIcon}) : new GMarker(point));
    map.addOverlay(marker);
    return marker;
  }

  // creates the marker popup and adds an onclick event to the marker
  var addMarkerPopup = function(marker, html) {
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(html);
	});
	
	marker.openInfoWindowHtml(html);
  }
  
  // map reset hook
  var resetMap;
  
  // sets up the map, adds a marker and a popup
  var setupMap = function(point) {
    var map   = new GMap2(document.getElementById('google_map'));
    
    centerMap(map, point, gZoom);
    var marker = addMarker(map, point);
    addMarkerPopup(marker, myHtml);
    
    // initialise map reset
    resetMap = function() {
      centerMap(map, point, gZoom);
      marker.openInfoWindowHtml(myHtml);
    }
    
    return map;
  }
  
  // sets up zoom & reset controls
  var setupControls = function(map) {
  	map.setUIToDefault();
  }
  
  /* INITIALISATION */

  if (GBrowserIsCompatible()) {
    // find map point by address (geocoding)
    var geocoder = new GClientGeocoder();

    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          // alert(address + " - address not found");
        } else {
          var map = setupMap(point);
          setupControls(map);
        }
      }
    );
  }
}

// add google maps initialisation to onload
if(window.addEventListener) {
  window.addEventListener('load', loadGoogleMap, false);
  
} else if (window.attachEvent) {
  window.attachEvent('onload', loadGoogleMap);
  
} else {
  window.onload = loadGoogleMap;
}