
/* ************************************************************************** */
// JQuery equivalent of onload function, this is the primary entry point
/* ************************************************************************** */
$(document).ready(function()
{
	// Init the map to show this user's cube
	initialize();
	
	// Standard unload for Google Maps
	$("body").bind("unload", GUnload);
	
	// Facebook Connect
	FB.init("30634f9df1c3b0680cf3dab3911ea26d", "/xd_receiver.htm", { "ifUserConnected": function(){ fbConnectLoggedIn(true); }, "ifUserNotConnected": function(){ fbConnectNotLoggedIn(true); } });
	
	// Facebook Connect feed dialog
	$("#fb-connect-publish").live("click", function(event)
	{
		event.preventDefault();
		fbConnectPublish();
	});
	
	// Invite friends to connect
	$("#fb-connect-invite").live("click", function(event)
	{
		event.preventDefault();
		fbConnectInvite();
	})
	
	// Logout of FB Connect
	$("#fb-connect-logout").live("click", function(event)
	{
		event.preventDefault();
		fbConnectLogout(true);
	})
});
/* ************************************************************************** */


/* ************************************************************************** */
function initialize()
{
	$("#spinner").show();
	
	if (GBrowserIsCompatible())
	{
		_liveblue.map = new GMap2(document.getElementById("map")); 
		_liveblue.map.setUIToDefault();
		_liveblue.map.setMapType(G_SATELLITE_MAP);
		
		// We can't center the map until the cube loads, so center it
		// in an area outisde existing lat/lng, so the gray background comes up.
		_liveblue.map.setCenter(new GLatLng(100.0, 100.0), 5);
		
		// Create a ClusterMarker cluster to add our markers to
		_liveblue.cluster = new ClusterMarker(_liveblue.map, { clusteringEnabled: _liveblue.ENABLE_CLUSTERING,  clusterMarkerClick: clusterClick, clusterMarkerIcon: getClusterCubeIcon() });
		
		// Load this user's cube
		data = {};
		if(_liveblue.username){ data.username = _liveblue.username; }
		else{ data.cube_id = _liveblue.cube_id; }
		
		$.get("/php/get-cube.php", data, function(response)
		{
			if(!response || !response.cube){ return; }
			
			// Oops, should not have named ice-island with a dash,
			// since now it needs to exist as a JS variable.
			_liveblue.extent_id = response.cube.area_id;
			if(_liveblue.extent_id == "ice-island"){ _liveblue.extent_id = "ice_island"; }
			
			// Store the current cube id
			_liveblue.cube_id = response.cube.id;
			
			// Update the page h1 to the username
			$("h1").html(response.cube.user.username + "'s plot");
			
			// Update the reason and action
			$("#my-reason").html(response.cube.reason);
			$("#my-action").html(response.cube.action);
			
			// Reset lat/lng
			$(".lat").html("");
			$(".lng").html("");
			
			// Turn on content for this area
			$(".content-area").hide();
			$(".content-" + _liveblue.extent_id).show();
			
			// Show a random expert in the sidebar
			showRandomFeaturedUserInSidebar(_liveblue.extent_id);
			
			// Clear overlays
			_liveblue.map.clearOverlays();
			// Clear marker cluster
			_liveblue.cluster.removeMarkers();
			
			// Load this user's cube into the map
			showCube(response);
			
			// Load other cubes from the area into the map
			showCubes(response);
			
			// load the KML extent info into the map
			loadExtent(response);
		}
		, "json");	
	}
	$("#spinner").hide();
}
/* ************************************************************************** */


