////////////////////////////////////////////
// clear search box	
////////////////////////////////////////////
function clearDefault(el) {
	if (el.defaultValue==el.value) el.value = ""
	}
////////////////////////////////////////////
// tools menu	
////////////////////////////////////////////
sfHover = function() {
	var sfEls = document.getElementById("tools").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

////////////////////////////////////////////
// VSlider 
////////////////////////////////////////////
var playerPlayListeners = [];
function playerPlayEvent() {
	var player = document.getElementById('vslides_video');
	for (var i = 0; i < playerPlayListeners.length; i++) {
		playerPlayListeners[i](player);
	}
}

function onPlayerPlay(listener) {
	playerPlayListeners[playerPlayListeners.length] = listener;
}

(function($) {
	VISIBLE_STORY_COUNT = 3;
	PAUSE_BEFORE_THUMBS = 150;
	STORIES_FADE_IN_STAGGER_DELAY = 200;
	STORIES_SCROLL_TIME = 600;
	STORY_HEIGHT = 90;
	BACKGROUND_FADE_TIME = 1000;
	HEADLINE_SLIDE_TIME = 600;
	AUTOSCROLL_DELAY = 8500;
	CLICK_THROUGH_TO_STORY_DELAY = 1000;
	
	var headlineAnimationOff = {'left': '150px', 'opacity': 0};
	var headlineAnimationOn = {'left': '0px', 'opacity': 1};
	
	function Feature(vslides, initialStoryData) {
		
		var storyHtml = $('<a class="main_story"><div class="transition"></div><p class="alt"></p><div class="headline"><div class="headin"><h3></h3></div></div><div id="vslides_video"></div></a>');
		$(vslides).html(storyHtml);
		
		var currentStoryData;
		var transitionLayer = $('.transition', 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});
				$('h3', vslides).attr('class', 'slidelink');

			} else {
				$(storyHtml).removeAttr('href');
				$('h3', vslides).removeAttr('class');
			}
			$(storyHtml).css({'background-image': 'url(' + storyData.backgroundImage + ')'});
			$('.alt', storyHtml).text(storyData.alt);
			// $('h3 span', headline).html(storyData.headline);
			$('h3', headline).html(storyData.headline);
			// $('h4 span', headline).html(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', vslides).attr('href', storyData.href);
				$('h3', vslides).attr('class', 'slidelink');
			} else {
				$('a.main_story', vslides).removeAttr('href');
				$('h3', vslides).removeAttr('class');
			}
			if (storyData.headline) {
				// $('h3 span', headline).html(storyData.headline);
				$('h3', headline).html(storyData.headline);
				// $('h4 span', headline).html(storyData.headline2);
				headline.animate(headlineAnimationOn, HEADLINE_SLIDE_TIME);
			}
		}
		
		function transitionToStory(storyData) {		
			/* 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', vslides).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', vslides).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 onPlayVideo(listener) {
			onPlayerPlay(listener);
		}
		
		showStory(initialStoryData);
		
		return {
			showStory: showStory,
			transitionToStory: transitionToStory,
			onPlayVideo: onPlayVideo
		}
	}
	
	function StoriesPanel(vslides, data, feature) {
		
		var currentStoryNumber = 0;
		var topVisibleTrayIndex = 0;
		var topPopulatedTrayIndex = 0;
		var bottomPopulatedTrayIndex = -1;
		
		var storiesPanel = $('<div class="thumbs"><div class="stories_nav vup"><a href="javascript:void(0)">Up</a></div><div class="thumbview"><div class="thumbtray"><ul class="stories"></ul></div></div><div class="stories_nav vdown"><a href="javascript:void(0)">Down</a></div></div>');
		var storiesUl = $('ul.stories', storiesPanel);
		var headline = $('.headline', vslides);
		
		/* 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();
			
			$('.thumbtray', 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 */
		vslides.append(storiesPanel);
		$('.vup', storiesPanel).hide();
		$('.vdown', storiesPanel).hide();
		
		/* fade on / create initial stories */
		$('.vup', storiesPanel).fadeIn();
		
		for (i = 0; i < VISIBLE_STORY_COUNT; i++) {
			appendStory({fade: true});
		}
		
		setTimeout(function() {
			$('.vdown', storiesPanel).fadeIn(function() {
				/* when this has finished fading in, we can adjust headline box width */
				headline.wrap('<div class="headview"></div>');
			});
		}, (VISIBLE_STORY_COUNT + 1) * STORIES_FADE_IN_STAGGER_DELAY);
		
		$('.vup', storiesPanel).click(function() {
			disableAutoscroll();
			selectPreviousStory();
		})
		
		$('.vdown', storiesPanel).click(function() {
			disableAutoscroll();
			selectNextStory();
		})
		
		return {
			startAutoscroll: startAutoscroll,
			stopAutoscroll: stopAutoscroll,
			disableAutoscroll: disableAutoscroll
		};
	}
	
	$.fn.wwfvslides = function(data) {
		var vslides = this;
		var feature = Feature(vslides, data[0]);
		
		if (data.length > 1) {
			$(function() {
				setTimeout(function() {
					storiesPanel = StoriesPanel(vslides, data, feature);
					$(vslides).hover(function() {
						storiesPanel.stopAutoscroll();
					}, function() {
						storiesPanel.startAutoscroll();
					})
					feature.onPlayVideo(function() {
						storiesPanel.disableAutoscroll();
					})
					storiesPanel.startAutoscroll();
				}, PAUSE_BEFORE_THUMBS);
			})
		}
		
		/* 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);

