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);
  
  // Zoom in based on window size.  1 (most zoomed in) - 16 (most zoomed out)
  var w = $(window).width();
  var zoomInt = (w < 1200) ? 16 :
  							(w < 2400) ? 15 :
							(w < 4800) ? 14 : 13;
  yMap.drawZoomAndCenter(myPoint, zoomInt);
  
  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 statsinsight_cache 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;
	
	// Cleanup objects - added by Justin Miller on 6.21.2010
//	delete myPoint;
//	delete 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>";
	} 
  
  //var marker_text = "<span style='color:black; margin: 0 0 0 20px; color: white; padding:5px 10px; border:1px solid black; background:#0e345b; opacity: 0.8;'>" + location_text.replace(" ", "&nbsp;") + "</span>"; //add display: block;
  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 (bUseLargeImages == true) {
    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);
  }
  else {
    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("$(\"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) {
    while (marker_array.length >= max_markers) {
      var marker = marker_array.shift();
      yMap.removeOverlay(marker);
	  delete marker;
    }
  }
}

/* Created by Justin Miller on 6.18.2010 for fullscreen mode */
function resizeMap() {
	yMap.resizeTo(new YSize($(window).width(),$(window).height()));
}




// Global variables
var current_visitor = 0;

$(document).ready(function(){
	
	// Stupid IE
	if ($.browser.msie) {
		$("#ie_map_alert").text("You're running Internet Explorer.  Please wait one moment for the map to load...").show();
		setTimeout("initialize_map(); updateAll(); $('#ie_map_alert').fadeOut(700);", 10000);
	}
	// Normal browsers
	else {
		initialize_map();
		updateAll();
	}
});


// Update map, BIG3, and visitor list
function updateAll() {
	$.getJSON('index.php?m=public&a=cache_day_total', function(data) {
		if (data != null && data.has_data) {
			
			if ((data.last_visitor_id != 0) && (data.last_visitor_id != current_visitor)) {
				current_visitor = data.last_visitor_id;
				var mp = data.map_points;
				
				// Update map
				var loc = (mp.city_name && mp.city_name.length > 0 && mp.country_name && mp.country_name.length > 0) ?
								(mp.city_name + ', ' + mp.country_name) : (mp.country_name && mp.country_name.length > 0) ?
								mp.country_name : 'Unknown';
				addNextMarker(mp.latitude, mp.longitude, mp.id, loc, mp.site_tracking_type_reference_id);
				
				// Update visitor list
				var h = '';
				var a = {
					2: 'decision',
					3: 'response_initiated_followup',
					4: 'visitor'
				};
				
				for (var i in data.visitor_list) {
					var v = data.visitor_list[i];
					var type = a[v.site_tracking_type_reference_id];
					var typeDisplay = type.substr(0,1).toUpperCase() + type.substr(1);
					
					var loc = v.country_formatted;
					if ($.trim(v.city_name) != '')
						loc += ' <span>&raquo;</span> ' + v.city_name + '</p>';
					
					// Update HTML
					h += '<div class="vd_item"><div id="vd_cover_' + type + '" class="vd_highlight_cover"></div>';
					
					// Visitor Type
					h += '<div class="container_response">';
					h += '<p><span class="response_type response_type_' + type + '" class="response_type"></span>&nbsp;' + typeDisplay + '</p>';
					h += '</div>';
					
					// Website
					h += '<div class="container_website">';
					h += '<span class="vd_divider"></span><p>' + v.url_formatted + '</p>';
					h += '</div>';
					
					// Time
					h += '<div class="container_time ">';
					h += '<span class="vd_divider"></span><p class="time">' + v.timestamp_formatted_time + '</p>';
					h += '</div>';
					
					// Location
					h += '<div class="container_location">';
					h += '<span class="vd_divider"></span><p class="location">' + loc + '</p>';
					h += '</div>';
					if ($.trim(v.flag_image) != '')
							h += '<img src="./images/country_flags/' + escape(v.flag_image) + '" class="flag" />';
					h += '</div>';
				}
				$('#visitor_list').html(h);
				$('#visitor_list .vd_highlight_cover').fadeOut(1500);
				
				// Update BIG3
				var h = '<div title="Visitor">' + data.big3.visitor + '</div>';
				h += '<div id="id" title="Indicated Decision">' + data.big3.decision + '</div>';
				h += '<div id="if" title="Initiated Followup">' + data.big3.followup + '</div>';
				$('#visitor_count').html(h);
			}
			
			// Nothing changed
			else {}
		}
	});
	
	setTimeout("updateAll();", 5000);
}