
/* ************************************************************************** */
/* ************************************************************************** */

// Global config object
var _liveblue = {};
_liveblue.DEBUG = false;
// Cache buster simply adds a random querystring value to URLs to force reload of assets
_liveblue.CACHE_BUSTER = false; 
_liveblue.MAX_MARKERS = 500;
_liveblue.MAX_SIDEBAR_PLEDGES = 4;
_liveblue.MAX_VIEW_SIDEBAR_PLEDGES = 2;
_liveblue.MAX_VIEW_SIDEBAR_ACTIONS = 2;
_liveblue.ENABLE_CLUSTERING = true;

_liveblue.map;
_liveblue.marker;
_liveblue.cluster;
_liveblue.initial_extent;
_liveblue.extent;
_liveblue.extent_id;
_liveblue.drag_start_lat;
_liveblue.drag_start_lng;
_liveblue.cube_id;

// Extent data
_liveblue.data = {};

_liveblue.data.andaman = {};
_liveblue.data.andaman.id = "andaman",
_liveblue.data.andaman.kml_url = "/data/andaman.kml";
_liveblue.data.andaman.name = "Thailand's Andaman Sea";
_liveblue.data.andaman.short_description = "Thailand's Andaman Sea: <small>After the Tsunami</small>";
_liveblue.data.andaman.zoom_level_modifier = 1;

_liveblue.data.bahamas = {};
_liveblue.data.bahamas.id = "bahamas",
_liveblue.data.bahamas.kml_url = "/data/bahamas.kml";
_liveblue.data.bahamas.name = "Bahamas";
_liveblue.data.bahamas.short_description = "Bahamas: <small>Exploring and Sharing the Caribbean</small>";
_liveblue.data.bahamas.zoom_level_modifier = 1;

_liveblue.data.bof = {};
_liveblue.data.bof.id = "bof",
_liveblue.data.bof.kml_url = "/data/bof.kml";
_liveblue.data.bof.name = "Bay of Fundy";
_liveblue.data.bof.short_description = "Bay of Fundy: <small>Right Whale Feeding Grounds</small>";
_liveblue.data.bof.zoom_level_modifier = -1;

_liveblue.data.celebes = {};
_liveblue.data.celebes.id = "celebes",
_liveblue.data.celebes.kml_url = "/data/celebes.kml";
_liveblue.data.celebes.name = "Celebes Sea";
_liveblue.data.celebes.short_description = "Celebes Sea: <small>The Unknown Depths</small>";
_liveblue.data.celebes.zoom_level_modifier = 1;

_liveblue.data.fiji = {};
_liveblue.data.fiji.id = "fiji",
_liveblue.data.fiji.kml_url = "/data/fiji.kml";
_liveblue.data.fiji.name = "Fiji";
_liveblue.data.fiji.short_description = "Fiji: <small>Nurturing Our Relationship with the Ocean</small>";
_liveblue.data.fiji.zoom_level_modifier = 1;

_liveblue.data.hector = {};
_liveblue.data.hector.id = "hector",
_liveblue.data.hector.kml_url = "/data/hector.kml";
_liveblue.data.hector.name = "The New Zealand Coast";
_liveblue.data.hector.short_description = "The New Zealand Coast: <small>Home of the Rare Hector's Dolphin</small>";
_liveblue.data.hector.zoom_level_modifier = 1;

_liveblue.data.ice_island = {};
_liveblue.data.ice_island.id = "ice-island",
_liveblue.data.ice_island.kml_url = "/data/ice-island.kml";
_liveblue.data.ice_island.name = "Ross Sea";
_liveblue.data.ice_island.short_description = "Ross Sea: <small>Journey of the Ice Island</small>";

_liveblue.data.phoenix = {};
_liveblue.data.phoenix.id = "phoenix",
_liveblue.data.phoenix.kml_url = "/data/phoenix.kml";
_liveblue.data.phoenix.name = "Phoenix Islands Protected Area";
_liveblue.data.phoenix.short_description = "Phoenix Islands Protected Area: <small>Preserving Paradise</small>";

