/* --------------------------------------------------------------------------------------------
	Natalie Downe
	natalie.downe@torchbox.com

	Version 0.00 (28/09/2006)
	(based on Permalink Slideshow Version 0.20 (27/02/2006))

	TODO :
		- if you change the url then use the forward/back buttons the url doesnt change, this
		bug is also in the origial version (FF) and could be to do with the URL casheing
		- make more componantised, keep namespace and make customisable
-------------------------------------------------------------------------------------------- */

var u_slideName = 'slide' // this is the initial id of your slide, without the number, the url may look like ... http://yourSite.com#slideName1
var u_fadeSlide = 1;
var u_maxNavLinks = 13;

/* --------------------------------------------------------------------------------------------
	Customise variables above, you probably shouldnt need to change anything below
	- if you are using this on a site that already has one similar then rename the functions
		to avoud namespace issues
-------------------------------------------------------------------------------------------- */

// uses yahoo dom, event and animation
var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $ = $D.get; // get element by ID

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

// change from one slide to another
function insStartChange(requested) {

	if((requested != gCurrentSlide) && (requested < gSlides.length) && (requested >= 0) && (!gChangeInProcess)) {
		gChangeInProcess = true;

		// using global varible from url checker
		clearInterval(URLchecker);

		// set all non requested slides to not display except for current slide
		var k = 0;
		for(k; k<gSlides.length; k++) {
			if(k != gCurrentSlide) {
				gSlides[k].style.display = 'none';
				gSlides[k].style.visibility = 'hidden';
				gSlides[k].style.zIndex = '3';
			} else {
				gSlides[k].style.display = 'block';
				gSlides[k].style.visibility = 'visible';
				gSlides[k].style.zIndex = '5';
			}
		}
		k = 0;

		// display requested slide
		var requestedSlide  = document.getElementById('slideshowSlide' + (requested + 1));
		requestedSlide.style.display = 'block';
		requestedSlide.style.visibility = 'visible';
		// fadeFrom must have a higher zindex than fadeTo (need to reset only for safari)
		requestedSlide.style.zIndex = '4';

		// fade the top image onto the bottom
		var anim = new YAHOO.util.Anim(gSlides[gCurrentSlide], { opacity: { from: 1, to: 0 } }, 0.5, YAHOO.util.Easing.easeBoth);
		anim.onComplete.subscribe(function() { insEndFade(requestedSlide) });
		anim.animate();
		anim = null;
	}
}

function insEndFade(slideTo) {

	// have numbers but we need nodes
	var slideFrom = gSlides[gCurrentSlide];

	// the fade has finished so reset visiblity, display and opacity
	// zindex need to reset only for safari (might fix it)
 	slideFrom.style.zIndex = '0';
 	slideTo.style.zIndex = '5';
 	slideFrom.style.visibility = 'hidden';
 	slideFrom.style.display = 'none';
	YAHOO.util.Dom.setStyle(slideFrom, 'opacity', 1);

	// reset current image
	gCurrentSlide = parseInt(slideTo.id.replace('slideshowSlide', ''), 10) - 1;

	// reassign the navigation and URL
 	insAssignNav();
	location.href = location.href.replace(location.hash, '#slide' + (gCurrentSlide +1));
 	document.title = "Slide "+ (gCurrentSlide + 1) +" : "+ gInitialDocTitle;

	// write what page we are on at the moment
 	if(document.getElementById('pages')) {
		document.getElementById('pages').innerHTML = (gCurrentSlide + 1) + ' of ' + gImages.length;
 	}

	// officially end the fade
 	gChangeInProcess = false;

	// restart the url checker
	URLchecker = setInterval(insListenForURLchange, 500);
}

// takes an array of images and the current image object
function insListenForURLchange() {
	// if the hash exists and is of the form #image

	if((location.hash) && (location.hash.indexOf('slide') != -1)) {
		var urlRequested = parseInt(location.hash.replace('#slide', '')) - 1;
		if(urlRequested != gCurrentSlide) {
			insStartChange(urlRequested);
		}
	}
}

