(function(){
  var Carousel = {
    initialize: function(element){
      if(!$(element)){ return; }
      this.carousel = $(element);
      this.contents = this.carousel.select(".content");
      this.picture_box = this.carousel.select(".pictures").first();
      this.links = this.carousel.select("a");
      this.arrow = this.carousel.select(".contents_container_arrow").first();
      this.timeout = 8;
      this.current = 0;
      this.timer = null;
      this.sliding_to = 0;
      this.current_effect = null;

      this.links.each(function(link, x){
        link.observe("mouseover", this.mouseOverEvent.bind(this));
        link.observe("mouseout", this.mouseOutEvent.bind(this));
        link.setStyle({opacity: x === 0 ? 0 : 0.5});
        link.setAttribute("identifier", x);
      }, this);

      this.startTimeout();
      this.arrow.setStyle({top: this.topForArrow(0) + "px"});
    },

    mouseOutEvent: function(event){
      this.startTimeout();
    },

    mouseOverEvent: function(event){
      var element = event.element().tagName == "A" ? event.element() : event.element().up("A");
      var identifier = parseInt(element.readAttribute("identifier"), 10);

      this.stopTimeout();
      this.show(identifier);
    },

    topForArrow: function(identifier){
      return this.contents[identifier].positionedOffset().top + (this.contents[identifier].getHeight() / 2) - 15;
    },

    show: function(identifier){
      if(this.sliding_to == identifier) { return; }

      if( this.current_effect !== null ){ this.current_effect.cancel(); }

      this.current_effect = new Effect.Parallel([
          new Effect.Morph(this.picture_box, { sync:true, style: "top:" + ((-1 * identifier) * 234) + "px" }),
          new Effect.Morph(this.arrow, { sync:true, style: "top:" + this.topForArrow(identifier) + "px" }),
          new Effect.Morph(this.links[this.current], {sync:true, style: "opacity:" + 0.5}),
          new Effect.Morph(this.links[identifier], {sync: true, style: "opacity:" + 0})
        ], {
        duration: 0.8,
        beforeStart: function(){ this.sliding_to = identifier; }.bind(this)
      });

      this.current = identifier;
    },

    startTimeout: function(){
      this.timer = setTimeout(function(){
        this.show((this.current + 1) % this.links.length);

        this.startTimeout();
      }.bind(this), this.timeout * 1000);
    },

    stopTimeout: function(){
      clearTimeout(this.timer);
    },

    setOpacity: function(old_item, new_item){
      this.links[old_item].setStyle({opacity: 0.5 });
      this.links[new_item].setStyle({opacity: 0.99 });
    }

  };

  document.observe("dom:loaded", function(){ 
    Carousel.initialize("carousel"); 
  });
})();