/* ************************************************************************** */
function showCube(response)
{	
	// Put the marker on the map and center the map on this cube
	_liveblue.marker = new GMarker(new GLatLng(response.cube.lat, response.cube.lng), { icon: getActiveCubeIcon(), draggable: false });
	snapToSecond(_liveblue.marker, _liveblue.marker.getLatLng());
	
	// Update any displayed lat/lng text
	$(".lat").html(latFormattedDms(_liveblue.marker.getLatLng(), true));
	$(".lng").html(lngFormattedDms(_liveblue.marker.getLatLng(), true));
	
	_liveblue.map.addOverlay(_liveblue.marker);
	//_liveblue.cluster.addMarkers([_liveblue.marker]);
	//_liveblue.cluster.refresh();
	
	// Event listener: click
	GEvent.addListener(_liveblue.marker, "click", function(event)
	{			
		var location = "";
		if(response.cube.user.city && response.cube.user.state){ location += response.cube.user.city + ", " + response.cube.user.state; }
		if(response.cube.user.country){ location += " " + response.cube.user.country; }
		
		var html = "";
		html += "<div class=\"map-infowindow\">";	
		html += "<h5>" + response.cube.user.username + "</h5>";
		if(location){ html += "<p>" + location + "</p>"; };
		html += "<p><span class=\"lat\">" + latFormattedDms(new GLatLng(response.cube.lat, response.cube.lng), true) + "</span>&nbsp;&nbsp;<span class=\"lng\">" + lngFormattedDms(new GLatLng(response.cube.lat, response.cube.lng), true) + "</span></p>";
		html += "<p>" + response.cube.reason + "</p>";
		html += "</div>";
		_liveblue.marker.openInfoWindowHtml(html);
	});
}
/* ************************************************************************** */


/* ************************************************************************** */
function showCubes(response)
{	
	$.get("/php/get-cubes.php", { area: response.cube.area_id }, function(response)
	{
		// Clear the loading message from the pledges and actions in the sidebar
		$("#cube-count").html("");
		$("#pledges-view").html("");
		$("#actions-view").html("");
		
		var count = 0;
		var markers = [];
		
		// Update the number of cubes in this area
		$("#cube-count").html(response.cubes.length);
		
		$.each(response.cubes, function(i, cube)
		{
			if(count > _liveblue.MAX_MARKS){ return; }
			
			count++;
			
			// Create a marker
			var marker = new GMarker(new GLatLng(cube.lat, cube.lng), { icon: getInactiveCubeIcon(), draggable: false });
			snapToSecond(marker, marker.getLatLng());
			
			var location = "";
			if(cube.user.city && cube.user.state){ location += cube.user.city + ", " + cube.user.state; }
			if(cube.user.country){ location += " " + cube.user.country; }
			
			// Add the user to the pledges in the sidebar
			if(count <= _liveblue.MAX_VIEW_SIDEBAR_PLEDGES)
			{
				if(_liveblue.cube_id && _liveblue.cube_id != cube.id)
				{
					var html = "";
					html += "<p><strong class=\"username\">" + cube.user.username + "</strong>";
					if(location){ html += "<br />" + location; }
					html += "<br />" + cube.reason + "</p>";
					var node = $(html);
					$("#pledges-view").append(node);
				}
			}
			
			// Add the user to the actions in the sidebar
			if(count <= _liveblue.MAX_VIEW_SIDEBAR_ACTIONS)
			{
				if(_liveblue.cube_id && _liveblue.cube_id != cube.id)
				{
					var html = "";
					html += "<p>" + cube.action + "</p>";
					var node = $(html);
					$("#actions-view").append(node);
				}
			}
			
			// Check if this is a featured user
			if(isFeaturedUser(cube.user.username))
			{
				// Event listener: click
				GEvent.addListener(marker, "click", function(event)
				{
					var html = "";
					html += "<div class=\"map-infowindow featured\">";	
					html += "<h5>" + cube.user.username + "</h5>";
					html += "<p>" + getFeaturedUser(cube.user.username).organization + "</p>";
					if(location){ html += "<p>" + location + "</p>"; };
					html += "<p><span class=\"lat\">" + latFormattedDms(new GLatLng(cube.lat, cube.lng), true) + "</span>&nbsp;&nbsp;<span class=\"lng\">" + lngFormattedDms(new GLatLng(cube.lat, cube.lng), true) + "</span></p>";
					html += "<p>" + cube.reason + "</p>";
					html += "<p><a href=\"" + getFeaturedUser(cube.user.username).url + "\" target=\"_blank\">Learn more about " + cube.user.username + "</a></p>";
					html += "</div>";
					marker.openInfoWindowHtml(html);
				});
				
				// Featured users don't go in the cluster
				_liveblue.map.addOverlay(marker);
			}
			else
			{
				// Event listener: click
				GEvent.addListener(marker, "click", function(event)
				{
					var html = "";
					html += "<div class=\"map-infowindow\">";	
					html += "<h5>" + cube.user.username + "</h5>";
					if(location){ html += "<p>" + location + "</p>"; };
					html += "<p><span class=\"lat\">" + latFormattedDms(new GLatLng(cube.lat, cube.lng), true) + "</span>&nbsp;&nbsp;<span class=\"lng\">" + lngFormattedDms(new GLatLng(cube.lat, cube.lng), true) + "</span></p>";
					html += "<p>" + cube.reason + "</p>";
					html += "</div>";
					marker.openInfoWindowHtml(html);
				});
				
				// Add the marker to the markers array
				// ONLY if it's not the current user's cube
				if(_liveblue.cube_id && _liveblue.cube_id != cube.id){ markers.push(marker); }
			}
		});
		
		// If there were no cubes to add to the sidebar, put a message there
		if($("#pledges-view").html() == ""){ $("#pledges-view").html("<p>There are no pledges yet in this area.</p>"); }
		if($("#actions-view").html() == ""){ $("#actions-view").html("<p>There are no actions yet in this area.</p>"); }
		
		// Add all of the markers to the cluster
		_liveblue.cluster.addMarkers(markers);

		// Refresh the marker cluster
		// Markers don't show up on load without this
		_liveblue.cluster.refresh();
	}
	, "json");
}
/* ************************************************************************** */


