var utimer, dtimer, autoscrolltimer;
var numthumbs, theobj, scale, thumbimg, scrollheight; 
var miny, maxy, thumby, thumbyoff, thumbhref, currentthumb, currentthumbloc;
var stageimgdiv, stageimg, stagefladiv, stagefla;
var stagewidth, stageheight;
var autoscrollpause;
var nvals = "n values: ";

var inscrollarea = false, isautoscrollmode = false, isautoscrolling = false;
var upscrollcount = 0, downscrollcount = 0;
var preloadactive = false;
var preloadAnimTimer = 0, preloadFrom, preloadFrame;
var imgPreload = new Image();

var ymargin = 8, xmargin = 4;
var gridheight, gridwidth, maxheight, maxwidth, aspect;
var scrollframe, scrolloffset, scrollcoef, framestoscroll = 7;

// Flash functions

function changeMovie(m) {
     var flashMovie=getFlash("stageflash");
     flashMovie.SetVariable("/:themovie", m);
}

function getFlash(movieName) {
	if (window.document[movieName]) {
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1) {
		if (document.embeds && document.embeds[movieName]) {
			return document.embeds[movieName]; 
		}
	} else	{
		return document.getElementById(movieName);
	}	
}

// Folio init and display functions

function initFolio(numshow,withauto) {
	isautoscrollmode = (withauto != 0);
	autoscrollpause = withauto * 1000;
	initWheel();
	
	stageimgdiv = document.getElementById("stageimagecontainer");  
	stageimg = document.getElementById("stageimage");
	stagefladiv = document.getElementById("stageflashcontainer");  

	var tdobj = document.getElementById('thumbdisplay');
	var stageobj = document.getElementById('maindisplay');
	var tw, th, i;

	stagewidth = stageobj.offsetWidth - 4;
	stageheight = stageobj.offsetHeight - 4;
	gridwidth = tdobj.offsetWidth;
	gridheight = Math.floor(tdobj.offsetHeight / numshow); 
	
	maxheight = gridheight - ymargin * 2;
	maxwidth = gridwidth - xmargin * 2;
	aspect = maxwidth / maxheight;
	
	// set numthumbs
	numthumbs = 0;
	while (document.getElementById('t'+numthumbs)) { numthumbs++; }	
		
	thumby = new Array(numthumbs);
	thumbyoff = new Array(numthumbs);
	thumbhref = new Array(numthumbs);
	scrollheight = gridheight * numthumbs;
	
	maxy = gridheight * numshow ;
	miny = maxy - (gridheight * (numthumbs - 1));
	currentthumbloc = gridheight * (Math.floor(numshow / 2) - 1);
	
	// window.alert("numthumbs: " + numthumbs + " \tgridheight: " + gridheight + " \tminy: " + miny + " \tmaxy: " + maxy);
	
	for (i = 0; i < numthumbs; i++) {
		theobj = document.getElementById('t'+i);
		thumbimg = theobj.firstChild.firstChild;
		link = theobj.firstChild;
		tw = thumbimg.width;
		th = thumbimg.height;
		if (tw / th > aspect) scale = maxwidth / tw;		
		else scale = maxheight / th;	
		if (scale < 1) {
			thumbimg.width = tw * scale;
			thumbimg.height = th * scale;
		}
		thumbyoff[i] = ymargin + (maxheight - thumbimg.height) / 2 - 2;
		thumby[i] = miny + i * gridheight;
		if (thumby[i] == currentthumbloc) { currentthumb = i; }
		thumbhref[i] = link.getAttribute("name");
		theobj.style.top = (thumby[i] + thumbyoff[i]) + 'px';
		theobj.style.left = (xmargin + (maxwidth - thumbimg.width) / 2 - 2) + 'px';
	}	
	showFull(currentthumb,0);
	tdobj.style.visibility = 'visible';
	resetScroll();
}

// Parts of this preload code are adapted from Caleb Sasser's FancyZoom

function doPreload(theindex,from) {

	if (!(isautoscrolling && from == 0)) { // only do something if autoscrolling, or from mouse, but not both
		theimage = thumbhref[theindex];
		while (theimage.indexOf("f/") != -1) {
			theindex = (theindex + 1) % numthumbs;
			theimage = thumbhref[theindex];
		}
		// Only preload if we have to, i.e. the image isn't this image already
	
		if (imgPreload.src.indexOf(theimage.substr(theimage.lastIndexOf("/"))) == -1) {
			preloadactive = true;
			imgPreload = new Image();
	
			// Set a function to fire when the preload is complete, setting flags along the way.
	
			imgPreload.onload = function() {
				preloadactive = false;
			}
	
			// Load it!
			imgPreload.src = theimage;
		}
	}
}

