/* File: animate.js
 * Author: Ned C. Lucks - Ned Lucks Digital Design
 * Copyright: 2003
 */

var speed;
var deltaSpeed = 100;
var totalToLoad = 0;
var numLoaded = 0;
var index = 0;
var images;
var img;
var text;
var running = false;
var warned = false;
var fwd = true;
var loop = true;
var stopped = true;
var loaded = false;
var initialized = false;
var hidethis = null;

function getImages(imgURLs) {
	var numString;
	var imgs = new Array(imgURLs.length);
	
	for(var i = 0; i < imgURLs.length; i++) {
		imgs[i] = new Image();
		imgs[i].src = imgURLs[i];
	}
	return imgs;
}

function getTotalToLoad() {
	return images.length;
}

function initAnimation(imgURLs, delay, image, textField, autostart, hide) {
	totalToLoad = imgURLs.length;
	hidethis = hide;
	speed = delay;
	img = image;
	text = textField;
	if(!initialized) {
		images = getImages(imgURLs);
		initialized = true;
	}
	if(autostart) { 
		waitForLoad(true);
	} else { waitForLoad(false); }
}

function imageAnim() {
	/*if(!loaded) {
		waitForLoad(true);
		return;
	}*/
	if(hidethis != null) hidethis.style.visibility='hidden';
	running = true;
	if(!stopped) {
		if(fwd) {
			if(!loop && index + 1 == images.length) {
				stop();
			} else {
				goForward();
			}
		} else { 
			if(!loop && index == 0) {
				stop();
			} else {
				goBack();
			}
		}
		setTimeout("imageAnim();", speed);
	} else {
		running = false;
	}
}

function show(num) {
	img.src = images[num].src;
}

function goForward() {
	if(index + 1 < images.length) {
		index++;
	} else {
		index = 0;
	}
	show(index);
}

function goBack() {
	if(index - 1 >= 0) {
		index--;
	} else {
		index = images.length - 1;
	}
	show(index);
}

function goFaster() {
	if(speed - deltaSpeed >= 0) speed -= deltaSpeed;
}

function goSlower() {
	speed += deltaSpeed;
}

function setDirection(bool) {
	bool ? fwd = true : fwd = false;
}

function setLooping(bool) {
	bool ? loop = true : loop = false;
}

function waitForLoad(thenStart) {
	var nLoaded = 0;
	if(numLoaded < images.length) {
		for(var i = 0; i < images.length; i++) {
			if(images[i].complete) nLoaded++;
		}
		numLoaded = nLoaded;
		if(text != null) text.value = numLoaded;
	}
	
	if(numLoaded >= images.length) {
		loaded = true;
		if(thenStart && !running) {
			stopped = false;
			imageAnim();
		}
	} else {
		setTimeout(thenStart ? "waitCallbackTrue();" : "waitCallbackFalse();", 500);
	}
}

function waitCallbackTrue() {
	waitForLoad(true);
}

function waitCallbackFalse() {
	waitForLoad(false);
}

function start() {
	if(!loaded && (warned || confirm("Not all images have loaded!\nClick \"Ok\" to start anyway."))) {
		stopped = false;
		warned = true;
		if(!running) imageAnim();
	} else {
		stopped = false;
		waitForLoad(true);
	}
}

function stop() {
	stopped = true;
}

function doClick() {
	if(stopped) {
		start();
	} else {
		stop();
	}
}

