$().ready( function() {
	$("div.accordion").each( function() {
		//add classes to the accordion element and the first and last children
		$(this).addClass("accordionEnabled");
		$(this).find(">div:first-child").addClass("first");
		$(this).find(">div:last-child").addClass("last");

		//find the total size of all headers except the first one (the first one is taken into account already) - this is to set other sizes and positions takig account of the accordion headers
		var modContainers = $(this).find("div.modContainer"),
			headerHeights = 0;
		for (var i = 1, j = modContainers.length; i<j; i++) {
			var header = $(modContainers[i]).find("div.hd")[0];
			if (!header) continue;
			headerHeights += header.offsetHeight;
		}
		//go through the promos and set their heights and the button positions
		modContainers.each( function() {
			var body = $(this).find("div.bd");
			var button = $(this).find("a.button");
			if (body.length > 0) {
				var newHeight = (parseInt(body.css("height")) - parseInt(body.css("paddingTop")) - parseInt(body.css("paddingBottom")) ) - headerHeights;
				body.css("height", newHeight + "px");
				var buttonTop = parseInt(button.css("top"));
				if (isNaN(buttonTop)) return;
				var newButtonPos = buttonTop - headerHeights;
				button.css("top", newButtonPos + "px");
			}
		} );
	} );
	$(".accordion").accordion( { header: '.hd', event: "mouseover", animated: "easeslide" } );
} );
$.extend($.ui.accordion.animations, {
	easeslide: function(options) {
		$.ui.accordion.animations.slide(options, { easing: "easeInOutQuad", duration: 700 } ) }
	}
);

// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
// behaviours - Shows and hides tabs;
// depends: 	jQuery library;
// author:		nr;
// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------

$().ready(function tabs() {
	// Set up ARIA for tabs
	$('.tabPanel .header li a').each(function(i) {
		$(this).attr('role', 'tab');
		$(this).attr('aria-selected', 'false');
		var ariaLabel = 'ariaLabel' + i;
		$(this).attr('id', ariaLabel);
		$(this.hash).attr('aria-labelledby', ariaLabel);
	});

	$('.tabPanel .header li.selected a').each(function() {
		$(this).attr('aria-selected', 'true');
	});

	// Set up ARIA for tab panels
	$('.tabPanel .content').each(function() {
		$(this).attr('role', 'tabpanel');
		$(this).attr('aria-hidden', 'true');
	});

	// Set up ARIA for tab panels
	$('.tabPanel .contentSelected').each(function() {
		$(this).attr('aria-hidden', 'false');
	});

	// Add event listener to tab header
	$('.tabPanel .header').children('p').remove().end().click(function(e) {
		var $target = $(e.target);

		if($target.is('a')) {
			$target.parent("li").siblings("li").each( function() {
				$($(this).find("a")[0].hash).removeClass('contentSelected').attr('aria-hidden', 'true');
			});
			$($target[0].hash).addClass('contentSelected').attr('aria-hidden', 'false');
			$target.attr('aria-selected', 'true').parent('li').siblings().removeClass('selected').children().attr('aria-selected', 'false').end().end().addClass('selected');
			return false;
		}

	});

});

// -----------------------------------------------------------------------------------------------------------------------------
// behaviours - Handles carousel behaviors.  Builds one per page only and only on project pages
// depends: 	jQuery library;
// author:		jsn;
// -----------------------------------------------------------------------------------------------------------------------------

