
/* ************************************************************************** */
$(document).ready(function()
{	
	// Set the extent id to the initial value passed in the querystring
	_liveblue.extent_id = _liveblue.initial_extent;
	
	// Init the interface to the default conservation area
	initialize();
	
	// Dropdown for conservation areas
	//$("#extents select option[value=" + _liveblue.initial_extent + "]").attr("selected", "selected");
	$("#extents select").change(function(event)
	{
		event.preventDefault();
		
		var extent = $(this).val();
		
		// Safari fires this event very freely, with the select on its default state with no value
		// If there's no value, do nothing
		if(extent && extent.length > 0)
		{
			// Reset dropdown so label is showing
			$("#extents select option[value=]").attr("selected", "selected");
			$("#panel").hide();
			$("#panel-open").addClass("inactive");
			$("#secondary .cta").show();
		
			loadExtent(extent);
		}
	});
	
	// Open panel link, inactive
	$("#panel-open.inactive").live("click", function(event)
	{
		event.preventDefault();
	});
	
	// Open panel link, active
	$("#panel-open:not(.inactive)").live("click", function(event)
	{
		event.preventDefault();
		$("#panel").toggle();
		// Remove the Next call to action
		$("#secondary .cta").hide();
		trackEvent("/" + _liveblue.extent_id + "/plot_select");
	});
	
	// Close panel link
	$("#panel-close").click(function(event)
	{
		event.preventDefault();
		$("#panel").hide();
		// Add back the Next call to action
		$("#secondary .cta").show();
	});
	
	// If someone chooses to type their own reason, reset the dropdown
	$("#action").click(function(event)
	{
		$("#action-dropdown option:first").attr("selected", "selected").parent("select");
	});
	
	// If someone chooses from the dropdown, reset the textarea
	$("#action-dropdown").change(function(event)
	{
		$("#action").attr("value", "");
	});
	
	// Back to cube link, send back to current area
	$("#back-to-cube").click(function(event)
	{
		if(_liveblue.extent_id)
		{
			event.preventDefault();
			location.href = "/?area=" + _liveblue.extent_id;
		}
	});
	
	// Register submit
	$("#panel #register-form .inputSubmit").click(registerUser);
	
	// Standard unload for Google Maps
	$("body").bind("unload", GUnload);
});
/* ************************************************************************** */


/* ************************************************************************** */
function initialize()
{
	// Turn on the spinner
	$("#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 KML 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 the extent in question
		loadExtent(_liveblue.extent_id);
	}
	
	$("#spinner").hide();
}
/* ************************************************************************** */


/* ************************************************************************** */
function loadExtent(extent_id)
{
	// Update the global config object with this extent id
	_liveblue.extent_id = extent_id;
	
	// Oops, should not have named ice-island with a dash,
	// since now it needs to exist as a JS variable.
	if(_liveblue.extent_id == "ice-island"){ _liveblue.extent_id = "ice_island"; }
		
	// Reset lat/lng
	$(".lat").html("");
	$(".lng").html("");
	
	// Clear overlays and marker cluster
	_liveblue.map.clearOverlays();
	_liveblue.cluster.removeMarkers();
	
	// Turn on content for this area
	$(".content-area").hide();
	$(".content-" + extent_id).show();
	
	// Show a random expert in the sidebar
	showRandomFeaturedUserInSidebar(extent_id);
	
	// Update form with current extent id
	$("#area").attr("value", _liveblue.extent_id);
	
	// 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);
	
	// Update the page h1 to the name of this extent/conservation area
	$("h1").html(extent_data.short_description);
	
	// Set the map type, respecting overrides in the JSON if present
	// 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
		_liveblue.map.setCenter(centroid, zoom_level);
		
		$.each(_liveblue.extent.gpolygons, function(i, polygon)
		{
			GEvent.addListener(polygon, "click", extentClick);	
		});
	});
	
	// Parse the KML
	_liveblue.extent.parse();
	
	// Add other users' markers
	showCubes(_liveblue.extent_id);
}
/* ************************************************************************** */


