/**
 * A very basic image crossfader
 * 
 * @param el {Object} The wrapping element
 * @param imgs {Array} An array containing the image relative paths
 * @param options {Object} Optional parameters
 */
function ImageCrossFader(el, imgs, options) {
	this.el = $(el);
	this.imgs = imgs;
	this.options = options;
	
	this.interval = null;
	this.index = 0;
	this.cache = [];
	
	this.init();
};

ImageCrossFader.prototype = {
	
	/**
	 * Initialize instance
	 */
	init: function() {
		if(this.el) {
			this.options = $.extend({
				duration: 1,
				delay: 5
			}, this.options || {});
			
			this.cache.push(this.el.find('img:first-child')[0]);
			
			this.start();
		}
	},
	
	/**
	 * Start crossfading the images
	 */
	start: function() {
		var self = this;
		
		this.interval = setInterval(function() {
			self.next();
		}, this.options.delay * 1000);
	},
	
	/**
	 * Crossfade to the next image
	 */
	next: function() {
		var self = this;
		var newImg = null;
		
		this.index = ((this.index + 1) === this.imgs.length) ? 0 : this.index + 1;
		
		if(this.cache[this.index]) {
			newImg = this.cache[this.index];
			this.append(newImg);
		}
		else {
			newImg = new Image();
			
			$(newImg).load(function() {
				this.setAttribute('width', this.width);
				this.setAttribute('height', this.height);
				self.append(this);
			});
			
			$(newImg).hide();
			newImg.src = this.imgs[this.index];
			
			this.cache[this.index] = newImg;
		}
	},
	
	/**
	 * Crossfade effect
	 * 
	 * @param img {Object} The image to append
	 */
	append: function(img) {
		this.el[0].appendChild(img);
		this.crossFade(this.el.find('img:first-child')[0], img);
	},
	
	/**
	 * Crossfade effect
	 * 
	 * @param current {Object} The currently visible image
	 * @param next {Object} The next image to appear
	 */
	crossFade: function(current, next) {
		$(current).fadeOut(this.options.duration * 1000, function() {
			$(this).remove();
		});
		$(next).fadeIn(this.options.duration * 1000);
	}
};
