/* --------------------------------------------------------------------------------------------
	Natalie Downe
	natalie@natbat.co.uk

	Version 1.0 (18/11/2006)
	(based on Permalink Slideshow Version 0.20 (27/02/2006))

	TODO :
		- make this object oriented to avoid namespace collisions!
		- 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_fadeSlide = 0; // the time in which to fade the slide - if you set it to 0 the fade will be instantanious
var u_importedCSSfile = 'slideshowImported.css'; // path from the root to the css file to import

var u_slideName = 'photo' // this is the initial id of your slide, without the number, the url may look like ... http://yourSite.com#slideName1
var u_slideTitlePrefix = 'Photo'; // this appears on the title bar
var u_slideContainerID = 'photoContainer'; // the containing div for all your slides

/* optional */
var u_nextLink = 'next'; // id of nextlink link - comma separated id list if there is more than one
var u_previousLink = 'previous'; // id of previouslink link - comma separated id list if there is more than one
var u_navList = 'pagenumbers'; // id of list for paging elements - comma separated id list if there is more than one
var u_pages = 'pages'; // id of page one of one paragraph - comma separated id list if there is more than one

/* --------------------------------------------------------------------------------------------
	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
   --------------------------------------------------------------------------------------------

   PLEASE NOTE: if you want your slides to fade set u_fadeSlide to a fraction of time in seconds for the transition, 0.3 works nicely. however if you *do* want fading slides you need to be sure of the height of your slide and that it will remain constant.

	Your document structure will need to look like:

	<div id="u_slideContainerID">
		<div id="u_slideName1" class="u_slideName">
			<!-- some sort of slide, an image or text or whatever -->
		</div>
		<div id="u_slideName2" class="u_slideName">
			<!-- some sort of slide, an image or text or whatever -->
		</div>
		<div id="u_slideName3" class="u_slideName">
			<!-- some sort of slide, an image or text or whatever -->
		</div>
		<div id="u_slideName4" class="u_slideName">
			<!-- some sort of slide, an image or text or whatever -->
		</div>

		<!-- and on and on and on ..... (you can have other divs in here but not with the same
		class name or ID format)-->

	</div>

	if you are working within RM your code can do:

	<cfif exists('REQUEST.objectName')>
		<div id="u_slideContainerID">
			<cf_rm_content name="objectName">
			 	<div class="u_slideName" id="u_slideName#counter#">
					<!-- some sort of slide, an image or text or whatever -->
				</div>
			</cf_rm_content>
		</div>
	</cfif>

	in the initial css called from the template you need to find a way of displaying your
	slides so that it looks good on one page which is what it will look like without
	javascript, you will probably want to set the next and previous links as well as the page
	X of X text to display: none however leave your navigational elements as a list of
	permalinks to allow for navigation by non script enabled browsers, eg ...

	<cfif exists('REQUEST.objectName')>
		<ol id="u_navList">
			<cf_rm_content name="objectName">
				<li><a href="##u_slideName#counter#">#counter#</a></li>
			</cf_rm_content>
		</ol>
	</cfif>

	set the className 'selected' for the links in the above list to have some sort of special style

	in the imported CSS you will need to override the display: none's you did for the pages
	and next previous etc. (these arent added dynamicly btw because I dont know where you want
	to put them!) then you want to make all the slides stack up on each other. One way to do
	this is to have the #u_slideContainerID div set to position relative and the indevidual
	.u_slideName set to position: absolute; top:0;

	You will need to set the slides to display: none and slide 1 to display: block (you may
	also need to set #slideshowSlide1 to display: block) the Javascript will work out the rest.

	An example of an imported css file for an animated slideshow of all the same height might look like this:

	#u_slideContainerID {
		position: relative;
		height: 200px;
		overflow: hidden;
	}

	#u_slideContainerID .u_slideName {
		position: absolute;
		top: 0;
		display: none;
	}

	#u_slideContainerID #u_slideName1,
	#u_slideContainerID #slideshowSlide1  {
		display: block;
	}

	whereas naturally you could miss the positioning off if you are setting the u_fadeSlide (the time between fades) to 0;

	#u_slideContainerID {
			position: relative;
	}

	#u_slideContainerID .u_slideName {
			display: none;
	}

	#u_slideContainerID #u_slideName1,
	#u_slideContainerID #slideshowSlide1  {
			display: block;
	}


-------------------------------------------------------------------------------------------- */

