var videoPlayerInitialised = false;
var playerReadyListeners = [];
function playerReady(obj) {
	/* ignore obj - it's some other random thing, not the player object we can actually call API methods on */
	var player = document.getElementById('mainstage_video');
	videoPlayerInitialised = true;
	for (var i = 0; i < playerReadyListeners.length; i++) {
		playerReadyListeners[i](player);
	}
	player.addViewListener('PLAY', 'playerPlayEvent');

player.addModelListener('STATE', 'stateMonitor');
}


function onPlayerReady(listener) {
	playerReadyListeners[playerReadyListeners.length] = listener;
}

var playerPlayListeners = [];
function playerPlayEvent() {
	var player = document.getElementById('mainstage_video');
	for (var i = 0; i < playerPlayListeners.length; i++) {
		playerPlayListeners[i](player);
	}
}

function onPlayerPlay(listener) {
	playerPlayListeners[playerPlayListeners.length] = listener;
}


var playerCompleteListeners=[];

function onPlayerComplete(listener) {
	playerCompleteListeners[playerCompleteListeners.length] = listener;
}

function playerCompleteEvent() {
	var player = document.getElementById('mainstage_video');
	for (var i = 0; i < playerCompleteListeners.length; i++) {
		playerCompleteListeners[i](player);
	}
}

function stateMonitor(obj)
{
if(obj.newstate == 'COMPLETED')
{
playerCompleteEvent();
}
};

