(function($) {

	$.fn.joeSpotlight = function(options) {

		var controls = $(this).find('.spotlight-controls'),
			prev = controls.find('.prev'),
			next = controls.find('.next'),
			title = $(this).find('h2'),
			inner = $(this).find('.spotlight-inner'),
			items = inner.find('li'),
			itemsWidth = items.eq(0).width(),
			desc = $(this).find('p'),
			currentIndex = 1,
			disabledClass = 'disabled',
			locked = false;
	
		var loop;
		var nextSlide = function() {
			
			if(currentIndex == items.length) {
				currentIndex = 1;
				move(true, true);
				
			}
			else {
				next.trigger('click');
			}	
		};
		
		loop = setInterval(function() {
			nextSlide();
		}, 5000);
		$(this).hover(function() {
			
			clearInterval(loop);
		}, function() {
			loop = setInterval(function() {
				nextSlide();
			}, 5000);
		});

		function prev_slide(e) {	
			if(locked) return;
			currentIndex --;
			move();
		}
		
		function next_slide(e) {
			if(locked) return;
			currentIndex ++;
			move(true);
		}
		
		function move(negative, reset) {
			
			locked = true;
			reset = reset || false;
			setTimeout(function() {
				locked = false;
			}, 600);
			
			title.add(desc).animate({
				left: '-10px',
				opacity: 0
			}, {
				duration: 200,
				complete: function() {
					update_details();
					var newLeft = (negative) ? (inner.position().left - itemsWidth) : (inner.position().left + itemsWidth);
					if(reset) newLeft = 0;
					inner.animate({
						left: newLeft
					}, {
						duration: 600,
						easing: 'custom',
						complete: function() {
							title.add(desc).animate({
								left: '0',
								opacity: 1
							}, {
								duration: 200
							});
						}
					});
				}
			});
			
			check_disabled();
			
		}
		
		function check_disabled() {
			prev.removeClass(disabledClass);
			next.removeClass(disabledClass);
			if(currentIndex == items.length) {
				next.addClass(disabledClass);
			}
			if(currentIndex == 1) {
				prev.addClass(disabledClass);
			}
		}
		
		function update_details() {
			var currentItem = items.eq(currentIndex-1).find('img');
			title.html('<a href="' + currentItem.parent('a').attr('href') + '">' + currentItem.attr('data-title') + '</a>');
			desc.html(currentItem.attr('data-description'));
		}
		
		controls.delegate('.prev:not(.' + disabledClass + ')', 'click', prev_slide);
		controls.delegate('.next:not(.' + disabledClass + ')', 'click', next_slide);
		controls.find('a').click(function(e) { e.preventDefault(); });
		
	};
		
})(jQuery);

