var state = {'next' : '', 'opacity' : 0, 'to' : '', current : 1, auto_index : 1};
var fade_prefs = {'duration' : 3000, 'fps' : 10, 'path_pre' : 'http://www.laurenbest.com/wp-content/themes/StickerCollection/images/header/', 'path_post' : '.png', 'auto_interval' : 5000};

var preloads = new Array();
var loaded_imgs = new Object();
for (var i = 1; i <= num_imgs; i++)
{
	var img = new Image();
	img.name = i;
	img.onload = function () {img_loaded(this.name);};
	img.src = fade_prefs.path_pre + i + fade_prefs.path_post;
	preloads.push(i);
}

function img_loaded (img)
{
	loaded_imgs[img] = 1;
	if (state.next == img)
	{
		start_fade(img);
	}
}

function auto_fade (start)
{
	if (!start)
	{
		state.auto_index++;
		if (state.auto_index > num_imgs) state.auto_index = 1;
		fade(state.auto_index);
	}
	setTimeout(auto_fade, fade_prefs.auto_interval);
}

function fade (to)
{
	if (to == state.to || (to == state.current && state.opacity == 0)) return;
	if (state.opacity == 0 && loaded_imgs[to] == 1)
	{
		start_fade(to);
	} else {
		state.next = to;
	}
}

function start_fade (to)
{
	state.to = to;
	state.next = '';
	document.getElementById('fader').style.background = 'url(' + fade_prefs.path_pre + state.current + fade_prefs.path_post + ')';
	document.getElementById('fader-container').style.background = 'url(' + fade_prefs.path_pre + to + fade_prefs.path_post + ')';
	state.opacity = 100;
	do_fade();
}

function do_fade ()
{
	state.opacity = Math.round(Math.max(state.opacity - ((1000/fade_prefs.fps)/fade_prefs.duration)*100, 0));
	var fader = document.getElementById('fader').style;
	fader.opacity = (state.opacity / 100);
	fader.MozOpacity = (state.opacity / 100);
	fader.KhtmlOpacity = (state.opacity / 100);
	fader.filter = "alpha(opacity=" + state.opacity + ")";
	if (state.opacity == 0)
	{
		state.current = state.to;
		state.to = '';
		if (state.next != '') start_fade(state.next);
	} else {
		setTimeout(do_fade, 100/(fade_prefs.fps/(1000/fade_prefs.duration)));
	}
}
