var map;
var customIcon;
var clusterer;

function initialize() {
  if (GBrowserIsCompatible()) {
    initMap();
    initClusterer();
    initCustomIcon();
    initMarkers();    
  }
}

function addMarkerToMap(lat, lng, title, infoWindow, useCustomIcon) {    
  var marker = createMarker(lat, lng, title, infoWindow, useCustomIcon)
  // map.addOverlay(marker);
  clusterer.AddMarker(marker, "<a href='javascript:panMapTo(" + lat +", " + lng + ", 14)'>" + title + "</a>");
}

function initMap() {
  map = new GMap2(document.getElementById("map_canvas"));        
  map.setCenter(new GLatLng(41.807866, -96.026601), 5);
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
}

function initClusterer() {
  clusterer = new Clusterer(map);
  clusterer.SetMaxVisibleMarkers(1);
  clusterer.SetMinMarkersPerCluster(2);
  clusterer.SetIcon(G_DEFAULT_ICON);
}

function initCustomIcon() {
  customIcon = new GIcon();
  customIcon.image = "images/red_push_pin.png";
  customIcon.shadow = "images/shadow-red_push_pin.png";
  customIcon.iconSize = new GSize(19.0, 48.0);
  customIcon.shadowSize = new GSize(44.0, 48.0);
  customIcon.iconAnchor = new GPoint(9.0, 48.0);
  customIcon.infoWindowAnchor = new GPoint(9.0, 48.0);
}

function initMarkers() {
  new Ajax.Request('/gotcha_utils/index.json', { method:'get',
    onSuccess: function(transport) {
      var json = transport.responseText.evalJSON();
      json.each(
        function(arry, index) {
          if (arry[1].size() > 1) {
            var first = arry[1][0];
            var count = arry[1].size();
            var lat = first.latitude;
            var lng = first.longitude;
            var markerCityState = gotchaCityState(first);
            var markerTitle = markerCityState + " - (" + count + ")";
            var infoWindow = "<h3>" + markerCityState + "</h3>";
            infoWindow += "<div class='info-window-content'><ul class='multi-info'>";
            
            arry[1].each(
              function(gotcha, index) {
                infoWindow += buildMultiInfoWindow(gotcha);
              }
            )
            
            infoWindow += "</ul></div>";
            
            addMarkerToMap(lat, lng, markerTitle, infoWindow);
          } else {
            arry[1].each(
              function(gotcha, index) {
                var lat = gotcha.latitude;
                var lng = gotcha.longitude;
                var title = gotchaCityState(gotcha);
                var infoWindow = buildSingleInfoWindow(gotcha);
                addMarkerToMap(lat, lng, title, infoWindow);
              }
            )
          }
        }
      )
    }
  });
}

function createMarker(lat, lng, title, infoWindow, useCustomIcon) {
  if (useCustomIcon)
  {
    var marker = new GMarker(new GLatLng(lat, lng), {title:title, icon:customIcon});
  } else {
    var marker = new GMarker(new GLatLng(lat, lng), {title:title});
  }
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(infoWindow);
  });
  return marker
}

function buildSingleInfoWindow(gotcha) {
  title = gotchaCityState(gotcha);
  retHtml = "<div class='info-window-content'>";
  retHtml +=  "<h3>" + title + "</h3>";
  retHtml += buildImageHtml(gotcha, "medium");
  retHtml += "</div>";
  return retHtml;
}

function buildMultiInfoWindow(gotcha) {
  retHtml = "<li>";
  retHtml += buildImageHtml(gotcha, "small", true);
  retHtml += "</li>";
  return retHtml;
}

function gotchaCityState(gotcha) {
  retVal = "";
  if (gotcha.city && gotcha.state && gotcha.country)
  {
    retVal = gotcha.city + ", " + gotcha.state;
  } else {
    retVal = gotcha.standardized_address;
  }
  return retVal;
}

function gotchaImageUrl(gotcha, size) {
  var filename = gotcha.gotcha_file_name;
  var id = gotcha.id;
  return "http://bound4life.com/system/gotchas/" + id + "/" + size + "/" + filename;
}

function gotchaMultiImageSet(gotcha) {
  return gotcha.lat + "" + gotcha.lng;
}

function buildImageHtml(gotcha, size, multi) {
  var smallUrl = gotchaImageUrl(gotcha, size);
  var retHtml = '';
  var originalUrl = gotchaImageUrl(gotcha, 'large');
  if (multi) {
    retHtml = "<a href='" + originalUrl + "' rel='lightbox[" + gotchaMultiImageSet(gotcha) + "]'><img src='" + smallUrl + "' /></a>";
  } else {
    retHtml = "<a href='" + originalUrl + "' rel='lightbox'><img src='" + smallUrl + "' /></a>";
  }
  return retHtml;
}

function panMapTo(lat, lng, zoomLevel) {
  map.closeInfoWindow
  map.setZoom(zoomLevel);
  map.panTo(new GLatLng(lat, lng));
}