
var Preloader = {
  callbacks: [],
  images: [],
  loadedImages: [],
  imagesLoaded: 0,

  add: function(image){
    if (typeof image == 'string') this.images.push(image);
    if (typeof image == 'array' || typeof image == 'object'){
      for (var i=0; i< image.length; i++){
        this.images.push(image[i]);
      }
    }
  },
  onFinish: function(func){
    if (typeof func == 'function') this.callbacks.push(func);
    if (typeof func == 'array' || typeof func == 'object'){
      for (var i=0; i< func.length; i++){
        this.callbacks.push(func[i]);
      }
    }
  },
  load: function(){
    for(var i=0; i<this.images.length; i++){
      this.loadedImages[i] = new Image();
      this.loadedImages[i].onload = function(){ Preloader.checkFinished.apply(Preloader) }
      this.loadedImages[i].src = this.images[i];
    }
  },

  checkFinished: function(){
    this.imagesLoaded++;
    if (this.imagesLoaded == this.images.length) this.fireFinish();
  },
  fireFinish: function(){
    for (var i=0; i<this.callbacks.length; i++){
      this.callbacks[i]();
    }
    this.images = [];
    this.loadedImages = [];
    this.imagesLoaded = 0;
    this.callbacks = [];
  }
}

// set up sequence
var _imagesToPreload = ['images/texture-splatter.gif', 'images/clothes-shoes.png', 'images/clothes-shirt.png', 'images/clothes-jeans.png', 'images/clothes-dress.png', 'images/clothes-bra.png'];
var _elemntsToCreate = ['textureSplatter', 'clothesShoes', 'clothesShirt', 'clothesJeans', 'clothesDress', 'clothesBra'];
var _curImg = 0;

// adds html element to stage and fades it in
function addToStage( htmlId )
{
	_curImg++;
	
	// create html element & fade in
	$('contentUnder').innerHTML += '<div id="' + htmlId + '" style="display:none"></div>';
	Effect.Appear( $( htmlId ), { duration:1.5, afterFinish: onNextImage } );

}

// loads the next image in queue
function onNextImage()
{
	if( _curImg == _imagesToPreload.length ) return;
	
	Preloader.add( _imagesToPreload[ _curImg ] );
	Preloader.onFinish( function(){ addToStage( _elemntsToCreate[ _curImg ] ); } );
	Preloader.load();
}

// kick off preloading background images when page is fully loaded
Event.observe(window, 'load', function() {
	onNextImage();
});