_liveblue.data.rockhopper = {};
_liveblue.data.rockhopper.id = "rockhopper",
_liveblue.data.rockhopper.kml_url = "/data/rockhopper.kml";
_liveblue.data.rockhopper.name = "Tierra Del Fuego";
_liveblue.data.rockhopper.short_description = "Tierra Del Fuego: <small>Southern Rockhopper Penguin Habitat</small>";

_liveblue.data.seus = {};
_liveblue.data.seus.id = "seus",
_liveblue.data.seus.kml_url = "/data/seus.kml";
_liveblue.data.seus.name = "Southeastern United States";
_liveblue.data.seus.short_description = "Southeastern United States: <small>Right Whale Calving Grounds</small>";
_liveblue.data.seus.centroid = {};
_liveblue.data.seus.centroid.lat = 30.8;
_liveblue.data.seus.centroid.lng = -81.271389;
_liveblue.data.seus.zoom_level_modifier = 2;

_liveblue.featured_users =
[
	{ "username": "Ian Bowles", "organization": "Massachusetts Secretary of Energy and Environmental Affairs", "url": "http://profiles.liveblueinitiative.org/post/156657936/ian-bowles-massachusetts-secretary-of-energy-and" },
	{ "username": "RobNixon", "organization": "Chairman, Surfrider Foundation South Texas Chapter", "url": "http://profiles.liveblueinitiative.org/post/156624765/rob-nixon-chairman-surfrider-foundation-south" },
	{ "username": "petnoyer", "organization": "Marine Biologist, NOAA Center for Coastal Environmental Health and Biomolecular Research (CCEHBR)", "url": "http://profiles.liveblueinitiative.org/post/156609650/peter-j-etnoyer-ph-d-candidate-texas-a-m" },
	{ "username": "ZoeFahy", "organization": "Teen Intern at the New England Aquarium", "url": "http://profiles.liveblueinitiative.org/post/156603233/zoe-fahy-teen-intern-at-the-new-england-aquarium" },
	{ "username": "mrt196", "organization": "Senior Conservation Associate/Aquaculture Specialist", "url": "http://profiles.liveblueinitiative.org/post/156597520/matt-thompson-senior-conservation" },
	{ "username": "KeithEllenbogen", "organization": "Underwater Photographer", "url": "http://profiles.liveblueinitiative.org/post/156401781/keith-ellenbogen-underwater-photographer-i" },
	{ "username": "RickMacPherson", "organization": "Director, Conservation Programs, Coral Reef Alliance", "url": "http://profiles.liveblueinitiative.org/post/156639408/rick-macpherson-director-conservation-programs" },
	{ "username": "ElyseCA", "organization": "Administrative Assistant, New England Aquarium Conservation Department", "url": "http://profiles.liveblueinitiative.org/post/156678938/elyse-antrim-conservation-assistant-i-live-blue" },
	{ "username": "salinity", "organization": "Conservation Assoc. / Wild fisheries specialist", "url": "http://profiles.liveblueinitiative.org/post/156686143/jason-clermont-conservation-assoc-wild" },
	{ "username": "JBeckmann", "Consultant to the Somerville Schools, Hispanic Office of Planning &amp; Evaluation, My-Turn, and other agencies": "Mullen", "url": "http://profiles.liveblueinitiative.org/post/156668851/joe-beckmann-consultant-to-the-somerville" },
	{ "username": "Paul Lauenstein", "organization": "Water Conservation Advocate", "url": "http://profiles.liveblueinitiative.org/post/156665172/paul-lauenstein-water-conservation-advocate-i" },
	{ "username": "MMyles", "organization": "Sustainability consultant", "url": "http://profiles.liveblueinitiative.org/post/156606859/mark-myles-sustainability-consultant-i-live-blue" },
	{ "username": "Wallace J. Nichols PhD", "organization": "Research Associate, California Academy of Sciences &amp; Founder/Co-Director, Ocean Revolution", "url": "http://profiles.liveblueinitiative.org/post/202770606/wallace-j-nichols-phd-research-associate" }
];

