(function($) {

	$.fn.reverse = [].reverse;

	var config = {
		distance : 980,
		speed    : 2000,
		easing   : 'easeOutQuad'
	};
	
	var smallConfig = {
		distance : 380,
		speed    : 800,
		easing   : 'easeOutQuad'
	};
	
	$('.scroller').each(function(i, scroller) {
		var scroller  = $(scroller);
		var scrollbox = scroller.children('div');
		var images    = scrollbox.children();
		
		if (scroller.attr('id') === 'scroller-small')
			config = smallConfig;
		
		images = scrollbox.children();
		
		var distance = 0;
		images.each(function(i, image) {
			image = $(image);
			image.css({
				position : 'absolute',
				top      : 0,
				left     : distance
			});
			distance += image.outerWidth();
		});
		
		var scroll = function(e, direction) {
			if ( ! images.is(':animated')) {
				tips.qtip('hide').qtip('disable');
				
				direction = direction ? true : false; // true = slide left, false = slide right
				
				// Sliding left
				if (direction) {
					scrollbox.children().each(function(i, image) {
						image = $(image);
						var width = image.outerWidth();
						var left  = image.position().left;
						
						if (left < 0 && Math.abs(left) > width) {
							var lastImg = scrollbox.children().last();
							var left = lastImg.position().left + lastImg.outerWidth();
							image.appendTo(scrollbox).css('left', left);
						}
					});
					
					images.stop().animate({left:'-=' + config.distance}, config.speed, config.easing);
				}
				// Sliding right
				else {
					// See where we will end up before actually scrolling
					scrollbox.children().reverse().each(function(i, image) {
						image = $(image);
						var left = image.position().left;
						
						if (left > scrollbox.width()) {
							var firstImg = scrollbox.children().first();
							var left = firstImg.position().left - image.outerWidth();
							image.prependTo(scrollbox).css('left', left);
						}
					});
					
					images.stop().animate({left:'+=' + config.distance}, config.speed, config.easing);
				}
				
				setTimeout(function() {
					tips.qtip('enable');
				}, config.speed + 100);
			}
		};
		
		scrollbox.click(function(e) {
			var half   = Math.round(scrollbox.width() / 2);
			var clickX = e.pageX - scrollbox.offset().left;
			
			var direction = (clickX < half) ? false : true;
			
			scroll(e, direction);
		});
		
		scrollbox.mousewheel(function(e, delta) {
			e.preventDefault();
			
			var direction = (delta > 0) ? false : true;
			
			scroll(e, direction);
		});
	});

})(jQuery);
