/* general variables */
var INITIAL_DISPLAY_DURATION = 0;			// in milliseconds
var DISPLAY_DURATION = 7000;				// in milliseconds
var COOKIE_NAME = 'LastViewedTestimonial';	// name of the cookie that stores the last testimonial the client viewed
var galleryId = 'testimonial_gallery';		// change this to the ID of the gallery list
var	gallery;								// this will be the object reference to the list later on
var galleryImages;							// array that will hold all child elements of the list
var currentImage;							// keeps track of which image should currently be showing
var previousImage;
var preInitTimer;

preInit();

function preInit() {
	/* an inspired kludge that - in most cases - manages to initially hide the image gallery list
	   before even onload is triggered (at which point it's normally too late, and the whole list already
	   appeared to the user before being remolded) */
	if ((document.getElementById)&&(gallery = document.getElementById(galleryId))) {
		gallery.style.visibility = "hidden";
		if (typeof preInitTimer != 'undefined') clearTimeout(preInitTimer); /* thanks to Steve Clay http://mrclay.org/ for this small Opera fix */
	} else {
		preInitTimer = setTimeout( "preInit()", 2 );
	}
}

function fader(imageNumber, opacity) {
    if (imageNumber < galleryImages.length) {
        /* helper function to deal specifically with images and the cross-browser differences in opacity handling */
        var obj = galleryImages[imageNumber];

        //alert("imageNumber: " + imageNumber + ", len: " + galleryImages.length);

        if (obj.style) {
            if (obj.style.MozOpacity != null) {
                /* Mozilla's pre-CSS3 proprietary rule */
                obj.style.MozOpacity = (opacity / 100) - .001;
            } else if (obj.style.opacity != null) {
                /* CSS3 compatible */
                obj.style.opacity = (opacity / 100) - .001;
            } else if (obj.style.filter != null) {
                /* IE's proprietary filter */
                obj.style.filter = "alpha(opacity=" + opacity + ")";
            }
        }
    }
}

function fadeInit() {
	if (document.getElementById) {
		preInit(); // shouldn't be necessary, but IE can sometimes get ahead of itself and trigger fadeInit first
		galleryImages = new Array;
		
		if( gallery != null ){
			var node = gallery.firstChild;
			/* instead of using childNodes (which also gets empty nodes and messes up the script later)
			we do it the old-fashioned way and loop through the first child and its siblings */
			while (node) {
			    if (node.nodeType == 1 && node.nodeName.toUpperCase().indexOf("LI") >= 0) {
					galleryImages.push(node);
				}
				node = node.nextSibling;
			}
			for(i=0;i<galleryImages.length;i++) {
				/* loop through all these child nodes and set up their styles */
				galleryImages[i].style.position = 'absolute';
				galleryImages[i].style.zIndex = 0;

				/* set their opacity to transparent */
				fader( i, 0 );
			}
			/* make the list visible again */
			gallery.style.visibility = 'visible';
			
			/* initialise a few parameters to get the cycle going */
			currentImage = getCookieNew( COOKIE_NAME );
			if( currentImage == null )
				currentImage = 0;
			
			currentImage *= 1;	// ensure we're dealing with integers
				
			previousImage = galleryImages.length - 1;
			opacity = 100;
			fader( currentImage, 100 );
			/* start the whole crossfade process after a second's pause */
			window.setTimeout( "crossfade(100)", INITIAL_DISPLAY_DURATION );
		}
	}
}

function crossfade( opacity ) {
	if (opacity < 100) {
		/* current image not faded up fully yet...so increase its opacity */
		fader( currentImage, opacity );
		fader( previousImage, 100-opacity );
		
		opacity += 10;
		window.setTimeout("crossfade(" + opacity + ")", 30);
	} else {
		// make note of the testimonial the client is currently viewing
		setCookieNew( COOKIE_NAME, currentImage, 999 );
		
		/* make the previous image - which is now covered by the current one fully - transparent */
		fader( previousImage, 0 );

		/* make sure the current image is on top of the previous one */
		if (previousImage < galleryImages.length)
		    galleryImages[previousImage].style.zIndex = 0;
		
		if( currentImage < galleryImages.length )
		    galleryImages[currentImage].style.zIndex = 100;
		
		// current image is now previous image, as we advance in the list of images
		previousImage = currentImage;
		currentImage += 1;
		
		// start over from first image if we cycled through all images in the list
		if (currentImage >= galleryImages.length) {
			currentImage = 0;
		}
		
		// start the crossfade after a pause
		opacity = 0;
		window.setTimeout("crossfade( " + opacity + " )", DISPLAY_DURATION );
	}
}


/* initialise fader by hiding image object first */
addEvent(window,'load',fadeInit);

/* 3rd party helper functions */

/* addEvent handler for IE and other browsers */
function addEvent(elm, evType, fn, useCapture) 
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
 if (elm.addEventListener){
   elm.addEventListener(evType, fn, useCapture);
   return true;
 } else if (elm.attachEvent){
   var r = elm.attachEvent("on"+evType, fn);
   return r;
 }
} 

// COOKIE FUNCTIONS
function setCookieNew( c_name, value, expiredays )
{
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + expiredays );
	//alert( "setting cookie \"" + c_name + "\": " + value );
	
	document.cookie = c_name + "=" + escape(value) + ( ( expiredays == null ) ? "" : ";path=/;expires=" + exdate );
}

function getCookieNew( c_name )
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf( c_name + "=" );
			
		if ( c_start != -1 && c_start != null )
		{ 
			c_start = c_start + c_name.length + 1;
			c_end =document.cookie.indexOf(";",c_start);
			if( c_end == -1 )
				c_end = document.cookie.length;
			
			//alert( "getting cookie \"" + c_name + "\": " + document.cookie.substring( c_start, c_end ) );
			
			return unescape( document.cookie.substring( c_start, c_end ) );
		} 
	}
	return null;
}