/* ************************************************************************** */
function getAreaNameById(id)
{
	return eval("_liveblue.data." + id + ".name");
}
/* ************************************************************************** */


/* ************************************************************************** */
function debug(msg)
{ 
	if(_liveblue.DEBUG)
	{
		$("#debug").show();
		$("#debug span").html(msg);
		// Comment out to disable Firebug console calls
		// IMPORTANT! This MUST be commented out or deleted for everything but Firefox development
		if(console && console.log){ console.log(msg); }
	}
}
/* ************************************************************************** */


/* ************************************************************************** */
$(document).ready(function()
{
	// External links
	$("a[rel=external]").click(function(event)
	{
		event.preventDefault();
		
		// Track external links in GA
		var area = _liveblue.extent_id;
		if(!area){ area = "area-undefined"; }
		trackEvent("/" + area + "/external/content/" + $(this).attr("href"));
		
		window.open($(this).attr("href"));
		
	});
	
	// Textarea maxlength
	$("textarea[maxlength]").keyup(function()
	{ 
		var maxlength = parseInt($(this).attr("maxlength")); 
		if($(this).val().length > maxlength)
		{ 
			$(this).val($(this).val().substr(0, maxlength)); 
		}
	});  
	
	// Open/close login panel
	$("#login-cta a").click(function(event)
	{
		if($(this).html() == "Login")
		{
			$(this).html("Cancel");
			event.preventDefault();
			$("#login").toggle();
		}
		else if($(this).html() == "Cancel")
		{
			$(this).html("Login");
			event.preventDefault();
			$("#login").toggle();
		}
		else
		{
			// Logout, just follow the link
			// aka don't preventDefault()
		}
	});
	
	// Select nav item should go to a random area
	$("#nav #nav-select a, #random-area").click(function(event)
	{
		event.preventDefault();
		location.href = "/select.php?area=" + randomArea();
	});
	
	// T-shirt link to Zazzle.com
	$(".t-shirt-link").click(function(event)
	{
		event.preventDefault();
		if($(".lat"))
		{
			var lat = $(".lat").html();
			var lng = $(".lng").html();
			
			// Split lat/lng into the needed parameter values 
			lat_params = tshirtSafeFormattedDms(lat);
			lng_params = tshirtSafeFormattedDms(lng);
			
			trackEvent("/" + _liveblue.extent_id + "/external/t_shirt");
			
			// Set up Zazzle URL
			var url = "http://www.zazzle.com/api/create/at-238509222876655962?rf=238509222876655962&ax=Linkover&pd=235176160003669152&fwd=ProductPage&ed=false";
			url += "&latd=" + lat_params.degrees;
			url += "&latmsh=" + lat_params.msh;
			url += "&lond=" + lng_params.degrees;
			url += "&lonmsh=" + lng_params.msh;

			window.open(url);
		}
	});
	
	// Login panel
	$("#login form #submitButton").click(function(event)
	{
		event.preventDefault();
		
		// Turn on the login spinner
		$("#login-spinner").show();
		
		// Pull the form data from the fields
		var f = {};
		f.username = $("#login-username").val();
		f.password = $("#login-password").val();
		
		// Post the data and process the JSON response
		// IE tries to cache this, so we're adding a random number to the end of the URL
		$.post("/php/login.php?" + Math.random(), f, function(data)
		{
			if(data.status == "OK")
			{
				// Take the user to the view page
				location.href = "/view.php?cube_id=" + data.message;
			}
			else if(data.status == "ERROR")
			{
				$("#login-spinner").hide();
				$("#login-error").html(data.message);
			}
		}
		, "json");
	});
	
	// Facebook, Twitter, StumbleUpon share links
	$("li.facebook a").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/social/facebook"); });
	$("li.twitter a").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/social/twitter"); });
	$("li.stumble a").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/social/stumble"); });
	
	// Google Earth
	$(".fly-to").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/earth"); });
	
	// Donate and membership links
	$("#make-donation").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/donate"); });
	$("#become-member").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/member"); });
	
	// NEAQ social links
	$("#neaq-facebook").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/social/follow/neaq_facebook"); });
	$("#neaq-twitter").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/social/follow/neaq_twitter"); });
	$("#neaq-youtube").click(function(event){ trackEvent("/" + _liveblue.extent_id + "/external/social/follow/neaq_youtube"); });
	
	// Open/close send to friend panel
	$("#sendtofriend-cta").click(function(event)
	{
		event.preventDefault();
		$("#sendtofriend").toggle();
		trackEvent("/" + _liveblue.extent_id + "/social/stf_click");
	});
	
	// Cancel out of send to friend panel
	$("#sendtofriend-cancel").click(function(event)
	{
		event.preventDefault();
		$("#stf-spinner").hide();
		$("#sendtofriend").hide();
	});
	
	// Send to friend panel
	$("#sendtofriend form .inputSubmit").click(function(event)
	{
		event.preventDefault();
		
		// Show the spinner
		$("#stf-spinner").show();
		
		// Pull the form data from the fields
		var f = {};
		f.sender_name = $("#your-name").val();
		f.sender_email = $("#your-email").val();
		f.recipient_name = $("#friends-name").val();
		f.recipient_email = $("#friends-email").val();
		f.lat = emailSafeFormattedDms($(".lat:first").html());
		f.lng = emailSafeFormattedDms($(".lng:first").html());
		
		trackEvent("/" + _liveblue.extent_id + "/social/stf_submit");
		
		// Post the data and process the JSON response
		$.post("/php/email-send-to-friend.php", f, function(data)
		{
			// Hide the spinner
			$("#stf-spinner").hide();
			
			if(data.status == "OK")
			{
				$("#sendtofriend").hide();
			}
			else if(data.status == "ERROR")
			{
				$("#stf-error").html(data.message);
			}
		}
		, "json");
	});	
});
/* ************************************************************************** */


