
var loadMap = null;

$(document).ready(function() {

  // Create a base icon for all of our markers that specifies the
  // shadow, icon dimensions, etc.
  var baseIcon = new GIcon();
  baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
  baseIcon.infoShadowAnchor = new GPoint(18, 25);

  $('#mapbox').addClass('vismap');
  var map = null;

  if ($('.searchitem .geotag').length > 0) {
    var map = new GMap2(document.getElementById("mapbox"));
  }

  loadMap = function() {
    if ($('.searchitem .geotag').length === 0) {
      return;
    }
    // add a class to the mapbox so it has a height and style
    // map.setCenter(new GLatLng(37.4419, -122.1419), 13);

    map = new GMap2(document.getElementById("mapbox"));

    map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT));

    var searchItems = $('.searchitem');
    var geotaggedItems = $('.searchitem .geotag');
    var untagged = searchItems.length - geotaggedItems.length;

    if (untagged !== 0) {
      map.addControl(new MessageControl(untagged));
    }

    var markers = [];
    var count = 0;

    geotaggedItems.each(function() {
      var p = $(this).parent();
      var oppDiv = $(p).parent();
      var h3 = oppDiv.find('h3');
      var placemarkHolder = oppDiv.find('.placemark_holder');
      var oppId = oppDiv.get(0).id.substring(3);
      var oppTitle = h3.text();

      // 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 = $(this).text().match(/-?\d+(.\d+)?/g);
      var latitude = parseable[0];
      var longitude = parseable[1];
      var point = latitude + "," + longitude;

      var marker = markers[point];
      if (marker === undefined) {
        var geoPoint = new GLatLng(latitude, longitude);
        marker = createMarker(geoPoint, count++, oppId, oppTitle);
        markers[point] = marker;
      } else {
        updateMarker(marker, oppId, oppTitle);
      }

      placemarkHolder.html('<img class="objmapicon pngimg" width="20" height="34" src="' + marker.getIcon().image + '" />');
    });

    var cluster=new ClusterMarker(map, { markers:markers, clusteringEnabled:false } );
    cluster.fitMapToMarkers();

    // random attempt to make the map slightly more useful -- if we're zoomed in
    // greater than 10, zoom out by 1; ideally this would be based on information
    // density on the map
    if (map.getZoom() > 10) {
      map.setZoom(map.getZoom() - 1);
    }

    // this is a huge hack, but for some reason safari appears to need a kick to load the
    // map tiles..
    window.setTimeout(function() {
      map.setZoom(map.getZoom());
    }, 500);
  }

  function getTitle(title, max) {
    if (title.length > max) {
      title = title.substring(0, max-3);
      title += "...";
    }

    return title;
  }

  function createMarker(point, count, oppId, oppTitle) {
    var letter = String.fromCharCode(65 + count);
    var letteredIcon = new GIcon(baseIcon);
    letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

    // Set up our GMarkerOptions object
    // clickable:false disables infoWindow; disabling until we can figure out how to display info properly [tooltip, bPwindow, etc.]
    markerOptions = { icon:letteredIcon, clickable:false};
    var marker = new GMarker(point, markerOptions);
    marker.oppInfo = "<a href=\"opp" + oppId + ".jsp\">" + getTitle(oppTitle, 40) + "</a>";
    marker.bindInfoWindowHtml("<p>" + marker.oppInfo + "</p>", {maxWidth:220});
    GEvent.addListener(map, "infowindowopen",function() {this.getInfoWindow().reset(this.getInfoWindow().getPoint(),  null,  new GSize(1,1),  null, null);this.getInfoWindow().redraw(true);});
    return marker;
  }

  function updateMarker(marker, oppId, oppTitle) {
    marker.oppInfo = marker.oppInfo + "<br />";
    marker.oppInfo = marker.oppInfo + "<a href=\"opp" + oppId + ".jsp\">" + getTitle(oppTitle, 40) + "</a>";
    marker.bindInfoWindowHtml("<p>" + marker.oppInfo + "</p>", {maxWidth:220});
  }

  function MessageControl(numOpps) {
    this.numOpps = numOpps;
  }

  MessageControl.prototype = new GControl();

  MessageControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var messageDiv = document.createElement("div");
    this.setButtonStyle_(messageDiv);
    container.appendChild(messageDiv);

    var msg = " 1 result is not displayed ";
    if (this.numOpps !== 1) {
      msg = this.numOpps + " results are not shown ";
    }

    messageDiv.appendChild(document.createTextNode(msg));
    messageDiv.style.whiteSpace = "nowrap";
    var img = document.createElement("img");
    img.src = "/images/iconsets/silk/help.png";
    img.style.verticalAlign = "middle";
    img.className = "pngimg";
    img.id = "testImg";

    link = document.createElement("A");
    link.href= "#";
    link.rel="#resultsNotDisplayed";
    link.className= "cluetipMap";
    link.title="Search Results Not Displayed";
    link.appendChild(img);

    messageDiv.appendChild(link);
    
    map.getContainer().appendChild(container);
    return container;
  };

  MessageControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
  };

  // Sets the proper CSS for the given button element.
  MessageControl.prototype.setButtonStyle_ = function(button) {
    button.style.backgroundColor = "white";
    button.style.fontSize = ".8em";
    button.style.border = "1px solid black";
    button.style.padding = "2px";
    button.style.textAlign = "center";
  };

  if (GBrowserIsCompatible()) {
    loadMap();
  }

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

  //re-run cluetip for cluetipMap class; it may have already run for other cluetip'd elements [i.e. CL badges] but that is run on pageload. 
  if ($('.cluetipMap') != null && $('.cluetipMap').cluetip) {
    $('.cluetipMap').cluetip({
    arrows: true,
    dropShadow: false,
    sticky: true,
    //mouseOutClose: true,
    closePosition: 'title',
    closeText: '<img src="/images/cross.png" alt="close" />',
    local: true,
    cluetipClass: 'vm',
    positionBy: 'mouse',
    activation: 'toggle'
  });
  }
});


