$("html").addClass('hasJs');

$(function() {

	// open external links in new window
	//$("a[href^='http']").attr("target", "_blank");
	function initExternalLinks() {
		var h = window.location.host.toLowerCase();
		$("a[href^='http']:not([href^='http://" + h + "']):not([href^='http://www." + h + "']), a[href$='.pdf']").attr("target", "_blank");
	}
	initExternalLinks();

	// remove extra space at the bottom of the document
	$(window).resize(resizeDocument);
	$(window).load(resizeDocument);

	// show flash messages as overlays
	if ($("#flashMessage, #authMessage").length > 0) {
		$("#flashMessage, #authMessage").show();
		$.fancybox(
			$("#flashMessage, #authMessage").get(0),
			{
				hideOnContentClick: true,
				onClosed: function() {
					$("#flashMessage, #authMessage").hide();
				},
				padding: 40
			}
		);
	}

	// highlight ULs in content
	$("#content ul li:nth-child(odd)").addClass("even");

	// hover effect on navigation tabs
	$("#navigation li").hover(
		function() {
			/*$("a", this).animate(
				{ "color": "white" },
				"fast"
			);*/
			$("span", this).animate(
				{ height: $(this).height() + "px" },
				"fast",
				"swing",
				function() {
					$("a", this.parentNode).css("color", "#FFFFFF");
				}
			);
		},
		function() {
			/*$("a", this).animate(
				{ color: $(this.parentNode).css("color") },
				"fast"
			);*/
			$("span", this).animate(
				{ height: "4px" },
				"fast",
				"swing",
				function() {
					$("a", this.parentNode).css("color", $(this.parentNode).css("color"));
				}
			);
		}
	);

	// collapse regions list to a select
	var regionsSelect = '<div class="input"><select onchange="document.location.href=$(this).val()">';
	$("#regions-list li a").each(function() {
		selected = '';
		if ($(this.parentNode).hasClass('current')) {
			selected = ' selected="selected"';
		}
		regionsSelect += '<option value="' + this.href + '"' + selected + '>'
		               + $(this).html()
		               + '</option>';
	});
	regionsSelect += '</select>';
	$("#regions-list").append(regionsSelect);
	$("#regions-list ul").hide();

	// remove top border on first list-item
	$("h1 + .list-item").css('border-top', 'none');

	// collapsable list items
	$(".list-item-collapse").each(function() {

		var main = $(".list-item-main", this);
		var secondary = $(".list-item-secondary", this);

		var first_heading = $($("h1,h2,h3", main).get(0));
		first_heading.html(
			'<a href="javascript://" onclick="toggleListCollapse(this)">' +
			first_heading.text() +
			'</a>'
		);

		secondary.hide();

	});
	
});

function resizeDocument() {
	var extraSpace = $(window).height() - $("body").height();
	if (extraSpace > 0) {
		$("#middle-bottom").height($("#middle-bottom").height() + extraSpace);
	}
}

function toggleListCollapse(link) {
	$("#middle-bottom").height("auto");
	$(".list-item-secondary", $(link).closest(".list-item-collapse")).toggle();
	resizeDocument();
}