/* ************************************************************************** */
// Convenience function for Google Analytics page/event tracking
function trackEvent(url)
{
	debug(url);
	if(pageTracker){ pageTracker._trackPageview(url); }
}

/* ************************************************************************** */


/* ************************************************************************** */
function randomArea()
{
	var areas = ["andaman", "bahamas", "bof", "celebes", "hector", "ice-island", "fiji", "phoenix", "rockhopper", "seus"];
	var rnd = Math.floor(Math.random() * 11) - 1;
	if(rnd < 0 || rnd > 9){ rnd = 2; }
	return areas[rnd];
}
/* ************************************************************************** */


/* ************************************************************************** */
function formattedDms(latlng, round_seconds)
{	
	function format(dms_part, is_lat)
	{
		return  dms_part.degrees.toString() + "&#176; " + dms_part.minutes.toString() + "&#8242;" + " " + dms_part.seconds.toString() + "&#8243; " + dms_part.hemisphere.toString();
	}
	return { lat: format(dms(latlng, round_seconds).lat), lng: format(dms(latlng, round_seconds).lng) };
}
latFormattedDms = function(latlng, round_seconds){ return formattedDms(latlng, round_seconds).lat; };
lngFormattedDms = function(latlng, round_seconds){ return formattedDms(latlng, round_seconds).lng; };
/* ************************************************************************** */


/* ************************************************************************** */
// Returns an object with .degrees and .msh
/* ************************************************************************** */
function tshirtSafeFormattedDms(dms_string)
{
	// Lose the special characters
	dms_string = dms_string.replace(/[^a-zA-Z0-9\s]/g, "");
	
	// Split into component pieces
	var split = dms_string.split(" ");
	var degrees = split[0];
	var minutes = split[1];
	var seconds = split[2];
	var hemi = split[3];
	
	// Reassemble as an object
	return { degrees: degrees, msh: minutes + "' " + seconds + "\" " + hemi };
}
/* ************************************************************************** */


/* ************************************************************************** */
function emailSafeFormattedDms(dms_string)
{
	// Lose the special characters
	dms_string = dms_string.replace(/[^a-zA-Z0-9\s]/g, "");
	
	// Split into component pieces
	var split = dms_string.split(" ");
	var degrees = split[0];
	var minutes = split[1];
	var seconds = split[2];
	var hemi = split[3];
	
	// Reassemble
	return degrees + "&deg; " + minutes + "' " + seconds + "\" " + hemi;
}
/* ************************************************************************** */


