function Timer() {
	var timerId, start, remainder, callback;
	
	this.start = function(cb, delay) {
		if(timerId !== undefined) {
			window.clearTimeout(timerId);
		}
		callback = cb;
		start = new Date();
		remainder = delay;
		timerId = window.setTimeout(callback, delay);
	};
	
	this.pause = function() {
		window.clearTimeout(timerId);
		remainder -= new Date() - start;
	};
	
	this.resume = function() {
		timerId = window.setTimeout(callback, remainder);
	};
}

/**
 * moviePlayer facilitates the control of the flash player promo videos.
 */
var moviePlayer = function() {
	
	var videoTrigger = $('<a href="/" title="Click here to play our video" id="video_trigger"><img src="/pws/images/img_video_trigger.png" alt="Open video" /></a>'),
		videoTriggerOverlay = $('<span id="trigger_overlay"></span>'),
		videoClose = $('<span id="video_close"><img src="/pws/images/img_video_close.png" alt="Close video" /></span>'),
		videoCloseOverlay = $('<span id="close_overlay"></span>'),
		videoContent = $('<div id="video_content"></div>'),
		swfObjectLoaded = false,
		videoTriggerClickable = false,
		videoFilename,
		background,
		video,
		speed,
		timer;
	
	videoCloseOverlay.css({
		'background' : '#000',
		'opacity' : '0.6'
	});
	
	videoTrigger.prepend(videoTriggerOverlay);
	videoClose.prepend(videoCloseOverlay);
	
	return {
		//Sets up the movie player ready for the first run
		init: function(imageFadeSpeed) {
			var self = this;
			speed = typeof imageFadeSpeed === 'number' ? imageFadeSpeed : 1000;
			$.getScript('/pws/javascript/swfobject.js', function() {
				var e = $('body').prepend(videoTrigger);
				videoTriggerOverlay.css('opacity', '0.6');
				videoTrigger.after(videoClose);
				$(window).resize(function(){
					self.positionTrigger();
				});
				videoClose.after(videoContent);
				videoClose.append(videoCloseOverlay);
				videoContent.css('top', $('#header').outerHeight());
				self.setupTriggerActions();
				swfObjectLoaded = true;
				
				if(window.location.hash == "#video=true"){
					videoTrigger.click();
				}
				
				$(window).bind('hashchange', function (event){
					var $currentHash = $.deparam.fragment();
					if(typeof $currentHash.video == "undefined" && $("body").hasClass("video_playing")){
						videoClose.click();
					} else if($currentHash.video == "true" && !$("body").hasClass("video_playing")){
						videoTrigger.click();
					}
				});
			});
		},
		
		//Store the filename for current image config and kick off the player launch
		start: function(filename, bg, t) {
			if(!filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1") === 'flv') {
				return false;	//no flv so don't go any further
			}
			
			timer = t;
			videoFilename = filename;
			background = bg;
			
			if(swfObjectLoaded) {
				this.showVideoTab();
			}else{
				// added to compensate for slow connections (WHI-1344)
				this.showVideoTab();
			}
		},
		
		//Shows the launch video button tab
		showVideoTab: function() {			
			videoTriggerClickable = true;
			videoTrigger.css({'display': 'block', 'opacity': 0}).stop().fadeTo(imageFadeSpeed, 1);
			this.positionTrigger();
		},
			
		hideVideoTab: function() {	
			if(!$('#browser_class').hasClass('ie7')) {
				videoTrigger.stop().fadeTo(imageFadeSpeed, 0, function() {																															 
					$(this).css({'display': 'none', 'opacity': 0})
				});
			}else {
				
			videoTrigger.css({'display': 'block', 'opacity': 0}).stop()
			}
			videoTriggerClickable = false;
		},
		
		setupTriggerActions: function() {
			var self = this;
			videoTrigger.click(function(e) {
				e.preventDefault();
				
				if(!videoTriggerClickable) {
					return false;
				}
				
				if(timer !== undefined && typeof timer.pause === 'function') {
					timer.pause();
				}
				
				$('body').addClass('video_playing');
				
				self.resizeVideo();
				
				if($.browser.msie){
					$('#background').hide();
					self.showVideo();
					videoContent.show();				
				} else {
					$('#background').fadeOut(1000, function(){
						videoContent.css({'opacity':'0', 'display':'block'}).fadeTo(1000, 1, function(){
							self.showVideo();
						});	
					});
				}
			});
			
			videoTrigger.hover(function() {						
				videoTriggerOverlay.stop().fadeTo(500,0.8);
			},function(){
				videoTriggerOverlay.stop().fadeTo(500,0.6);
			});
			
			videoClose.hover(function(){													
				videoCloseOverlay.fadeTo(500,0.8);
			},function(){
				videoCloseOverlay.fadeTo(500,0.6);
			}).click(function(){
				videoClose.hide();			
				if($.browser.msie){
					self.hideVideo();
					$('#background').show();
				} else {
					videoContent.fadeTo(1000, 0, function(){
						$('#background').fadeIn(1000, function(){
							self.hideVideo();
						});
					});	
				}
			});
		},
		
		positionTrigger: function(){
			videoTrigger.css({
				'top' : ($(window).height() - $('#footer').height() - $('#header').height() - videoTrigger.height()) / 2 + $('#header').height(),
				'left' : ($(window).width() - videoTrigger.width()) / 2
			});
		},
		
		resizeVideo: function(){
			if($('body').hasClass('video_playing')){
				$(video).css({
					'width':$(window).width(),
					'height':($(window).height() - $('#header').outerHeight())
				});
			}
		},
		
		showVideo: function(){
			var so = new SWFObject('/pws/client/homepage/video/player.swf','mpl', $(window).width(), ($(window).height() - $('#header').outerHeight()), '9');
			so.addParam('allowfullscreen','true');
			so.addParam('allowscriptaccess','always');
			so.addParam('wmode','opaque');
			so.addVariable('file',videoFilename);
			so.addVariable('screencolor','262626');
			so.addParam('bgcolor','262626');
			so.addVariable('skin','/pws/client/homepage/video/modieusslim/stylish_slim.swf');
			so.addVariable('autostart','true');
			if(typeof background === 'string' && background.length > 0) {
				so.addVariable('image', background);
			}
			so.write('video_content');
			$('body').addClass('video_playing');
			video = document.getElementById('mpl');
			videoClose.show();
			$.bbq.pushState({'video':'true'});
		},
		
		hideVideo: function(){
			videoContent.hide();
			
			if(typeof video.sendEvent !== 'undefined'){
				video.sendEvent('STOP', 'true');
			}
			
			$('body').removeClass('video_playing');
			window.location.hash = "";
			$(video).remove();
			if(timer !== undefined && typeof timer.resume === 'function') {
				timer.resume();
			}
		}
	};
}();


