// A gallery for doing image rotations

// Library Revision: $Rev$

// images = an array of image urls
// node = the node that is fading in and out and being passed to setSrcFunc
// setSrcFunc = the function that changes the url.  It takes in node and one of the images.
function Gallery(images, node, setSrcFunc){
	if(typeof(setSrcFunc) == 'function'){
		this.setSrcFunc = setSrcFunc;
	}
	else{
		this.setSrcFunc = function(node, image){
			$(node).attr('src', image);
		};
	}

	this.images = images;
	// $(this.images).hide();
	this.imgNode = node;
	this.position = 0;
	this.delay = 4000; // milliseconds
}

Gallery.prototype.begin = function(){
	if(this.images.length > 1){
		this.wait();
	}
}

// preloads the images
Gallery.prototype.preload = function(){
	var loadImg = function(url){
		var image = new Image();
		image.src = url;
		return image;
	};

	$.map(this.images, loadImg);
}

Gallery.prototype.wait = function(){
	// console.log('wait');
	// we need this line so we can actually call nextImage on 'this' object
	var currentObject = this;
	setTimeout(function(){ currentObject.nextImage(); }, this.delay);
}

Gallery.prototype.nextImage = function(){
	console.log('nextImage');
	// we need this line so we can actually call nextImage on 'this' object
	var currentObject = this;
	// get the position of the next image
	this.position = (this.position + 1) % this.images.length;

	$(this.imgNode).fadeOut('slow', function(){
		$(currentObject.imgNode).attr('visibility', 'hidden');
		// $(currentObject.imgNode).attr('src', currentObject.images[currentObject.position].src);
		currentObject.setSrcFunc(currentObject.imgNode, currentObject.images[currentObject.position]);
		$(currentObject.imgNode).attr('visibility', 'visible');
		
		var fadeInAndWait = function(){
			$(currentObject.imgNode).fadeIn('slow', function(){ currentObject.wait() });
		}
		
		setTimeout(fadeInAndWait, 100);
		
		
	});
}