/* ************************************************************************** */
function snapToSecond(marker, latlng)
{
	// TODO Do I really need to round it to the second? Drop this functionality,
	// but keep the function
	
	// Get the DMS value, with the seconds rounded
	//var dms_value = dms(latlng, true);
	
	// Convert back to decimal
	//var dec = decimal(dms_value);
	
	// Move the marker to its new location
	marker.setLatLng(latlng);
	//marker.setLatLng(dec);
}
/* ************************************************************************** */


/* ************************************************************************** */
// IN: dms object
// IN: boolean that determines if the seconds value is rounded
// OUT: GLatLng
function dms(latlng, round_seconds)
{	
	// Use an nested function to process both lat and lng
	function convert(point, is_lat)
	{
		// Hold on to the sign as 1 or -1, we'll need it later
		var sign = (point < 0) ? -1 : 1;
		
		// Get rid of the sign for now
		point = Math.abs(point);
		
		// Degrees is the integer portion of the value, NOT rounded
		// Floor on a positive number gives us what we need
		var degrees = Math.floor(point);
		
		// Get the decimal part of the degrees value
		var degrees_remainder = point - degrees;
		
		// Minutes is the degrees remainder * 60, with its remainder removed
		var minutes = Math.floor(degrees_remainder * 60);
		
		// Get the remainder from the minutes calculation
		var minutes_remainder = (degrees_remainder * 60) - minutes;
		
		// Seconds is the minutes remainder * 60
		var seconds = minutes_remainder * 60;
		if(round_seconds)
		{
			seconds = Math.round(seconds);
		}
		
		// Determine the associated hemisphere (N, S, E, W)
		// Get the proper hemisphere suffix
		var hemisphere = "";
		if(is_lat){ hemisphere = (sign >= 0) ? "N" : "S"; }
		else { hemisphere = (sign >= 0) ? "E" : "W"; }
		
		// Return an object literal holding the three values and the sign
		return { degrees: degrees, minutes: minutes, seconds: seconds, sign: sign, hemisphere: hemisphere };
	}
	return { lat: convert(latlng.lat(), true), lng: convert(latlng.lng(), false) };
}
/* ************************************************************************** */


/* ************************************************************************** */
function decimal(dms)
{	
	// Use an nested function to process both lat and lng
	function convert(dms_part)
	{
		// Degrees stays the same, but multiplied by the sign
		var degrees = dms_part.degrees * dms_part.sign;
		
		// The initial decimal part is the minutes divided by 60
		var minutes_decimal = dms_part.minutes / 60;
		
		// The initial seconds part is the seconds divided by 60, divided by 60
		var seconds_decimal = dms_part.seconds / 60 / 60;
		
		// The full decimal part is the sum of the two individual decimal parts
		var decimal = minutes_decimal + seconds_decimal;
		
		// The final result is the degrees plus the decimal, multiplied by the sign
		var val = (degrees + decimal) * dms_part.sign;
		
		return val;
	}
	return new GLatLng(convert(dms.lat), convert(dms.lng));
}
/* ************************************************************************** */


/* ************************************************************************** */
function extentContains(latlng)
{
	var contains = false;
	
	// Loop through all polygons in this extent
	$.each(_liveblue.extent.gpolygons, function(i, polygon)
	{
		if(_liveblue.extent_id != "fiji")
		{
			// Use the epoly.js Contains function to check each polygon
			if(polygon.Contains(latlng))
			{
				contains = true;
			}
		}
		else
		{
			// The Fiji problem. It acts like it's horizontally inside-out, but vertically fine.
			// This is because it crosses the 180 degree line.
			if(!polygon.Contains(latlng) && polygon.getBounds().containsLatLng(latlng))
			{
				contains = true;
			}
		}
	});
	return contains;
}
/* ************************************************************************** */