// uses array of images and index to that array
function insAssignNav() {
	// calculate next and previous page index
	var nextPage = gCurrentSlide + 1;
	var previousPage = gCurrentSlide - 1;
	if(gCurrentSlide >= (gSlides.length - 1)) {
		// on the last image
		nextPage = 0;
	} else if(gCurrentSlide <= 0) {
		// on the first image
		previousPage = gSlides.length - 1;
	} else {
		// not
	}

	// 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.title = 'Next (image ' + (nextPage + 1) + ')';
	nextPageLink.onclick = function() {
		insStartChange(nextPage);
		return false;
	};
	previousPageLink.title = 'Previous (image ' + (previousPage + 1) + ')';
	previousPageLink.onclick = function() {
		insStartChange(previousPage);
		return false;
	};

	// Clear DOM references to avoid cycle (and resulting memoryleak)
	nextPageLink = null;
	previousPageLink = null;

	var navListElements = document.getElementById('navSlides').getElementsByTagName('a');
	var navListContainers = document.getElementById('navSlides').getElementsByTagName('li');

	// reset the className of all list items before setting selected - also add onclick - also hide all before showing relevant ones
	var l = 0;
	for(l; l<navListElements.length;l++) {
		navListElements[l].className = "";

		(function() {
			var current= l;
			navListElements[l].onclick= function() {
				insStartChange(current);
				return false;
			};
		})();
		navListElements[l].href = '';
		navListContainers[l].style.display = 'none';
	}
	
	// set current page to be selected
	navListElements[gCurrentSlide].className = "selected";
	
	//set nearest navElements to show (the maths is only this complicated to allow for possibility of maxNavLinks being even)
	navStartBuffer = Math.round((u_maxNavLinks / 2) - 1);
	navEndBuffer = u_maxNavLinks - navStartBuffer - 1;
	
	if (gCurrentSlide < navStartBuffer) {
		navStart = 0;
		navEnd = u_maxNavLinks;
		if (navEnd > navListElements.length) navEnd = navListElements.length;
	} else if (gCurrentSlide >= navListElements.length - navEndBuffer) {
		navStart = navListElements.length - u_maxNavLinks;
		if (navStart < 0) navStart = 0;
		navEnd = navListElements.length;
	} else {
		navStart = gCurrentSlide - navStartBuffer;
		navEnd = navStart + u_maxNavLinks;
	}
	for (l=navStart;l<navEnd;l++) navListContainers[l].style.display = 'list-item';
	navListElements = null;
}

function insSetupPage() {

	// initial document title
	gInitialDocTitle = document.title;

	// set up array of slide divs and rename id
	var tempSlides = document.getElementById('slideContainer').getElementsByTagName('div');
	var tempSlideNo;
	var i = 0;
	for(i;i<tempSlides.length; i++) {
		if(tempSlides[i].className.indexOf('Content') != -1) {

			// what slide is this
			tempSlideNo = parseInt(tempSlides[i].id.replace('slide', ''), 10);

			// re-set slide id to avoid jumping but to maintain graceful degredation
			// URL will still maintain old ID of #imageXX
			tempSlides[i].id = 'slideshowSlide' + tempSlideNo;

			// add to array
			gSlides[gSlides.length] = tempSlides[i];
		}
	}

	// reseting tempoary variables
	tempSlides = '';
	tempSlideNo = ''

	// what page are we on? take hash and turn to index : #1 --> [0]
			if(location.hash) {
		if(location.hash.indexOf('slide') != -1) {
			gCurrentSlide = parseInt(location.hash.replace('#slide', ''), 10) - 1;
		} else if(location.hash.indexOf('top') != -1) {
			gCurrentSlide = 0;
			location.href = location.href.replace(location.hash, '#slide1');
		} else {
			gCurrentSlide = 0;
			location.href = location.href.replace(location.hash, '#slide1');
		}
		if(gCurrentSlide >= gSlides.length) {
			// SLIDE TOO HIGH
			gCurrentSlide = 0;
			location.href = location.href.replace(location.hash, '#slide1');
		}
			} else {
				gCurrentSlide = 0;
				location.href = location.href + '#slide1';
			}

	// replace current title with slide number and title
	document.title = "Slide "+ (gCurrentSlide + 1) +" : "+ gInitialDocTitle;

	// initialise and assign links
	insAssignNav();

	// display correct slide to start with
	if(gCurrentSlide != 0) {
		gSlides[0].style.display = 'none';
		gSlides[gCurrentSlide].style.display = 'block';
	}

	// assign our listener to a global variable so we can purge it later
	URLchecker = setInterval(insListenForURLchange, 700);
}


// on load
$E.addListener(window,'load',insSetupPage);

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

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

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

