/*
 * Google map helper functions; depends on jquery and google map
 */


VMATCH.namespace('gmap.opps');

VMATCH.gmap.opps.load = function() {
  // 0. add our logo in the appropriate spots
  var logo = '<p align="right"><a href="http://www.volunteermatch.org/"><img src="http://www.volunteermatch.org/images/poweredby_112x52.gif" height="52" width="112" alt="Powered By VolunteerMatch" border="0" /></a></p>';
  $('#VM_listings').append(logo);
  $('#VM_virtual').append(logo);

  if (VMATCH.config.opps != null && VMATCH.config.opps.length > 0) {
    VMATCH.gmap.opps.opps = VMATCH.config.opps;

    // 1. build our DOM
    VMATCH.gmap.opps.buildDOM();

    // 2. for each opp, add the listing
    for (var index = 0; index < VMATCH.gmap.opps.opps.length; index++) {
      var opp = VMATCH.gmap.opps.opps[index];

      VMATCH.gmap.opps.addListing(opp);
      VMATCH.gmap.opps.addMarker(opp);
    }

    // 3. display appropriately
    VMATCH.gmap.opps.display();
  } else {
    // 4. update the status
    $('#VM_status').empty().append('<p>There are no active Opportunities to display.</p>');
  }
}

VMATCH.gmap.opps.buildDOM = function() {
  // 1. remove loading info
  $('#VM_status').remove();

  var width = VMATCH.config.mapwidth ? VMATCH.config.mapwidth : 250;
  var height = VMATCH.config.mapheight ? VMATCH.config.mapheight : 230;

  $('#VM_opps').append('<div>\
      <span class="VM_tab VM_selectedtab" id="VM_showmap">Map</span>\
      <span class="VM_tab" id="VM_showlistings">Listings</span>\
      <span class="VM_tab" id="VM_showvirtual" style="display: none;">Virtual</span>\
      <div id="VM_map">\
        <div>\
          <div id="VM_mapdiv" style="width: ' + width + 'px; height: ' + height + 'px"></div>\
        </div>\
      </div>\
      <div id="VM_listings"><p align="right"><a href="http://www.volunteermatch.org/"><img src="http://www.volunteermatch.org/images/poweredby_112x52.gif" height="52" width="112" alt="Powered By VolunteerMatch" border="0"/></a></p></div>\
      <div id="VM_virtual" style="display: none;"><p align="right"><a href="http://www.volunteermatch.org/"><img src="http://www.volunteermatch.org/images/poweredby_112x52.gif" height="52" width="112" alt="Powered By VolunteerMatch" border="0"/></a></p></div>\
    </div>');
}

VMATCH.gmap.opps.addListing = function(opp) {
  // 1. build up the HTML for this opp
  var oppHTML = '<p class="VM_listing" oppid="';
  oppHTML += opp.id;
  oppHTML += '"><a href="';
  oppHTML += VMATCH.config.href ? VMATCH.config.href : opp.href ? opp.href : 'http://www.volunteermatch.org/';
  oppHTML += 'results/opp_detail.jsp?oppid=';
  oppHTML += opp.id;
  oppHTML += '" target="volunteermatch">';
  oppHTML += opp.title;
  oppHTML += '</a><br />';
  if (!opp.location.virtual) {
    oppHTML += opp.location.address;
    oppHTML += '<br />';
  }
  oppHTML += opp.description;
  oppHTML += '</p>';

  // 2. append it to the appropriate div
  if (opp.location.virtual) {
    // 3. flag that we have virtual opps
    VMATCH.gmap.opps.hasVirtual = true;
    $('#VM_virtual').prepend(oppHTML);
  } else {
    $('#VM_listings').prepend(oppHTML);
  }
}

