
$(document).ready(function() {
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Generic link highlighting - uses the pagePath array pumped out by the footer element.
	// runs in reverse order, and once it has found a matching link will break out of the loop (gets around child pages where necessary)
	var highlightNavs = function(els) {
		// select the passed group of elements
		var myGroup = $(els);
		// for each link in the passed group:
		for (var i = (myGroup.length-1); i >= 0; i--) {
			// get the href
			var linkStr = String($(myGroup[i]).attr('href'));
			// test for an element link: &element=blah - if true then do a different test based on window location(?)
			if (linkStr.indexOf('element=') != -1) {
				// the "catch all" safety highlight is true unless a link is found
				var catchAll = true;
				var elFlag = false;
				var loc = String(window.location);
				// if there's an element=1234 match then set highlight, and flag up to break out of the loop
				if (loc.indexOf(linkStr) != -1) {
					$(myGroup[i]).addClass('selected');
					// set the elFlag to true for outer for loop
					elFlag = true;
					// kill off the catch all variable, so no default item is highlighted
					catchAll = false;
				}
			} else {
				// loop through the pagePath array backwards too
				for (var c = (pagePath.length-1); c >= 0; c--) {
					if (linkStr.indexOf(pagePath[c]) != -1) {
						$(myGroup[i]).addClass('selected');
						// set break flag for outer for loop
						var breakFlag = true;
						// break out of this local for loop
						break;
					}
				}
			}
			// if we've found anything in either scenario, break out of this loop
			if (breakFlag == true || elFlag == true) {
				break;	
			}
		}
		// catch all: if at the end of the full loop nothing is selected, then add .selected to the first item:
		if (catchAll == true) {
			$(myGroup[0]).addClass('selected');
		}
	}
	if (typeof(pagePath) != 'undefined') {
		highlightNavs('#top_menu li a');
		highlightNavs('#subnavigation li a');
		highlightNavs('#tertiary_nav ul li a');
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Top nav logo "fade" rollover
	$('#logotype')
		.hover(function() {
			$(this)
				.stop()
				.animate({ 'opacity' : 0.6 }, 300, 'easeOutQuad');	// easing plugin
		}, function() {
			$(this)
				.stop()
				.animate({ 'opacity' : 1 }, 300, 'easeOutQuad');	// easing plugin
		});
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Inner bits AND them but not me rollovers - applied to all .vis_link items in a page (ie homepage, showcase)
	
	$('li.vis_link a').each(function(i) {
		// get heights etc for each item
		this.myHeight = $(this).parent().outerHeight();	// dimensions plugin dependency
		this.inPos = this.myHeight - $(this).children('span.link_panel').children('strong').outerHeight();
		this.outPos = this.myHeight - $(this).children('span.link_panel').outerHeight();
		// reposition link text elements at bottom (part overflowing)
		$(this).children('span.link_panel').css({
			'position' : 'absolute',
			'top' : this.inPos + 'px'
		});
		$(this)
			/*.hover(function() {
				$(this).parent().addClass('focal');
				$('li.vis_link:not(.focal)')
					.stop()
					.animate({ 'opacity' : 0.6 }, 300, 'easeOutQuad');	// easing plugin
				var $outPos = this.outPos;
				$(this).children('span.link_panel')
					.stop()
					.animate({ 'top' : $outPos + 'px' }, 300, 'easeOutQuad');	// easing plugin
			}, function() {
				$('li.vis_link:not(.focal)')
					.stop()
					.animate({ 'opacity' : 1 }, 300, 'easeOutQuad');	// easing plugin
				$(this).parent().removeClass('focal');
				var $inPos = this.inPos;
				$(this).children('span.link_panel')
					.stop()
					.animate({ 'top' : $inPos + 'px' }, 300, 'easeOutQuad');	// easing plugin
			})*/
			/* keyboard access binding */
			.bind("mouseenter focus", function() {
				$(this).parent().addClass('focal');
				$('li.vis_link:not(.focal)')
					.stop()
					.animate({ 'opacity' : 0.6 }, 300, 'easeOutQuad');	// easing plugin
				var $outPos = this.outPos;
				$(this).children('span.link_panel')
					.stop()
					.animate({ 'top' : $outPos + 'px' }, 300, 'easeOutQuad');	// easing plugin
			})
			.bind("mouseleave blur", function() {
				$('li.vis_link:not(.focal)')
					.stop()
					.animate({ 'opacity' : 1 }, 300, 'easeOutQuad');	// easing plugin
				$(this).parent().removeClass('focal');
				var $inPos = this.inPos;
				$(this).children('span.link_panel')
					.stop()
					.animate({ 'top' : $inPos + 'px' }, 300, 'easeOutQuad');	// easing plugin
			})
		});
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// them but not me rollovers - applied to "puff link" and event/date listing items
	$('div.event_listing li a, li.puff_link a, #home_events_feed li a, div.date_listing li a').each(function(i) {
		$(this)
			// store the parent div (avoids multiple instance of .puff_links all fading in and out)
			.data('target', $(this).parent().parent().parent())
			.hover(function() {
				$(this).parent().addClass('focal');
				$(this).data('target').find('li:not(.focal)')
					.stop()
					.animate({ 'opacity' : 0.6 }, 300, 'easeOutQuad');	// easing plugin example
			}, function() {
				$(this).data('target').find('li:not(.focal)')
					.stop()
					.animate({ 'opacity' : 1 }, 300, 'easeOutQuad');	// easing plugin example
				$(this).parent().removeClass('focal');
			})
		});
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// slide out menu functions for #context_nav
	// toggling func for title rollover
	var rollToggle = function(dir) {
		if (dir == 'off') {
			$('#context_nav h4').unbind();
		} else {
			$('#context_nav h4').hover(function() {
					$(this).css({ backgroundPosition : "-196px 0" });
				}, function() {
					$(this).css({ backgroundPosition : "0 0" });
				});
		}
	}
	rollToggle('on');
	// immediately hide the ul menu
	$('#context_nav ul').hide();
	$('#context_nav ul').css({ opacity : '0.95' });
	$('#context_nav')
		// set to new position
		.removeClass('context_inactive')
		.addClass('context_active')
		.click(function() {
			// on click, remove the header rollover
			rollToggle('off');
			// bind a mouseleave event for the overall div:
			$(this).bind('mouseleave', function() {
				// on "leave", kill the leave event, slide back up, reset header to rollover
				$(this).unbind('mouseleave');
				$('#context_nav ul').slideUp('fast');
				$('#context_nav h4').css({ backgroundPosition : "0 0" });
				rollToggle('on');
			});
			// in the click event, slide out the menu, set the header to a "selected" position
			$('#context_nav ul').slideDown('fast');
			$('#context_nav h4').css({ backgroundPosition : "-196px 0" });
		});
		
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Scrolling items
	
	// this setting allows px to em conversion (it's the base body font-size)
	var globalFontSize = 12;
	
	// set up a scroll container - set container div height and add "+ -" buttons
	var setScrollContainer = function($el, num) {
		// TEST FIRST: if there are more <li> elements than "num" then continue, otherwise there is no effect
		if ($el.find('li').length > num) {
			// get the "overflow" div
			var $overflowEl = $el.children('div.overflow');
			// now get the height of 'visLength' scroller items (these are always LI elements):
			var elHeight = $el.find('li').outerHeight({ margin : true });
			// set the overflow div height to "num" * elHeight - ie "3 times 176"
			var overFlowHeight = elHeight * num;
			// set the overflow div height to overFlowHeight converted to EMS, and set overflow to hidden.
			$overflowEl.css({
				//height : overFlowHeight.pxToEm({ scope : convertScope }),
				height : (overFlowHeight / globalFontSize) + 'em',
				position : 'relative',
				top : '0',
				left : '0',
				overflow : 'hidden'
			}).data('storage', {
				count : 0,	// store a current item count in div.overflow
				visLength : num	// store the visible length too
			});
			// now set appropriate css for the child UL or OL:
			$overflowEl.children('ul, ol').css({
				position : 'absolute',
				top : '0',
				left : '0'
			});
			// insert "+" and "-" buttons:
			var navEl = $('<ul class="scroll_btns"><li class="plus_btn" title="Scroll up">Next</li><li class="minus_btn" title="Scroll down">Previous</li></ul>');
			$el.prepend(navEl);
			// add rollover behaviours to these buttons
			$el.find('ul.scroll_btns li').hover(function() {
				$(this).css({ backgroundPosition : 'bottom left' });
			}, function() {
				$(this).css({ backgroundPosition : 'top left' });
			});
			// add click behaviours to these buttons
			$el.find('ul.scroll_btns li.plus_btn').click(function() {
				doScroll('inc', $(this));
			});
			$el.find('ul.scroll_btns li.minus_btn').click(function() {
				doScroll('dec', $(this));
			});
		}
	}
	
	// function for scrolling buttons, pass in direction, and the specific div.overflow to act upon
	var doScroll = function(dir, $buttonEl) {
		// get to the div.overflow based on the caller button:
		var $overflowEl = $buttonEl.parent().parent().children('div.overflow')
		// extract the overflow div's current index and either increase or decrease it:
		var cur = $overflowEl.data('storage').count;
		// the limit is the number of <li> items present minus the visible length:
		var limit = ($overflowEl.find('li').length) - $overflowEl.data('storage').visLength;
		if ((dir == 'inc') && (cur < limit)) {
			$overflowEl.data('storage').count++;
		} else if ((dir == 'dec') && (cur > 0)) {
			$overflowEl.data('storage').count--;
		}
		animateScroll($overflowEl);
	}
	
	// just the animation here - get the amount needed to scroll: get the <li> offset relative to div.overflow, then animate from there
	var animateScroll = function($overflowEl) {
		// get the POSITION of the <li> with an index of "count" relative to the container
		var index = $overflowEl.data('storage').count
		var $item = $overflowEl.find('li').eq(index);
		var amount = $item.position().top;
		// get the current "top" value of the containing <ul> or <ol> (this is what moves)
		var $mover = $overflowEl.find('ul, ol');
		var targVal = 0 - amount;
		$mover.animate({ 'top' : targVal }, 400, 'easeOutQuad', function() {
			// test count, then grey out (or bring back in) appropriate buttons
		});
	}
	
	// to start off the scroll setup, first test that there are more elements than the default window (also acts as an existence test)
	//setScrollContainer($('.event_listing'), 4);
	setScrollContainer($('.puff_links'), 2);
	//setScrollContainer($('.article_listing'), 4);
	//setScrollContainer($('.news_listing'), 3);
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// set up "lh col" and internal links for each person panel
	$('.people_spotlight').each(function(i) {
		// If there are more than 1:
		if ($(this).find('div.overflow li.person').length > 1) {
			// append a "next" link to each "person" EXCEPT the last one - this will let a user go "next" through the "spotlight on" column (additional to "+" and "-" buttons)
			/*var linkStr = '<div class="puff_link"><a href="#"><span>Meet the next person</span></a></div>';
			$(this).find('li.person:not(:last)').append(linkStr);
			// set up each persons "next" link (will simply fire the "+" button's event handler function)
			$(this).find('li.person div.puff_link a').click(function() {
				$(this).parents('.people_spotlight').find('ul.scroll_btns li.plus_btn').trigger('click');
				return false;
			});*/
			// next set up the list of people that appears in the main content area - each link acts as a scroll call
			var htmlStr = '<ul class="people_links">';
			$(this).find('div.overflow li.person').each(function() {
				htmlStr += '<li><a href="#">' + $(this).find('h4').text() + '</a></li>';
			});
			htmlStr += '</ul>';
			// append this to the first div.wys:
			$('div.wys:first').append(htmlStr);
			// this bit allows the people links to scroll x times - ie from the first to the fifth (Who we are)
			$('ul.people_links li a').each(function(i) {
				$(this)
					.attr('id', i)
					.click(function() {
						var $overflowEl = $('.people_spotlight div.overflow');
						$overflowEl.data('storage').count = Number($(this).attr('id'));
						animateScroll($overflowEl);
						return false;
					});									  
			});
		}
	});
	setScrollContainer($('.people_spotlight'), 1);
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// target an oveflow element and toggle it to show / hide all items:
	/*var showAll = function($overflowEl, dir) {
		// if showing, get the height of the scrolling <ul>
		if (dir == 'show') {
			var elHeight = $overflowEl.find('ul').outerHeight({ margin : true });
			elHeight = elHeight / globalFontSize;
		} else {
		// if hiding, get the height of an <li> and * it by the visible length, already stored in the div.overflow
			var elHeight = $overflowEl.find('li').outerHeight({ margin : true });
			elHeight = (elHeight * $overflowEl.data('storage').visLength) / globalFontSize;
		}
		// animate the overflow div to full height. On callback, if not currently at 0 in the list, reset the list
		$overflowEl.animate({ 'height' : elHeight + 'em' }, 800, 'easeOutQuad', function() {
			$overflowEl.css({ overflow : 'hidden' });	// reinforce this, Safari req
			if ($overflowEl.data('storage').count > 0) {
				$overflowEl.data('storage').count = 0;
				animateScroll($overflowEl);
			}
		});
	}
	// append this toggling behaviour to any button with a class of .reveal
	$('.reveal').toggle(function() {
		$(this).text('Collapse list');
		$(this).parent().find('ul.scroll_btns').fadeOut('slow');
		showAll($(this).parent().find('div.overflow'), 'show');
	}, function() {
		$(this).text('Show all');
		$(this).parent().find('ul.scroll_btns').fadeIn('slow');
		showAll($(this).parent().find('div.overflow'), 'hide');
	});*/
	
});