var iOffer = iOffer ? iOffer : {}

iOffer.HomepageSlider = Class.create({
  DURATION: 0.4,
  DELAY : 7,
  
  initialize : function(count) {
    this.count     = count;
    this.current   = count - 1;
    this.executer  = new PeriodicalExecuter(this.autoChange.bind(this), this.DELAY);
    this.container = $("homepage-featured-items");
    this.attachMouseEvents();
  },

  attachMouseEvents : function() {
    this.container.observe("mouseover", this.pause.bind(this));
    this.container.observe("mouseout",  this.resume.bind(this));
  },

  pause : function() {
    this.executer.stop();
  },

  resume : function() {
    this.pause();
    this.executer.registerCallback();
  },

  autoChange : function() {
    if (this.current == 0) {
      this.changeTo(this.count -1);
    } else {
      this.changeTo((this.current - 1) % this.count);
    }
  },

  blockAtIndex : function(index) {
    return $("homepage-featured-items-block-" + index);
  },

  buttonAtIndex : function(index) {
    return $("homepage-featured-button-" + index);
  },

  changeTo : function(index) {
    if (index != this.current) {
      this.pause();
      this.toggleActive(index);
      this.displayEffect(index);
      this.swapZIndex(index);
      this.resume();
    }
  },

  swapZIndex : function(index) {
    this.blockAtIndex(this.current).setStyle({
      zIndex : "0"
    });
    this.current = index;
    this.blockAtIndex(this.current).setStyle({
      zIndex : "10"
    });
  },

  toggleActive : function(index) {
    this.buttonAtIndex(index).addClassName("active").siblings().each(function(sibling){
      sibling.removeClassName("active");
    });
  },

  displayEffect : function(index) {
    new Effect.Parallel([
      new Effect.Morph(this.blockAtIndex(this.current), {
        sync : true,
        style: "opacity:0.0;filter:alpha(opacity=0);"
      }),
      new Effect.Morph(this.blockAtIndex(index), {
        sync : true,
        style: "opacity:1.0;filter:alpha(opacity=100);"
      })
      ], {
        duration: this.DURATION
      });
  }
});