VMATCH.gmap.opps.addMarker = function(opp) {
  if (!GBrowserIsCompatible || !opp.location.hasGeoLoc) {
    return;
  }

  // 1. init the map, if it hasn't been done
  if (!VMATCH.gmap.opps.map) {
    VMATCH.gmap.opps.markers = [];
    VMATCH.gmap.opps.points = new Object();
    VMATCH.gmap.opps.tooltip = document.createElement('div');
    VMATCH.gmap.opps.tooltip.style.visibility = 'hidden';

    VMATCH.gmap.opps.map = new GMap2($('#VM_mapdiv').get()[0]);
    VMATCH.gmap.opps.map.addControl(new GSmallMapControl());
    VMATCH.gmap.opps.map.getPane(G_MAP_FLOAT_PANE).appendChild(VMATCH.gmap.opps.tooltip);
    VMATCH.gmap.opps.map.setCenter(new GLatLng(37.4419, -90.1419), 4);

    VMATCH.gmap.opps.mgr = new GMarkerManager(VMATCH.gmap.opps.map);

    VMATCH.gmap.opps.icon = new GIcon();
    VMATCH.gmap.opps.icon.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
    VMATCH.gmap.opps.icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    VMATCH.gmap.opps.icon.iconSize = new GSize(12, 20);
    VMATCH.gmap.opps.icon.shadowSize = new GSize(22, 20);
    VMATCH.gmap.opps.icon.iconAnchor = new GPoint(6, 20);
    VMATCH.gmap.opps.icon.infoWindowAnchor = new GPoint(5, 1);
  }

  var key = opp.location.lat + ',' + opp.location.lon;
  var marker = VMATCH.gmap.opps.points[key];
  if (marker == null) {
    var point = new GLatLng(parseFloat(opp.location.lat), parseFloat(opp.location.lon));
    marker = new GMarker(point, VMATCH.gmap.opps.icon);
    marker.tooltip = '<div class="VM_tooltip">' + opp.title + '</div>';

    marker.infoElement = '<div>';
    marker.infoElement += '<div class="VM_listingpopup">';
    marker.infoElement += '<a href="';
    marker.infoElement += VMATCH.config.href ? VMATCH.config.href : opp.href ? opp.href : 'http://www.volunteermatch.org/';
    marker.infoElement += 'results/opp_detail.jsp?oppid=' + opp.id + '" target="volunteermatch">' + opp.title + '</a>';
    marker.infoElement += '<br />';
    marker.infoElement += opp.dates;
    marker.infoElement += '</div>';
    marker.infoElement += '</div>';

    VMATCH.gmap.opps.points[key] = marker;

    GEvent.addListener(marker, 'click', function() {
      marker.openInfoWindowHtml(this.infoElement);
    });

    GEvent.addListener(marker, 'mouseover', function() {
      showTooltip(marker);
      marker.setImage('http://labs.google.com/ridefinder/images/mm_20_yellow.png');
      for (var i = 0; i < this.opps.length; i++) {
        $(this.opps[i]).addClass('VM_selected');
      }
    });

    GEvent.addListener(marker, 'mouseout', function() {
      VMATCH.gmap.opps.tooltip.style.visibility = 'hidden'
      marker.setImage('http://labs.google.com/ridefinder/images/mm_20_red.png');
      for (var i = 0; i < this.opps.length; i++) {
        $(this.opps[i]).removeClass('VM_selected');
      }
    });

    if (VMATCH.gmap.opps.bounds == null) {
      VMATCH.gmap.opps.bounds = new GLatLngBounds(point, point);
    } else {
      VMATCH.gmap.opps.bounds.extend(point);
    }

    VMATCH.gmap.opps.markers.push(marker);
  } else {
    marker.infoElement = marker.infoElement.substring(0, marker.infoElement.length - 6);
    marker.infoElement += '<div class="VM_listingpopup"><b>';
    marker.infoElement += '<a href="';
    marker.infoElement += VMATCH.config.href ? VMATCH.config.href : opp.href ? opp.href : 'http://www.volunteermatch.org/';
    marker.infoElement += 'results/opp_detail.jsp?oppid=' + opp.id + '" target="volunteermatch">' + opp.title + '</a>';
    marker.infoElement += '<br />';
    marker.infoElement += opp.dates;
    marker.infoElement += '</div>';
    marker.infoElement += '</div>';

    marker.tooltip = '<div class="VM_tooltip nowrap">' + (marker.opps.length + 1) + ' Listings</div>';
  }

  var oppdiv = $('p[oppid=' + opp.id + ']').get()[0];
  oppdiv.marker = marker;
  if (marker.opps == null) {
    marker.opps = [];
  }
  marker.opps.push(oppdiv);

  $(oppdiv).mouseover(function() {
    this.marker.setImage('http://labs.google.com/ridefinder/images/mm_20_yellow.png');
  });

  $(oppdiv).mouseout(function() {
    this.marker.setImage('http://labs.google.com/ridefinder/images/mm_20_red.png');
  });
}