$().ready(function() {
	//Are we on a project page and with the need for a carousel?
	var features = $(".project .features li");
	if (features.length < 4) return;

	var featuresContainer = $(".features"),
		featuresList = $(".features ul"),
		features = featuresList.find("li");
		numberOfVisibleItems = 3,
		firstVisibleItem = 0,
		nextItem = $('<a href="#" class="next"><span>Next</span></a>'),
		previousItem = $('<a href="#" class="previous"><span>Previous</span></a>'),
		nextArrow = nextItem.find("span"),
		previousArrow = previousItem.find("span");
	init();

	function init() {
		//we dont want or need the existing header and footer - remove them
		$(".contentMainHeader").remove();
		$(".contentMain .footer").remove();
		//set the activating class on the features container
		featuresContainer.addClass("featuresCarousel");
		//remove the first class from any items
		features.removeClass("first");
		// Add span for play icon for youtube thumbnails
		features.find("a.lightbox").append("<span></span>");
		//remove any bottom padding from contentMain
		$(".contentMain").css("padding-bottom", 0);
		//add the controls
		featuresContainer.before(previousItem).after(nextItem);
		//add event handlers to controls
		previousItem.click(movePrevious);
		nextItem.click(moveNext);
		//set the initial display status
		updateFeaturesDisplay();
	}

	function updateFeaturesDisplay() {
		//set the "last" class on the last element
		features.removeClass("last");
		$(features[firstVisibleItem + numberOfVisibleItems - 1]).addClass("last");
		//animate everything into position
		featuresContainer.animate( {
			"height": getHeightOfFeatures()
		}, "fast" );
		featuresList.animate( {
			"top": getTopPositionOfList()
		}, "fast" );
		//change the display of the up and down arrows
		previousArrow[ (firstVisibleItem > 0 ? "remove" : "add") + "Class" ]("end");
		nextArrow[ (firstVisibleItem+numberOfVisibleItems < features.length ? "remove" : "add") + "Class" ]("end");
	}

	function getHeightOfFeatures() {
		var height = 0,
			i = firstVisibleItem,
			j = firstVisibleItem + numberOfVisibleItems;
		for (i; i<j; i++) {
			height += features[i].offsetHeight;
		}
		return height;
	}

	function getTopPositionOfList() {
		var top = 0,
			i = 0;
		for (i; i<firstVisibleItem; i++) {
			top += features[i].offsetHeight;
		}
		//if top is greater than 1 add another 2 to account for border between items
		return (top>0?top+2:top) * -1;
	}

	function movePrevious(e) {
		e.preventDefault();
		if (firstVisibleItem === 0) return;
		firstVisibleItem--;
		updateFeaturesDisplay();
	}
	function moveNext(e) {
		e.preventDefault();
		if (firstVisibleItem+numberOfVisibleItems >= features.length) return;
		firstVisibleItem++;
		updateFeaturesDisplay();
	}
});

//change email addresses to clickable mailto links
$().ready(function() {
	$(".mailto").each(function() {
		var address = this.innerHTML.replace(/\[at\]/, "@");
		this.innerHTML =	'<a href="mailto:' + address + '">' + address + '</a>';
	});
});

// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
// behaviours - Marks up document with ARIA Roles;
// depends: 	jQuery library;
// author:		nr;
// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------

$(document).ready(function setUpAriaRoles() {
	$("#sitewideNav").attr("role", "navigation");
	$("#header").attr("role", "banner");
	$("#bd").attr("role", "main");
	$("#footer").attr("role", "contentinfo");
});

// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
// behaviours - Dialog (Lightbox);
// depends: 	jQuery UI library;
// author:		nr;
// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------

function grabParam(name,url){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( url );
	if (results == null) {
		return "";
	}
	else {
		return results[1];
	}
}

function showLightbox(container, type) {
	if (type === "youTube") {
		var videoUrl = "http://www.youtube.com/v/" + grabParam('v',container.href) + "&hl&hl=en&fs=1&";
		var so = new SWFObject(videoUrl, "", "640", "385", "9.0.0", "#fff");
		so.addParam("allowFullScreen", true);
		so.addVariable("flashvars", this.id);
		so.addVariable("allowScriptAccess", "always");
		so.write("dialog");

		$("#dialog").dialog({
			modal: true,
			autoOpen: false,
			height: 385,
			width: 640,
			dialogClass: 'youTubeDialog',
			close: function(event, ui) {
				$(this).dialog("destroy");
			}
		});
	}

	$("#dialog").dialog('open');

	return false;
}

