(function($){

$.fn.montage = function(imageArray, options) {
	$.fn.montage.defaults = {
		'delay' : 1000,
		'pauseOnMouseover' : true
	};
	
	var opts = $.extend({}, $.fn.montage.defaults, options);
	
	return this.each(function() {
		var timer,
			index = 1,
			nextImg,
			then,
			fading = false,
			delay = opts.delay,
			pauseOnMouseover = opts.pauseOnMouseover,
			montage = this,
			images = imageArray;
					
		function startIt() {
		
			nextImg = new Image();
			nextImg.src = images[index];
			
			$('img', montage).eq(0).css({ position:'absolute', zIndex:'9' });
			
			then = (new Date()).getTime();
			
			if (!fading)
				showNext();
		}
		
		function restartIt() {
		
			var diff = (new Date()).getTime() - then;
		
			if (diff >= delay)
				startIt();
			else
				t = setTimeout(restartIt, diff);
		}
		
		function showNext(){
		
			fading = true;
			clearTimeout(timer);
			
			$(montage).append(nextImg);
			$(nextImg).css({ position:'absolute', zIndex:'1' });
			
			$('img', montage).eq(0).fadeOut(1500, function(){
			
				$('img', montage).eq(1).css({ position:'absolute', zIndex:'9' });

				index = ++index % images.length;
				nextImg = new Image();
				nextImg.src = images[index];

				$('img', montage).eq(0).remove();

				timer = setTimeout(showNext, delay);
				fading = false;

				if (pauseOnMouseover) {
					$('img', montage).mouseover(function(){ 
						clearTimeout(timer) 
					});
					$('img', montage).mouseout(restartIt);
				}
			});
		}
		
		$(montage).parent().height($(montage).height());
		timer = setTimeout(startIt, delay);
	});
}

})(jQuery);

$(document).ready(function() {
	var montageImages = [
			'images/home-center-1.jpg',
			'images/home-center-2.jpg',
			'images/home-center-3.jpg'
		],
		montageOptions = {
			'delay' : 4000,
			'pauseOnMouseover' : true
		};

	$('#montage').montage(montageImages, montageOptions);

});

