var map_initialized = false;
var current_marker = null;
var marker_array = Array(); //this will a revolving list of up to N YahooMarkers
var yMap = null;
var max_markers = 50;
var max_labels_to_show = 5;

//
// Don't do this until the page load has completely finished. IE, you could put it in the
// page's onLoad() function or equivalent.
//
function initialize_map() {
  if (document.getElementById('map') == 'undefined') { return false; }
  // Create a map object
  yMap = new YMap(document.getElementById('map'));

  // Set map type to either of: YAHOO_MAP_SAT, YAHOO_MAP_HYB, YAHOO_MAP_REG
  yMap.setMapType(YAHOO_MAP_REG);
  yMap.disablePanOnDoubleClick();
  yMap.disableDragMap();
  yMap.disableKeyControls();

  // Display the map centered on a geocoded location
  var myPoint = new YGeoPoint(37.4041960114344,-122.008194923401);
  yMap.drawZoomAndCenter(myPoint, 16); //1-most zoomed in, 16-most zoomed out

  map_initialized = true;
  return true;
}

/**
 * Destroys the Yahoo YMap object on the web page and resets the current_marker and
 * marker_array queue.
 *
 * @return bool
 */
function destroy_map() {
  if (map_initialized == true) {
    yMap = null;
    current_marker =  null;
    marker_array = Array();
    map_initialized = false;
  }
  return true;
}

/**
 * Adds a new marker to the map using the given coordinates. The data for this coordinate is
 * stored in the resulting Yahoo YMarker and that marker object is stored in a rotating array
 * queue.
 *
 * @param float   latitude       Latitude for the location
 * @param float   longitude      Longitude for the location
 * @param int     db_record_id   ID of the record in the database for this record
 * @param string  location_text  City and/or Country for this location marker
 * @param int     record_type    Value indicating type of visitor (1|4=visitor, 2=decision, 6=followup)
 *
 * @return void
 */
function addNextMarker(latitude, longitude, db_record_id, location_text, record_type) {
  // Add record type tracking via optional parameter
  if (typeof record_type == "undefined") {
    record_type = 4;
  }
  
  if (map_initialized == false) { initialize_map(); }

  if (current_marker) {
    //Add the current marker to the END of revolving array
    marker_array.push(current_marker);
  }

  //If we have more than 5 markers on the map, close the tooltip for the 6th one
  if (marker_array.length > max_labels_to_show-1) {
    var marker_index = marker_array.length - max_labels_to_show;


    //Remove the marker (I can erase the label but changing the image isn't working with the new smaller dimensions)
    yMap.removeOverlay(marker_array[marker_index]);

    //Re-create the marker using the smaller images
    var myPoint = new YGeoPoint(marker_array[marker_index].latitude, marker_array[marker_index].longitude);
    var recreated_marker = createYahooMarker(myPoint, '', '', marker_array[marker_index].record_type, false);

    //Store additional marker details with the marker object (in case we need to re-create the marker)
    recreated_marker.db_record_id = marker_array[marker_index].db_record_id;
    recreated_marker.record_type = marker_array[marker_index].record_type;
    recreated_marker.label = marker_array[marker_index].label;
    recreated_marker.latitude = marker_array[marker_index].latitude;
    recreated_marker.longitude = marker_array[marker_index].longitude;
    yMap.addOverlay(recreated_marker);
    marker_array[marker_index] = recreated_marker;
  }

  //Get the new current marker
  myPoint = new YGeoPoint(latitude, longitude);
	if (record_type == 2) {  
		var tooltip_text = "<span style='color:black;'>" + location_text.replace(" ", "&nbsp;") + "</span>";
		var marker_text = "<div id='bubble_btm'><div id='bubble_top'>" + location_text.replace(" ", "&nbsp;") + "</div></div>";
	} else if (record_type == 6) { 
		var tooltip_text = "<span style='color:black;'>" + location_text.replace(" ", "&nbsp;") + "</span>";
		var marker_text = "<div id='bubble_btm' class='bubble_orange'><div id='bubble_top'>" + location_text.replace(" ", "&nbsp;") + "</div></div>";
	} else {  
		var tooltip_text = "<span style='color:black;'>" + location_text.replace(" ", "&nbsp;") + "</span>";
		var marker_text = "<div id='bubble_btm' class='bubble_blue'><div id='bubble_top'>" + location_text.replace(" ", "&nbsp;") + "</div></div>";
	} 
  
  current_marker = createYahooMarker(myPoint, marker_text, tooltip_text, record_type, true);

  //Store additional marker details with the marker object (in case we need to re-create the marker)
  current_marker.db_record_id = db_record_id;
  current_marker.record_type = record_type;
  current_marker.label = marker_text;
  current_marker.latitude = latitude;
  current_marker.longitude = longitude;
  yMap.addOverlay(current_marker);
  yMap.panToLatLon(myPoint);

  //If we have more than N markers, remove the old ones
  removeOldMarkers();
}

