/**
 * The map object, null until script loads in.
 * @type {GMap2}
 */
var map = null;  

/**
 * The bounds of the markers once loaded in.
 * @type {GLatLngBounds}
 */
var bounds = null;

/**
 * The marker with currently opened info window.
 * @type {GMarker}
 */
var currentMarker = null;

/**
 * The dom element that the map is loaded into
 * @type {Element}
 */
var mapDiv = null;

/**
 * The dom element that everything is a child of.
 * @type {Element}
 */
var containerDiv = null;

/**
 * Position of mouse click (clientX) on map div when in static mode.
 * @type {Number}
 */
var clickedX = 0;

/**
 * Position of mouse click (clientY) on map div when in static mode.
 * @type {Number}
 */
var clickedY = 0;

/**
 * Indicates whether we've created a script tag with Maps API yet
 * @type {Boolean}
 */
var isLoaded = false;

// design icone
/*
var icon = new GIcon();
icon.image = "http://www.pirates-corsaires.com/geolocalisation/icone.png";
icon.iconSize = new GSize(35, 35);
icon.iconAnchor = new GPoint(18, 3);
icon.infoWindowAnchor = new GPoint(10, 1);
*/

/*
var icon = new GIcon();
icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);

*/

/**
 * Called after script is asynchronously loaded in.
 * Creates the GMap2, GMarker objects and performs actions according to 
 * what the user did to trigger the map load (search, zoom, click etc).
 */
function loadMap() {
  if (GBrowserIsCompatible()) {
    mapDiv.style.background = '#fff';
    mapDiv.style.cursor = '';
    map = new GMap2(mapDiv, {logoPassive: true});
    bounds = new GLatLngBounds();
    for (var i = 0; i < moussaillons.length; i++) {
      bounds.extend(new GLatLng(moussaillons[i].lat, moussaillons[i].lng));
    }
    var latSpan = bounds.toSpan().lat();
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

    // The static map server gives markers more space when calculating
    // bounds and zoom level, so sometimes the API will give a higher
    // zoom level than was used by the static map server.
    // The .98 value is just a guess right now, may need tweaking.
    var newBounds = map.getBounds();
    var newLatSpan = newBounds.toSpan().lat();
    if (latSpan/newLatSpan > .90) { map.zoomOut(); }

    for (var i = 0; i < moussaillons.length; i++) {
      //var marker = createMarker(i,icon);
      var marker = createMarker(i);
      var latlng = marker.getLatLng();
      var pixel = map.fromLatLngToDivPixel(latlng);
      if (Math.abs(pixel.x - clickedX) < 12 && Math.abs(pixel.y - clickedY) < 20) {
        //GEvent.trigger(marker, 'click');
      }
      map.addOverlay(marker);
    }
  }
}

/**
 * Zooms to the viewport that fits all the markers.
 */
function zoomToAll() {
  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

/**
 * Creates a marker for the given moussaillon.
 * @param {Number} ind
 * @return {GMarker}
 */
//function createMarker(ind,icon) {
function createMarker(ind,icon) {
  var moussaillon = moussaillons[ind];
  //var marker = new GMarker(new GLatLng(moussaillon.lat, moussaillon.lng), icon);
  var marker = new GMarker(new GLatLng(moussaillon.lat, moussaillon.lng));
  GEvent.addListener(marker, 'click', function() {
    if (moussaillon.city != '') {
      text = "City: " + moussaillon.city + "<br>Country: " + moussaillon.country;
    } else {
      text = "City unspecified<br>Country: " + moussaillon.country;
    }
    marker.html = ['<b>Arrr! you\'re well curious!</b><br>',
                   text].join('');
    currentMarker = marker;
    marker.openInfoWindowHtml(marker.html);
  });
  return marker;
}
/*
function createMarker(ind,icon) {
  var moussaillon = moussaillons[ind];
  var marker = new GMarker(new GLatLng(moussaillon.lat, moussaillon.lng), icon);
  GEvent.addListener(marker, 'click', function() {
	marker.openInfoWindowHtml(legende);
  });
  return marker;
} */

/**
 * Formats moussaillon info into a URL-friendly version for maps url.
 * @param {Object} moussaillon
 * @return {String}
 */
function formatAddressForMaps(moussaillon) {
  var address = moussaillon.street + ' ' + moussaillon.city + ' ' + moussaillon.state + ' ' + moussaillon.zip;
  return escape(address.replace(' ', '+'));
}

/**
 * Convenience function for creating an element and assigning an id to it.
 * @param {String} elementType
 * @param {String} id
 * @return {Element} 
 */
function _cel(elementType, id) {
  var element = document.createElement(elementType);
  element.id = id;
  return element;
}

/**
 * Loads in the Maps API script. This is called after some sort of user interaction.
 * The script loads asynchronously and calls loadMap once it's in.
 */
function loadScript() {
  if (!isLoaded) {
    isLoaded = true;
    var div = document.createElement('div');
    div.className = 'message';
    div.innerHTML = 'Loading...';
    div.style.left = (490/2 - 53) + 'px';
    div.style.top = 490/2 + 'px'; 
    mapDiv.appendChild(div);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://maps.google.com/maps?file=api&v=2.x' + 
                 '&async=2&callback=loadMap&key=ABQIAAAAGzjYZ8anX9por2PbGj3v0BTvZX1iIdrM8ABu3oQwvirlD3bVRhQEvcnN4TEqzEBsr3qtYhr--Jvmkg';
    document.body.appendChild(script);
  }
}

/**
 * Sets up the gadget by setting CSS and click events.
 */
function loadMapGadget() {
  containerDiv = document.getElementById('container');
  mapDiv = document.getElementById('map');

  mapDiv.onclick = function (e) {
    clickedX = (window.event && window.event.offsetX) || e.clientX;
    clickedY = (window.event && window.event.offsetY) || e.clientY;
    loadScript(); 
  };

  mapDiv.style.cursor = 'pointer';

  var urlString = ['http://maps.google.com/staticmap?markers='];
  var markerString = [];
  for (var i = 0; i < moussaillons.length; i++) {
    markerString.push(moussaillons[i].lat + ',' + moussaillons[i].lng + ',red');
  }
  urlString.push(markerString.join('|'));
  urlString.push('&size=490x490');
  urlString.push('&key=ABQIAAAAGzjYZ8anX9por2PbGj3v0BTvZX1iIdrM8ABu3oQwvirlD3bVRhQEvcnN4TEqzEBsr3qtYhr--Jvmkg');
  mapDiv.style.background = 'url(\'' + urlString.join('') + '\')';

}

