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);
	};
}

function pausecomp(ms) {
    ms += new Date().getTime();
    while (new Date() < ms) { }
} 

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');

		document.getElementById("lh1").innerHTML = backgroundImages[index].lh1;
		document.getElementById("lh2").innerHTML = backgroundImages[index].lh2;
		document.getElementById("lp").innerHTML = backgroundImages[index].lp;
		document.getElementById("rh1").innerHTML = backgroundImages[index].rh1;
		document.getElementById("rh2").innerHTML = backgroundImages[index].rh2;
		document.getElementById("rp").innerHTML = backgroundImages[index].rp;
        
		document.getElementById("left_overpic").setAttribute("class", backgroundImages[index].lClass);
		document.getElementById("right_overpic").setAttribute("class", backgroundImages[index].rClass);

        		
		$.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 : 672);

		        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);
					}
				}
			}
	}
}
col = 255;

function fade() {
	document.getElementById("left_overpic").style.color = "rgb(" + col + "," + col + "," + col + ")"; 
	col -= 5;
	if (col > 0) setTimeout('fade()', 1000); 
}

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;
}
