// add class js for browsers that support the DOM
if (document.getElementById&&document.getElementsByTagName) document.documentElement.className = "js";

$(function() {
	// catch external links and open in new window/tab
	$("a.external").click(function() {
		//alert($(this).attr('href'));
		window.open($(this).attr('href'));
		return false;
	});
	
	// initialise swapPanels
	if ($("#panels").length != 0) {
		swapPanels.init();
	}
	
	// initialise overlays
	$(document).ready(function() {
		if ($("#overlays").length != 0) {
			$('#overlays').appendTo('#main');
			$(".ol-link").overlay(
				{
					effect: 'apple',
					speed: 200,
					expose: {
						color:"#333333",
						loadSpeed: 200,
						opacity: 0.6
					},
					onLoad: function(event) {
						// sending this as 'About overlays' for now. Will need a check for page url once we use overlays on multiple pages
						trackEvent('About overlays','select',this.getOverlay().attr('id')); // sending the id of the overlay
					}
				}
			);
		}
	});

	
	// -----------------
	//  Recommendations
	// -----------------

	$('.recommendations .items').shuffle();
	$('.recommendations .items .item').append('<a class="next more">Next</a>');
	$('.recommendations .items').cycle({ 
		fx:		'fade',
		speed:	600,
		timeout:	20000,
		delay:	2000,
		next:		'.recommendations .next',
		pause:	1,
		prevNextClick: function(isNext, zeroBasedSlideIndex, slideElement) {
			trackEvent('Recommendations','next');
		}
	});
	
	
	// ---------- 
	//  Carousel
	// ----------
	
	Carousel = {
		currentItem: 3,
		itemCount: 0,
		shortNames: [],
		showItem: function(idx) {
			var currentMediaPanel = $("#mediapanels .mediapanel:nth-child("+this.currentItem+")");
			var newMediaPanel = $("#mediapanels .mediapanel:nth-child("+idx+")");
			if (currentMediaPanel.hasClass("video") && $f(currentMediaPanel[0])) {
				$f(currentMediaPanel[0]).stop();
				$f(currentMediaPanel[0]).unload();
			}
			currentMediaPanel.hide();
			this.currentItem = idx - 0;
			newMediaPanel.show();
			$("#contentpanels .panel").hide();
			$("#contentpanels .panel:nth-child("+idx+")").show();
			var title = $("#contentpanels .panel:nth-child("+idx+") h2").text();
			trackEvent('Carousel','show',title);
		},
		scrollToContent: function() {
			$.scrollTo("#content" , 400, {easing: 'swing'});
		},
		init: function(selectedItem) {
			var content = $('#content');
			
			var blocks = $('#blocks');
			var blocksMpanels = blocks.find('.mediapanel');
			var blocksPanels = blocks.find('.panel');
			
			Carousel.itemCount = blocksMpanels.length;
			
			// build array of shortnames for all blocks
			var allBlocks = blocks.find('.block');
			
			for (i=0; i<allBlocks.length; i++) {
				id = $(allBlocks[i]).attr('id');
				this.shortNames[id] = i;
			}
			
			var mPanels = $('<div></div>').attr({id:'mediapanels'});
			blocksMpanels.clone().hide().appendTo(mPanels);
			$("#blocks").before(mPanels);

			var carousel = $('<div></div>').attr({'class':'carousel'});
			$('<a class="arrow prev"></a>').appendTo(carousel);
			var scrollable = $('<div></div>').attr({'class':'scrollable'});
			scrollable.appendTo(carousel);
			var scrItems = $('<ul></ul>').attr({'class':'items'}).appendTo(scrollable);
			$('<a class="arrow next"></a>').appendTo(carousel);			
			
			for (i=0; i<blocksMpanels.length; i++) {
				var li = $('<li></li>').attr({'rel': 'it'+(i+1)});
				li.appendTo(scrItems);
				var tnail = $(blocksMpanels[i]).find('img').clone().attr({width:135,height:76});
				// use thumbnail image for carousel
				tnailSrc = tnail.attr('src', function(i,src) {
				  return src.replace(/.jpg/,'_tn.jpg');
				});
				tnail.appendTo(li);
			}
			$("#blocks").before(carousel);

			var contentPanels = $('<div></div>').attr({id:'contentpanels'});

			blocksPanels.appendTo(contentPanels);
			$("#blocks").before(contentPanels);

			blocks.remove(); // remove non-js version
			
			$(".scrollable").scrollable({
				size: 4,
				clickable: true,
				loop: true,
				indexed: true,
				keyboard: false
			}).circular();
			this.scrollable = $(".scrollable").scrollable();

			// check if an item was selected via url and set current item accordingly
			if (selectedItem) {
				var idx = this.shortNames[selectedItem];
				if (idx != undefined) this.currentItem = idx+1;
			}

			this.scrollable.click(this.currentItem-1);
			this.showItem(this.currentItem);


			// clicked on an item in the carousel
			$(".items li").click(function(e) {
				//Carousel.scrollToContent();
				var liEl = $(e.currentTarget);
				var idx = liEl.attr('rel').substr(2);
				Carousel.showItem(idx);
			});

			// clicked on 'previous' arrow
			$(".arrow.prev").click(function() {
				//Carousel.scrollToContent();
				var gotoItem = (Carousel.currentItem == 1)?Carousel.itemCount:(Carousel.currentItem-1);
				$("li[rel='it"+Carousel.currentItem+"']").removeClass('active');
				$("li[rel='it"+gotoItem+"']").addClass('active');
				Carousel.showItem(gotoItem);
			});

			// clicked on 'next' arrow
			$(".arrow.next").click(function() {
				//Carousel.scrollToContent();
				var gotoItem = (Carousel.currentItem == Carousel.itemCount)?1:(Carousel.currentItem+1);
				$("li[rel='it"+Carousel.currentItem+"']").removeClass('active');
				$("li[rel='it"+gotoItem+"']").addClass('active');
				Carousel.showItem(gotoItem);
			});
		}
	};
	
	if ($("#blocks").length != 0) {
		// get selected item from url
		var url = window.location.hash;
		var selectedItem = url.split('#')[1];
		
		// initialise the carousel
		Carousel.init(selectedItem);
	}
	
	
	// -----------
	//  Slideshows
	// -----------

	$('.slides').append('<div class="nav prev"></div><div class="nav next"></div>');
	$('.slides .items').cycle({ 
		fx:		'fade',
		speed:	700,
		timeout:	6000,
		delay:	1000,
		next:		'.slides .nav.next',
		prev:		'.slides .nav.prev',
		pause:	0
	});
	$('.slides').mouseenter(function(e) {
		$('.slides .nav').fadeIn(200);
		$('.slides .items').cycle('pause');
	});
	$('.slides').mouseleave(function(e) {
		$('.slides .nav').fadeOut(200);
		$('.slides .items').cycle('resume');
	});

	
	
	// Flash video embed
	if (flashembed.getVersion()[0] >= 9) {
		var videos = $(".video");
		for (i=0; i<videos.length; i++) {
			var vidId = videos[i];
			var vidUrl = $(videos[i]).find('a')[0].href;
			var vidWidth = 514;
			if (vidUrl.match(/4x3/)) {
				vidWidth = 400;
			}
			

			$f(vidId, '/js/flowplayer/flowplayer-3.1.5.swf', {
				width: '80%',
				clip: {
					width: vidWidth,
					height: 288,
					autoPlay: true,
					autoBuffering: true,
					accelerated: true,
					/*provider: 'lighttpd'*/
					url: vidUrl
				},
				onLoad : function() {
					var url = this.getClip(0).url;
					var idx = url.indexOf('/video/');
					var url2 = url.substr(idx); // remove server name etc. from url
					trackEvent('Video player','play',url2); // for now this is set to default to video. Will require custom function when we add support for audio
				},
				plugins: {
					/*lighttpd: { 
						url: 'js/flowplayer/flowplayer.pseudostreaming-3.1.3.swf', 
						queryString: escape('?target=${start}') 
					},*/
					controls: {
						url: '/js/flowplayer/flowplayer.controls-3.1.5.swf',
						fullscreen: false,
						autoHide: 'always',
						hideDelay: 1000,
						backgroundColor: '#205025',
						durationColor: '#ffffff',
						timeColor: '#66bb66',
						progressColor: '#888888',
						progressGradient: 'low',
						bufferColor: '#555555',
						bufferGradient: 'low',
						sliderColor: '#000000',
						sliderGradient: 'low',
						buttonColor: '#99aa99',
						buttonOverColor: '#337744',
						volumeSliderColor: '#000000',
						volumeSliderGradient: 'none',
						timeBgColor: '#224422',
						tooltips: {
							buttons: true
						}
					}
				}
			});								
		}
	};
});