/**
 * Create a new Yahoo marker (image with text) that uses the specified YGeoPoint, label, etc.
 * Large images are used for 5 most recent plotted points, and smaller images are used for the
 * plotted points older than the 5 most recent.
 *
 * @param YGeoPoint geopoint         A Yahoo YGeoPoint object for the latitude and longitude of this marker
 * @param string    marker_label     Used for the label of the marker
 * @param string    tooltip_html     Used for the "AutoExpand" and/or "SmartWindow" - CMG disabled use of these for now since the styling is all messed up
 * @param int       record_type      Value indicating type of visitor (1|4=visitor, 2=decision, 6=followup)
 * @param bool      bUseLargeImages  Indicates whether to use the large marker images (true) or the small marker images (false)
 *
 * @return YMarker  marker           Returns a Yahoo YMaker object
 */
function createYahooMarker(geopoint, marker_label, tooltip_html, record_type, bUseLargeImages) {
  if (map_initialized == false) { initialize_map(); }

  //Set the marker image to the corresponding colored icon (based on type of record)
  var new_image = new YImage();
    if (record_type == 2) { new_image.src = '/images/marker_person_yellow.png'; }      //decision
    else if (record_type == 6) { new_image.src = '/images/marker_person_orange.png'; } //followup
    else { new_image.src = '/images/marker_person_blue.png' }                          //visitor (1 or 4 or anything else)
    new_image.size = new YSize(9,13);

  var marker = new YMarker(geopoint, new_image);
  marker.addLabel(marker_label);
  setTimeout("$j(\"img[id^='ymiymarkeryid']\").css(\"z-index\",\"4\");", 200);
  return marker;
}

/**
 * Removes the last marker from the map and removes it from the marker array as well.
 *
 * @return bool
 */
function removeOldMarkers() {
  if (map_initialized == false) { initialize_map(); }

  if (marker_array) {
    if (marker_array.length >= max_markers) {
      var marker = marker_array.shift();
      yMap.removeOverlay(marker);
    }
  }
  return true;
}

/**
 * When the menu is shown/hidden then this method is used to resize the map container
 * accordingly so we don't get flicker in the map.
 *
 * @param  bool bMenuIsVisible
 * @return bool
 */
function resizeMap(bMenuIsVisible) {
  if (map_initialized == false) { return true; }

  if (yMap) {
    var oMapContanerSize = yMap.getContainerSize();

    //Set the height
    var iHeight = 449; //height of map for the Map/Counter/Visitor List visual
    if (oMapContanerSize.height > 600) {
      iHeight = 634; //height of map for the Map visual
    }

    //Set the width
    var iWidth = 726; //width if the menu is visible
    if (bMenuIsVisible == false) {
      iWidth = 992; //width if the menu is hidden
    }
    yMap.resizeTo(new YSize(iWidth,iHeight));
  }
  return true;
}
