$(function() {
		   
	//Reformat the published dates (on nees items)
	$(".publishedDate").each(function() {
		var date = $(this).html();
		var newDate = "";
		
		if (date.indexOf("-") != -1) {
			var dateParts = $(this).html().split("-");
			if (dateParts.length == 3) {
				newDate = dateParts[2] + " ";
				switch (dateParts[1]) {
					case "01":
						newDate += "Jan";
						break;
					case "02":
						newDate += "Feb";
						break;
					case "03":
						newDate += "Mar";
						break;
					case "04":
						newDate += "Apr";
						break;
					case "05":
						newDate += "May";
						break;
					case "06":
						newDate += "Jun";
						break;
					case "07":
						newDate += "Jul";
						break;
					case "08":
						newDate += "Aug";
						break;
					case "09":
						newDate += "Sep";
						break;
					case "10":
						newDate += "Oct";
						break;
					case "11":
						newDate += "Nov";
						break;
					case "12":
						newDate += "Dec";
						break;
				}
				newDate += " " + dateParts[0];
			}
		}
		
		$(this).html(newDate);
	});

	// Bind the print preview functionality
	$(".printPreview").printPreview();
	// Bind the font size functionality
	$(".content").textResize($(".decreaseFont"), $(".increaseFont"), null, { baseFontSize: 11, maxZoom: 1.5 });
	// Show the tools
	$(".tools").show();

	// Restyle the HR elements
	$("hr").wrap("<div class=\"hr\"></div>");

	// Add the zebra stripes to the tables
		$("table").each(function() {
			var table = $(this);
			var tHeadRows = $("thead tr", table);
			var tBodyRows = $("tr", $(this)).not(tHeadRows);
			var startRow = 0;
			// If there is no thead rows, offset the odd striping
			if (tHeadRows.length == 0) startRow = 1;
			tBodyRows.each(function(i) {
				// Test if the row is odd
				if ((startRow + i) % 2 == 0) {
					$(this).addClass("odd");
				} else {
					$(this).removeClass("odd");
				}
			});
	});
	
	// Correct a Matrix Bug with how asset listing output the pagination page lists (to match search pages)
	var pages = $(".globalListingPagination ul li.pages");
	if (pages.length > 0) {
		var newList = $("<div></div>");
		var anchors = pages.eq(0).children("a");
		if (anchors.length > 0) {
			anchors.each(function() {
				var currLink = $(this);
				currLink.remove();
				newList.append(currLink);
			});
			var currPage = parseInt(pages.eq(0).html());
			pages.html("");
			newList.children().each(function(i) {
				var currLink = $(this);
				if (i == 0 && parseInt(currLink.html()) == currPage + 1) pages.append($("<b>" + currPage + "</b>"));
				pages.append(currLink);
				if (parseInt(currLink.html()) == currPage - 1) pages.append($("<b>" + currPage + "</b>"));
			});
		} else {
			pages.wrapInner("<b></b>");
		}
	}

	// Helper function to replace all instances within a string
	function replaceAll(str, replaceStr, withStr) {
		while (str.indexOf(replaceStr) != -1) {
			str = str.replace(replaceStr, withStr);
		}
		return str;
	}

	// Highlight search terms in the Metadata Description field in the search results
	var searchField = $(".searchForm .sq-form-field");
	var searchTerms = $(".header .search .sq-form-field").val();
	if (searchTerms == "" || searchTerms == null) searchTerms = $(".searchForm .sq-form-field").val();
	if (searchTerms != undefined && searchTerms != null && searchTerms.length > 0) {
		var keywords = searchTerms.split(" ");
		$(".searchResults li h3 a, .searchResults li div").each(function() {
			var currTag = $(this);
			for (i = 0; i < keywords.length; i++) {
				// Filter out keywords that contain %% and **, as these are used as indicators of opening and closing highlight tags
				if (keywords[i].indexOf("%%") != -1 || keywords[i].indexOf("**") != -1) continue;
				var thisHTML = currTag.html();
				var newHTML = "";
				var matchedTerms = new Array();
				while (true) {
					var currIndex = thisHTML.toUpperCase().indexOf(keywords[i].toUpperCase());
					if (currIndex == -1) break;
					if (currIndex > 0) {
						newHTML += thisHTML.substring(0, currIndex);
						thisHTML = thisHTML.substring(currIndex, thisHTML.length);
					}
					newHTML += "%%" + thisHTML.substr(0, keywords[i].length) + "**";
					if (thisHTML.length > keywords[i].length) {
						thisHTML = thisHTML.substring(keywords[i].length, thisHTML.length);
					} else {
						thisHTML = "";
						break;
					}
				}
				newHTML += thisHTML;
				currTag.html(newHTML);
			}
			currTag.html(replaceAll(replaceAll(currTag.html(), "%%", "<strong class=\"highlight\">"), "**", "</strong>"));
		});
	}

	// Add the prompt to the search field
	$(".header .search .sq-form-field").val("").defaultValue("Enter keywords", "#a6a6a6", "italic");
	$(".searchForm .sq-form-field").defaultValue("Enter keywords", "#a6a6a6", "italic");

	// Add the icons to the external links
	// Content External Links
	$(".contentArea a[href^=http]").add(".contextualLinks a[href^=http]").each(function(){
		if(this.href.indexOf(location.hostname) == -1) {
			$(this).attr('target', '_blank').attr('class', 'externalLink').attr('title', 'External link (will open in new window)');
		}
	});

	// Add the JS driven hover and focus states on button elements in IE6
	if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
		$(".searchButton input, .submitButton input").hover(
			function() {
				$(this).addClass("ieHover");
			},
			function() {
				$(this).removeClass("ieHover");
			}
		).focus(
			function() {
				$(this).addClass("ieFocus");
			}
		).blur(
			function() {
				$(this).removeClass("ieFocus");
			}
		);
	}

	// Run the slideshow on the homepage
	$(".bannerArea").cycle({
		fx: "fade",
		speed: 2000,
		timeout: 8000,
		random: 1,
		pause: 1
	});

	// Use the cycle plugin to handle the video pagination on the project pages
	var videos = $(".videos");
	if (videos.children().length > 1) {
		videos.cycle({
			fx: 'fade',
			speed: 0,
			timeout: 0,
			nowrap: 1,
			pager: '.videoPagination .pages',
			prev: '.videoPagination .prev',
			next: '.videoPagination .next'
		});
		$(".videoPagination").show();
	}

	// Function to retrieve the anchor link from a url (also converts assetIDs to an index)
	function getAnchorLinkFromUrl(url) {
		var returnVal = "";
		if (url.indexOf("#") != -1) {
			var panel = url;
			var assetID = "";
			url = url.substr(url.indexOf("#") + 1, url.length);
			if (url.indexOf("-") != -1) {
				panel = url.substr(0, url.indexOf("-")).toLowerCase();
				assetID = url.substr(url.indexOf("-") + 1, url.length);
			}
			var itemContainer = null;
			switch (panel) {
				case "video":
					itemContainer = $(".videos div");
					break;
				case "image":
					itemContainer = $(".imageThumbs .thumbs a");
					break;
				case "news":
					itemContainer = $(".news ul li .newsItemLink");
					break;
			}
			if (itemContainer != null) {
				itemContainer.each(function(i) {
					if (this.id == (panel + "-" + assetID)) {
						returnVal = panel + "-" + i;
					}
				});
			}
		}
		return returnVal;
	}

	// Build the image gallery and thumbnail scroller
	var imageGallery = $(".imageGallery");
	var imageThumbs = $(".imageThumbs");
	// Show the scrollLeft and scrollRight arrows if required and bind the events
	imageThumbs.children(".scrollLeft").show();
	imageThumbs.children(".scrollRight").show();
	var thumbsWidth = 0;
	var thumbsMarginLeft = 0;
	imageThumbs.find(".thumbs a").each(function() {
		var currThumb = $(this);
		var currImg = currThumb.children("img");
		var currImgWidth = currImg.width();
		var currImgHeight = currImg.height();
		// To get around a safari bug where the images do not have dimensions at this point
		if (currImgWidth == 0 && currImgHeight == 0) {
			currImgWidth = 318;
			currImgHeight = 318;
		}
		thumbsMarginLeft = parseInt(currThumb.css("margin-left"));
		thumbsWidth += currThumb.outerWidth() + thumbsMarginLeft;
		if (currImgWidth > currImgHeight) {
			currImg.css("height", currThumb.height() + "px");
			currImg.css("width", (parseInt(currThumb.width() * (currImgWidth / currImgHeight))) + "px");
		} else {
			currImg.css("width", currThumb.width() + "px");
			currImg.css("height", (parseInt(currThumb.height() * (currImgHeight / currImgWidth))) + "px");
		}
	});
	imageThumbs.children(".thumbs").css({ width: (imageThumbs.width() - imageThumbs.children(".scrollLeft").outerWidth() - imageThumbs.children(".scrollRight").outerWidth()) + "px" }).wrapInner("<div class=\"scroller\"></div>");
	var scroller = imageThumbs.find(".scroller");
	scroller.css({ width: thumbsWidth + "px", marginLeft: (0 - thumbsMarginLeft) + "px" });
	if (thumbsWidth > imageThumbs.width()) {
		var scrollerTimeout = 0;
		var scrollJump = 5;
		var scrollThumbs = function(direction) {
			var offset = scrollJump;
			if (direction == "right") offset = 0 - scrollJump;
			var currLeft = parseInt(scroller.css("left")) + offset;
			if (currLeft < (imageThumbs.children(".thumbs").width() - thumbsWidth + thumbsMarginLeft)) currLeft = (imageThumbs.children(".thumbs").width() - thumbsWidth + thumbsMarginLeft);
			if (currLeft > 0) currLeft = 0;
			scroller.css("left", currLeft + "px");
		}
		var scrollLeft = function() {
			scrollThumbs("left");
		}
		var scrollRight = function() {
			scrollThumbs("right");
		}
		imageThumbs.children(".scrollLeft").hover(
			function() {
				scrollerTimeout = setInterval(scrollLeft, 25);
			},
			function() {
				clearInterval(scrollerTimeout);
			}
		).click(function(e) {
			e.preventDefault();
		});
		imageThumbs.children(".scrollRight").hover(
			function() {
				scrollerTimeout = setInterval(scrollRight, 25);
			},
			function() {
				clearInterval(scrollerTimeout);
			}
		).click(function(e) {
			e.preventDefault();
		});
	}
	// Set the height of the image thumbs
	$(".imageThumbs, .imageThumbs .thumbs, .imageThumbs .thumbs .scroller").css("height", imageThumbs.children(".scrollLeft").outerHeight() + "px");
	// Absolutely position the thumbnails to allow for scrolling
	imageThumbs.find(".scroller").css({ position: "absolute", left: 0, top: 0 });
	imageThumbs.find(".thumbs a").each(function(i) {
		var currImg = $(this);
		currImg.css({ position: "absolute", left: ((currImg.outerWidth() + parseInt(currImg.css("margin-left"))) * i) + "px", top: 0 });
	});
	// Hide the 'IMAGE GALLERY' header
	$(".contextualPanel.images h2").hide();
	// Show the image gallery
	imageGallery.show();
	// Set the height of the image gallery
	var galleryHeight = 0;
	imageGallery.find("img").each(function() {
		var currHeight = $(this).outerHeight();
		// To get around a safari bug where the images do not have dimensions at this point
		if (currHeight == 0) galleryHeight = 320;
		if (currHeight > galleryHeight) {
			galleryHeight = currHeight;
		}
	});
	imageGallery.css("height", galleryHeight + "px");

	// Function to get the index from the anchor link in the url (the asset ID is converted to an index)
	function getAssetIndexFromUrl(url) {
		var anchorLink = getAnchorLinkFromUrl(url);
		if (anchorLink.indexOf("-") != -1) {
			return parseInt(anchorLink.substr(anchorLink.lastIndexOf("-") + 1, anchorLink.length));
		}
		return -1;
	}

	// Show the contextual links panel on the projects page an bind the events
	var contextualPanels = $(".project .content .contextualPanel");
	if (contextualPanels.length > 0) {
		// Hide the non-JS versions of the listings and fade in the contextual links panel
		var contextualLinks = $(".contextualLinks");
		var clWidth = contextualLinks.width();
		var clPadding = contextualLinks.outerWidth() - clWidth;
		contextualLinks.css({ opacity: 0, width: 0, paddingLeft: 0, marginLeft: 0 });
		contextualLinks.show();
		$(".content").css({ marginRight: (clWidth + clPadding)  + "px"});
		contextualLinks.css({ width: clWidth + "px", marginLeft: (0 - clWidth) + "px", opacity: 1 });
		// Helper function to show a specific contextual panel
		var transitionPanels = function(panelToFadeIn) {
			if (panelToFadeIn != undefined && panelToFadeIn != null) {
				var panelToFadeOut = $(".content .projectContent:visible, .content .contextualPanel:visible");
				if (panelToFadeIn.get(0) != panelToFadeOut.get(0)) {
					var projectContentPanel = $(".content .projectContent");
					panelToFadeOut.fadeOut(150, function() {
						if( $(panelToFadeIn).hasClass("images")) {
						   $(".contextualLinks").hide();
						   $(".content").css("margin-right","16px");
						   $(".contentArea").css("width","auto");
						}
						else{
						   $(".contextualLinks").show();
						   $(".content").css("margin-right","191px");
						   $(".contentArea").css("width","517px");
						}					
						panelToFadeIn.fadeIn(150);
					});
				}
			}
		}
		// Bind the click events to the contextual link headers to show the appropriate panels
		$(".contextualLinks div").each(function() {
			var contextualLinkArea = $(this);
			if ($("ul", contextualLinkArea).length > 0) {
				$("h3 a", contextualLinkArea).click(function(e) {
					e.preventDefault();
					var panelToFadeIn = null;
					var currentItemDesc = $(this).find("span").html();
					switch (currentItemDesc.toUpperCase()) {
						case "RELATED LINKS":
							panelToFadeIn = $(".content .contextualPanel.relatedLinks");
							break;
						case "IMAGE GALLERY":
							panelToFadeIn = $(".content .contextualPanel.images");
							break;
						case "LATEST VIDEO":
							panelToFadeIn = $(".content .projectContent");
							break;
						case "PUBLICATIONS":
							panelToFadeIn = $(".content .contextualPanel.publications");
							break;
						case "NEWS":
							panelToFadeIn = $(".content .contextualPanel.news");
							break;
					}
					transitionPanels(panelToFadeIn);
				});
			} else {
				contextualLinkArea.hide();
			}
		});
		// Show the back links and bind the event to re-show the project content
		$(".content .backLink").css("display", "block").click(function(e) {
			e.preventDefault();
			transitionPanels($(".content .projectContent"));
		});
		// Bind the Contextual Links for Videos
		$(".contextualLinks a.videoLink").each(function(i) {
			$(this).click(function(e) {
				e.preventDefault();
				var itemNum = getAssetIndexFromUrl(this.href);
				if (itemNum != -1) {
					transitionPanels($(".content .projectContent"));
					$(".videoPagination .pages a").eq(itemNum).click();
				}
			});
		});
		// Bind the Contextual Links for Images
		$(".contextualLinks a.imageLink").each(function(i) {
			$(this).click(function(e) {
				e.preventDefault();
				var itemNum = getAssetIndexFromUrl(this.href);
				if (itemNum != -1) {
					transitionPanels($(".content .contextualPanel.images"));
					$(".imageThumbs .thumbs a").eq(itemNum).click();
				}
			});
		});
		// Bind the Contextual Links for News Items
		$(".contextualLinks a.newsLink").each(function(i) {
			$(this).click(function(e) {
				e.preventDefault();
				var itemNum = getAssetIndexFromUrl(this.href);
				if (itemNum != -1) {
					var newsPanel = $(".content .contextualPanel.news");
					// Check if the news panel is already visible
					if (newsPanel.filter(":visible").length == newsPanel.length) {
						$(".contextualPanel.news ul li .newsItemLink").eq(itemNum).click();
					} else {
						transitionPanels(newsPanel);
						$(".contextualPanel.news ul li .newsItem").hide().eq(itemNum).show();
						$(".contextualPanel.news ul li span").removeClass("selected").eq(itemNum).addClass("selected");
					}
				}
			});
		});
	}

	// Create the news show/hide functionality
	var newsLinks = $(".contextualPanel.news ul li .newsItemLink");
	var newsItems = $(".contextualPanel.news ul li .newsItem");
	newsItems.hide();
	newsLinks.each(function(i) {
		var currNewsLink = $(this);
		var currNewsItem = newsItems.eq(i);
		//if (i == 0) currNewsItem.show();
		var arrow = $("<a href='#' class='arrow'>&nbsp;</a>");
		currNewsLink.after(arrow);
		arrow.click(function() {
			currNewsLink.click();
		}).hover(
			function() {
				currNewsLink.addClass("hover");
			},
			function() {
				currNewsLink.removeClass("hover");
			}
		);
		currNewsLink.click(function(e) {
			e.preventDefault();
			newsLinks.each(function() {
				$(this).parent().removeClass("selected");					
			});
			currNewsLink.parent().addClass("selected");
			var visibleItems = newsItems.filter(":visible");
			if (visibleItems.length > 0) {
				visibleItems.each(function() {
					var currVisibleItem = $(this);
					if (currVisibleItem.get(0) != currNewsItem.get(0)) {
						currVisibleItem.stop(true, false).animate({ height: 0 }, 250, function() {
							$(this).hide().css({ height: "auto" });
							currNewsItem.show();
							var itemHeight = currNewsItem.height();
							currNewsItem.css({ height: 0 })
							currNewsItem.stop(true, false).animate({ height: itemHeight + "px" }, 250);
						});
					} else {
						currVisibleItem.stop(true, false).animate({ height: 0 }, 250, function() {
							$(this).hide().css({ height: "auto" });
							currNewsLink.parent().removeClass("selected");
						});
					}
				});
			} else {
				currNewsItem.show();
				var itemHeight = currNewsItem.height();
				currNewsItem.css({ height: 0 })
				currNewsItem.stop(true, false).animate({ height: itemHeight + "px" }, 250);
			}
		});
	});

	// Hide the contextual panels
	contextualPanels.hide();

	// Process the initial anchor reference from the url on page load
	var initialImage = 0;
	var anchorLink = getAnchorLinkFromUrl(location.href);
	if (anchorLink.indexOf("-") != -1) {
		var panel = anchorLink.substr(0, anchorLink.indexOf("-"));
		var itemNum = parseInt(anchorLink.substr(anchorLink.indexOf("-") + 1, anchorLink.length));
		switch (panel) {
			case "video":
				$(".videoPagination .pages a").eq(itemNum).click();
				break;
			case "image":
				$(".content .projectContent").hide();
				$(".contextualLinks").hide();
				$(".content").css("margin-right","16px");
				$(".contentArea").css("width","auto");				
				$(".images").show();
				initialImage = itemNum;
				break;
			case "news":
				var newsPanel = $(".content .contextualPanel.news");
				$(".content .projectContent").hide();
				newsPanel.show();
				$(".contextualPanel.news ul li .newsItem").hide().eq(itemNum).show();
				$(".contextualPanel.news ul li span").removeClass("selected").eq(itemNum).addClass("selected");
				break;
		}
		location.hash = "content";
	}

	// Use the cycle plugin to handle the image gallery on the project pages
	imageGallery.cycle({
		fx: 'fade',
		speed: 500,
		timeout: 0,
		pager: '.imageThumbs .thumbs',
		startingSlide: initialImage,
		pagerAnchorBuilder: function(idx, slide) {
			// return selector string for existing anchor
			return '.imageThumbs .thumbs a:eq(' + idx + ')';
		}
	});
	// Consume the click event for the thumbnails as the hover event is used for the cycle plugin (above)
	imageThumbs.find(".thumbs a").bind('mouseenter', function(e) {
		$(this).click();
	});

	// Add the rounded corners to the content area
	var contentArea = $(".contentArea");
	contentArea.css("width", (contentArea.parent().width() - (contentArea.outerWidth() - contentArea.width())) + "px");
	contentArea.corner("top 12px");

	var resultsPerPageFromMatrix = $("input[name='results_per_page']");
	var resultsPerPageSelectbox = $("select[name='results_per_page']");
	if (resultsPerPageFromMatrix.length > 0 && resultsPerPageSelectbox.length > 0) {
		var resultsPerPage = resultsPerPageFromMatrix.val();
		$("option", resultsPerPageSelectbox).each(function (i) {
			if(this.value == resultsPerPage){
				$(this).attr("selected", "selected");
			}
		});
		resultsPerPageFromMatrix.remove();
	}

});