addRadiusCircle = null;
removeRadiusCircle = null;

$(document).ready(function() {
  var locs = $('.geotag');
  var circleRadiusInMilesElement = $('#circleRadiusInMiles');

  if (locs.length === 0) {
    return;
  }

  var loc = locs.get(0);

  // we should theoretically be able to simply use loc.children[0] and [1],
  // but IE fails to process the children correctly.  Fall back to
  // the somewhat slower regexp parsing method.
  var parseable = $(loc).text().match(/-?\d+(.\d+)?/g);
  var latitude = parseable[0];
  var longitude = parseable[1];

  var circleRadiusInMiles = 0;
  if (circleRadiusInMilesElement != null) {
    circleRadiusInMiles = circleRadiusInMilesElement.html();
  }

  addRadiusCircle = function() {
    locateOnMap(latitude, longitude, 'mapbox', circleRadiusInMiles );
  }

  addRadiusCircle();

  removeRadiusCircle = function() {
    locateOnMap(latitude, longitude, 'mapbox', (circleRadiusInMiles * -1));
  }

  $(document).unload(function() {
    GUnload();
  });
});

var MILES_IN_METERS = 1609.344;
var EARTH_RADIUS_IN_MILES = 3963.1676;

function radiansToDegrees(radian) {
  return radian*180/Math.PI;
}

function locateOnMap(latitude, longitude, mapElementName){
  locateOnMap(latitude, longitude, mapElementName, 0);
}

function locateOnMap(latitude, longitude, mapElementName, circleRadiusInMiles){
  if (GBrowserIsCompatible()) {
    // add a class to the mapbox so it has a height and style
    $('#'+mapElementName).addClass('vismap');

    var geoPoint = new GLatLng(latitude, longitude);

    var map = new GMap2(document.getElementById(mapElementName));

    // "fix" for safari et al
    GEvent.addListener( map, 'load', function() {
      window.setTimeout( function() {
          var zoom = map.getZoom();
          map.setZoom( zoom > 1 ? zoom - 1 : zoom + 1 );
          map.setZoom( zoom );
      }, 500 );
    });
    map.setCenter(geoPoint, 12);
    map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT));

    var pushpin = new GIcon();
    pushpin.image = "http://maps.google.com/mapfiles/ms/micons/red-pushpin.png";
    pushpin.shadow = "http://maps.google.com/mapfiles/ms/micons/pushpin_shadow.png";
    pushpin.iconSize = new GSize(32, 32);
    pushpin.shadowSize = new GSize(59, 32);
    pushpin.iconAnchor = new GPoint(10, 30);

    marker = new GMarker(geoPoint, {icon: pushpin, clickable: false});
    
    if (circleRadiusInMiles != null && circleRadiusInMiles >0){
      var circleThickness = 1;
      var circleColor = "#034150";
      var circleOpacity = 1;
      var circleInnerColor = "#034150";
      var circleInnerOpacity = 0.0;

      map.addOverlay(GPolygon.Circle(geoPoint,circleRadiusInMiles*MILES_IN_METERS,
                                     circleColor,circleThickness,circleOpacity,
                                     circleInnerColor,circleInnerOpacity));

      setZoomLevel(geoPoint, circleRadiusInMiles);
    } else if (circleRadiusInMiles != null && circleRadiusInMiles < 0 ) {
      //use circle radius to calculate zoom level, but leave out the circle itself.  This acts as a toggle to remove the circle from an existing map, but keep the same zoom level
      setZoomLevel(geoPoint, (circleRadiusInMiles * -1));
    }

    map.addOverlay(marker);
    // we now have a map; we know we have javascript,
    // so just take the address and use it for a link.
    // this depends on two things:  first, the address
    // field has to have the id "address".  second, the
    // placement is set -- always at the end of the
    // address field
    var addr = $('#address');
    var addrText = jQuery.trim(addr.text());
    addr.append("<br /><a class='read_more' href='http://maps.google.com/maps?h1=en&saddr=&daddr=" + escape(addrText) + "' target=\"_blank\">Get Directions</a>");
  }

  function setZoomLevel(geoPoint, radius) {
      var deltaLatitudeLongitude = radiansToDegrees( Math.asin(radius/EARTH_RADIUS_IN_MILES) );
      var north = geoPoint.lat() + deltaLatitudeLongitude;
      var south = geoPoint.lat() - deltaLatitudeLongitude;
      var east  = geoPoint.lng() + deltaLatitudeLongitude;
      var west  = geoPoint.lng() - deltaLatitudeLongitude;
      var bounds = new GLatLngBounds(new GLatLng(south, west),
                                         new GLatLng(north, east));
      map.setCenter(geoPoint, map.getBoundsZoomLevel(bounds));
  }


}
