// variable definitions
var projects = new Array(); // to contain project arrays
var project = new Array(); // to be set to current project

var imageDuration = 3.8; // must be greater than 1
var fadeDuration = 1.6;
// determine delta based on number of fade seconds
// the slower the fade the more increments needed
var fps = 30; // frames per second
var fadeDelta = 1 / (fps * fadeDuration);

var isStart = false;
var isPaused = false;
var showImageInterval;

// functions

function startRotate() {
	
	showSite();
	isStart = true;

	// get elements
	imageMain = $('#project .image');
	imageFore = imageMain.find('img');
	stand1st = $('#standfirst').css('opacity', 0);
	
	nextProject();
	preloadCheck();
}

function queueNextProject() {
	
	nextProject();
	addProject();
	shuffleDeck();
}

function nextProject() {
	
	// get elements
	imageMain = $('#project .image');
	imageFore = imageMain.find('img');
	detailsMain = $('#project .details:first');
	detailsFore = $('#project .details:last');
	
	// get next project and rotate project array
	project = projects.shift();
	projects.push(project);
	
	// preload next images
	cachedImage = preloadImage(project[3]); // main image
}

function rotate() {

	nextProject();

	// set timeout for next fade
	setTimeout('preloadCheck()', fadeDuration * 1000 + (imageDuration - 1) * 1000); // -1 on imageDuration for IE6 fix (see below)
}

function preloadCheck() {
	
	if (cachedImage.complete && !isPaused) {
		showProject();
	} else {
		setTimeout('preloadCheck()', 1000);
	}
}

function showProject(progress) {
	
	switch (true) {
		
		case (progress > 1 - fadeDelta):
			// finished fade
			isStart = false;
			shuffleDeck();
			rotate();
			break;
			
		case (!progress):
			// starting fade
			addProject();
			setTimeout('showProject(' + fadeDelta + ')', 1000); // IE6 fix
			break;

		default:
			// fade top out to reveal bottom image
			// use trigonometry to calculate smooth fade
			var opacity = 1 - ((-Math.cos(progress * Math.PI) / 2) + 0.5);
			imageFore.css('opacity', opacity);
			detailsFore.css('opacity', opacity);
			if (isStart) {
				stand1st.css('opacity', 1 - opacity);
			}
			setTimeout('showProject(' + (progress + fadeDelta) + ')', fps);  // frames per second
	}
}

function addProject() {
	
	// set next project image as background

	imageMain
	 .css('background', '#000 url(' + cachedImage.src + ')')
	 .find('a')
	  .attr('href', project[14])
	  .find('img')
	   .attr('alt', project[0]);
	   
	//imageMain.css('opacity', 1);

	detailsMain
	 .clone()
	  .insertBefore(detailsMain)
	  .find('a')
	   .attr('href', project[14])
	   .text(project[0])
	   .end()
	  .find('.location')
	   .text(project[1])
	   .end()
	  .find('.locality')
	   .text(project[2]);
}

function shuffleDeck() {
	
	// copy image from background to foreground
	imageFore.one('load', function() { imageFore.css('opacity', 1); });
	imageFore.attr('src', cachedImage.src);
	detailsFore.remove();
}

$(document).ready(function() {

	var images  = $('#project li').map(getImage).get(),
	    buttons = $('a.button-link'),
	    parent  = $('#project ul').get(0),
	    total   = images.length,
	    i       = 0,
	    currentImage = 0;

	var nextButton = $("a.button-link-next").get()[0];
	var previousButton = $("a.button-link-previous").get()[0];
	var nextButtonDisabled = true;
	var previousButtonDisabled = true;
		
	//buttons.hover(imageLinkOver, imageLinkOut);

	$(nextButton).click( function() {
		if (currentImage < (total-1)) {
			currentImage++;
			showImage();
			updateButtons();
		}
		return false;
	}).hover( function() {
		if (!nextButtonDisabled) {
			imageLinkOver.call(this);	
		}
	},function() {
		imageLinkOut.call(this);	
	});

	$(previousButton).click( function() {
		if (currentImage > 0) {
			currentImage--;
			showImage();
			updateButtons();
		}
		return false;
	}).hover( function() {
		if (!previousButtonDisabled) {
			imageLinkOver.call(this);	
		}
	},function() {
		imageLinkOut.call(this);	
	});
	
	var updateButtons = function() {
		if (currentImage == 0) {
			$(previousButton).addClass("button-link-disabled");
			$(previousButton).removeClass("hover");
			previousButtonDisabled = true;
		}
		else {
			$(previousButton).removeClass("button-link-disabled");
			previousButtonDisabled = false;
		}
		if (currentImage == (total-1)) {
			$(nextButton).addClass("button-link-disabled");
			$(nextButton).removeClass("hover");
			nextButtonDisabled = true;
		}
		else {
			$(nextButton).removeClass("button-link-disabled");
			nextButtonDisabled = false;
		}
	}
	$('#standfirst, #project div.details, #project div.image').css('opacity', 0);

	if (nextButton && previousButton) {
		updateButtons();
	}


	replaceNode(parent, 'div');

	images[i].onload = function() {
		var c = $('#project div.image div');
		c.css('background', '#000 url("' + this.src + '") no-repeat');

		if ($.browser.msie) {
			c.css('filter',
			      'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'
				      + this.src
				      + '", sizingMethod="scale")');
		}

		$('#standfirst, #project div.details')
			.css('display', 'block')
			.animate({opacity: 1}, 600, afterFadeIn);
	};
	


	function getImage() {
		return preloadImage($(this).text().replace(" ",""));
	}

	function replaceNode(n, t) {
		n.parentNode.replaceChild(document.createElement(t), n);
	}

	function afterFadeIn() {
		$('#project div.image')
			.css('display', 'block')
			.animate({opacity: 1}, 600, removeFilter);
	}

	function removeFilter() {
		if ($.browser.msie) {
			$(this).css('filter', 'none');
			$('#project div.image div').get(0).style.filter = '';
		}
	}

	function showImage() {
		var abv = $('#project .image'),
		    img = $('#project .image div'),
		    src = images[currentImage].src,
		    int = setInterval(swap, 100);

		$('#project a.select').removeClass('select');
		swap();

		return false;

		function swap() {
			if (!isPaused) {
				isPaused = true;
				abv.css('background', '#000 url("' + src + '") no-repeat');
				setTimeout(afterPause, 600);
				clearInterval(int);
			}
		}

		function afterPause() {
			img.animate({opacity: 0}, fadeDuration * 1000, function() {
				$(this).css('background', '#000 url("' + src + '") no-repeat');
				$(this).css('opacity', 1);
				isPaused = false;
			});
		}
	}

});