/**
	Rotating Banner Control
	Written by Sam Clark, Polaris Digital
	(c) Polaris Digital Limited
	http://polaris-digital.com
	Released under the GNU Public Licence version 2	
**/

/* GLOBAL VARIABLES */
var imagePosition	= 0;				// Current image displayed
var maxNumber		= 1;				// Maximum number of positions (SET AUTOMATICALLY)
var xmlPath			= "/assets/xml/";			// Absolute path to the XML files
var xmlFile;
										// XML file that contains files
var imageFileURI	= new Array();						// Image URI array
var animationPlay	= true;			// Animation play state (boolean, false = no; true = yes)
var imageHistory	= new Array();		// History to which image is being displayed

/* MOOTOOLS SPECIFIC GLOBALS */
var periodical;							// Periodical variable that contains instructions to swap the current image
var holdDuration 	= 5000;			// Hold the image for xxx milliseconds
var animationDuration = 1000;			// Animation duration is xxx milliseconds

addLoadEvent(initialiseBanner);

/* METHODS */

function getXMLFilename() {				// Gets the name of the XML file from the body
	if(!document.getElementsByTagName('ul'))
		return false;
	var bodyId = document.getElementsByTagName('ul')[0].getAttribute('id');
//	alert(bodyId);
	return (bodyId + '.xml');
}

function initialiseBanner() {			// Script controller function
	
	xmlFile = (xmlPath + getXMLFilename());
	loadXMLlist(xmlFile);				// Load xml files and preload image files (loadXMLlist->fileHandler->parseFiles->loadImages)
//	maxNumber = imageFileURI.length;	// Get the maximum number of images
	imagePosition = generateRandomNumber(imagePosition, maxNumber);
										// Get the next image position
//	if(!document.getElementById()||!document.getElementById('playButton')||!document.getElementById('forwardButton')||!document.getElementById('imageBanner'))
//		return false;					// GET OUT if getElementById does not exist, OR the elements are not present

	$('playButton').addEvent('click', function() {
		 playButton(animationPlay)
	});

	$('forwardButton').addEvent('click', function() {
		$('playButton').setAttribute('class', 'play');
		animationPlay = false;
		$clear(periodical);
		swapOutImage();
	});				
	
	$('backButton').addEvent('click', function() {
		$('playButton').setAttribute('class', 'play');
		animationPlay = false;
		$clear(periodical);
		swapOutImage();
	});						
										
	periodical = swapOutImage.periodical(holdDuration);
										// Begin playback
}

function playButton(playState) {	// Control the animation
	var playbutton = document.getElementById('playButton');
	if(!playState) {
		if(BrowserDetect.browser == 'Explorer')
			playbutton.className = 'pause';
		else
			playbutton.setAttribute('class', 'pause');
		animationPlay = true;
		periodical = swapOutImage.periodical(holdDuration);
//		alert('Playing Animation!');
	} else {
		if(BrowserDetect.browser == 'Explorer')
			playbutton.className = 'play';
		else
			playbutton.setAttribute('class', 'play');
		animationPlay = false;
		$clear(periodical);
//		alert('Stopping Animation!');
	}
}

function generateRandomNumber(currentNum, maxNum) {
										// Generates a random number, ensuring it isn't the same as the current one
	var myNumber = currentNum;
	var upperLimit = maxNum;
	while(myNumber == currentNum)
	{
		myNumber = Math.round(Math.random()*maxNum);
		if(myNumber > upperLimit)
			myNumber = currentNum;
	}
	
	imageHistory.push(myNumber);
//	alert('Number generated : ' + myNumber + '\nMaximum allowed : ' + upperLimit);
	return myNumber;
}

function loadXMLlist(fileuri){			// Create an XHR request for an XML file
	var request = getHTTPObject();
	if (request) {
		request.onreadystatechange = function() {
			fileHandler(request);
		}
	}
	request.open("GET", fileuri, true);
	request.send(null);
}

function fileHandler(request) {		// Handle the response from the server
	if(request.readyState == 4) {
		// File finished loading, parse the XML file
		if(request.status == 200 || request.status == 304) {
			var filelist = request.responseXML;
			var files = filelist.getElementsByTagName("file");
//			alert(files.length);
			parseFiles(files);
		}
	}
}

function parseFiles(data) {			// Parse the XML data to create a file list
	for(i = 0; i < data.length; i++) {
		imageFileURI.push(data[i].firstChild.nodeValue);
	}
//	alert(imageFileURI[0]);
	loadImages(imageFileURI);
}

function loadImages(imageArray) {	// Load splash images	
	var myImages = new Asset.images(imageArray, {
	    onComplete: function(){
		maxNumber = (imageArray.length-1);
//		alert('all ' + maxNumber + ' images loaded!');
	    }
	});	
}

function swapOutImage() {
	imagePosition = generateRandomNumber(imagePosition, maxNumber);
	var myFx = new Fx.Style('imageBanner', 'opacity', {'duration' : animationDuration, 'onComplete' : swapInImage}).start(1,0);
}

function swapInImage() {
	var imageToReplace = document.getElementById('imageBanner');
	imageToReplace.setAttribute('src', imageFileURI[imagePosition]);
	var myFx = new Fx.Style('imageBanner', 'opacity', {'duration' : animationDuration}).start(0,1);
}

function getHTTPObject() {			// Creates an XMLHttpRequest object for all browsers, and returns it
	var xhr = false;
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false
			}
		}
	}
	return xhr;
}

/*	Add Load Event function
	Written by Simon Willison
	© 2004 Simon Willison, http://simon.incutio.com
	GPL Licence
*/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}