// 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 = 0; // index to gSlides[] the actual slide 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
var startSlideIndex=0;
var productPromoName=new Array();

function insStartChange1(){		
	if(startSlideIndex>5)
		startSlideIndex=0;
	insStartChange(startSlideIndex);
	startSlideIndex++;	
	if(startSlideIndex>5)
		startSlideIndex=0;
	setTimeout('insStartChange1()',3000);
}
// change from one slide to another
function insStartChange(requested) {	
	startSlideIndex=requested;		
	var elProductNameNext=document.getElementById("productNameNext");
			var elProductNamePrev=document.getElementById("productNamePrev");	
			if(startSlideIndex!=5)
				elProductNameNext.innerHTML=productPromoName[startSlideIndex+1];
			else
				elProductNameNext.innerHTML=productPromoName[0];
			
			if(startSlideIndex!=0)
				elProductNamePrev.innerHTML=productPromoName[startSlideIndex-1];
			else
			elProductNamePrev.innerHTML=productPromoName[2];
			try
			{
			if(titleSpan && document.getElementById('lnkProdName'))
			    titleSpan.innerHTML=productPromoName[startSlideIndex];//document.getElementById('lnkProdName').innerHTML;			    
            }
			catch(ex){}
	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  = $('slideshowSlide' + (requested + 1));

		if(u_fadeSlide <= 0) {
			gSlides[gCurrentSlide].style.display = 'none';
			gSlides[gCurrentSlide].style.visibility = 'hidden';
			gSlides[gCurrentSlide].style.zIndex = '3';
			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';
			insEndFade(requestedSlide);

		} 
	}
	
	
			
}

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 slide
	gCurrentSlide = parseInt(slideTo.id.replace('slideshowSlide', ''), 10) - 1;

	// reassign the navigation and URL
	insAssignNav();
	location.href = location.href.replace(location.hash, '#' + u_slideName + '' + (gCurrentSlide +1));
	document.title =  u_slideTitlePrefix + ': ' + (gCurrentSlide + 1) +" : "+ gInitialDocTitle;

	// write what page we are on at the moment
	var pagesText =  u_pages.split(',');
	for(var i = 0; i < pagesText.length; i++) {
		if($(pagesText[i])) {
			$(pagesText[i]).innerHTML = u_slideName + ' ' + (gCurrentSlide + 1) + ' of ' + gSlides.length;
		}
	}
	// officially end the fade
	gChangeInProcess = false;

	// restart the url checker
	//URLchecker = setInterval(insListenForURLchange, 500);
	
	
}

function insListenForURLchange() {
	// if the hash exists and is of the form #u_slideName

	if((location.hash) && (location.hash.indexOf(u_slideName) != -1)) {
		var urlRequested = parseInt(location.hash.replace('#'+u_slideName, '')) - 1;
		if(urlRequested != gCurrentSlide) {
			insStartChange(urlRequested);
		}
	}
}

