$(document).ready(function () {
	// --------------- mouse-over thumbnail stuff --------------

	// Attach a mouse-over function to each thumbnail image to display the
	// full-size image.
	$('a[enlargeimage]').each(function (index) {
		// Pre-load each image as we go through this.
		(new Image()).src = $(this).attr('enlargeimage');

		// Set the mouseover function.
		$(this).mouseover(function () {
			var loadarea = $('div#loadarea');
			var img = $(this).attr('enlargeimage');

			// We only need to act if the image we're supposed to put in place
			// isn't already in place.
			if (loadarea.data('current') != img) {
				// Construct the HTML.
				var href = $(this).attr('href');
				if (href) {
					var new_html = '<a href="' + href + '"><img src="' + img + '" border="0" /></a>';
				} else {
					var new_html = '<a><img src="' + img + '" /></a>';
				}

				// Insert the HTML.
				loadarea.html(new_html);

				// If the original thumbnail is a colorbox trigger, create a
				// click action to fire the original thumbnail's click action.
				if ('colorbox' in $(this).data()) {
					loadarea.children('a').click(function () {
						$('a[enlargeimage][href="' + href + '"]').click();
						// Prevent the click from propagating.
						return false;
					});
				}

				// Fade-in the image.
				loadarea.find('img').hide().fadeIn(500);

				// Note which image is now in place.
				loadarea.data('current',img);
			}
		});
	});


	// --------------- rotating image stuff --------------------

	// How many images are we rotating through?
	rotationElementCount = $('a[enlargeimage]').length;

	// Track which image we most recently rotated to.
	mostRecentRotation = rotationElementCount - 1;

	// The table that contains the thumbnails and the loading area.
	rotatingImageTable = $('a[enlargeimage]').closest('table')

	// The function to rotate the images.
	rotateImg = function() {
		// Increment mostRecentRotation, mod the number of elements through
		// which we are rotating.
		mostRecentRotation = (mostRecentRotation + 1) % rotationElementCount;

		// Swap to the target image by triggering its mouseover handler (since
		// mousing over the thumbnail is what normally triggers the image
		// swap).
		$($('a[enlargeimage]')[mostRecentRotation]).mouseover();

		// Clear any existing timer.
		clearTimeout(rotatingImageTable.data('timeoutId'))

		// Set a timer to rotate to the next image in 5 seconds (5000
		// milliseconds) and store its ID for future clearing.
		var timeoutId = setTimeout("rotateImg();", 5000);
		rotatingImageTable.data('timeoutId', timeoutId);
	}

	// When the mouse enters the table containing the thumbnails and loading
	// area, clear any timers so as to freeze the rotation; when the mouse
	// leaves, restart the rotation.
	rotatingImageTable.hover(
		function () {
			clearTimeout(rotatingImageTable.data('timeoutId'))
		},
		function () {
			rotateImg();
		});

	// Start the rotation.
	rotateImg();
});