(function($) {
	VISIBLE_STORY_COUNT = 3;
	PAUSE_BEFORE_STORIES_PANEL = 2000;
	STORIES_FADE_IN_STAGGER_DELAY = 200;
	STORIES_SCROLL_TIME = 600;
	STORY_HEIGHT = 90;
	BACKGROUND_FADE_TIME = 1000;
	HEADLINE_SLIDE_TIME = 600;
	AUTOSCROLL_DELAY = 5000;
	CLICK_THROUGH_TO_STORY_DELAY = 1000;
	
	var headlineAnimationOff = {'left': '150px', 'opacity': 0};
	var headlineAnimationOn = {'left': '0px', 'opacity': 1};
	/* less exciting but less processor-intensive version */
	//var headlineAnimationOff = {'left': '618px'};
	//var headlineAnimationOn = {'left': '0px'};
	
	function Feature(mainstage, initialStoryData) {
	
		var videoFlashVariables = {
			controlbar: 'over'
		//	skin: "player_skin.swf",
		//	lightcolor: "4A81B7",
		//	frontcolor: "FFFFFF",
		//	backcolor: "343434"
		};
		
		var videoParameters = {
			menu: "false",
			allowfullscreen: "true",
			allowscriptaccess: "always"
		};
		
		var storyHtml = $('<a class="main_story"><div class="transition_layer"></div><p class="alt"></p><div class="headline"><div class="headline_inner"><h1></h1><h2><span></span></h2></div></div><div id="mainstage_video"></div></a>');
		$(mainstage).html(storyHtml);
		
		var currentStoryData;
		var transitionLayer = $('.transition_layer', storyHtml);
		transitionLayer.fadeTo(1, 0);
		var headline = $('.headline', storyHtml);
		
		/* show story immediately, with no transition */
		function showStory(storyData) {
			currentStoryData = storyData;
			if (storyData.href) {
				$(storyHtml).attr({'href': storyData.href});
			} else {
				$(storyHtml).removeAttr('href');
			}
			$(storyHtml).css({'background-image': 'url(' + storyData.backgroundImage + ')'});
			$('.alt', storyHtml).text(storyData.alt);
			$('h1', headline).text(storyData.headline);
			$('h2 span', headline).text(storyData.headline2);
			
			if (!storyData.headline) {
				headline.css(headlineAnimationOff);
			}
			if (storyData.video) {
				initVideo(storyData);
			}
		}
		
		/* Change story link and headline to the new story, and fade the headline on */
		var switchHeadline = function(storyData) {
			if (storyData.href) {
				$('a.main_story', mainstage).attr('href', storyData.href);
			} else {
				$('a.main_story', mainstage).removeAttr('href');
			}
			if (storyData.headline) {
				$('h1', headline).text(storyData.headline);
				$('h2 span', headline).text(storyData.headline2);
				headline.animate(headlineAnimationOn, HEADLINE_SLIDE_TIME);
			}
		}
		
		function transitionToStory(storyData) {
			/* Stop any currently playing video */
			$('#mainstage_video', mainstage).replaceWith('<div id="mainstage_video"></div>')
			videoPlayerInitialised = false;
			
			/* make sure the back layer is showing the background image from the previous current
			story - it might not if transition is still happening */
			$('a.main_story', mainstage).css({'background-image': 'url(' + currentStoryData.backgroundImage + ')'});
			$('a.main_story .alt').text(currentStoryData.alt);
			
			transitionLayer.stop().css({'opacity': 0});
			transitionLayer.css({'background-image': 'url(' + storyData.backgroundImage + ')'});
			transitionLayer.fadeTo(BACKGROUND_FADE_TIME, 1, function() {
				$('a.main_story', mainstage).css({'background-image': 'url(' + storyData.backgroundImage + ')'});
				$('a.main_story .alt').text(storyData.alt);
				if (storyData.video) {
					initVideo(storyData);
				}
			});
			
			if (currentStoryData.headline) {
				/* need to fade current headline off first */
				headline.stop().animate(headlineAnimationOff, HEADLINE_SLIDE_TIME, function() {
					switchHeadline(storyData);
				})
			} else {
				switchHeadline(storyData);
			}
			
			currentStoryData = storyData;
		}
		
		function initVideo(storyData) {
			$('#mainstage_video').css({'z-index': -2});
			swfobject.embedSWF("http://assets.wwf.org.uk/custom/homepage/resources/player.swf", "mainstage_video", "638", "311", "9.0.0", false, videoFlashVariables, videoParameters, false);
			$('#mainstage_video').css({'z-index': -2});
			
			onPlayerReady(function(player) {
				player.style.zIndex = -2;
				player.sendEvent('LOAD', {
					file: storyData.video,
					image: storyData.backgroundImage
				});
				player.style.zIndex = 12;
			})
			
			onPlayerComplete(function(){ $('#mainstage_video').css({"visibility":"hidden"});
			$('a.main_story').css({"background-image":"url("+ storyData.endImage+")"}).attr("href",storyData.href)
			$('div.transition_layer').css("opacity","0")})
		}
		
		function onPlayVideo(listener) {
			onPlayerPlay(listener);
		}
		
		showStory(initialStoryData);
		
		return {
			showStory: showStory,
			transitionToStory: transitionToStory,
			onPlayVideo: onPlayVideo
		}
	}
	
	function StoriesPanel(mainstage, data, feature) {
		
		var currentStoryNumber = 0;
		var topVisibleTrayIndex = 0;
		var topPopulatedTrayIndex = 0;
		var bottomPopulatedTrayIndex = -1;
		
		var storiesPanel = $('<div class="stories_panel"><div class="stories_nav stories_nav_up"><a href="javascript:void(0)">Up</a></div><div class="stories_viewport"><div class="stories_tray"><ul class="stories"></ul></div></div><div class="stories_nav stories_nav_down"><a href="javascript:void(0)">Down</a></div></div>');
		var storiesUl = $('ul.stories', storiesPanel);
		var headline = $('.headline', mainstage);
		
		/* timestamp of the last click on a story which didn't take us through to the story;
		we will not click through to the story unless this is more than CLICK_THROUGH_TO_STORY_DELAY ago */
		var lastNavigationClickTime;
		
		/* return the index into 'data' of the story in tray position i */
		function storyNumberAtTrayIndex(i) {
			var storyNumber = ((VISIBLE_STORY_COUNT - 1) - i) % data.length;
			if (storyNumber < 0) storyNumber += data.length;
			return storyNumber;
		}
		
		function scrollTrayIntoPosition() {
			while (topVisibleTrayIndex < topPopulatedTrayIndex) prependStory();
			
			var bottomVisibleTrayIndex = topVisibleTrayIndex + VISIBLE_STORY_COUNT - 1;
			while (bottomVisibleTrayIndex > bottomPopulatedTrayIndex) appendStory();
			
			$('.stories_tray', storiesPanel).stop().animate(
				{'top': (-topVisibleTrayIndex * STORY_HEIGHT) + 'px'}, STORIES_SCROLL_TIME);
		}
		
		/* return true if story has changed, false if not */
		function selectStory(trayIndex) {
			topVisibleTrayIndex = trayIndex - VISIBLE_STORY_COUNT + 1;
			scrollTrayIntoPosition();
			var storyNumber = storyNumberAtTrayIndex(trayIndex);
			$('li.current_story', storiesUl).removeClass('current_story');
			$('li.story_number_' + storyNumber, storiesUl).addClass('current_story');
			
			if (storyNumber != currentStoryNumber) {
				currentStoryNumber = storyNumber;
				feature.transitionToStory(data[storyNumber]);
				return true;
			} else {
				return false;
			}
		}
		
		/* return a <li> for a story item */
		function createStoryLi(trayIndex) {
			var storyNumber = storyNumberAtTrayIndex(trayIndex);
			var storyData = data[storyNumber];
			var story = $('<li class="story"><div class="thumbnail"><img src="" width="72" height="53" alt="" /></div><div class="title"><a></a></div></li>');
			story.addClass('story_number_' + storyNumber);
			if (storyNumber == currentStoryNumber) story.addClass('current_story');
			$('.thumbnail img', story).attr('src', storyData.thumbnail);
			$('.title a', story).attr('href', storyData.href);
			$('.title a', story).text(storyData.storyTitle);
			story.hover(function() {
				story.addClass('story_hover');
			}, function() {
				story.removeClass('story_hover');
			}).click(function() {
				disableAutoscroll();
				var storyHasChanged = selectStory(trayIndex);
				var currentTime = (new Date).getTime();
				if (storyHasChanged || lastNavigationClickTime > (currentTime - CLICK_THROUGH_TO_STORY_DELAY)) {
					lastNavigationClickTime = currentTime;
				} else {
					var href = $('.title a', this).attr('href');
					if (href != null) {
						document.location.href = href;
					}
				}
				return false;
			})
			return story;
		}
		
		function prependStory() {
			topPopulatedTrayIndex -= 1;
			var story = createStoryLi(topPopulatedTrayIndex);
			
			storiesUl.prepend(story);
			centreStoryText(story);
			storiesUl.css({'top': topPopulatedTrayIndex * STORY_HEIGHT});
		}
		function appendStory(opts) {
			opts = opts || [];
			bottomPopulatedTrayIndex += 1;
			var story = createStoryLi(bottomPopulatedTrayIndex);
			storiesUl.append(story);
			centreStoryText(story);
			
			if (opts.fade) {
				story.hide();
				setTimeout(function() {story.fadeIn()}, (bottomPopulatedTrayIndex + 1) * STORIES_FADE_IN_STAGGER_DELAY);
			}
		}
		
		function centreStoryText(story) {
			var title = $('.title', story);
			title.css({'padding-top': (STORY_HEIGHT - title.get(0).offsetHeight) / 2 + 'px'});
		}
		
		function selectNextStory() {
			selectStory(topVisibleTrayIndex + VISIBLE_STORY_COUNT);
		}
		
		function selectPreviousStory() {
			selectStory(topVisibleTrayIndex + VISIBLE_STORY_COUNT - 2);
		}
		
		var autoscrollTimer;
		var isAutoscrolling = false;
		var autoscrollIsDisabled = false;
		function startAutoscroll() {
			if (!isAutoscrolling && !autoscrollIsDisabled) {
				autoscrollTimer = setInterval(selectPreviousStory, AUTOSCROLL_DELAY);
				isAutoscrolling = true;
			}
		}
		function stopAutoscroll() {
			clearInterval(autoscrollTimer);
			isAutoscrolling = false;
		}
		function disableAutoscroll() {
			autoscrollIsDisabled = true;
			stopAutoscroll();
		}
		
		/* hide in preparation for fade-on */
		mainstage.append(storiesPanel);
		$('.stories_nav_up', storiesPanel).hide();
		$('.stories_nav_down', storiesPanel).hide();
		
		/* fade on / create initial stories */
		$('.stories_nav_up', storiesPanel).fadeIn();
		
		for (i = 0; i < VISIBLE_STORY_COUNT; i++) {
			appendStory({fade: true});
		}
		
		setTimeout(function() {
			$('.stories_nav_down', storiesPanel).fadeIn(function() {
				/* when this has finished fading in, we can adjust headline box width */
				headline.wrap('<div class="headline_viewport"></div>');
			});
		}, (VISIBLE_STORY_COUNT + 1) * STORIES_FADE_IN_STAGGER_DELAY);
		
		$('.stories_nav_up', storiesPanel).click(function() {
			disableAutoscroll();
			selectPreviousStory();
		})
		
		$('.stories_nav_down', storiesPanel).click(function() {
			disableAutoscroll();
			selectNextStory();
		})
		
		return {
			startAutoscroll: startAutoscroll,
			stopAutoscroll: stopAutoscroll,
			disableAutoscroll: disableAutoscroll
		};
	}
	
	$.fn.wwfMainstage = function(data) {
		var mainstage = this;
		var feature = Feature(mainstage, data[0]);
		
		if (data.length > 1) {
			$(function() {
				setTimeout(function() {
					storiesPanel = StoriesPanel(mainstage, data, feature);
					$(mainstage).hover(function() {
						storiesPanel.stopAutoscroll();
					}, function() {
						storiesPanel.startAutoscroll();
					})
					feature.onPlayVideo(function() {
						storiesPanel.disableAutoscroll();
					})
					storiesPanel.startAutoscroll();
				}, PAUSE_BEFORE_STORIES_PANEL);
			})
		}
		
		/* start preloading images when the page's own images have loaded */
		$(window).load(function() {
			var backgroundImages = [];
			for (var i = 0; i < data.length; i++) {
				backgroundImages[i] = new Image();
				backgroundImages[i].src = data[i].backgroundImage;
			}
		})
	}
	
})(jQuery);