$().ready( function() {

	function handleGallery(e) {
		// Get image url
		var $target = $(e.target);

		while (!$target.is("a") && $target.parent()) {
			$target = $target.parent();
		}
		if (!$target.is("a")) {
			return false;
		}

		if ($target.hasClass("youTube")) {
			showLightbox($target[0], $target[0].className);
			return false;
		}

		if(!document.getElementById("dialog")) {
			$("<div id='dialog'></div>").appendTo("body");
		}

		var currentImageURL = $target.attr("href");
		var currentIndex = 0;

		// Get list of image URLs in gallery
		var imageURLs = $(this).find("li > a");
		for (var i = 0; i < imageURLs.length; i++) {
			imageURLs[i] = imageURLs[i].href;
			// Set current image index
			if (imageURLs[i].indexOf(currentImageURL) > 0) {
				currentIndex = i;
			}
		}

		// Get list of image URLs in gallery
		var imageTitles = $(this).find("li .dialog-title");

		var imgWidthWithBorder = 660;
		var imgMargin = 20;
		var h1Text = $(this).find("li:eq(" + currentIndex + ") .dialog-title")[0];
		h1Text = h1Text.tagName == 'IMG'? h1Text.alt : h1Text.innerHTML;
		var description = $(this).find("li:eq(" + currentIndex + ") .dialog-desc").text();
		var a =  $(this).find("li:eq(" + currentIndex + ") a")[0];
		var type = a.className.split("|")[0].split("=")[1];
		var size = a.className.split("|")[1].split("=")[1];
		var currentLeftPos = -((currentIndex) * (imgWidthWithBorder + imgMargin));

		// Show lightbox and current image
		var galleryHTML = "<div class='galleryOverlay'><ul style='width:" + (imageURLs.length * (imgWidthWithBorder + imgMargin)) + "px; left:" + currentLeftPos + "px;'>";
		for(var i = 0; i < imageURLs.length; i++) {
			galleryHTML += "<li><img src='" + imageURLs[i] + "' /></li>";
		}
		galleryHTML += "</ul></div><div class='galleryInfo'><h1>" + h1Text + "</h1><p>" + description + "</p><a href='" + imageURLs[currentIndex] + "' class='download'>Download image (<span class='type'>" + type + "</span>, <span class='size'>" + size + "</span>)</a>";
		galleryHTML += "<div class='controls'><a href='' class='next'>next image</a> <a href='' class='prev'>previous image</a></div>";
		galleryHTML += "</div>";

		$("#dialog").empty();
		$("#dialog").dialog({
			modal: true,
			autoOpen: false,
			height: 519,
			width: 643,
			dialogClass: 'galleryDialog',
			open: function(event, ui) {
				$(this).append(galleryHTML);

			},
			close: function(event, ui) {
				$(this).dialog("destroy");
				$(this).empty();
			}
		});

		$("#dialog").dialog('open');

		var $galleryUL = $(".galleryOverlay ul");
		var $galleryInfo = $(".galleryInfo");
		var $that = $(this);

		$(".galleryInfo .next").click(function() {
			var newLeft = parseInt($galleryUL.css("left")) - imgWidthWithBorder - imgMargin;
			currentIndex++;
			if (newLeft < -(imageURLs.length * imgWidthWithBorder) ) {
				newLeft = 0;
				currentIndex = 0;
			}
			$galleryUL.css("left", newLeft + "px");
			var h1Text = $that.find("li:eq(" + currentIndex + ") .dialog-title")[0];
			h1Text = h1Text.tagName == 'IMG'? h1Text.alt : h1Text.innerHTML;
			$galleryInfo.find("h1").text(h1Text);
			$galleryInfo.find("p").text($that.find("li:eq(" + currentIndex + ") .dialog-desc").text());
			var a = $that.find("li:eq(" + currentIndex + ") a")[0];
			var type = a.className.split("|")[0].split("=")[1];
			var size = a.className.split("|")[1].split("=")[1];
			$galleryInfo.find("span.type").text(type);
			$galleryInfo.find("span.size").text(size);
			$galleryInfo.find("a.download")[0].href = $galleryUL.find("img:eq(" + currentIndex + ")")[0].src;
			return false;
		});

		$(".galleryInfo .prev").click(function() {
			var newLeft = parseInt($galleryUL.css("left")) + imgWidthWithBorder + imgMargin;
			currentIndex--;
			if (newLeft > 0 ) {
				currentIndex = imageURLs.length - 1;
				newLeft = -(currentIndex * (imgWidthWithBorder + imgMargin));
			}
			$galleryUL.css("left", newLeft + "px");
			var h1Text = $that.find("li:eq(" + currentIndex + ") .dialog-title")[0];
			h1Text = h1Text.tagName == 'IMG'? h1Text.alt : h1Text.innerHTML;
			$galleryInfo.find("h1").text(h1Text);
			$galleryInfo.find("p").text($that.find("li:eq(" + currentIndex + ") .dialog-desc").text());
			var a = $that.find("li:eq(" + currentIndex + ") a")[0];
			var type = a.className.split("|")[0].split("=")[1];
			var size = a.className.split("|")[1].split("=")[1];
			$galleryInfo.find("span.type").text(type);
			$galleryInfo.find("span.size").text(size);
			$galleryInfo.find("a.download")[0].href = $galleryUL.find("img:eq(" + currentIndex + ")")[0].src;
			return false;
		});

		return false;
	}

	$(".gallery").click(handleGallery);
	$(".videoLink .play").click(handleGallery);

});

//force external links to open in new window
$().ready( function() {
	$("body").click(function(e) {
		if (e.target.tagName && e.target.tagName.toLowerCase() === "a" && e.target.hostname !== location.hostname) {
			openExternalLink($(e.target).attr("href"));
			return false;
		}
	});
});
function openExternalLink(url) {
	window.open( url, "new", "width=992,height=700,resizable=yes,scrollbars=yes,location=yes,menubar=yes,toolbar=yes");
}
