var Header = Class.create(
{  
  currentImage: 0,
  images: new Array(), 
  
	initialize: function()
	{
	  //$('headerImageDefault').hide();
	  this.images[0] = { image: $('headerImage0'), loaded: true };
	  
	  new Ajax.Request('/home/home-page-images', 
    {
      method: 'get',
      onSuccess: function(transport) 
      {      
        if (transport.responseText.isJSON())
        {
          this.imagePaths = transport.responseText.evalJSON();
          //this.images     = new Array();
          this.imageCount = this.imagePaths.length;
         
          for (var i=1; i<this.imageCount; i++)
          {
            var image = new Image();
            image.id  = "headerImage" + i;
            image.alt = "";

            Element.observe(image, 'load', function(e) 
            {
              var imageNumber = Event.element(e).id.replace(/headerImage/, '');
              this.images[imageNumber]['loaded'] = true;
            }.bind(this));

            this.images[i] = { image: image, loaded: false }
            $('headerImageWrapper').insert({ bottom: image });

            image.hide();
            image.src = this.imagePaths[i];
          }
          
          new PeriodicalExecuter(function(pe) 
          {
            this.updateImage();
          }.bind(this), 5);  
        }      
      }.bind(this)
    });    
	},
	
	updateImage: function()
	{  	  
	  var tryImage      = this.currentImage + 1;
	   
    if (tryImage == this.imageCount) tryImage = 0;
	  
	  if (this.images[tryImage]['loaded'])
	  {
	    new Effect.Fade(this.images[this.currentImage]['image']);
	    new Effect.Appear(this.images[tryImage]['image']);
	    this.currentImage = tryImage;
	  }
  }
  
	/*
	updateImage: function()
	{  	  
	  var attemptCount  = 0;
	  var tryImage      = this.currentImage;
	   
	  do 
	  {
	    if (tryImage == 0) tryImage = 2;
	    else tryImage++;

	    if (tryImage == this.imageCount + 1) tryImage = 1;
	    attemptCount++;
	  }
	  while (!this.images[tryImage]['loaded'] && attemptCount < 100)

	  if (this.images[tryImage]['loaded'])
	  {
	    new Effect.Fade(this.images[this.currentImage]['image']);
	    new Effect.Appear(this.images[tryImage]['image']);
	    this.currentImage = tryImage;
	  }
  }
  */
});



document.observe("dom:loaded", function() 
{ 
  var header = new Header();  
});