$(document).ready(function() {
	
	if($('div#beauty-moment').length > 0) {
		if ($.cookie("homepage-fadeout") == 'true') {
			//we're on the homepage and the fade out has been done
			homepageSplash(false);
			setHomePageColumnHeights($('div.section.content div.splash-hidden'));
		}
	}
	
	/* vertically align the text on the homepage information columns */
	$(".inform-item .inform-item-content").vAlign();
	
	/* Photo credit */
	if ($(".hero .caption-link").length) {
		
		var config = {
			timeout: 300,
			over: function(){
				$(this).siblings('.caption').fadeTo('slow', 1.0); // This sets the opacity to 100% on hover
			},
			out: function(){
				$(this).siblings('.caption').fadeTo("slow", 0); // This sets the opacity back to 60% on mouseout
			}
		}
		
		$(".hero .caption-link").hoverIntent(config);
	}
	showHideCategories();
	
	/* Perform cookieTest for Text size */
	cookieTest();
	
	/* Text resizing functionality - adds a class to the body tag to reset the size of the text and flushes to a cookie to maintain from page to page */
	$('.text-resizing a').click(function() {
		var textSize = $(this).attr('class');
		$('body').removeClass('smaller medium bigger').addClass(textSize);
		$.cookie('TEXT_SIZE',textSize, { path: '/', expires: 10000 });
		return false;
	 });
	 
	/* JQuery Cycle carousels */
	if ($('.blog-carousel').length) {
		$('.blog-carousel') 
		.cycle({ 
			fx:		 'fade',
			prev:	 '.left', 
			next:	 '.right',
			speed:	500, 
			timeout: 7000, 
			pause: 1
		});
	}
	
	if ($('div.home-carousel').length) {
		if($('div.home-carousel').parent().attr('class') != 'home-centre-col') {
			$('div.home-carousel')
			.cycle({
				fx:		 'fade',
				prev:	 '.home-left', 
				next:	 '.home-right',
				speed:	500, 
				timeout: 7000, 
				pause: 1,
				after: onAfter
			});
		}
	}

	if ($('.focus-wrapper').length) {
		$('.focus-wrapper ul').jcarousel();
	}
	
	if ($("input.s").length > 0) {
		setSearchText($("input.s"), "SEARCH");
	}
	
	if ($("input.news-signup").length > 0) {
		setSearchText($("input.news-signup"), "Enter your e-mail here");
	}
	
	// Finding aids are MASSIVE, and this is massively blocking
	if ($('body').hasClass('finding-aid-body') == false) {
		/* Equalise heights */
		equalHeight($("div.holder"));
		equalHeight($("div.column"));
		equalHeight($("div.col"));
		equalHeight($("div.visual-column"));
		equalHeight($("div.content-col"));
		equalHeight($(".res-colimns ul"));
		equalHeight($("div.story,div.story-aside"));
		equalHeight($("div.aside,div.article"));
		equalHeight($("div.aside,div.main-content"));
	}
	
	
	// sort out the event popovers
	if($('div.events-holder div.popupContainer').length > 0) {
		$('div.events-holder div.popupContainer').each(function() {
			setUpEventPopup($(this));
		})	
	}
	
	// sort out the slideshow and video popovers
	if($('div.story-aside div.popupContainer').length > 0) {
		$('div.story-aside div.popupContainer').each(function(containerIndex) {
			setUpPopup($(this), containerIndex);
		})	
	}
	
	
	// sort out the events landing page slider
	if($('div.main-gallery.events-slider').length > 0) {
		var sliderContent = $('div.main-gallery.events-slider').find('div.slide');
		$('div.main-gallery.events-slider')
			.before('<div id="events-slider-nav"></div>')
			.cycle({
				fx:		 'fade', 
					speed:	'fast', 
 					timeout: 9000,
				pager: '#events-slider-nav'
			});
		setUpEventPager();
	}
	
	
	setHoverDiv($('div.splash-hidden div.highlight'), 'a img', 'h3 a');
	
	setHoverDiv($('ul#mycarousel li.jcarousel-item'), 'a img', 'h3 a');
	
	setHoverDiv($('ul.collection-list li div.holder'), 'a img', 'span a');
	
	setHoverDiv($('div.collection-box'), 'div.home-carousel div.home-carousel-item', 'h2 a');
	
	//set up an interval to trigger clicking on the object highlight pagination
	if($('div.visual-carousel').length > 0) {
		setInterval(function() {
			$('div.visual-carousel div.pagination a#collNext').trigger('click')
		}, 4000);
	}
	
});

