$(function() {
	var settings = {
			width: $('.testimonial:first').outerWidth(true),
		total: $('.testimonial').length,
		current: 0,
		speed: 400
	};
	var setup = function() {
		$('#testimonials .list').css('overflow', 'hidden');
		$('.testimonial').each(function() {
			var controls = $('<div />')
				.addClass('controls')
				.appendTo($('.author', this));
			$('<img />')
				.attr('src', '/wp-content/themes/clearbooks/images/home/previous.gif')
				.appendTo(controls)
				.click(previous)
				.clone()
				.attr('src', '/wp-content/themes/clearbooks/images/home/next.gif')
				.appendTo(controls)
				.click(next);
		});
		$('#testimonials ul li a').each(function(i) {
			$(this).click(function(e, setup) {
				if ($(this).hasClass('more')) { return; }
				e.preventDefault();
				$(this).blur();
				settings.current = i;
				setItem(i * settings.width, setup ? 1 : false);
			});
		})
		.eq(Math.round(Math.abs(Math.random() * settings.total - 1)))
		.trigger('click', [true]);
	}
	var previous = function() {
		if (settings.current == 0) {
			settings.current = settings.total - 1;
			offset = settings.width * settings.total;
		} else {
			settings.current--;
			offset = '-=' + settings.width + 'px';
		}
		setItem(offset);
	};
	var next = function() {
		if (settings.current == settings.total - 1) {
			settings.current = offset = 0;
		} else {
			settings.current++;
			offset = '+=' + settings.width + 'px';
		}
		setItem(offset);
	};
	var setItem = function(offset, speed) {
		$('#testimonials .list')
			.stop()
			.animate({scrollLeft: offset}, (speed || settings.speed), 'swing', function() {
				$('#testimonials ul li a')
					.removeClass('selected')
					.eq(settings.current)
					.addClass('selected');
			});
	};
	setup();
});