/*
	FIXES
	- trying to fix performance problem using display:none
	- also fixing forward and back bug that sometimes leaves images blank
	- stops any kind of interaction if a fade is in process
	- changed so index's start at 0 and hashes start at 1
	
	relates to index5.html, style.css, style3.css
*/

var gCurrentImage; // index to images[] the actual image is 'gCurrentImage+1' any passing of href must minus 1
var gImages = [];
var URLchecker; // global variable so we can clear and reset interval
var fadingInProcess = false; // to stop unexpected behaviour if fading is interupted

var autoRoller; // global variable so we can stop the automatic rolling

function debug(msg) {/*
	var debugDock = document.getElementById('debug');
	if(debugDock.innerHTML) {
		debugDock.innerHTML = msg + '<br /> \n' + debugDock.innerHTML ;
	} else {
		debugDock.innerHTML = msg
	}*/
}

// takes an array of images and the current image object
function listenForURLchange() {
	if(location.hash) {
		var requested = parseInt(location.hash.replace('#image', '')) - 1;
		
		if((requested != gCurrentImage) && (requested <= gImages.length) && (requested >= 0)) {
			// correct image number trying to fade
			debug('requested ='+ requested)
			startFade(gImages[gCurrentImage], gImages[requested]);
		} else {
			// incorrect image number : requested = ' +requested+' : current = '+ gCurrentImage + ' : images.length = '+gImages.length);
		}
	}
}

function setOpacity(obj, opacity) {
	opacity = (opacity == 1)?0.99999:opacity;
	opacity = (opacity < 0.1)?0:opacity;
	// IE/Win
	obj.style.filter = "alpha(opacity:"+(opacity*100)+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity;
}

function endFade(imgFrom, imgTo) {

	// the fade has finished so reset visiblity, display and opacity
	imgFrom.style.visibility = 'hidden';
	imgFrom.style.display = 'none';
	setOpacity(imgFrom, 1);
	
	// restart the url checker
	URLchecker = setInterval(listenForURLchange, 500);
	
	// reset current image
	gCurrentImage = parseInt(imgTo.id.replace('image','')) - 1;
	debug('END FADE TO' +gCurrentImage);
	
	// reassign the navigation and URL
	assignNav();
	//location.href = location.pathname + '#image' + parseInt(imgTo.id.replace('image', ''), 10);
	//document.title = 'Image '+ (gCurrentImage + 1) +' : Proof of concept';
	
	// write what page we are on at the moment
	document.getElementById('pages').innerHTML = (gCurrentImage + 1) + ' of ' + gImages.length;
	
	// officially end the fade
	fadingInProcess = false;
}

function fadeImages(imgFrom, imgTo, opacity) {
	//debug('fadeImages('+parseInt(imgFrom.id.replace('image',''))+', '+opacity+')');
	if(opacity >= 0.05) {
		// still fading, reduce imgFrom opacity and call again
		opacity = opacity - 0.1;
		setOpacity(imgFrom, opacity);
		setTimeout(function() {fadeImages(imgFrom, imgTo, opacity); }, 100);
	} else {
		// image has finished fading
		endFade(imgFrom, imgTo);
	}
}

function startFade(imgFrom, imgTo) {

	debug('** startFade('+imgFrom.id+', '+imgTo.id+')');
	
	//alert(imgFrom.id +' '+ imgTo.id);
	
	if(fadingInProcess) {
		debug('fadingInProcess YES');
	} else  {
		debug('fadingInProcess NO');
	}
	
	// check that we are not requested to move pages
	if((imgFrom.id != imgTo.id) && (!fadingInProcess)) { 
	
		// using global varible from url checker
		clearInterval(URLchecker);
		
		// fadeFrom must have a higher zindex than fadeTo (not important to reset)
		imgFrom.style.zIndex = '103';
		imgTo.style.zIndex = '102';
		
		// set visibility and display to show both images one on top of the other
		imgFrom.style.visibility = 'visible';
		imgTo.style.visibility = 'visible';
		imgFrom.style.display = 'block';
		imgTo.style.display = 'block';
		
		// fade the top image onto the bottom
		fadeImages(imgFrom, imgTo, 1);
		
		//alert('** startFade('+imgFrom.id+', '+imgTo.id+')');
		
		// tell program we are fading so dont try doing it again
		fadingInProcess = true
	}
}