function handleBackground(){
	
	var background = $('#background');
	var currentImage, backgroundImageTimeout, changeImageTimeout, zIndex = 0;
	var loadedImages = [];
	var fadeToSpeed = (typeof imageFadeSpeed != 'undefined' && imageFadeSpeed != '' ? imageFadeSpeed : 1000);
	var changeTimeoutSpeed = (typeof imageChangeDelay != 'undefined' && imageChangeDelay != '' ? imageChangeDelay : 10000);
	var timer = new Timer();
	
	moviePlayer.init(fadeToSpeed);
	
	loadImage(0);
	
	function loadImage(index){
		
		currentImage = index;
		
		// variable backgroundImage.source is set in the Background Image CMS field on the Home template. A default value is set if that variable is undefined.
		var backgroundImageSrc = (typeof backgroundImages[index].source != 'undefined' && backgroundImages[index].source != '' ? backgroundImages[index].source : '/pws/client/homepage/background_1.jpg');
		
		background.addClass('loading');
		
		$.fn.appendImage = function(src, callback){
			
			if(loadedImages.contains(src)){
				callback();
			} else {
				return this.each(function(){
					$('<img />').appendTo(this).each(function(e){
						var that = this;
						this.src = src;
						this.onmousedown = function(){ return false };				
						backgroundImages[index].image = $(this);
						
						var loaded = false;
	
						// let's test to see if an image is in cache. Race this timeout vs. an ajax call
						window.setTimeout(isLoaded, 200);
						
						$.ajax({url: this.src,
							complete: function(data, status) {								
								loaded = true;
							}
						});
						
						function isLoaded(){
							if(loaded){
								callback();
								return true;
							} else {
								loaded = true;
								that.onload = isLoaded;
								window.setTimeout(isLoaded, 10000);
								return false;
							}
						}
						
					});
				});
			
			}
		}
		
		background.appendImage(backgroundImageSrc, function(){
			
			if(background.hasClass('loading')){
				
				loadedImages[loadedImages.length] = backgroundImageSrc;
						
				// variables backgroundImage.width and backgroundImage.height are set in the Background Image CMS field on the Home template. A default value is set if the variables are undefined.
				
				var backgroundImageWidth = (typeof backgroundImages[index].width != 'undefined' && backgroundImages[index].width != '' ? backgroundImages[index].width : 1200);
				var backgroundImageHeight = (typeof backgroundImages[index].height != 'undefined' && backgroundImages[index].height != '' ? backgroundImages[index].height : 675);
				
				var imageRatio = backgroundImageWidth / backgroundImageHeight;
	
				resizeBackground(imageRatio);
				$(window).bind('resize',function(){
					resizeBackground(imageRatio);
				});
				
				showImage();			
			}
		});
	
	}
	
	function resizeBackground(imageRatio){
		
		var windowRatio = $(window).width() / $(window).height();
				
		if(windowRatio > imageRatio){
			background.addClass('wide');
		} else {
			background.removeClass('wide');
		}
		
		background.css({
			'width':$(window).width(),
			'height':$(window).height()
		});
		
	}
	
	function showImage(){
			
		//clearTimeout(changeImageTimeout);
		
		zIndex = zIndex + 1;
		
		backgroundImages[currentImage].image.css({'display':'none','visibility':'visible','position':'absolute','zIndex':zIndex}).fadeIn(imageFadeSpeed, function(){
			background.removeClass('loading');
		});
		
		if(backgroundImages.length > 1){
			var imageToLoad = (currentImage === backgroundImages.length - 1) ? 0 : currentImage + 1;
			//changeImageTimeout = window.setTimeout(function(){loadImage(imageToLoad)},changeTimeoutSpeed);
			timer.start(function(){loadImage(imageToLoad)}, changeTimeoutSpeed);
		}
			//The resource and background are properties to handle the flash popup. The background appears at the end of the movie.
			//The resource is the path to the flv to play.
			var resource = backgroundImages[currentImage].resource,
				videoBg = backgroundImages[currentImage].background;
			
			moviePlayer.hideVideoTab();
			
			if(resource !== undefined && resource !== '') {
				if(resource.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1") === 'flv') {	//if it's an flv allow the movie player to play it
					moviePlayer.start(resource, videoBg, timer);
				} else {//assume a url
					var img = backgroundImages[currentImage].image;
					if(!jQuery.data(img, 'actionApplied')) {
						img.addClass('clickable').click(function() {
							window.location = resource;
						});
						jQuery.data(img, 'actionApplied', true);
					}
				}
			}
	}
}