function preloadAnimStart() {

	document.getElementById("progress").style.left = (stagewidth / 2) + 'px';
	document.getElementById("progress").style.top = (stageheight / 2) + 'px';
	document.getElementById("progress").style.visibility = "visible";	
	preloadFrame = 1;
	document.getElementById("progressimg").src = '/ui/square-'+preloadFrame+'.gif'; 
	preloadAnimTimer = setInterval("preloadAnim()", 70);
}

function preloadAnim(from) {
	if (preloadactive != false) {
		document.getElementById("progressimg").src = '/ui/square-'+preloadFrame+'.gif';
		preloadFrame++;
		if (preloadFrame > 12) preloadFrame = 1;
	} else {
		document.getElementById("progress").style.visibility = "hidden";    
		clearInterval(preloadAnimTimer);
		preloadAnimTimer = 0;
		finishShow(preloadFrom);
	}
}

function showFull(theindex,from) {

	theimage = thumbhref[theindex];
		
	if (theimage.indexOf("f/") != -1) {
		stageimgdiv.style.visibility = "hidden";
		stagefladiv.style.visibility = "visible";	
		changeMovie(theimage);	
			
	} else {
		if (from == 0) { 
			if (isautoscrollmode) { quitAutoScroll(); }
			doPreload(theindex,0);
		}
		if (preloadactive == true) {
			// But only display the spinner if it'theobj not already being displayed!
			if (preloadAnimTimer == 0) {
				preloadFrom = theindex;
				preloadAnimStart();	
			}
		} else {
			finishShow(theindex);			
		}	
	}
}

function finishShow(theindex) {
	theimage = thumbhref[theindex];
	stagefladiv.style.visibility = "hidden";
	stageimgdiv.style.visibility = "hidden";
	stageimg.src = theimage;

	var iw = imgPreload.width;
	var ih = imgPreload.height;

	if (iw / ih > stagewidth / stageheight) scale = stagewidth / iw;		
	else scale = stageheight / ih;	
	
	if (scale > 1) scale = 1;
	stageimg.width = iw * scale;
	stageimg.height = ih * scale;
	
	stageimgdiv.style.top = (3 + (stageheight - stageimg.height) / 2) + 'px';
	stageimgdiv.style.left = (3 + (stagewidth - stageimg.width) / 2) + 'px';
	stageimgdiv.style.visibility = "visible";
	if (isautoscrollmode) { doPreload((theindex + 1) % numthumbs,1); }
}

// Autoscroll functions

function startAutoScroll() {
	doPreload((currentthumb + 1) % numthumbs,1);
	clearTimeout(autoscrolltimer);
	isautoscrolling = true;
	framestoscroll = autoscrollpause * 0.03;
	scrollDown(1);
}

function checkAutoScroll(from) {
	if (isautoscrollmode) {
		clearTimeout(autoscrolltimer);
		if (from == 0) quitAutoScroll();
	}
}

function quitAutoScroll() {
	clearTimeout(autoscrolltimer);
	isautoscrolling = false;
	framestoscroll = 7;
	autoscrolltimer = setTimeout("startAutoScroll()",autoscrollpause);
}

// Scroll functions

function setScrollOn() {
	inscrollarea = true;
}

function setScrollOff() {
	inscrollarea = false;
}

function resetScroll() {
	scrollcoef = 6.9833 / framestoscroll;
	scrollframe = 0;
	scrolloffset = 0;
}

function snapScroll() {
	for (i=0; i < numthumbs; i++) {		
		thumby[i] = ((Math.round((thumby[i] - miny) / gridheight) + numthumbs) % numthumbs) * gridheight + miny; // clean up after scroll, snap to grid
		if (thumby[i] == currentthumbloc) { currentthumb = i; } // thumb at y=0 is current thumb
		theobj = document.getElementById('t'+i);
		if (thumby[i] >= -gridheight && thumby[i] <= maxy) { theobj.style.display = 'block'; }
		else { theobj.style.display = 'none'; }
		theobj.style.top = (thumby[i] + thumbyoff[i]) + 'px';
	}
	if (isautoscrollmode && !isautoscrolling) { doPreload((currentthumb + 1) % numthumbs,1); }
}

function scrollUp(from) {
	checkAutoScroll(from);
	if (downscrollcount == 0) {
		if (isautoscrolling) { upscrollcount = 1; }
		else { upscrollcount++; }
		if (upscrollcount == 1) {			
			resetScroll();				
			snapScroll();
			clearInterval(utimer);
			utimer = setInterval("animScrollUp()",25);	
		}
	}
}

