// Story Rotator - used for home page story rotation module

var Rotator = {
  
  Container: null,
  Interval: null,
  Controls: null,
  Slides: null,
  Videos: null,
  Halt: false,

  initialize: function(){
    Array(Rotator.Controls, Rotator.Slides).each(function(a){
	  if (a.length > 0)
        a.first().addClassName('on');
    });
  },

  start: function() {
    Rotator._startExecuter();
    
    Rotator.Container.observe('mouseover', function(e) {
      Rotator._mouseOverHandler(e);
    });
    
    Rotator.Container.observe('mouseout', function(e) {
      Rotator._mouseOutHandler(e);
    });
    
    Rotator.Controls.each(function(el){
      el.observe('click', function(e) {
        Rotator._mouseClickHandler(e);
      });
    });
    
    Rotator.Videos.each(function(el){
      el.observe('click', function(e) {
        Rotator._mouseClickHandler(false);
      });
    });
  },
  
  _startExecuter: function() {
    if (Rotator.Executer) 
      Rotator.Executer.stop();
    Rotator.Executer = new PeriodicalExecuter(function(){
      Rotator._rotate();
    }, Rotator.Interval);
  },
  
  _rotate: function(e) {
    var el = Rotator.Slides.find(function(s){ return s.hasClassName('on') });
    Array(Rotator.Slides, Rotator.Controls).each(function(a){ a.invoke('removeClassName', 'on'); });
    if (e)
      el = Rotator.Slides[Rotator.Controls.indexOf(e.element())];
    else
      el = el == Rotator.Slides.last() ? Rotator.Slides.first() : Rotator.Slides[Rotator.Slides.indexOf(el)+1];
    Array(el, Rotator.Controls[Rotator.Slides.indexOf(el)]).invoke('addClassName', 'on');
  },
  
  _mouseOverHandler: function(e) {
    e.stopPropagation();
    if (Rotator.Executer) 
      Rotator.Executer.stop();
  },
  
  _mouseOutHandler: function(e) {
    e.stopPropagation();
    if (Rotator.Executer && !Rotator.Halt)
      Rotator._startExecuter();
  },
  
  _mouseClickHandler: function(e) {
	Rotator.Halt = true;
    if (e) e.stopPropagation();
    if (Rotator.Executer)
      Rotator.Executer.stop();
    if (e) Rotator._rotate(e);
  }
}
