/**
 * Changes a work image and information in the photography gallery.
 *
 * @param	Integer		workId	ID of the work to display.
 * @access	public
 */
function changeWork(workId) {

	var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].id.indexOf('work_') == 0) {
			divs[i].style.display = 'none';
		}
	}
	document.getElementById('work_' + workId).style.display = '';
	var image = document.getElementById('work_' + workId + '_image');
	if (image.src.indexOf('_images/loading.gif') > -1) {
		image.src = image.src.replace(/_images\/loading.gif/, '_photos/work_' + workId + '.jpg');
	}

} // end function changeWork.

//document.registerEvent(document, 'click', cancelRightClick);
//document.registerEvent(document, 'dblclick', cancelRightClick);

var TD_ImageGrid_currentSlots = {};

$(document).ready(function() {

	if ($('.TD_ImageGrid').length) {
		setTimeout(rotateImageGrid, 2000);
		setTimeout(rotateImageGrid, 3000);
//		setTimeout(rotateImageGrid, 4000);
	}

});

function rotateImageGrid() {

	// Determine information about available slots and spare images.
	var slots = $('.TD_ImageGrid .TD_ImageGrid_slot');
	var spares = $('.TD_ImageGrid .TD_ImageGrid_spare');
	var nSlots = slots.length, nSpares = spares.length;

	// Determine a random slot to replace, and
	// a random spare image to replace it with.
	var slotId = Math.floor(Math.random() * nSlots);
	var spareId = Math.floor(Math.random() * nSpares);
	var slot = slots.eq(slotId), spare = spares.eq(spareId);
	var slotImage = slot.contents(), spareImage = spare.contents();

	// If multiple timeouts have been set, the selected spare image
	// may be empty. If this is the case, reset the timeout and abort.
	if (spareImage.children().length == 0) {
		setTimeout(rotateImageGrid, Math.floor(Math.random() * 2000));
		return;
	}

	// Check that the selected image hasn't been changed in the last 3 seconds.
	// If it has, reset the timeout and abort.
	var timestamp = new Date().getTime();
	if (slotId in TD_ImageGrid_currentSlots && TD_ImageGrid_currentSlots[slotId] >= (timestamp - 3000)) {
		setTimeout(rotateImageGrid, Math.floor(Math.random() * 2000));
		return;
	}

	// Remember the time at which this slot was replaced.
	TD_ImageGrid_currentSlots[slotId] = timestamp;

	// Ensure current image appears above the replacement.
	slotImage.css('z-index', 101);
	spareImage.css('z-index', 100);
	spareImage.remove().appendTo(slot).show();

	// Fade the current image out to reveal the replacement.
	// Once fading is complete, this image needs to be placed
	// in the now empty spare position and the timeout reset.
	slotImage.fadeOut(1000, function() {
		$(this).remove().appendTo(spare);
		setTimeout(rotateImageGrid, Math.floor(Math.random() * 2000));
	});

} // end function rotateImageGrid.