$(document).ready(function () {
	
	// plug-ins
	// -----------------------------------------------------
	// truncate
	jQuery.fn.truncate=function(max,settings){settings=jQuery.extend({chars:/\s/,trail:["...",""]},settings);var myResults={};var ie=$.browser.msie;function fixIE(o){if(ie){o.style.removeAttribute("filter")}}return this.each(function(){var $this=jQuery(this);var myStrOrig=$this.html().replace(/\r\n/gim,"");var myStr=myStrOrig;var myRegEx=/<\/?[^<>]*\/?>/gim;var myRegExArray;var myRegExHash={};var myResultsKey=$("*").index(this);while((myRegExArray=myRegEx.exec(myStr))!=null){myRegExHash[myRegExArray.index]=myRegExArray[0]}myStr=jQuery.trim(myStr.split(myRegEx).join(""));if(myStr.length>max){var c;while(max<myStr.length){c=myStr.charAt(max);if(c.match(settings.chars)){myStr=myStr.substring(0,max);break}max--}if(myStrOrig.search(myRegEx)!=-1){var endCap=0;for(eachEl in myRegExHash){myStr=[myStr.substring(0,eachEl),myRegExHash[eachEl],myStr.substring(eachEl,myStr.length)].join("");if(eachEl<myStr.length){endCap=myStr.length}}$this.html([myStr.substring(0,endCap),myStr.substring(endCap,myStr.length).replace(/<(\w+)[^>]*>.*<\/\1>/gim,"").replace(/<(br|hr|img|input)[^<>]*\/?>/gim,"")].join(""))}else{$this.html(myStr)}myResults[myResultsKey]=myStrOrig;$this.html(["<div class='truncate_less'>",$this.html(),settings.trail[0],"</div>"].join("")).find(".truncate_show",this).click(function(){if($this.find(".truncate_more").length==0){$this.append(["<div class='truncate_more' style='display: none;'>",myResults[myResultsKey],settings.trail[1],"</div>"].join("")).find(".truncate_hide").click(function(){$this.find(".truncate_more").css("background","#fff").fadeOut("normal",function(){$this.find(".truncate_less").css("background","#fff").fadeIn("normal",function(){fixIE(this);$(this).css("background","none")});fixIE(this)});return false})}$this.find(".truncate_less").fadeOut("normal",function(){$this.find(".truncate_more").fadeIn("normal",function(){fixIE(this)});fixIE(this)});jQuery(".truncate_show",$this).click(function(){$this.find(".truncate_less").css("background","#fff").fadeOut("normal",function(){$this.find(".truncate_more").css("background","#fff").fadeIn("normal",function(){fixIE(this);$(this).css("background","none")});fixIE(this)});return false});return false})}})};

	// language selector hover/click
	// -----------------------------------------------------
	$("#languageselector .inner").hover(
		function () {
			$(this).addClass('hover');
		},
		function () {
			$(this).removeClass('hover');
			$(this).removeClass('on');
		}
	);
	
	$("#languageselector .inner").click(function () {
		$(this).addClass('on');
	});
	
	// footer hover
	// -----------------------------------------------------
	pagefooter = {
		
		timeoutinterval: null,
		
		closeFooter: function() {
			// fire only if footer is not at it's default position
			if( $('#footer').css('height') != '34px' ) {
				$('#footer').animate({ height: "34px"}, {duration:500, queue:true, complete: function(){
					$('#footer').removeClass('showpromotions');
					$('#footer').removeClass('showsendtofriend');
					$('#footer .whackermoles').show(); // hack to hide whackamoles
				}});
			}
		},

		resetFooter: function() {
			$('#footer').removeClass('showpromotions');
			$('#footer').removeClass('showsendtofriend');
			$('#footer').css('height','30px');
		},

		openFooter: function(footerclass, footerheight) {
			// only open if not already open
			if( $('#footer').css('height') != '500px' ) {
				$("#footer").animate({ height: footerheight}, {duration:500, queue:false});
				$('#footer').addClass(footerclass);
			}
			$('#footer .whackermoles').hide(); // hack to hide whackamoles
		},

		initPromotions: function() {
			$("#footer .promotionsevents a").mouseover(function () {
				pagefooter.openFooter('showpromotions','151px');
			});
			
			$("#footer .flyoutpromotions li").hover(
				function () {
					$(this).find('.popoutimage').animate({top:'-104px'},{duration:500, queue:false, complete: function() {
						$(this).addClass('hover');
					}});
				},
				function () { // close footer
					$(this).find('.popoutimage').animate({top:'0'}, {duration:500, queue:false, complete: function() {
						$(this).removeClass('hover');
					}});
				}
			);
		},
		
		initTellafriend: function() {
			// click event on "tell a friend"
			$("#footer .tellafriend a").click(function () {
				if($('#footer').hasClass('showsendtofriend')) {
					pagefooter.closeFooter();
				} else {
					pagefooter.resetFooter();
					pagefooter.openFooter('showsendtofriend','151px');
				}
				/*pagefooter.resetFooter();
				pagefooter.openFooter('showsendtofriend','151px');
				return false;*/
			});
			// validate for email on submission
			$(".flyoutsendtofriend form").submit(function () {
				// Check for name (but not essential for submission)
				/*if($(".flyoutsendtofriend form #friendsname").val().length > 0){
					$(".flyoutsendtofriend form #friendsname").removeClass("error");
				}else{
					$(".flyoutsendtofriend form #friendsname").addClass("error");
				}*/
				
				var currentURL = window.location.href;
				$('input#url').val(currentURL);
				
				// Check email
				if($(".flyoutsendtofriend form #friendsname").val().match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)){
					$(".flyoutsendtofriend form #friendsname").removeClass("error");
					return true;
				}else{
					$(".flyoutsendtofriend form #friendsname").addClass("error");
					return false;
				}
			});
		},
		
		init: function() {
			$("#footer").hover(
				function () { // open footer
					clearInterval(pagefooter.timeoutinterval);
				},
				function () { // close footer
					pagefooter.timeoutinterval = setTimeout(pagefooter.closeFooter,1000);
					//pagefooter.closeFooter();
				}
			);
		}

	};
	
	//pagefooter.init();
	//pagefooter.initTellafriend();

	// age verification form validation
	// -----------------------------------------------------
	// see old.js, this also contains code for showing/hiding the verification.
	
	// navigation
	// -----------------------------------------------------
	navigationSidebar = {
		
		// varibles
		$toplevelitems: $('#navigation ul.toplevel li.toplevel'),
		
		// methods
		bindCloseNav: function() {
			$(navigationSidebar.$toplevelitems).children('a').unbind();
			$(navigationSidebar.$toplevelitems).children('a').click( function() {
				navigationSidebar.topnavClose(this);
			});
		},
		
		bindOpenNav: function() {
			$(navigationSidebar.$toplevelitems).find('.secondlevel .close').click( function() {
				navigationSidebar.topnavOpen(this);
			});
		},
		
		topnavClose: function(whichnav, force) {
			navigationSidebar.$toplevelitems.children('.currentpage').hide();
			for (var i = 0; i < navigationSidebar.$toplevelitems.length; i++) {
				width = $(navigationSidebar.$toplevelitems[i]).width()-18;
				distance = width - width * 2 + 35;
				if(force){
					$(navigationSidebar.$toplevelitems[i]).css("left", distance);
				}else{
					// IE doesn't like the movement on top of the flash
					if($.browser.msie) {
						$(navigationSidebar.$toplevelitems[i]).css("left", distance);
					} else {
						$(navigationSidebar.$toplevelitems[i]).animate({ 
							left: distance
						}, 300, false);
					}
				}
			}
			
			navigationSidebar.subnavShow(whichnav, force);
			$(whichnav).children('.secondlevel').addClass('active');
			navigationSidebar.bindOpenNav();
		},
		
		topnavOpen: function(whichnav) {
			//navigationSidebar.$toplevelitems.children('.currentpage').show();
			for (var i = 0; i < navigationSidebar.$toplevelitems.length; i++) {
				distance = 0;
				if($.browser.msie) {
					$(navigationSidebar.$toplevelitems[i]).css("left", distance);
				} else {
					$(navigationSidebar.$toplevelitems[i]).animate({
						left: distance
					}, 300, false);
				}
			}

			navigationSidebar.subnavHide(whichnav);
			$(whichnav).children('.secondlevel').removeClass('active');
		},
		
		subnavShow: function(whichnav, force) {
			navigationSidebar.subnavHide(whichnav);
			$(whichnav).addClass('on');
			if(force)
				$(whichnav).nextAll('.secondlevel').show();
			else
				$(whichnav).nextAll('.secondlevel').show();
		},
		
		subnavHide: function(whichnav) {
			navigationSidebar.$toplevelitems.children('a.on').removeClass('on');
			navigationSidebar.$toplevelitems.children('.secondlevel').hide();
		},
		
		init: function() {
			navigationSidebar.bindCloseNav();
			navigationSidebar.topnavClose($('#navigation ul.toplevel > li.selected').children('a'), true);
		}
		
	};
	
	navigationSidebar.init();

	// gallery sliders
	// -----------------------------------------------------
	gallerySlider = {
		
		// ignore
		index: 0,
		total: 0,
		
		// set this
		imagesize: 297,
		
		init: function(galleryid) {
			
			// bind control arrows
			$('#' + galleryid  + ' .controls a.previous').click( function() {
				gallerySlider.next(galleryid);
				return false;
			});
			
			$('#' + galleryid  + ' .controls a.next').click( function() {
				gallerySlider.previous(galleryid);
				return false;
			});
			
			// get total count of objects
			total = $('#' + galleryid + ' .items ul li').length;
			total=-total;
			
			// hide arrows
			this.incrementindex(0, galleryid);
			
		},
		
		next: function(galleryid) {
			this.incrementindex(1, galleryid);
			$('#' + galleryid  + ' .items ul').animate({
				marginLeft: this.index * this.imagesize + 'px'
			}, 500);
		},
		
		previous: function(galleryid) {
			this.incrementindex(-1, galleryid);
			$('#' + galleryid  + ' .items ul').animate({
				marginLeft: this.index * this.imagesize + 'px'
			}, 500);
		},
		
		hidearrow: function(galleryid, arrow) {
			$('#' + galleryid  + ' .controls a.' + arrow).fadeOut('500');
		},
		
		showarrow: function(galleryid, arrow) {
			$('#' + galleryid  + ' .controls a.' + arrow).fadeIn('500');
		},
		
		updatecounter: function(galleryid) {
			humanindex = this.index - 1;
			$('#' + galleryid  + ' .count').html(-humanindex + '/' + -total);
		},
		
		incrementindex: function(amount, galleryid) {
			
			// increment counter
			this.index += amount;
			
			// counter bound checking, show/hide arrows
			if( this.index <= total+1) {
				this.index = total+1;
				this.hidearrow(galleryid, 'next');
			} else if ( this.index >= 0 ) {
				this.index = 0;
				this.hidearrow(galleryid, 'previous');
			} else {
				this.showarrow(galleryid, 'next');
				this.showarrow(galleryid, 'previous');
			}
			
			this.updatecounter(galleryid);
			
		}
		
	};

	// promotions page animations
	// -----------------------------------------------------
	promotions = {
		
		$promos: new Object(),
		
		init: function(promoid) {

			this.$promos = $('#'+promoid);
			
			this.$promos.find('li').click( function() {
				window.location = $(this).find('h4 a').attr('href');
			});
			
			// hide any items with empty h4s
			var lis = this.$promos.contents().find('li')
			for(var i = 0; i < lis.length; i++) {
				var h4 = $("h4", lis[i]);
				// is h4 empty?
				if(!h4.text().match(/[a-z]./)) {
					h4.parent().parent().hide();
				}
			}
			
			// bind hover on items
			this.$promos.contents().find('li:visible').hover(function() {
				$(this).animate({ 'background-color': '#000000', top: '52px' }, { duration: 500, queue: false }).addClass('hover');
				$(this).children(".thumbnail").animate({ height: '105px' }, { duration: 500, queue: false });
			}, function() {
				$(this).animate({ 'background-color': "#ffffff", top:'0px' }, { duration: 500, queue: false }).removeClass('hover');
				$(this).children(".thumbnail").animate( { height: '0px' }, { duration: 500, queue: false });
			});
			
			//unbind the first item as it's used for instructions
			//this.$promos.contents().find('li').eq(0).unbind().css({cursor:'auto'});
			
		}
	};
	
	// homepage whackamoles
	// -----------------------------------------------------
	whackamole = {
		
		// moves the whackamole
		move: function($moleid, $container) {
			var distance = -124;
			//var speed = Math.floor((1000-499)*Math.random()) + 499; /* random: 500 - 1000 */
			var speed = 700;
			$moleid.animate({ top: distance + 'px' }, speed).animate({ opacity: 1 }, 2500).animate({ top: 0 }, speed, function() { whackamole.pick($container) });
		},
		
		// picks a random whackamole to move
		pick: function($container) {
			randomcontainer = Math.random()*6;
			this.move($container.children().eq(randomcontainer),$container);
		}
		
	};

	// our story scroller
	// -----------------------------------------------------
	storyscroller = {
		
		//constants
		previewPaneHeight: 142,
		lineItemHeight: 51,
		
		// index
		index: 0,
		indexmax: 0,
		
		// useful objects
		$scroller: new Object(),
		$controlPrevious: new Object(),
		$controlNext: new Object(),
		$itemList: new Object(),
		$previewBox: new Object(),
		$previewSlider: new Object(),
		$instructions: new Object(),
		
		init: function(id, style) {
			
			// set useful objects
			$scroller = $('#'+id); // scroller itself
			$controlPrevious = $scroller.find('.previewitem .controlprevious'); // next button
			$controlNext = $scroller.find('.previewitem .controlnext'); // previous button
			$itemList = $scroller.find('.previewlist ul');
			$previewBox = $scroller.find('.previewitem');
			$previewSlider = $scroller.find('.previewitem ul');
			$instructions = $scroller.find('.previewlist .instructions');
			
			// get element sizes
			//storyscroller.lineItemHeight = $itemList.children('li').outerHeight({margin:true});
			//alert(storyscroller.lineItemHeight);
			
			// hide any items with empty h4s
			var lis = $itemList.children('li');
			for(var i = 0; i < lis.length; i++) {
				var h2 = $("h2", lis[i]);
				// is h2 empty?
				if(!h2.text().match(/[a-z]./)) {
					h2.parent().parent().remove();
				}
			}
			
			// build preview item list
			this.buildPreviewList(style);
			
			// set indexmax
			this.indexmax = $itemList.children('li:visible').length;
			
			// hide arrow
			storyscroller.incrementindex(0);
			
			// bind controllers
			$controlPrevious.click(storyscroller.previous);
			$controlNext.click(storyscroller.next);
			
			// bind jumpto links
			this.bindJumpTo();
			
		},
		
		buildPreviewList: function(style) {
			// import items from previewlist and build previewitems
			$scroller.find('.previewitem').show();
			
			var html = "";
			
			/* 
				the previw list is used in multiple places now, this switch selects the approiate HTML build
				truncating the content also takes place after the HTML has been written out.
			*/
			
			
			switch (style) {
				case 'storiesintro':
					$itemList.children().each( function () {
						var link = $(this).find('.header h2').html();
						var more = $(this).find('.header p.more').html();
						var imageFull = $(this).find('.imagefull').html();
						var content = $(this).find('.content').html();

						html += "<li>\
									<div class=\"link\">\
										" + link + "\
									</div>\
									<div class=\"preview\">\
										" + imageFull + "\
									</div>\
									<div class=\"details\">\
										<h2>" + link + "</h2>\
										" + content + "\
										<p class=\"more\">" + more + "</p>\
									</div>\
								</li>"
					});
					// output html
					$previewSlider.html(html);
					$previewSlider.find('.details p').truncate(210);
				break;
				case 'storiesdetail':
					$itemList.children().each( function () {

						var link = $(this).find('.header h2').html();
						var more = $(this).find('.header p.more').html();
						var imageFull = $(this).find('.imagefull').html();
						var content = $(this).find('.content').html();

						html += "<li>\
									<div class=\"link\">\
										" + link + "\
									</div>\
									<div class=\"preview\">\
										" + imageFull + "\
									</div>\
									<div class=\"details\">\
										<h2>" + link + "</h2>\
										" + content + "\
										<p class=\"more\">" + more + "</p>\
									</div>\
								</li>"
					});
					// output html
					$previewSlider.html(html);
					$previewSlider.find('.details p').truncate(210);
				break;
				case 'faq':
					$itemList.children().each( function () {
						if($(this).find('.header h2').text().match(/[a-z]./)) {
							var headerH2 = $(this).find('.header h2').html();
							var header = $(this).find('.header').html();
							var content = $(this).find('.content').html();

							html += "<li>\
										<div class=\"link\">\
											" + headerH2 + "\
										</div>\
										<div class=\"details\">\
											" + header + "\
											" + content + "\
										</div>\
									</li>"
						}
					});
					// output html
					$previewSlider.html(html);
					$previewSlider.find('.details p').truncate(300);
				break;
			}
		},
		
		previous: function() {
			storyscroller.incrementindex(-1);
			return false;
		},
		
		next: function() {
			storyscroller.incrementindex(1);
			return false;
		},
		
		animatePreview: function() {
			positionPreview = this.index * -this.previewPaneHeight;
			positionList = this.index * -this.lineItemHeight;
			
			/* show/hide instructions based on index */
			if( this.index > 0 ) {
				$instructions.fadeOut('500');
			}
			
			$previewSlider.animate({top:positionPreview}, {duration:500});
			$itemList.animate({top:positionList}, {duration:500});
			
			// set classes on current/next elements
			$itemList.children().removeClass('next');
			$itemList.children().eq(storyscroller.index+1).addClass('next');
			$itemList.children().removeClass('current');
			$itemList.children().eq(storyscroller.index).addClass('current');
			
			if( !this.index > 0 ) {
				$instructions.fadeIn('500');
			}
			
		},
		
		incrementindex: function(amount, directjump) {
			
			// are we directly jumping to an item or just incrementing the index?
			if(directjump) {
				this.index=amount;
			} else {
				this.index += amount;
			}
			
			// counter bound checking, show/hide arrows
			if( this.index <= 0 ) {
				this.index = 0;
				$controlPrevious.fadeOut('500');
				$controlNext.fadeIn('500');
			} else if ( this.index >= this.indexmax-1) {
				this.index = this.indexmax-1;
				$controlPrevious.fadeIn('500');
				$controlNext.fadeOut('500');
			} else {
				$controlPrevious.fadeIn('500');
				$controlNext.fadeIn('500');
			}
			
			storyscroller.animatePreview();
			
		},
		
		bindJumpTo: function() {
			// loop through items and bind a click even equal to the position they are in the stack.
			$itemList.children().each( function (i) {
				$(this).find('h2').click( function() {
					storyscroller.incrementindex(i, true);
					return false;
				});
			});
		}

	};
	
	
	clearPastNews = {
		// Hide unused elements on news & event listings
		hidePastEvents: function(){
			pastEvents = $('.pastevents h2');
			if(!pastEvents.text().match(/[a-z]./)) {
			    $('div.pastevents').hide();
			}
		}
	};
	// Init function
	clearPastNews.hidePastEvents();
});