POINTS = new Hash();
MARKERS = new Hash();



// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, index) {
  var dot = new GIcon(baseIcon);
  // Set up our GMarkerOptions object
  markerOptions = { icon:dot};
  var marker = new GMarker(point, markerOptions);
  
  return marker;
}

// simple browser check for use with pngs
function is_ie() {
	var agent = navigator.userAgent.toLowerCase();
	if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)) {
		return true;
	} else {
		return false;
	}
}

// recursive function that runs on each marker that is created
// causes them to flash between yellow and green randomly on a 6 second interval from when 
// they are added to the map
// param: marker obj
function animate_marker(marker) {
	setTimeout( function() {
		var bool = Math.round(Math.random());
		if (bool == 0) {
			marker.setImage('/resources/images/mashup/house_marker.png');
		} else {
			marker.setImage('/resources/images/mashup/house_marker_green.png');
		}
		animate_marker(marker);
	}, 5000);
}


function initialize_map() {
	
	// We define the function first
	function ActivityBoxControl() {}
	function HeadlineDSControl() {}
	function CounterControl() {}
	
	// To "subclass" the GControl, we set the prototype object to
	// an instance of the GControl object
	ActivityBoxControl.prototype = new GControl();
	HeadlineDSControl.prototype = new GControl();
	CounterControl.prototype = new GControl();
	
	// setup the DOM element and any methods
	ActivityBoxControl.prototype.initialize = function(map) {
		
		// create the background graphic as a <div> containing an image
		var container = document.createElement("div");
		container.id = "ActivityBox";
		container.style.display = "none";
		
		var textbox = document.createElement("div");
		textbox.id = "ActivityText";
		textbox.innerHTML = "<span class='event'>Searching for Homes</span><span class='location'>Sacramento, CA</span><a class='website' href='/bin/elite_frameset.php?domain=ihouseelite.com' target='blank'>domainhere.com</a>";
		
		container.appendChild(textbox);
		
		// attach the control to the map
		map.getContainer().appendChild(container);
		return container;
	}
	
	// Set the default position for the control ==
	ActivityBoxControl.prototype.getDefaultPosition = function() {
		var ctrl_left_offset = Math.round(map.getSize().width/2) - 47; 
		var ctrl_top_offset = Math.round(map.getSize().height/2) - 116;
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(ctrl_left_offset, ctrl_top_offset));
	}
	
	// setup the DOM element and any methods
	HeadlineDSControl.prototype.initialize = function(map) {
		var ds = document.createElement("div");
		ds.id = "HeadlineDS";
		// attach the control to the map
		map.getContainer().appendChild(ds);
		return ds;
	}
	
	// Set the default position for the control ==
	HeadlineDSControl.prototype.getDefaultPosition = function() {
		var ctrl_left_offset = 0; 
		var ctrl_top_offset = 0;
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(ctrl_left_offset, ctrl_top_offset));
	}
	
	// setup the DOM element and any methods
	CounterControl.prototype.initialize = function(map) {
		
		// create the background graphic as a <div> containing an image
		var container = document.createElement("div");
		container.id = "Counter";
		container.innerHTML = "<span id='VisitorCount'>0</span><span class='counter_description'>Elite Website visitors this week</span>";
		
		// attach the control to the map
		map.getContainer().appendChild(container);
		return container;
	}
	
	// Set the default position for the control ==
	CounterControl.prototype.getDefaultPosition = function() {
		var ctrl_left_offset = 24; 
		var ctrl_top_offset = 250;
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(ctrl_left_offset, ctrl_top_offset));
	}
	
	
	
	
	
	var map = new GMap2(document.getElementById("ih_customers_map"));
	//map.setMapType(G_SATELLITE_MAP);
	
	map.addControl(new ActivityBoxControl());
	map.addControl(new HeadlineDSControl());
	$("HeadlineDS").pngFix();
	map.addControl(new CounterControl());
	
	map.setCenter(new GLatLng(37.5, -97.5), 4);
	map.disableDoubleClickZoom();
	
	
	GEvent.addListener(map, "movestart", function() {
	  $("ActivityBox").hide();
	});
	GEvent.addListener(map, "moveend", function() {
	  $("ActivityBox").show().pngFix();
	});
	
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.image = "/resources/images/mashup/house_marker.png";
	baseIcon.shadow = "/resources/images/mashup/spacer.gif";
	baseIcon.iconSize = new GSize(26, 26);
	baseIcon.shadowSize = new GSize(0, 0);
	baseIcon.iconAnchor = new GPoint(12, 23);
	baseIcon.infoWindowAnchor = new GPoint(10, 0);
	baseIcon.printImage = "/resources/images/mashup/house_marker.png";
	baseIcon.mozPrintImage = "/resources/images/mashup/house_marker.png";
	baseIcon.printShadow = "/resources/images/mashup/house_marker.png";
	
	
	animation_started = false;
	
	var json_url = "/bin/elite_accounts_map.php";
	new Ajax.Request(json_url, {
		method:'post',
		onSuccess: function(transport) {
			
			NEW_POINTS = transport.responseJSON;
			total_points = $(NEW_POINTS).size();
			
			
			var marker_count = 0;
			
			function loadMarkerBatch(marker_batch) {	
				$(marker_batch).each(function(p, index) {
					
					// if marker does not exist yet, create it
					if (!MARKERS.get(p.acnt)) {
						
						var point = new GLatLng(p.latitude, p.longitude);
						marker = createMarker(point, p.acnt);
						MARKERS.set(p.acnt, marker);
						map.addOverlay(marker);
						animate_marker(marker);
						
					}
					
					marker_count++;
					
					// when the last marker loads...
					if (marker_count >= total_points) {
						
						animate_points();
						visitor_count_updater = new PeriodicalExecuter(function(pe) {
							getVisitorCount();
						}, 1);
						
						setTimeout( function() {
							$("MashupMask").hide();
							$("MashupLoadingMsg").hide();
						}, 5000);
					}
				});
			}
			
			
			
			// break up cities into batches of 20 and load them incrementally
			// every 0.75 seconds
			$(NEW_POINTS).eachSlice(20, function(markergroup, groupindex) {
				loadMarkerBatch.delay(groupindex*0.75, markergroup);
			});
			
		},
		onFailure: function() {
			alert('Failed to load map markers.');
		}
	});
	
	
	
	point_count = 0;
	function animate_points() {
		animation_started = true;
		new PeriodicalExecuter(function(pe) {
			
			// go back to the first marker if we reach the end
			if (point_count == total_points) {
				point_count = 0;
			}
			
			var p = NEW_POINTS[point_count];
			var marker = MARKERS.get(p.acnt);
			
			// if the marker doesn't exist yet, create it
			if (!marker) {
			
				var point = new GLatLng(p.latitude, p.longitude);
				marker = createMarker(point, p.acnt);
				MARKERS.set(p.acnt, marker);
				map.addOverlay(marker);
				
				animate_marker(marker);
				
			} 
			// else marker exists already
			else {
				var point = marker.getLatLng();
			}
			
			$$("#ActivityText span.event").each( function(s) {
				s.update(p.activity);
			});
			$$("#ActivityText span.location").each( function(s) {
				s.update(p.city + ", " + p.state);
			});
			$$("#ActivityText a.website").each( function(s) {
				s.update(p.domain);
				var url = s.href.split("?", 2);
				s.href = url[0] + "?domain=" + p.domain;
			});
			
			map.panTo(point);
			point_count++;
			
		}, 4);
	}
	
	
}


function getVisitorCount() {
	
	var current_count = parseInt($("VisitorCount").innerHTML);
		
	if (current_count == 0) {
		
		current_count++;
		$("VisitorCount").update(current_count);
		
		
		var json_url = "/bin/elite_visitor_count.php";
		new Ajax.Request(json_url, {
			method:'post',
			onSuccess: function(transport) {
				var count = transport.responseText;
				if (count) {	
					$("VisitorCount").update(count);
				}
			},
			onFailure: function() {
				alert('Failed to get visitor count.');
			}
		});
		
		
	} else {
		
		// get a random number between 1 and 2.
		var extra_amt = 1;
		if (Math.round(Math.random()) == 1) {
			extra_amt = 2;
		}
		current_count = current_count + extra_amt;
		$("VisitorCount").update(current_count);
	
	}
	
}




Event.observe(window, 'load', function() {
	
	initialize_map();
		
});

Event.observe(window, 'unload', function() {
	
	GUnload();
		
})