// ----------------------------------------------------------------------------
// home_animations.js - updated 2010 June 22
// ----------------------------------------------------------------------------

var numberOfAnimationImages = 93;
var numberOfAnimatedItems = 4;

var currentImageIndexes = new Array( numberOfAnimatedItems );
for ( var i = 0; i < numberOfAnimatedItems; ++i )
   currentImageIndexes[i] = 0;

function AnimatedImagePath( index )
{
   return (IsOnLine() ? "/home/" : "/home/juan/newsite/home/") + ZeroPad( index, 2 ) + ".jpg";
}

function AnimatedItem( itemIndex )
{
   this.index = itemIndex;
   this.id = "animated" + ZeroPad( itemIndex+1, 2 );
   this.opacity = 100;
   this.fadingOut = true;
   this.waitCount = 100;

   this.animate = function()
   {
      if ( this.waitCount > 0 )
      {
         --this.waitCount;
         return;
      }

      var item = document.getElementById( this.id );

      if ( this.fadingOut )
      {
         if ( --this.opacity == 0 )
         {
            this.fadingOut = false;
            var newIndex;
            do
               newIndex = Math.round( Math.random()*(numberOfAnimationImages - 1) + 1 );
            while ( currentImageIndexes.indexOf( newIndex ) >= 0 );
            currentImageIndexes[this.index] = newIndex;
            item.__loaded__ = false;
            item.onload = function() { this.__loaded__ = true; };
            item.onerror = function() { this.fadingOut = true; this.opacity = 1; };
            item.src = AnimatedImagePath( newIndex );
         }
      }
      else
      {
         if ( item.__loaded__ )
            if ( ++this.opacity == 100 )
            {
               this.fadingOut = true;
               this.resetWaitCount();
            }
      }

      if ( isIE ) // IE detected in utils.js
         item.style.filter = 'alpha(opacity=' + this.opacity + ')'; // MSIE bizarre code for opacity
      else
         item.style.opacity = 0.01*this.opacity; // for real browsers
   };

   this.resetWaitCount = function()
   {
      this.waitCount = Math.round( Math.random()*350 + 150 );
   };
}

var animatedItems = new Array;
for ( var i = 0; i < numberOfAnimatedItems; ++i )
   animatedItems.push( new AnimatedItem( i ) );

function AnimateItem( itemIndex )
{
   setInterval( "animatedItems[" + itemIndex + "].animate();", 50 );
}

function StartAnimation()
{
   for ( var i = 0; i < numberOfAnimatedItems; ++i )
      setTimeout( "AnimateItem( " + i + ");", i*1000 );
}

__preload_images__ = new Array;

function PreloadAnimatedImages()
{
   for ( var i = 0; i < numberOfAnimatedItems; ++i )
   {
      __preload_images__[i] = new Image;
      __preload_images__[i].src = AnimatedImagePath( i+1 ); // file name index suffixes are one-based
   }
}

window.onload = function()
{
   IE6Warning();
   AdjustCSSPageComponents();
   PreloadAnimatedImages();
   StartAnimation();
}

// ----------------------------------------------------------------------------