// function which takes a parent element which when the first argument is hovered, the second argument is given the class hover to be styled in CSS
function setHoverDiv(parentElement, elementToHover, elementToStyle) {
	
	parentElement.each(function() {
		var currentParent =	$(this);
		currentParent.find(elementToHover).each(function() {
			var objectToStyle = $(currentParent.find(elementToStyle+":eq(0)"));
			$(this).hover(function(){
				objectToStyle.addClass('hover');
			},
			function() {
				objectToStyle.removeClass('hover');
			})
		})
	})
}

// show and hide the membership category details
function showHideCategories() {
	/* Show/hide Categories */
	$('div.category-details').hide();
	// shows the category-details on clicking the noted link	
	$('div.category-choice a.expand').click(function() {
	$(this).closest('div.category-choice').children('.category-details').toggle(400);
		return false;
	});
}

/*	Takes an input field element (elInputField) and adds a specified text value (textToHide)
 *	FOCUS: When that input field is given focus the term is removed
 *	BLUR: If the focus is lost when the field is empty the text value (textToHide) is reinstated	
 */	
function setSearchText(elInputField, textToHide) {
		elInputField.attr("value", textToHide)
		elInputField.focus(function() {
				if (elInputField.attr("value") == textToHide) elInputField.attr("value", ""); 
		})
		elInputField.blur(function() {
				if (elInputField.attr("value") == "") elInputField.attr("value", textToHide); 
		})
}

//Slide count function for home page center module slideshow
function onAfter(curr,next,opts) {
	var caption = (opts.currSlide + 1) + '/' + opts.slideCount;
	$('div.count').html(caption);
}

//Sort out the CSS classes for the pager on the event landing page because they use background images
function setUpEventPager() {
	pager = $('div#events-slider-nav');
	pager.find('a').each(function(index) {
		$(this).addClass('slider-nav-'+index);
	});
}

//Simple text resize
function cookieTest() {
if($.cookie('TEXT_SIZE')) {
	$('body').addClass($.cookie('TEXT_SIZE')); 
 }
}
/* Text resizing functionality - adds a class to the body tag to reset the size of the text and flushes to a cookie to maintain from page to page */
$('.text-resizing a').click(function() {
	var textSize = $(this).attr('class');
	$('body').removeClass('smaller medium bigger').addClass(textSize);
	$.cookie('TEXT_SIZE',textSize, { path: '/', expires: 10000 });
	return false;
 });

// Takes a group of elements and sets their min heights to be the same as that of the tallest element
function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	
	group.css("min-height", tallest);
}

$.fn.vAlign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).closest('.inform-item').height();
	var mh = Math.ceil((ph-ah) / 2);
	$(this).css('margin-top', mh);
	});
};

/* grab the hidden slideshow div and on click of the link, initialise. Works for multiple popup elements (video and slideshow) on a page */
function setUpPopup(container, containerIndex) {
	
	var wrapper = container.find('div.popupWrapper');
	var slideshowContent = wrapper.find('div.slideshowContent');

	container.find('a.popupLaunch').each(function() {
		
		$(this).click(function() {
			
			//if the element popoverBG already exists then the popover has already been set up so we can skip to just fading in the content.
			if($('div.popoverBG'+containerIndex).length == 0) {

				//make the slideshow background and prepend to the body element. Create one unique to the popupContainer so that each link fades in the correct container
				var slideshowBG = $('<div class="popoverBG popoverBG'+containerIndex+'"></div>');
				setHeight(slideshowBG);
				//attach the slideshow to the newly created background element
				slideshowBG.prepend(wrapper);
				//attach the background element to the body so that it can cover the entire page
				$('body').prepend(slideshowBG);

				//put in the close popover button
				wrapper.prepend('<a class="closePopover" href="#"><span class="hideContent">Close Slideshow</span></a>');
				closeLink($('a.closePopover'), $('div.popoverBG'+containerIndex));

				//if this is a slideshow rather than a video then we must initialise it
				if(slideshowContent.length > 0) {
					
					//initialise the slideshow
					wrapper.fadeIn('fast', function() {
						slideshowContent
						.after('<div class="counterControls"><a class="prev-alias" title="previous image" href="#">&lt;</a><div class="count"></div><a class="next-alias" href="#">&gt;</a></div>')
						.cycle({ 
								fx:		 'fade', 
								speed:	'fast', 
								timeout: 0,
						 	next: '.next',
							prev: '.prev',
							after: popoverOnAfter
						});
						//handle the double navigation
						mimicLinks($('a.prev'),$('a.prev-alias'));
						mimicLinks($('a.next'),$('a.next-alias'));
						
						//vertical position the element
						centreElement(wrapper);
					});

				}
				else {
					centreElement(wrapper);
					wrapper.fadeIn('fast');
				}

			}
			else if($('div.popoverBG'+containerIndex).length > 0) {
				//vertically position the element
				$('div.popoverBG'+containerIndex).fadeIn('fast');
				centreElement($('div.popoverBG'+containerIndex).find('div.popupWrapper'));
			}

			return false;
		});
		
	});

}

