var preload = new Array();
var slideshow = 0;
var slideshowdelay = 12;
var secs = 0;
var timerID = null;
var timerRunning = false;
var delay = 400;

// stop the timer
function stoptimer() {
    if(timerRunning) {
        clearTimeout(timerID);
        timerRunning = false;
    }
}

// preload next image for quick loading
function preloadimg() {
    if(!preload[nextimg]) {
	preload[nextimg] = new Image;
	preload[nextimg].src = working + photos[nextimg];
	//preload[nextimg].caption = captions[nextimg];
    }
}


// determine the previous and next image based on the current one
function prevnext(imgid) {
    if(imgid == 0) {
        previmg = (photos.length-1);
    } else {
        previmg = imgid - 1;
    }
    if(imgid == (photos.length-1)) {
        nextimg = 0;
    } else {
        nextimg = imgid + 1;
    }
    preloadimg();
}

// rotate images
function newimg(which) {
    if(which=="prev") {
	imgid = previmg;
	prevnext(imgid);
    }

    if(which=="next") {
        imgid = nextimg;
        prevnext(imgid);
    }

    if(secs == 0) { 
	if(slideshow == 1) { 
            imgid = nextimg;
            prevnext(imgid);
            secs = slideshowdelay;
	    timerRunning = true; 
	    timerID = self.setTimeout("newimg()", delay);
	}
    document.getElementById("image_rotate").style.background = 'url('+working+photos[imgid]+')';
	document.getElementById("captions").innerHTML = captions[imgid];
    } else {
	    secs = secs - 1; timerRunning = true; timerID = self.setTimeout("newimg()", delay);
    }
}

// advance to the next image
function nextimage() {
    if(slideshow) { toggleslideshow(); };
    newimg("next");
}

// back to the previous image
function previmage() {
    if(slideshow) { toggleslideshow(); };
    newimg("prev");
}

// toggle slideshow mode on / off
function toggleslideshow() {
    if(!slideshow) {
	slideshow = 1;
	newimg();
	document.getElementById("slideshow").className = "on";
    } else {
	// stop that thing! 
	slideshow = 0;
	secs = 0;
	stoptimer();
	document.getElementById("slideshow").className = "off";
    }
}

window.onload = function() {
/*    loadtextsize();*/
    document.getElementById("image_rotate").style.background = 'url('+working+photos[imgid]+')';
	document.getElementById("captions").innerHTML = captions[imgid];
	
    prevnext(imgid); preloadimg();
}
