$(function() {
	var INTERVAL = 4000;

	function showHide(title) {
		var old = title.siblings('.on');
		if (old.length > 0) {
			old.next().fadeOut(function() {
				title.addClass('on');
				title.next().fadeIn();
			});
			old.removeClass('on');
		} else {
			title.addClass('on');
			title.next().fadeIn();
		}
	}

	var autoRotate = 0;

	function rotate(concertina) {
		if (autoRotate == 0) {
			var title = $('.on', concertina);
			var next = null;

			if (title.length == 0) {
				next = $('.title:first', concertina);
			} else {
				next = title.nextAll('.title:first');
			}
			if (next.length == 0) {
				next = title.siblings('.title:first');
			}
			showHide(next);
		}
		setTimeout(function() {
			rotate(concertina);
		}, INTERVAL);
	}

	$('.concertina').each(function() {
		var concertina = $(this);
		$('.title', this).each(function() {
			var title = $(this);
			title.hoverIntent(
				function() {
					showHide(title);
					autoRotate++;
				},
				function() {}
			);
			title.next().hide();
		});
		concertina.hoverIntent(
			function() {
				autoRotate++;
			},
			function() {
				autoRotate = 0;
			}
		);
		rotate(concertina);
	});
});