function scrollDown(from) {
	checkAutoScroll(from);
	if (upscrollcount == 0) {
		if (isautoscrolling) { downscrollcount = 1; }
		else { downscrollcount++; }
		if (downscrollcount == 1) {			
			resetScroll();				
			snapScroll();
			clearInterval(dtimer);
			dtimer = setInterval("animScrollDown()",25);	
		}
	}
}

function animScrollUp() { // Scroll at a rate of 40 frames per second
	var i, thumbobj;	
			
	scrolloffset = 0.7 * gridheight * Math.atan(scrollcoef * scrollframe);
	scrollframe++;
	
	for (i=0; i < numthumbs; i++) {				
		thumbobj = document.getElementById('t'+i);
		thumbobj.style.top = (thumby[i] + thumbyoff[i] + scrolloffset) + 'px';
	}
	
	if (scrollframe > framestoscroll) {
		upscrollcount--;	
		for (i = 0; i < numthumbs; i++) { thumby[i] += gridheight; }
		resetScroll();
		snapScroll();
		if (isautoscrolling) { showFull(currentthumb,1); }
	}
	
	if (upscrollcount <= 0) {
		upscrollcount = 0;
		clearInterval(utimer);
		if (isautoscrolling) {
			clearTimeout(autoscrolltimer);
			autoscrolltimer = setTimeout("scrollDown(1)",autoscrollpause);	
		}
	}
}

function animScrollDown() { // Scroll at a rate of 40 frames per second
	var i, thumbobj;	
			
	scrolloffset = 0.7 * gridheight * Math.atan(scrollcoef * scrollframe);
	scrollframe++;
	
	for (i=0; i < numthumbs; i++) {				
		thumbobj = document.getElementById('t'+i);
		thumbobj.style.top = (thumby[i] + thumbyoff[i] - scrolloffset) + 'px';
	}
	
	if (scrollframe > framestoscroll) {
		downscrollcount--;	
		for (i = 0; i < numthumbs; i++) { thumby[i] -= gridheight; }
		resetScroll();
		snapScroll();
		if (isautoscrolling) { showFull(currentthumb,1); }
	}
	
	if (downscrollcount <= 0) {
		downscrollcount = 0;
		clearInterval(dtimer);
		if (isautoscrolling) {
			clearTimeout(autoscrolltimer);
			autoscrolltimer = setTimeout("scrollDown(1)",autoscrollpause);	
		}
	}
}

function setOpacity(opacity, theID) {

	var object = document.getElementById(theID).style;

	// If it's 100, set it to 99 for Firefox.

	if (navigator.userAgent.indexOf("Firefox") != -1) {
		if (opacity == 100) { opacity = 99.9999; } // This is majorly awkward
	}

	// Multi-browser opacity setting

	object.filter = "alpha(opacity=" + opacity + ")"; // IE/Win
	object.opacity = (opacity / 100);                 // Safari 1.2, Firefox+Mozilla

}

// Mouse wheel functions -- from adomas.org

function handle(delta) {
	if (inscrollarea) {
		if (delta < 0) {
			scrollDown(0);
			downscrollcount = Math.ceil(-delta);
		} else {
			scrollUp(0);
			upscrollcount = Math.ceil(delta);
		}
	}
}

function wheel(event){
	var delta = 0;
	if (!event) /* For IE. */
			event = window.event;
	if (event.wheelDelta) { /* IE/Opera. */
			delta = event.wheelDelta/120;
			/** In Opera 9, delta differs in sign as compared to IE.
			 */
			if (window.opera)
					delta = -delta;
	} else if (event.detail) { /** Mozilla case. */
			/** In Mozilla, sign of delta is different than in IE.
			 * Also, delta is multiple of 3.
			 */
			delta = -event.detail/3;
	}
	/** If delta is nonzero, handle it.
	 * Basically, delta is now positive if wheel was scrolled up,
	 * and negative, if wheel was scrolled down.
	 */
	if (delta)
			handle(delta);
	/** Prevent default actions caused by mouse wheel.
	 * That might be ugly, but we handle scrolls somehow
	 * anyway, so don't bother here..
	 */
	if (event.preventDefault)
			event.preventDefault();
	event.returnValue = false;
}

function initWheel() {
	/** Initialization code. 
	 * If you use your own event management code, change it as required.
	 */
	if (window.addEventListener)
			/** DOMMouseScroll is for mozilla. */
			window.addEventListener('DOMMouseScroll', wheel, false);
	/** IE/Opera. */
	window.onmousewheel = document.onmousewheel = wheel;
}
