$(function () {
	wrapAntigramLettersInSpans();
});

// Wrap each letter in each antigram with a <span>.
function wrapAntigramLettersInSpans() {

	// Loop through each <dd>.
	var dds = $('#primaryContent dd');
	dds.each(function () {

		// Grab its antigram.
		var dd = $(this);
		var antigram = dd.html();
		var spanifiedAntigram = '';

		// Loop through each character of the antigram and wrap in a span.
		for (var i = 0; i < antigram.length; i++) {
			spanifiedAntigram += '<span>' + antigram.charAt(i) + '</span>';
		}

		// Replace <dd>'s HTML with the spanified antigram.
		dd.html(spanifiedAntigram);
	});

	// Make each <span> invisible.
	$('#primaryContent dd span').css('visibility', 'hidden');

	showAndHideAntigram();
}

// When each term is hovered upon, show its antigram. When moused off of, hide its antigram.
function showAndHideAntigram() {

	// When each <dt> is hovered upon.
	$('#primaryContent dt').hover(function() {

		// Grab references to relevant elements.
		var dt = $(this);
		var dd = dt.next('dd');
		var spans = $('span', dd);
		var i = 0;

		// Add 'hover' class to <dt>.
		dt.addClass('hover');

		// Ensure the <dt>'s corresponding <dd> is visible.
		dd.css('visibility', 'visible');

		// Hide a <span>, then hide the next <span> after a delay, and so on until no <span>s remain.
		var fadeInSpans = function() {
			var span = spans.eq(i);

			// If there's no more <span>s to fade in, exit the function.
			if (i >= spans.length || dd.css('visibility') == 'hidden') return;

			// Show the <span>s.
			span.css('visibility', 'visible');

			// Show the next <span> after a delay.
			setTimeout(function () {
				i++;
				fadeInSpans();
			}, 50);
		};

		// Begin the <span> fade-in recursion process.
		fadeInSpans();
	},

	// When the <dt> is moused off of.
	function () {
		var dt = $(this);
		var dd = dt.next('dd');
		var spans = $('span', dd);

		// Remove 'hover' class.
		dt.removeClass('hover');

		// Hide its corresponding <dd> and the <dd>'s <span>s.
		dd.css('visibility', 'hidden');
		spans.css('visibility', 'hidden');
	});
}