// JavaScript Document
window.addEvent('domready', function() {      

  var changingDivs = $$('.icChangeDiv'); 
  
  var nextButtons = $$('.nextButton');  
  var prevButtons = $$('.prevButton');
  
  var start = 0;
        
  changingDivs.each(function(item, index){  
       
    if (item.get('start') != null) {
        start = index;
    }
          
  }); 
  
  if (nextButtons.length > 0) {
    this.auto = false;
  } else {
    this.auto = true;
  }
  
  
  this.current = start;
  
  
  var next = function() {
     var oldIndex = this.current;
     if (++this.current >= changingDivs.length) {
         this.current = 0;
     }       
     blend(changingDivs[oldIndex], changingDivs[this.current]);
  }
    
  var prev = function() {
     var oldIndex = this.current;
     if (--this.current < 0) {
       this.current = changingDivs.length-1;
     } 
     blend(changingDivs[oldIndex], changingDivs[this.current]);      
  }
  
  this.next = next;
  this.prev = prev;  
  
  instance = this;
       
  initialiseDivs();
  
  function blend (blendOut, blendIn) {
    
    if(blendOut.fx){blendOut.fx.stop();}
    if(blendIn.fx){blendIn.fx.stop();}
    
    divOut = new Fx.Tween(blendOut, {
      property: 'opacity',
      duration: 3000, 
      transition: Fx.Transitions.Quart.easeInOut
    });
    
    divIn = new Fx.Tween(blendIn, {
      property: 'opacity',
      duration: 3000, 
      transition: Fx.Transitions.Quart.easeInOut
    });    
    
    divOut.start(1.0, 0.0);
    divIn.start(0.0, 1.0);
  } // end blend
  
  
  
  var periodicSwap = function() {
    instance.next();    
  }
  
  if (this.auto == true && changingDivs.length > 1) {
    periodicSwap.periodical(10000, instance); 
  }
  
    
  function initialiseDivs() {                   
    // set all but the start to invisible
    changingDivs.each(function(item, index){
    if (index != this.current)
    {     
      divOut = new Fx.Tween(item, {
      property: 'opacity',
      duration: 1, 
      transition: Fx.Transitions.Quart.easeInOut
      });    
    
      divOut.start(1.0, 0.0);         
    }
    });
    
    
    nextButtons.each(function(item, index){
      item.addEvent('click', function() {
        instance.next();            
      });
    });
    
    prevButtons.each(function(item, index){
      item.addEvent('click', function() {
        instance.prev();                
      });
    });
    
       
    
  } // end initialiseDivs
  
  

                                    
});