var map;
var lat;
var lng;
var mappables;

$(document).ready(function() {

  function createMarker(latitude, longitude, link_url, link_name, address, icon_name) {
    if (icon_name != '') {
      var icon = new GIcon();
      icon.image = '/images/' + icon_name;
      icon.iconSize = new GSize(16, 16);
      icon.iconAnchor = new GPoint(8, 8);
      icon.infoWindowAnchor = new GPoint(8, 8);
      var marker = new GMarker(new GLatLng(latitude, longitude), icon);
    }
    else {
      var marker = new GMarker(new GLatLng(latitude, longitude));
    }
    // Information window that opens when marker is clicked.
    GEvent.addListener(marker, 'click', function() {
      var para = "<p>";
      if (link_url != '' && link_url != null) {
        para += "<a href='" + link_url + "'>" + link_name + "</a>";
      }
      else {
        para += link_name;
      }
      if (address != '') {
        para += "<br/>" + address;
      }
      para += "</p>";
      marker.openInfoWindowHtml(para);
    });
    return marker;
  }

  function initMap() {
    if (GBrowserIsCompatible()) {
      var map_element = document.getElementById('map');
      if (map_element != null) {
        map = new GMap2(map_element);
        map.setUIToDefault();
        map.setCenter(new GLatLng(lat, lng), zoom);

        for (i = 0; i < mappables.length; i++) {
          // There is only one key but it varies ('map', 'team').
          // Therefore we extract it dynamically.
          for (var key in mappables[i]) {
            map.addOverlay( createMarker(
              mappables[i][key].lat,
              mappables[i][key].lng,
              mappables[i][key].url,
              mappables[i][key].name,
              mappables[i][key].address,
              'football.png') );
          }
        }
      }
    }
  }



  //
  // Geocoding
  //
  // http://code.google.com/apis/maps/documentation/services.html#Geocoding
  // http://code.google.com/apis/maps/documentation/reference.html#GClientGeocoder
  //

  var geocoded = false;
  var submitting = false;

  function setLatLngFields(lat, lng) {
    $('input[name$="[lat]"]').val(lat);
    $('input[name$="[lng]"]').val(lng);
  }

  // Function to use as callback in asynchronous geocoding call.
  function showLocations(response) {
    if (!response || response.Status.code != 200) {
      setLatLngFields('', '');
      alert("Sorry, we were unable to find that address on a map.\nPlease try another variation.");
    }
    else {
      place = response.Placemark[0];
      // replace address field value with normalised address
      $('input[name$="[address]"]').val(place.address);
      // set lat, lng in hidden fields
      setLatLngFields(place.Point.coordinates[1], place.Point.coordinates[0]);
    }
    geocoded = true;
    submitAddressForm();
  }

  function geocodeAddress(address) {
    if (address == '') {
      setLatLngFields('', '');
      geocoded = true;
      submitAddressForm();
    }
    else {
      var geocoder = new GClientGeocoder();
      geocoder.setBaseCountryCode('uk');
      geocoder.getLocations(address, showLocations);
    }
  }

  // If we were in the middle of submitting the form,
  // go ahead and submit it.
  function submitAddressForm() {
    if (submitting) {
      $('input[name$="[address]"]').parents('form').submit();
    }
  }

  // Geocode the address when the user leaves the address field.
  $('input[name$="[address]"]').blur(function() {
    geocodeAddress($(this).val());
  });

  // Geocode the address when the form is submitted...if it hasn't
  // already been geocoded.
  $('input[name$="[address]"]').parents('form').submit(function() {
    if (!geocoded) {
      submitting = true;
      geocodeAddress($('input[name$="[address]"]').val());
      // Return false to stop original form submission because it doesn't
      // have post-geocoding values.
      return false;
    }
  });


  initMap();
});

// Prevent memory leaks.
$(document).unload(function() {
  GUnload;
});