function handleFeaturesAndItems(){
	
	var elements = $('#items .feature, #items .item');
	
	elements.each(function(){
												 
		var element = $(this);
		
		var isFeature = element.hasClass("feature");
		
		if(isFeature){
			var featureImage = element.find('img:not(.marker)');
			featureImage.wrap('<div class="reveal"></div>');
			var reveal = element.find('.reveal');
			var revealHeight = reveal.height();
			var featureImageHeight = featureImage.height();
			
			if($.browser.msie && $.browser.version == 6){
				element.append('<img class="marker" src="/pws/client/homepage/panels/marker_up.png" />');
			}
			
			var information = element.find('.information');
		} else {
			var information = element.find('.transparency');
		}
		
		information.append('<div class="information_overlay"></div>');
		var overlay = element.find('.information_overlay');
		
		var anchorLink = element.find('a');
		
		if(anchorLink.length > 0){
			element.css("cursor","pointer");
		}
		
		element.css("overflow","visible");
		
		element.hover(function(){
			
			var openedFeature = element.siblings(".opened");
					
			if(!openedFeature.data("preventAutoClose")){
			
				if(openedFeature.length > 0){
					var openedReveal = openedFeature.find(".reveal");
					var openedImage = openedReveal.find("img");
					var openedOverlay = openedFeature.find('.information_overlay');
					
					openedReveal.animate({
						'height' : revealHeight
					}, 500);
					
					openedImage.fadeTo(500, '0.6');
					
					openedOverlay.fadeTo(500, '0');
					
					openedFeature.removeClass('opened');
				}
			
			}
			
			if(element.hasClass('opened')){
				
				element.removeClass('opened');
				
			} else {
				
				if(isFeature){
					
					reveal.animate({
						'height' : featureImageHeight
					}, 500);
					
					featureImage.fadeTo(500, '0.9');
				}
				
				overlay.css({'opacity':'0', 'display':'block'}).fadeTo(500, '0.5'); //0.5 will mean the overall opacity of the information div is around 80% as per the style guide for WHI_11
				
				if(element.hasClass('open')){
					element.addClass('opened').removeClass('open');
				}
				
			}
			
		}, function(){
			
			if(isFeature){
				
				reveal.animate({
					'height' : revealHeight
				}, 500);
				
				featureImage.fadeTo(500, '0.6');
				
			}
			
			overlay.fadeTo(500, '0');
			
		}).click(function(){
			
			if(anchorLink.length > 0){			
				window.location = anchorLink.attr("href");
			}
			
		});
		
		if(element.hasClass('open')){
			element.data("preventAutoClose",true).mouseover();
		}
		
	});
	
	elements.each(function(){$(this).data("preventAutoClose",false)});
	
}

$(document).ready(function(){
	
	handleBackground();
	handleFeaturesAndItems();
	//handleVideo();
	
});

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}
