
Cufon.replace("" +
	"#user-navigation a.normal," +
	"#generic-navigation a," +
	"#generic-navigation label," +
	"#generic-navigation li form button," +
	"#browse-wevees .header h2," +
	"#browse-wevees .header a.previous," +
	"#browse-wevees .header a.next," +
	"#browse-wevees .header form.filter a," +
	"#browse-wevees .header form.filter button," +
	"#browse-wevees form.search button," +
	"#browse-wevees .footer a.previous," +
	"#browse-wevees .footer a.next," +
	"#footer a",
	{
		hover: true,
		hoverables: {
			a: true,
			label: true,
			button: true
		}
	}
);

function parseQueryString()
{
	var chunks = window.location.search.substring(1).split("&");
	var variables = {};
	for (var chunk, i=0; chunk=chunks[i]; ++i) {
		var components = chunk.split("=");
		variables[components[0]] = components[1];
	}
	return variables;
}

function buildQueryString(variables)
{
	var chunks = [];
	for (variable in variables) {
		chunks.push(variable + "=" + variables[variable]);
	}
	return "?" + chunks.join("&");
}

function openPopup(href, callback)
{
	var popupDocument = $("<div></div>");
	var overlay = $("<div id='overlay'></div>");
	$("body").append(overlay);
	popupDocument.load(href.replace(" ", "+").replace(" ", "+") + "&timestamp=" + (1 * new Date()) + " .popup", function(responseText, textStatus, XMLHttpRequest) {
		var popup = popupDocument;
		//popup.hide();
		$("body").append(popup);
		popup.find("a.close").click(closePopup);
		//popup.fadeIn(function() { if (callback) callback(); });
		if (callback) callback();
	});
}

function closePopup(event)
{
	/*
	 *	There are various ways in which a popup can be opened without JavaScript, e.g. if JavaScript is switched off, if the user
	 *	middle-clicks, if they arrive from a search engine, etc.  In these cases, we don't want to simply close the popup, as if
	 *	they later bookmark the page, email the link to a friend, etc., then they will inadvertently be using the link with the
	 *	popup open.
	 *
	 *	What we do to handle this situation is check the query string variables to see if this is the case, and if it is, then
	 *	we don't close the popup with JavaScript, we simply follow the link instead, loading the page anew and gaining a proper URL.
	 */
	var queryStringVariables = parseQueryString();
	if (queryStringVariables["show-wevee"]) return true;
	if (queryStringVariables["show-archive-clip"]) return true;
	if (queryStringVariables["show-registration"]) return true;
	if (queryStringVariables["edit-wevee"] || queryStringVariables["create"]) {
		// Doesn't take pagination into account.
		location.search = "";
		return true;
	}
	if ($(".popup #create").length > 0) {
		location.reload();
	}

	if (event) {
		event.preventDefault();
	}

	setTimeout(function() {
		/*
		 * Warning: originally this function just removed the popup elements directly.  However in
		 * Internet Explorer 8 (at least), this crashes the browser with a null pointer being dereferenced.
		 * It looks like the problem is that this function is being called from Flash via
		 * ExternalInterface, which removes the Flash from the page.  Apparently the ActiveX Flash plugin
		 * expects the Flash to still be on the page when the function exits.
		 *
		 * To get around this, we put the removal code into an anonymous function which is called from
		 * a setTimeout().  This function exits normally, then after a short delay, the removal code is
		 * called, and since the function called from ExternalInterface exited normally, the Flash can be
		 * removed without a problem.  Note that the JavaScript execution model is single-threaded, so it
		 * doesn't matter how short the delay is, the outer function is guaranteed to exit before the
		 * removal function is called - even a delay of 1ms works.
		 */
		$(".popup").remove();
		$("#overlay").remove();
	}, 1);

	return false;
}