//Slide count function for home page center module slideshow
function popoverOnAfter(curr,next,opts) {
	var caption = (opts.currSlide + 1) + '/' + opts.slideCount;
	$('div.count').html(caption);
	
	var currentPopupObj = $('div.slideshowContent div.slideshowObject:eq('+opts.currSlide+')');
	var objHeight = currentPopupObj.height();
	$('div.slideshowContent').css('height',objHeight+'px');
}

/* grab the hidden slideshow div and on click of the link, initialise. Works for multiple popup elements (video and slideshow) on a page */
function setUpEventPopup(container) {
	
	var wrapper = container.find('div.popupWrapper');
	container.find('a.popupLaunch').each(function() {
		
		$(this).click(function() {
			
			//if the popover is showing, return false immediately
			if(container.css('position') == 'absolute') {
				return false;
			}
			
			//if the element popoverBG already exists then the popover has already been set up so we can skip to just fading in the content.
			if($('div.popoverBG').length == 0) {

				//make the slideshow background and prepend to the body element. Create one unique to the popupContainer so that each link fades in the correct container
				var slideshowBG = $('<div class="popoverBG eventPopoverBG"></div>');
				slideshowBG.css('z-index','1000');
				setHeight(slideshowBG);

				//attach the background element to the body so that it can cover the entire page
				$('body').prepend(slideshowBG);
				
				fadeInEventPopover(wrapper,container);

			}
			else {
				
				$('div.popoverBG').fadeIn('fast');
				fadeInEventPopover(wrapper,container);
			}

			return false;
		});
		
	});

}

//sets the height of a div to fill the entire window, whether that's document size or window size, whichever is greater
function setHeight(divToSize) {
	
	var docHeight = $(document).height();
	var winHeight = $(window).height();
	
	var height = (docHeight > winHeight) ? docHeight : winHeight;
	
	divToSize.css('height',parseFloat(height/10)+'em');
}

//the slideshow has two next and two previous buttons. jquery cycle only allows one of each. by triggering the click of the real one when the fake one is clicked we can 
//pretend this works normally.
function mimicLinks(linkToTrigger,clickedLink){
	//when clickedLink is clicked, trigger the other link
	clickedLink.click(function() {
		linkToTrigger.trigger('click');
		return false;
	});
	
}

//click one link and fade out a container 
function closeLink(link, container) {
	//fade out the slideshow when the close button is clicked.
	link.live('click', function() {
		container.fadeOut('fast');
		return false;
	})
}

//close event popover and reset it back to where it was
function closeEventPopover(container, elems) {
	var params = {
		active: container,
		fadeBg: $('div.eventPopoverBG')
	};
	
	for (i in elems) {
		// Fade out the slideshow when the close button is clicked.
		elems[i].live('click', params, _closeEventPopover);
	}
}

function _closeEventPopover (e) {
	e.data.fadeBg.fadeOut('fast');
	
	e.data.active
		.removeClass('visible')
		.find('a.closePopover')
			.css('display','none').end()
		.find('div.eventBody')
			.css('display','none').end()
		.parent()
			.removeClass('zHigher');
	
	return false;
}

//vertically center a div on the screen
function centreElement(element) {	
	element.css("top", (($(window).height() - element.outerHeight()) / 2) + $(window).scrollTop() + "px");
}

// the events bit is grim. we have to position the popover in the same place as the original static positioned item while making it position absolute without affecting any of the other 
// events listed.
function fadeInEventPopover(wrapper, container) {
	
	// if this is a new popover then put in the close popover button
	if(wrapper.find('a.closePopover').length == 0){
		wrapper.prepend('<a class="closePopover" href="#">close<span class="hideContent"> popover</span></a>');
		closeEventPopover(container, [$('a.closePopover'), $('div.eventPopoverBG')]);
	}

	var parent = container.closest('div.info-box');
	// to make sure the containers below do not suck up when this container goes position absolute (have to plus 1 as it wasn't working otherwise).
	var parentHeight = parent.height();

	// make the container position absolute
	container.addClass('visible');
	// add a z index on the parent cos IE7 doesn't work otherwise
	parent.addClass('zHigher');
	
	// give the parent a height so that it doesn't suck up
	parent.css('height',parseInt(parentHeight)+'px');
	
	//remove the overflow hidden from the article div two parents up
	container.closest('div.article').css('overflow','visible');
	
	wrapper.fadeIn('fast', function() {
		//show the close popover button
		wrapper.find('a.closePopover').css('display','block');
		
		//show the event body that's hidden when not popped over
		container.find('div.eventBody').css('display','block');
	});
}