/* ************************************************************************** */
function isFeaturedUser(username)
{
	var featured = false;
	$.each(_liveblue.featured_users, function(i, featured_user)
	{
		if(featured_user.username == username){ featured = true; }
	});
	return featured;
}
/* ************************************************************************** */


/* ************************************************************************** */
function getFeaturedUser(username)
{
	var featured = null;
	$.each(_liveblue.featured_users, function(i, featured_user)
	{
		if(featured_user.username == username){ featured = featured_user; }
	});
	return featured;
}
/* ************************************************************************** */


/* ************************************************************************** */
function showRandomFeaturedUserInSidebar(extent_id)
{
	// Hide them all
	$("#sidebar .content-" + extent_id + " .expert").hide();
	
	// Show a random one
	var num_experts = $("#sidebar .content-" + extent_id + " .expert").length;
	if(num_experts > 0)
	{
		// Get a random number between 0 and num_experts
		 var rand = Math.random() * (num_experts - 1);
	  	rand = typeof floatVal == "undefined" ? Math.round(rand) : rand.toFixed(rand);
		
		// Show the random expert
		$("#sidebar .content-" + extent_id + " .expert:eq(" + rand + ")").show();
	}
}
/* ************************************************************************** */


/* ************************************************************************** */
function fbConnectLoggedIn(use_compact)
{	
	var fb_content = $("#fb-connect-content");
	
	var xfbml = "";
	if(use_compact)
	{
		xfbml += "<p>";
		xfbml += "<a href=\"\" id=\"fb-connect-publish\">Post a message to Facebook</a> showing your friends that you Live Blue.";
		xfbml += "</p>";
	}
	else
	{
		xfbml += "<p>";
		xfbml += "<div id=\"fb-connect-pic\"><fb:profile-pic uid=\"loggedinuser\" linked\"true\" size=\"square\" width=\"32\" height=\"32\" /></div>";
		xfbml += "Welcome, <fb:name uid=\"loggedinuser\" useyou=\"false\"></fb:name>. You are signed in with your Facebook account.";
		xfbml += "</p>";
		xfbml += "<p class=\"clear\">";
		xfbml += "<a href=\"\" id=\"fb-connect-publish\">Post a message to Facebook</a> showing your friends that you Live Blue.";
		xfbml += "</p>";
		xfbml += "<p>";
		xfbml += "<a href=\"\" id=\"fb-connect-logout\">Logout</a> of Facebook and the Live Blue Initiative.";
		xfbml += "</p>";
	}
	$(fb_content).html(xfbml);
	FB.XFBML.Host.parseDomTree();
}
/* ************************************************************************** */


/* ************************************************************************** */
function fbConnectNotLoggedIn(use_compact)
{
	var fb_content = $("#fb-connect-content");
	
	if(use_compact)
	{
		var xfbml = "<fb:login-button size=\"medium\" background=\"dark\" length=\"short\" onlogin=\"fbConnectLoggedIn()\"></fb:login-button>";
	}
	else
	{
		var xfbml = "<fb:login-button size=\"medium\" background=\"dark\" length=\"long\" onlogin=\"fbConnectLoggedIn()\"></fb:login-button>";
	}
	
	$(fb_content).html(xfbml);

	FB.XFBML.Host.parseDomTree();
}
/* ************************************************************************** */


/* ************************************************************************** */
function fbConnectLogout(redirect)
{
	if(redirect)
	{
		FB.Connect.logoutAndRedirect("/php/logout.php");
	}
	else
	{
		FB.Connect.logout();
	}
	FB.XFBML.Host.parseDomTree();
}
/* ************************************************************************** */


/* ************************************************************************** */
function fbConnectPublish()
{
	if(_liveblue.username)
	{
		FB.Connect.showFeedDialog(98548715255, 
		{
			"home-url": "http://www.liveblueinitiative.org", 
			"username": _liveblue.username, 
			"latlng": $(".lat:first").html() + " " + $(".lng:first").html()
		});
	}
}
/* ************************************************************************** */


/* ************************************************************************** */
function fbConnectInvite()
{
	FB.Connect.inviteConnectUsers();
}
/* ************************************************************************** */