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

	$(function () {
		$('.masthead-homecarousel').each(function () {
			var masthead = $(this);
			var pauseAutoRotation = false;

			masthead.hover(function () {
				pauseAutoRotation = true;
			}, function () {
				pauseAutoRotation = false;
			});

			function swap(e) {
				e.siblings('.on').removeClass('on').find('.tab span').fadeOut(FADE_SPEED);
				e.addClass('on');
				e.find('.tab span').fadeIn(FADE_SPEED);
				masthead.css('background-position', -935 + e.position().left + parseInt(e.css('margin-left')) + 'px 233px');
			}

			masthead.find('li').hoverIntent(function () {
				swap($(this));
			}, function () {
			});

			masthead.find('li:not(.on)').find('.tab span').hide();

			function autoRotate() {
				if (!pauseAutoRotation) {
					var e = masthead.find('.on');
					if (e.next().size() > 0) {
						e = e.next();
					} else {
						e = e.siblings(':first-child');
					}
					swap(e);
				}
				setTimeout(autoRotate, ROTATE_DELAY);
			}
			
			$(window).load(function () {
				setTimeout(autoRotate, ROTATE_DELAY);
			});
		});
	});
})(jQuery);
