(function($){

$.fn.montage = function(imageArray, options) {
	$.fn.montage.defaults = {
		'delay' : 1000,
		'fadeSpeed' : 1000,
		'pauseOnMouseover' : true,
		'hoverCursor' : 'pointer'
	};
	
	var opts = $.extend({}, $.fn.montage.defaults, options);
	
	return this.each(function() {
		var timer,
			index = 0,
			nextImg,
			montage = this,
			$montage = $(this),
			images = imageArray,
			elapsedTime = 0,
			mouseIsOverImage = false;
		
		function nextIndex() {
			return (index + 1) % images.length;
		}
		
		function hasLink() {
			return images[index][1] && $.trim(images[index][1]) != '';
		}
		
		function addLink(whichImage) {
			if (hasLink()) {
				$montage.css('cursor', opts.hoverCursor);
				$('img', montage).eq(whichImage)
					.css('border', 0)
					.wrap('<a href="' + images[index][1] + '"></a>');
			} else
				$montage.css('cursor', 'default');
		}
		
		function showNext() {
			timer = clearTimeout(timer);
			index = nextIndex();
			
			$(montage).append(nextImg);
			$(nextImg).css({ position:'absolute', zIndex:'1' });
			
			addLink(1);
			
			$('img', montage).eq(0).fadeOut(opts.fadeSpeed, function(){																
				$('img', montage).eq(1).css({ position:'absolute', zIndex:'9' });
				
				nextImg = new Image();
				nextImg.src = images[nextIndex()][0];

				$('img', montage).eq(0).remove();
				
				elapsedTime = 0;
				timer = setInterval(update, 10);
			});
		}
		
		function update(){
			if (elapsedTime >= opts.delay && (!opts.pauseOnMouseover || !mouseIsOverImage)) {
				showNext();
			} else
				elapsedTime += 10;
		}
		
		(function init() {
			$(montage).height($('img', montage).height());
			
			addLink(0);
			
			nextImg = new Image();
			nextImg.src = images[nextIndex()][0];
			
			$('img', montage).eq(0).css({ position:'absolute', zIndex:'9' });
			
			$montage.mouseover(function() { mouseIsOverImage = true; });
			$montage.mouseout(function() { mouseIsOverImage = false; });
			
			timer = setInterval(update, 10);
		})();
	});
}

})(jQuery);