VMATCH.gmap.opps.display = function() {
  if (VMATCH.gmap.opps.map) {
    $('#VM_showmap').click(function() {
      $('#VM_listings').css('display', 'block');
      $('#VM_showlistings').removeClass('VM_selectedtab');

      $('#VM_map').css('display', 'block');
      $('#VM_showmap').addClass('VM_selectedtab');

      if (VMATCH.gmap.opps.hasVirtual) {
        $('#VM_virtual').css('display', 'none');
        $('#VM_showvirtual').removeClass('VM_selectedtab');
      }
    });

    if (VMATCH.gmap.opps.bounds != null) {
      var center = VMATCH.gmap.opps.bounds.getCenter();
      var newZoom = VMATCH.gmap.opps.map.getBoundsZoomLevel(VMATCH.gmap.opps.bounds);
      VMATCH.gmap.opps.map.setCenter(center, newZoom);
    }

    VMATCH.gmap.opps.mgr.addMarkers(VMATCH.gmap.opps.markers, 2);
    VMATCH.gmap.opps.mgr.refresh();

    GEvent.addListener(VMATCH.gmap.opps.map, 'zoomend', function() {
      recalcMarkers();
    });

    GEvent.addListener(VMATCH.gmap.opps.map, 'moveend', function() {
      recalcMarkers();
    });
  } else {
    $('VM_showmap').css('display','none');
    $('VM_map').css('display','none');
  }

  $('#VM_showlistings').click(function() {
    $('#VM_listings').css('display', 'block');
    $('#VM_showlistings').addClass('VM_selectedtab');

    if (VMATCH.gmap.opps.map) {
      $('#VM_map').css('display', 'none');
      $('#VM_showmap').removeClass('VM_selectedtab');
    }

    if (VMATCH.gmap.opps.hasVirtual) {
      $('#VM_virtual').css('display', 'none');
      $('#VM_showvirtual').removeClass('VM_selectedtab');
    }
  });

  if (VMATCH.gmap.opps.hasVirtual) {
    $('#VM_showvirtual').css('display','inline');
    $('#VM_showvirtual').click(function() {
      $('#VM_listings').css('display', 'none');
      $('#VM_showlistings').removeClass('VM_selectedtab');

      if (VMATCH.gmap.opps.map) {
        $('#VM_map').css('display', 'none');
        $('#VM_showmap').removeClass('VM_selectedtab');
      }

      $('#VM_virtual').css('display', 'block');
      $('#VM_showvirtual').addClass('VM_selectedtab');
    });
  }
}

function recalcMarkers() {
  // get the x and y offset for a box surrounding our icon at this zoom level
  var bounds = VMATCH.gmap.opps.map.getBounds();

  var centerPoint = VMATCH.gmap.opps.map.getCenter();

  var pixel = VMATCH.gmap.opps.map.fromLatLngToDivPixel(centerPoint);
  var nePixel = new GPoint(pixel.x - 6, pixel.y - 20);
  var neLatLng = VMATCH.gmap.opps.map.fromDivPixelToLatLng(nePixel);

  var latDelta = centerPoint.lat() - neLatLng.lat();
  var lngDelta = centerPoint.lng() - neLatLng.lng();

  for (var i = 0; i < VMATCH.gmap.opps.markers.length; i++) {
    var marker = VMATCH.gmap.opps.markers[i];
    var point = marker.getPoint();

    // remap bounds -- we only want to show if the complete bounds of the
    // marker is on screen
    var ne = new GLatLng(point.lat() - latDelta, point.lng() + lngDelta);
    var sw = new GLatLng(point.lat(), point.lng() - lngDelta);

    var markerBounds = new GLatLngBounds(sw, ne);

    if (bounds.containsBounds(markerBounds)) {
      for (var j = 0; j < marker.opps.length; j++) {
        $(marker.opps[j]).css('display', 'block');
      }
    } else {
      for (var j = 0; j < marker.opps.length; j++) {
        $(marker.opps[j]).css('display', 'none');
      }
    }
  }
}

// from .. some blog re: maps
function showTooltip(marker) {
  VMATCH.gmap.opps.tooltip.innerHTML = marker.tooltip;
  var point = VMATCH.gmap.opps.map.getCurrentMapType().getProjection().fromLatLngToPixel(VMATCH.gmap.opps.map.fromDivPixelToLatLng(new GPoint(0, 0), true), VMATCH.gmap.opps.map.getZoom());
  var offset = VMATCH.gmap.opps.map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), VMATCH.gmap.opps.map.getZoom());
  var anchor = marker.getIcon().iconAnchor;
  var width = marker.getIcon().iconSize.width;
  var height = VMATCH.gmap.opps.tooltip.clientHeight;
  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y - anchor.y - height));
  pos.apply(VMATCH.gmap.opps.tooltip);
  VMATCH.gmap.opps.tooltip.style.visibility = 'visible';
}

if (!$.browser.msie) {
  $(document.body).unload(GUnload());
}