/* ************************************************************************** */
function showCubes(area)
{	
	$.get("/php/get-cubes.php", { area: area }, function(data)
	{
		// Clear the loading message from the pledges sidebar
		$("#pledges").html("");
		var count = 0;
		var markers = [];
		
		// Update the number of cubes in this area
		if(data.cubes && data.cubes.length && data.cubes.length >= 1)
		{
			$("#cube-count").html(data.cubes.length - 1);
		}
		else
		{
			$("#cube-count").html("0");
		}
		
		$.each(data.cubes, function(i, cube)
		{
			count++;
			
			// Don't go beyond the global max for markers to add
			if(count > _liveblue.MAX_MARKS){ return; }
			
			// Put the marker on the map
			if(!(cube && cube.lat && cube.lng)){ return; }
			var marker = new GMarker(new GLatLng(cube.lat, cube.lng), { icon: getInactiveCubeIcon(), draggable: false });
			
			// TODO Add to cluster, not map
			snapToSecond(marker, marker.getLatLng());
			//_liveblue.map.addOverlay(marker);
			
			var location = "";
			if(cube.user.city && cube.user.state){ location += cube.user.city + ", " + cube.user.state; }
			if(cube.user.country){ location += " " + cube.user.country; }
			
			// Check if this is a featured user
			if(isFeaturedUser(cube.user.username))
			{
				// Featured users don't go in the sidebar, they're already there
				
				// 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);
					trackEvent("/" + _liveblue.extent_id + "/other_plot");
				});
				
				// Featured users don't go in the cluster
				//markers.push(marker);
				_liveblue.map.addOverlay(marker);
			}
			else
			{			
				// Add the user to the pledges in the sidebar
				if(count <= _liveblue.MAX_SIDEBAR_PLEDGES)
				{
					var html = "";
					html += "<p><strong class=\"username\">" + cube.user.username + "</strong>";
					if(location){ html += "<br />" + location; }
					html += "<br />" + cube.action + "</p>";
					var node = $(html);
					$("#pledges").append(node);
				}
				
				// 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);
					trackEvent("/" + _liveblue.extent_id + "/other_plot");
				});
				
				// Add the marker to the markers array
				markers.push(marker);
			}
		});
		
		// If there were no cubes to add to the sidebar, put a message there
		if(data.cubes.length == 0){ $("#pledges").append($("<p>There are no pledges yet in this area.</p>")); }
		
		// Add all of the markers to the cluster
		_liveblue.cluster.addMarkers(markers);
		_liveblue.cluster.refresh();
	}
	, "json");
}
/* ************************************************************************** */



/* ************************************************************************** */
function registerUser(event)
{
	// Don't actually post the form
	event.preventDefault();
	
	// Start the spinner
	$("#spinner").show();
	
	// Pull the form data from the fields
	var f = {};
	f.username = $("#username").val();
	f.password = $("#password").val();
	f.confirm_password = $("#confirm-password").val();
	// Check password confirm
	if(f.password != f.confirm_password)
	{
		$("#error").html("Password and confirm password do not match");
		$("#spinner").hide();
		return;
	}
	f.city = $("#city").val();
	f.state = $("#state").val();
	f.country = $("#country").val();
	f.email = $("#email").val();
	f.optin = $("#optin:checked").val();
	if(!f.optin){ f.optin = ""; }
	f.reason = $("#reason").val();
	f.action = $("#action").val();
	f.action_dropdown = $("#action-dropdown").val();
	if(f.action_dropdown){ f.action = f.action_dropdown; }
	
	// Check for reason and action
	if(!f.reason || f.reason == "" || f.reason == "I live blue because ")
	{
		$("#error").html("Please enter your reason for living blue");
		$("#spinner").hide();
		return;
	}
	if(!f.action || f.action == "" || f.action == "I live blue by ")
	{
		$("#error").html("Please enter the way you live blue");
		$("#spinner").hide();
		return;
	}
	
	// Check for other required fields
	if(f.username == "" || f.email == "" || f.password == "" || f.confirm_password == "")
	{
			$("#error").html("Please complete all required fields marked with a *");
			$("#spinner").hide();
			return;
	}
	
	f.lat = $("#lat").val();
	f.lng = $("#lng").val();
	f.area = $("#area").val();
	
	trackEvent("/" + _liveblue.extent_id + "/register_submit");
	
	// Post the data and process the JSON response	
	$.post("/php/register-user.php", f, function(data)
	{
		$("#spinner").hide();
		if(data.status == "OK")
		{
			location.href = "/share.php?cube_id=" + data.message;
		}
		else if(data.status == "ERROR")
		{
			$("#error").html(data.message);
		}
	}
	, "json");
}
/* ************************************************************************** */
