// boolean to limit movement
var isMoving = false;

//
// swapImg()
// Function runs on window load, going through link tags looking for rel="preview".
// These links receive onmouseover events that enable the preview display for their targets.
//
function swapImg(theLink) 
{
	var img = theLink.href;
	var imgtext = theLink.title;

	// stop if we've already loaded that image
	if ($("detailImg").src.split("?")[0] == theLink.href)
		return;
	// stop if we're already animating.	
	if (isMoving)
		return;
	
	// hilight the thumbnail	
	Element.addClassName(theLink, "active");
	
	// remove the hilight from the previous thumbnail
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "preview" && anchor !== theLink)){
			Element.removeClassName(anchor, "active");
		}
	}
	
	isMoving = true;	
	
	imgPreload = new Image();
	// Fade out the current image
	Effect.Fade('detailImg', {duration: .25, afterFinish: function() {imgPreload.src=img;}});
	// Preload the next image
	imgPreload.onload = function() {
		// Swap the image into place
		$("detailImg").src = img;
		$("detailImg").alt = imgtext;
		$("detailImg").width = imgPreload.width;
		$("detailImg").height = imgPreload.height;
		// Now fade it in
		Effect.Appear('detailImg', {duration: .25, afterFinish: function() {isMoving=false;}});
 	}
}

//
// initPreview()
// Function runs on window load, going through link tags looking for rel="preview".
// These links receive onmouseover events that enable the preview display for their targets.
//
function initPreview()
{	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "preview")){
			anchor.onclick= function() {swapImg(this); return false;}
		}
	}
}

//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}

// run initPreview onLoad
addLoadEvent(initPreview);