/* ************************************************************************** */
function loadExtent()
{
	// Check for cache busting
	var url_suffix = "";
	if(_liveblue.CACHE_BUSTER){ url_suffix += "?" + Math.random(); }
	
	// Initialize the map based on the data for this extent
	var extent_data = eval("_liveblue.data." + _liveblue.extent_id);
	
	// Set the map type, respecting overrides in the JSON if present
	if(extent_data.map_type)
	{
		if(extent_data.map_type == "G_PHYSICAL_MAP"){ _liveblue.map.setMapType(G_PHYSICAL_MAP); }
		if(extent_data.map_type == "G_SATELLITE_MAP"){ _liveblue.map.setMapType(G_SATELLITE_MAP); }
		if(extent_data.map_type == "G_NORMAL_MAP"){ _liveblue.map.setMapType(G_NORMAL_MAP); }
		if(extent_data.map_type == "G_HYBRID_MAP"){ _liveblue.map.setMapType(G_HYBRID_MAP); }
	}
	else
	{
		_liveblue.map.setMapType(G_SATELLITE_MAP);
	}
	
	// We're using EGeoXml because it has better support for addressing the underlying polygon(s)
	// The "standard" version: _liveblue.extent = new GGeoXml(json.kml_url + url_suffix);
	_liveblue.extent = new EGeoXml("exml", _liveblue.map, extent_data.kml_url + url_suffix, { addmarker: function(){} });
	
	// Determine map center and zoom level
	// IMPORTANT! This needs to be done after the KML is done loading so we can get its bounds
	// ALSO IMPORTANT! IE7 and IE6 want this event handler to be defined before the call to parse() below
	GEvent.addListener(_liveblue.extent, "parsed", function()
	{			
		// Get the centroid and zoom level
		var centroid = _liveblue.map.getCenter();
		var zoom_level = _liveblue.map.getZoom();
		
		// Check for overridden centroid, zoom level and/or zoom modifier
		if(extent_data.centroid)
		{
			centroid = new GLatLng(extent_data.centroid.lat, extent_data.centroid.lng);
		}
		if(extent_data.zoom_level){ zoom_level = extent_data.zoom_level; }
		if(extent_data.zoom_level_modifier){ zoom_level += extent_data.zoom_level_modifier; }
		
		// Center and zoom the map to the user's cube
		_liveblue.map.setCenter(_liveblue.marker.getLatLng(), zoom_level);
		
		$.each(_liveblue.extent.gpolygons, function(i, polygon)
		{
			GEvent.addListener(polygon, "click", function(){ _liveblue.map.closeInfoWindow(); });	
		});
	});
	
	// Parse the KML
	_liveblue.extent.parse();
}
/* ************************************************************************** */

