
$(document).ready(function () {
	
	// All lists on the current page
	var $lists = $('.reviews');
	// Boolean, whether or not lists should scroll. By default, only if there's
	// only one list on the page, if there are more it would look confusing.
	var scroll = $lists.size() == 1;
	
	// For each list of reviews (specials)
	$lists.each( function() {
		var $this = $(this);
		// Get all reviews (specials) in the current list
		var $reviews = $this.find('.reviews-content');
		var $reviews_foot = $this.find('.reviews-foot');
		// Get the tabs list
		var $tabs = $reviews_foot.find('ul');
		
		// Extend $this (the list)
		$reviews.extend({
			
			// Initialize
			init: function () {
				// Set the number of tabs equal to the number of reviews, and
				// hide them
				$reviews.tabCount = $reviews.find('li').hide().size();
				// Return the reviews
				return $reviews;
			},
			
			// Make review 'i' active
			setReview: function (i) {
				
				// Ignore the same click event twice.
				if (i == $reviews.activeTab) {
					return;
				}
				
				// Find the i'th review
				var $review = $reviews.find('li').eq(i);
				
				// If we have an active tab
				if ($reviews.activeTab >= 0) {
					// Find the active review, fade it out, and fade in the new
					// one
					$reviews.find('li')
						.eq($reviews.activeTab)
							.fadeOut('fast', function () {
								$review.fadeIn();
							});
				} else {
					// Otherwise, just fade in this tab
					$review.fadeIn();
				}
				
				// Find the current tab and remove the 'active' class from it
				$tabs.find('a.active').removeClass('active');
				// Add the 'active' class to what is now the active class
				$tabs.find('a').eq(i).addClass('active');
				
				// Set the active tab
				$reviews.activeTab = i;
				
				// Autoscroll
				if( scroll )
				{
					clearInterval($reviews.intervalId);
					$reviews.intervalId = setInterval (function () { $reviews.nextReview() },
						8 * 1000);
				}
			},
			
			nextReview: function () {
				// Get the number of the next tab
				var nextTab = $reviews.activeTab + 1;
				
				// Wrap around
				if (nextTab >= $reviews.tabCount) {
					nextTab = 0;
				}
				
				// Set the active review to the new tab
				$reviews.setReview (nextTab);
			},
			
			activeTab: -1
			
		}).init();
		
		// Get the title of the active review
		var $title = $reviews_foot.find('.reviews-title');
		
		// Empty the list of tabs
		$tabs.find('ul').empty();
		
		// Loop through each review adding links to the widget.
		$reviews.find('li').each(function (i) {
			
			var $review = $(this);
			
			var a = $('<a href="#" />')
				.mouseover(function () {
					$title.text($review.find('h2').text());
				})
				.mouseout(function () {
					$title.text('');
				})
				.click(function () {
					$reviews.setReview(i);
					return false;
				});
			
			$tabs.append($('<li>').append(a));
		});
		
		// Trigger the change for the first link.
		$reviews_foot.find('a').eq(0).trigger('click');
	});
});
