(function ($) {
	var FADE_SPEED = 'fast';
	var ROTATE_DELAY = 4000;

	var SELECTOR = '.carousel';
	var WINDOW_SELECTOR = '.carousel_window';
	var NAV_SELECTOR = '.carousel_nav';
	var ON_CLASS = 'on';

	$(function () {
		$(SELECTOR).each(function () {
			var carousel = $(this);
			var carouselWindow = carousel.find(WINDOW_SELECTOR);
			var carouselNav = carousel.find(NAV_SELECTOR);

			var pauseAutoRotation = false;

			// Sets up the pausing on the carousel.
			carousel.hover(function () {
				pauseAutoRotation = true;
			}, function () {
				pauseAutoRotation = false;
			});

			// Swaps the windows.
			function swap(navigationTab) {
				$(navigationTab.siblings('.' + ON_CLASS).removeClass(ON_CLASS).find('a').attr('href')).removeClass(ON_CLASS).hide();
				$(navigationTab.addClass(ON_CLASS).find('a').attr('href')).addClass(ON_CLASS).show();
			}

			// Setup the hovers for the tabs.
			carouselNav.children().hover(function () {
				swap($(this));
			}, function () {
			});

			// Hide all alternative windows.
			carouselNav.children(':not(.' + ON_CLASS + ')').each(function () {
				$($(this).find('a').attr('href')).hide();
			});

			carouselNav.children('.' + ON_CLASS).each(function () {
				$($(this).find('a').attr('href')).addClass(ON_CLASS);
			});

			// Sets up, and starts the auto rotation of windows & tabs.
			function autoRotate() {
				if (!pauseAutoRotation) {
					var e = carouselNav.find('.' + ON_CLASS);
					if (e.next().size() > 0) {
						e = e.next();
					} else {
						e = e.siblings(':first-child');
					}
					swap(e);
				}
				setTimeout(autoRotate, ROTATE_DELAY);
			}

			setTimeout(autoRotate, ROTATE_DELAY);

			carouselNav.find('a').click(function () {
				$(this).attr('href', $($(this).attr('href')).find('a').attr('href'));
				// return false;
			});
		});
	});
})(jQuery);
