var id


  function doFadeNext(  ) {
        imageFader.fadeNextImage();
  }

var ImageFader = Class.create({

  //Flag to say if the fader is on or off
  isFading: false,

  //The current image in the image list array
  currentImageIndex: 0,

  //Delay between image swops
  delay: 5000,

  instances: new Array(),

  initialize: function(imageList) {
	//Randomise the array and store it
	this.imageList = imageList;
	this.currentImgElement = $('mainImageImg');

	if(!ImageFader.instances)ImageFader.instances = new Array()
	this.id = ImageFader.instances.length;
	ImageFader.instances[this.id] = this;

  },
  

  start: function(){
	this.isFading = true;
	id = this.id;
    
    this.fadeTimer = setInterval( "doFadeNext(); ", this.delay  );
  },

  stop: function(){
	  clearInterval(this.fadeTimer);
	  this.isFading = false;
  },

  //This function is called by setInterval,
  //which is stateless SO IT CANNOT ACCESS 'THIS'
  fadeNextImage: function(){
	  
	  if(this.isFading){
		this.currentImageIndex = (this.currentImageIndex + 1) % this.imageList.length;
		this.currentImgElement = this.fadeImage(this.imageList[this.currentImageIndex], this.currentImgElement);
	  }
  },

  fadeImage: function(image, currentImg) {

	if(image){
		//Hide the current image, make sure that after it
		//is had dissapeared, it is removed from the DOM
		//to keep things tidy.
		currentImg.fade({
			afterFinish: function(){
				currentImg.remove();
			}
		});

		image.src   = (typeof(image.src)!="undefined") ? image.src : "";
		image.title = (typeof(image.title)!="undefined") ? image.title : "";

		//Make a new image, and prep it.
		var newImage = new Element("img",{
			src: image.src,
			alt: image.title,
			title: image.title,
			className: 'hand'
		});

		if(image.href){
			newImage.onclick = function(){
				document.location = image.href;
			}
		}
        
		newImage.setStyle({
			display: 'none',
			position: 'absolute'
		});
		//Add the new image to the page with a fader
		currentImg.parentNode.insertBefore(newImage, currentImg);
		newImage.appear();

		//Return the new image
		return newImage;
	}
	return currentImg;

  }
});