if (typeof stakr == 'undefined' || !stakr)  { stakr                       = {}; }
if (!stakr.google)                          { stakr.google                = {}; }
if (!stakr.google.maps)                     { stakr.google.maps           = {}; }
if (!stakr.google.maps.instances)           { stakr.google.maps.instances = {}; }
if (!stakr.timers)                          { stakr.timers                = {}; }

stakr.google.maps.initialize = function(id, longitude, latitude, location) {
  stakr.google.maps.instances[id] = new google.maps.Map2($(id + '_google_maps'), { size: new google.maps.Size(500, 300) });
  stakr.google.maps.instances[id].addControl(new google.maps.SmallMapControl());
  stakr.google.maps.instances[id].addControl(new google.maps.MapTypeControl());
  if (arguments.length >= 4) {
    var point = new google.maps.LatLng(latitude, longitude);
    stakr.google.maps.setMarker(id, point, location);
  }
}

stakr.google.maps.geocode = function(id) {
  var geocoder = new google.maps.ClientGeocoder();
  var location = $(id).value;
  geocoder.getLatLng(location, function(point) {
      if (point) {
        if (typeof(stakr.google.maps.instances[id]) == 'undefined') {
          stakr.google.maps.initialize(id);
        }
        if (!$(id + '_google_maps').visible()) {
          Effect.SlideDown(id + '_google_maps', { duration: 0.2 });
        }
        stakr.google.maps.setMarker(id, point, location);
        $(id + '_longitude').value = point.lng();
        $(id + '_latitude').value = point.lat();
      } else {
        if ($(id + '_google_maps').visible()) {
          Effect.SlideUp(id + '_google_maps', { duration: 0.2 });
        }
        $(id + '_longitude').value = null;
        $(id + '_latitude').value = null;
      }
    }
  );
}

stakr.google.maps.setMarker = function(id, point, location) {
  stakr.google.maps.instances[id].setCenter(point, 15);
  stakr.google.maps.instances[id].clearOverlays();
  var marker = new google.maps.Marker(point);
  stakr.google.maps.instances[id].addOverlay(marker);
  google.maps.Event.addListener(marker, 'click', function() {
    marker.openInfoWindow(new Element('a', { href: 'http://maps.google.de/maps?daddr=' + encodeURI(location), target: '_blank' }).update('Route planen'));
  });
}

stakr.google.maps.delayedGeocode = function(id, delay) {
  if (stakr.timers[id]) {
    window.clearTimeout(stakr.timers[id]);
    stakr.timers[id] = null;
  }
  stakr.timers[id] = window.setTimeout('stakr.google.maps.geocode(\'' + id + '\');', delay);
}