function insAssignNav() {
	// calculate next and previous page index
	var nextPage = gCurrentSlide + 1;
	var previousPage = gCurrentSlide - 1;
	if(gCurrentSlide >= (gSlides.length - 1)) {
		// on the last slide
		nextPage = 0;
	} else if(gCurrentSlide <= 0) {
		// on the first slide
		previousPage = gSlides.length - 1;
	} else {
		// not
	}

	var nextlinks =  u_nextLink.split(',');
	for(var i = 0; i < nextlinks.length; i++) {

		if($(nextlinks[i])) {
			var nextPageLink = $(nextlinks[i]);

			// 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 (' + u_slideName + ' ' + (nextPage + 1) + ')';
			nextPageLink.onclick = function() {
				insStartChange(nextPage);
				return false;
			};

			nextPageLink = null;
		}
	}

	var previousLinks =  u_previousLink.split(',');
	for(var i = 0; i < previousLinks.length; i++) {

		if($(previousLinks[i])) {
			var previousPageLink = $(previousLinks[i]);

			previousPageLink.title = 'Previous (' + u_slideName + ' ' + (previousPage + 1) + ')';
			previousPageLink.onclick = function() {
				insStartChange(previousPage);
				return false;
			};

			// Clear DOM references to avoid cycle (and resulting memoryleak)
			previousPageLink = null;
		}
	}


	var navLists =  u_navList.split(',');
	for(var i = 0; i < navLists.length; i++) {
		if($(navLists[i])){
			var navListElements = $(navLists[i]).getElementsByTagName('a');
			if(navListElements.length > 0) {
				// reset the className of all list items brefore setting selected - also add onclick
				var l = 0;
				for(l; l<navListElements.length;l++) {

					if(navListElements[l].className != '') {
						navListElements[l].className = navListElements[l].className.replace('selected', '');
					}

					(function() {
						var current= l;
						navListElements[l].onclick= function() {
							insStartChange(current);
							return false;
						};
					})();
					navListElements[l].href = '';
				}

				// set current page to be selected
				navListElements[gCurrentSlide].className = 'selected ' + navListElements[gCurrentSlide].className;
				navListElements = null;
			}
		}
	}
}

function insSetupPage() {
	if($(u_slideContainerID)) {
		// initial document title
		gInitialDocTitle = document.title;

		// set up array of slide divs and rename id
		var tempSlides = $(u_slideContainerID).getElementsByTagName('div');


		if(tempSlides.length > 0) {
			var tempSlideNo;
			var largestHeight;
			var i = 0;
			for(i;i<tempSlides.length; i++) {
				if(tempSlides[i].className.indexOf(u_slideName) != -1) {

					// what slide is this
					tempSlideNo = parseInt(tempSlides[i].id.replace(u_slideName, ''), 10);

					// re-set slide id to avoid jumping but to maintain graceful degredation
					// URL will still maintain old ID of #u_slideNameXX
					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(u_slideName) != -1) {
					gCurrentSlide = parseInt(location.hash.replace('#'+u_slideName, ''), 10) - 1;
				} else if(location.hash.indexOf('top') != -1) {
					gCurrentSlide = 0;
					location.href = location.href.replace(location.hash, '#'+u_slideName);
				} else {
					gCurrentSlide = 0;
					location.href = location.href.replace(location.hash, '#'+u_slideName);
				}
				if(gCurrentSlide >= gSlides.length) {
					// SLIDE TOO HIGH
					gCurrentSlide = 0;
					location.href = location.href.replace(location.hash, '#'+u_slideName+'1');
				}
			} else {
				gCurrentSlide = 0;
				location.href = location.href + '#'+u_slideName+'1';
			}
			// replace current title with slide number and title
			document.title = u_slideTitlePrefix + ': ' + (gCurrentSlide + 1) +" : "+ gInitialDocTitle;

			// initialise and assign links
			insAssignNav();

			// write what page we are on at the moment

			var pagesText =  u_pages.split(',');
			for(var i = 0; i < pagesText.length; i++) {
				if($(pagesText[i])) {
					$(pagesText[i]).innerHTML = u_slideName + ' ' + (gCurrentSlide + 1) + ' of ' + gSlides.length;
				}
			}

			// 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);
		}
	}
	
	insStartChange1();
}


// 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",u_importedCSSfile);
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;

