// (c) 2006-2007 by Visibility Works, Inc. - All Rights Reserved.

var timerId = 0;
var waitcount = 0;
//var unloaded_array = [ "images/002.jpg", "images/003.jpg" ];
//var preloaded_array = [ "images/001.jpg" ];
var viewingindex = 0;
var auto_show = true;

onload = function() {
  if( document.images && document.images["slide"] && document.images["slide"].style ) {
    document.images["slide"].style.opacity = 1;
  }
  setTimer( "preloadNext()" );
}

function setTimer( f )
{
  if( timerId ) {
    clearTimeout( timerId );
  }
  timerId = setTimeout( f, 42 );	// 1000ms / 24 frames per second = 42ms
}

var next_img;
function preloadNext()
{
  if( document.images && document.images["slide"] ) {
	if( unloaded_array.length > 0 ) {
		var loading_img = new Image(512,512);
		loading_img.src = unloaded_array.shift();
		preloaded_array.push( loading_img.src );
		next_img = loading_img;
	}
	setTimer( "waitForNext()" );
  }
}

function waitForNext()
{
  if( document.images && document.images["slide"] && auto_show ) {
    if( ++waitcount > 120 && next_img.complete ) { // 5 seconds at 24 fps
	  if( waitcount > 121 ) {
	    window.status = "";
	  }
	  waitcount = 0;
	  setTimer( "fadeOut()" );
    } else {
	  if( waitcount > 120 ) {	// still waiting, give feedback
		window.status = "Loading next slide ...";
	  }
	  setTimer( "waitForNext()" );
    }
  }
}

function swapImages()
{
    if( ++viewingindex >= preloaded_array.length ) {
		viewingindex = 0;
    }
    document.images["slide"].src = preloaded_array[viewingindex];	
}

function fadeOut()
{
  var rate = 0.03;

  if( document.images && document.images["slide"] && document.images["slide"].style ) {
	document.images["slide"].style.opacity = Number( document.images["slide"].style.opacity ) - rate;
    document.images["slide"].style.filter = 'alpha(opacity=' + (Number( document.images["slide"].style.opacity ) - rate) * 100 + ')';
  } else {
	swapImages();
	setTimer( "preloadNext()" );
	return;
  }
  
  if( document.images["slide"].style.opacity <= rate || waitcount++ > 35 ) {
    waitcount = 0;
    document.images["slide"].style.opacity = 0;
    swapImages();
    document.images["slide"].style.opacity = 0;
    setTimer( "fadeIn()" );
  } else {
    setTimer( "fadeOut()" );
  }
}

function fadeIn()
{
  var rate = 0.03;
  document.images["slide"].style.opacity = Number( document.images["slide"].style.opacity ) + rate;
  document.images["slide"].style.filter = 'alpha(opacity=' + (Number( document.images["slide"].style.opacity ) + rate) * 100 + ')';
  if( document.images["slide"].style.opacity >= 1-rate || waitcount++ > 35 ) {
    waitcount = 0;
	document.images["slide"].style.opacity = 1;
    setTimer( "preloadNext()" );
  } else {
	setTimer( "fadeIn()" );
  }
}

function showImage( s )
{
	auto_show = false;
	document.images["slide"].src = s;
	fadeIn();
}

function resumeShow()
{
	auto_show = true;
	fadeOut();
}