var swapPanels = {
	current: 3,
	init: function() {
		var panels = $("#panel-nav");
		var li = panels.find('li');
		// set this to a constant value (3) above - this.current = Math.floor(Math.random() * li.length+1);
		$(li[this.current - 1]).addClass('on');
		this.showPanel(this.current);
		var links = panels.find("a");
		links.click(swapPanels.selectPanel);
	},
	selectPanel: function() {
		var link = $(this);
		var li = link.parent();
		if (li.hasClass('on')) return false;
		li.parent().children().removeClass('on');
		li.addClass('on');
		var panelNo = link.attr('href').split('#panel')[1];
		swapPanels.showPanel(panelNo);
		trackEvent('Homepage Panels','select',link.text());
		return false;
	},
	showPanel: function(panelNo) {
		$('#panel'+panelNo).addClass('on');
		if (panelNo != swapPanels.current) $('#panel'+swapPanels.current).removeClass('on');
		var currVid = $('#panel'+swapPanels.current).find('.video')[0];
		if (currVid && $f(currVid)) {
			$f(currVid).stop();
			$f(currVid).unload();
		}
		swapPanels.current = panelNo;		
	}
};

var trackEvent = function(category, action, optional_label, optional_value) {
	try {
		pageTracker._trackEvent(category, action, optional_label, optional_value);
	} catch(err) {}	
}