// uses array of images and index to that array
function assignNav() {

	// calculate next and previous page index
	var nextPage = gCurrentImage + 1;
	var previousPage = gCurrentImage - 1;
	debug('currentIndex = '+gCurrentImage +' | gImages.length = '+gImages.length);
	if(gCurrentImage >= (gImages.length - 1)) {
		// on the last image
		nextPage = 0;
		//debug('last');
	} else if(gCurrentImage <= 0) {
		// on the first image
		previousPage = gImages.length - 1;
		//debug('first');
	} else {
		//debug('not');
	}
	debug('<' + (previousPage) +' | '+(gCurrentImage)+' | '+(nextPage) +'>');
	//debug('<' + (previousPage + 1) +' | '+(currentImage +1)+' | '+(nextPage + 1) +'>');
	
	// initialise links links
	var nextPageLink = document.getElementById('nextLink');
	var previousPageLink = document.getElementById('previousLink');
	
	// set up listners for the forward and back links
	// NOTE: the code was throwing an error when I used links, hence currently using spans
	//nextPageLink.href = location.pathname + '#image' + nextPage;
	nextPageLink.title = 'Image ' + (nextPage + 1);
	nextPageLink.onclick = function() {	
		clearInterval(autoRoller);
		startFade(gImages[gCurrentImage], gImages[nextPage]);
		return false;
	};
	//previousPageLink.href = location.pathname + '#image' + previousPage;
	previousPageLink.title = 'Image ' + (previousPage + 1);
	previousPageLink.onclick = function() {	
		clearInterval(autoRoller);
		startFade(gImages[gCurrentImage], gImages[previousPage]);
		return false;
	};
}

function setupPage() {
	
	// initialise arrays and set styleId to be #imageXX
	var allImages = document.getElementsByTagName('img');
	var i = 0;
	for(i; i<allImages.length; i++) {
		allImages[i].id.display = 'none';
		if (allImages[i].className.indexOf('slideshowImage') != -1) {
			gImages[gImages.length] = allImages[i];
			
			// add click handler to stop autoroll and progress.
			allImages[i].onclick = function(){
				clearInterval(autoRoller);
				var nextPage = (gCurrentImage >= (gImages.length - 1) ? 0 : gCurrentImage + 1);
				startFade(gImages[gCurrentImage], gImages[nextPage])
			}
		}
	}
	
	// what page are we on? take hash and turn to index : #1 --> [0]
	if(location.hash) {
		gCurrentImage = parseInt(location.hash.replace('#image', ''), 10) - 1;
		if(gCurrentImage >= gImages.length) {
			debug('IMAGE TOO HIGH');
			gCurrentImage = 0;
			//location.href = location.pathname + '#image1';
		}
	} else {
		gCurrentImage = 0;
		//location.href = location.pathname + '#image1';
	}
	
	// write what page we are on at the moment
	document.getElementById('pages').innerHTML = (gCurrentImage + 1) + ' of ' + gImages.length;
	//document.title = 'Image '+ (gCurrentImage + 1) +' : Proof of concept';
	
	// initialise and assign links
	assignNav();
	
	// display correct image and links to start with
	gImages[gCurrentImage].style.visibility = 'visible';
	gImages[gCurrentImage].style.display = 'block';
	
	// assign our listener to a global variable so we can purge it later
	URLchecker = setInterval(listenForURLchange, 700);
	
	// auto roll the images
	autoRoller = setInterval(function() {
			var nextPage = (gCurrentImage >= (gImages.length - 1) ? 0 : gCurrentImage + 1);
			startFade(gImages[gCurrentImage], gImages[nextPage])
		}, 3000);
		
	
}

function setCSS(css) {
	try {
		// append stylesheet to alter
		document.getElementsByTagName("head")[0].appendChild(css);
	} catch (e) {
		setTimeout(function(){setCSS(css)}, 100);
	} 
}

// on load
addEvent(window, 'load', setupPage);

// create CSS element to set up the page
var css = document.createElement("link");
css.setAttribute("href","/inc/slideshow.css");
css.setAttribute("rel","stylesheet");
css.setAttribute("type","text/css");

// attempt to add the css and then keep trying till we do
setCSS(css);
