function HomeCarousel(emt){
	this.wrapper = emt;
	this.init();
}

(function($){
	$.extend(HomeCarousel.prototype, {
		currentIndex: 0,
		auto: 4000,
		timer: null,
		animSpeed: 'slow',
		visibleItems: 4,
		items: null,
		
		init: function(){
			var that = this;
			$(this.wrapper).shuffle();
			this.items = $(this.wrapper).find('li');
			
			if(this.items.size() > this.visibleItems){
				this.update(false);
			}
		},
		
		update: function(animate){
			var that = this;
			if(animate){
				var first = $(that.wrapper).find('li:first');
				var width = $(that.wrapper).find('li:first').outerWidth(); 
				
				first.animate({
					"margin-left": (0 - width),
					"opacity": 0
				}, that.animSpeed, 'swing', function(){
					var emt = first.detach();
					emt.css({
						"margin-left": 0,
						"opacity": 1
					});
					that.wrapper.append(emt);
				});
			}
			
			if(that.auto !== false){
				that.timer = setTimeout(function(){that.next();}, that.auto);
			}
		},
		
		next: function(){
			clearTimeout(this.timer);
			this.currentIndex++;
			this.update(true);
		}
	});
})(jQuery);


(function($){
	$.fn.carousel = function(){
		window.homeCarousel = new HomeCarousel($(this).eq(0));
		window.homeCarousel.defaultAuto = window.homeCarousel.auto;
		
		$(this).find('li').each(function(){
			$(this).click(function(){
				window.location.href = $(this).find('a:first').attr('href');
			});
		});
		
		$(this).mouseover(function(){
			clearTimeout(window.homeCarousel.timer);
			window.homeCarousel.defaultAuto = window.homeCarousel.auto;
			window.homeCarousel.auto = false;
		});
		
		$(this).mouseout(function(){
			window.homeCarousel.auto = window.homeCarousel.defaultAuto;
			window.homeCarousel.update(false);
		});
		
		return this;
	}
})(jQuery);