jQuery(function() {
				
	/* Watermark feature causing error in IE6 on login form submit */
	if (!thisIsIE6 && !thisIsIE7 && !thisIsIE8) {
		$("#login-username").watermark("Username");
		$("#login-password").watermark("Password");
	}

	if ($(".wevees").length > 0) {
		/*
		 * Truncate tag list.
		 *
		 * There is limited space available to show the tags, so we need to truncate them.  We do this by checking the position of
		 * the LI element - if it is slightly larger, that means it has dropped down onto the next line and needs to be removed.
		 * In addition, if the height is slightly larger, that means it is split onto two lines and needs to be removed.  If we
		 * remove any tags, we take off the trailing comma after the previous item and replace it with an ellipsis.
		 *
		 * At the moment, this relies on magic numbers that are dependent upon layout metrics.  It would be better to run an
		 * initial pass to figure out these numbers dynamically, but this will suffice for now.  If you are reading this wondering
		 * why the tag truncation isn't working correctly since making design changes, log the pertinent variables and it should
		 * be obvious which values you can use to differentiate things appropriately.
		 *
		 * Bug: Occasionally, a long tag can be removed and ellipsis appended, only to continue and find a shorter tag that will
		 * fit in the space remaining.  In this case, the ellipsis will appear in the middle of the tags rather than the end.
		 */
		function truncateTagList()
		{
			var li = $(this);
			var tags = li.parents(".tags");
			//console.log("A: " + li.position().top);
			//console.log("B: " + li.height());
			if (li.position().top < 5 && li.height() < 16) return;
			var previous = li.prev("li");
			if (previous.length > 0) {
				var previousLink = previous.find("a");
				previous.html(previous.html().substring(0, previous.html().length - 1) + "&hellip;");
			}
			li.remove();
		}

		$(".wevee .tags li").each(truncateTagList);
		/*
		 *	We run the truncation twice as there is a slight possibility that the act of adding the ellipsis makes the last tag
		 *	in the list long enough to have to drop down onto the next line.  A second pass removes any tag that this happens to.
		 */
		$(".wevee .tags li").each(truncateTagList);
	
		/*
		 * We need to fake link behaviour for the whole .wevee element.  We cannot make it all a link as there are also links
		 * within the .wevee element that go to different places.
		 */
		$(".wevee").not(".popup").hover(function(event) {
			$(this).addClass("hover");
			$(this).append("<div class='rolloverPlaySymbol'></div>")
			
			window.status = $(this).find("h3 a")[0].href;
		}, function(event) {
			$(this).removeClass("hover");
			$(this).find('.rolloverPlaySymbol').remove();
			window.status = null;
		});
	
		$(".wevee").not(".popup").click(function(event) {
			if ($(event.target).is("a") && !$(event.target).parent().is("h3")) {
				// A link that was not the title link was clicked.
				 return true;
			}
			if ($(event.target).is("button")) {
				// A form button was clicked.
				return true;
			}
			event.preventDefault();
			var weveeLink = $(this).find("h3 a");
			openPopup(weveeLink.attr("href"), function() {
				var weveeId;
				if ($(".popup").hasClass("archive")) {
					weveeId = weveeLink.attr("href").split("show-archive-clip=")[1];
					swfobject.embedSWF("/flash/clipPlayer.swf", "wevee-player", 320, 240, "9", "/flash/expressInstall.swf", {"clipPath": $(".popup a.flv").attr("href"), "clipLength": parseFloat($(".popup a.flv").text().split("(length ")[1])});
				} else if ($(".popup").hasClass("help")) {
					weveeId = weveeLink.attr("href").split("show-help-clip=")[1];
					swfobject.embedSWF("/flash/helpPlayer.swf", "wevee-player", 720, 405, "9", "/flash/expressInstall.swf", {"clipPath": $(".popup a.flv").attr("href"), "clipLength": parseFloat($(".popup a.flv").text().split("(length ")[1]), "autoplay": true}, {"allowfullscreen": true});
				} else {
					weveeId = weveeLink.attr("href").split("show-wevee=")[1];
					swfobject.embedSWF("/player/playerrtmp.swf", "wevee-player", 320, 240, "9", "/flash/expressInstall.swf", {"crtr": 1, "editId": weveeId, "gig_lt": "1268309329738", "gig_pt": "1268309333051", "gig_g": 2, "isInternal": true}, {}, {"id": "W4b16a2e791ed61f0", "allowscriptaccess": "always"});
					jQuery.post("/view-counter.aspx", {"editId": weveeId});
				}
			});
			return false;
		});
	}

	$("a.create").click(function(event) {

		event.preventDefault();
		$("body").append("<div id='overlay'></div><div class='popup' style='position: absolute; margin-top: 0; top: 0;'><div id='create'></div></div>");
		swfobject.embedSWF("/VideoMixer.swf", "create", 975, 660, "9", "/flash/expressInstall.swf", {"userProfile": $("meta[name=username]").attr("content")});
		return false;
	});

	function showFeedbackForm(event)
	{
		event.preventDefault();
		var popup = $(this).parents(".popup");
		var loader = $("<div></div>").load(this.href + " form.feedback", function() {
			if (popup.hasClass("wevee")) {
				popup.find(".profile").remove();
			}
			var form = loader.find("form");
			popup.find(".info").replaceWith(form);
			form.submit(sendFeedback);
		});
		return false;
	}
	$("p.elicit-feedback a").live("click", showFeedbackForm);

	function sendFeedback(event)
	{
		event.preventDefault();
		var form = $(this);
		$.post(this.action, form.serialize(), function(data, textStatus, xhr) {
			var response = $(data);
			response.find(".acknowledge-feedback a").click(backToInfo);
			form.replaceWith(response.find(".acknowledge-feedback"));
		});
		return false;
	}
	$("form.feedback").submit(sendFeedback);

	function backToInfo(event)
	{
		event.preventDefault();
		var replaced = $(this).parents(".acknowledge-feedback");
		var popup = $("<div></div>").load(this.href + " div.popup", function() {
			if (replaced.parents(".popup").hasClass("wevee")) {
				popup.find(".profile").insertBefore(replaced);
			}
			popup.find(".info p.elicit-feedback a").click(showFeedbackForm);
			replaced.replaceWith(popup.find(".info"));
		});
		return false;
	}
	$(".acknowledge-feedback a").click(backToInfo);

	$("a.share").live("click", function(event) {
		event.preventDefault();
		var flash = $("#view-wevee .flash").children().first()[0];
		if (flash.extLoadShareMenu) flash.extLoadShareMenu();
		this.blur();
		return false;
	});

	/* Ping the server every five minutes to avoid session timeouts. */
	setInterval(function() {
		jQuery.get("/noop.aspx");
	}, 5 * 60 * 1 * 1000);

});

