Application = Class.create({
  initialize: function() {
    // Delay init when dom is loaded
    document.observe("dom:loaded", this.init.bind(this));
  },

  init: function() {
    if ($("carousel"))
      this.carousel = new Carousel();
    if ($("aktionen"))
      this.aktionen    = new aktionen();
  }
});

Layout = {
  updateHeight: function() {
    $("container").style.height = "auto"
    var delta = document.viewport.getHeight() - $("body").getHeight();
    if (delta > 0) {
      $("container").style.height = $("container").getHeight() + delta  + "px"
    }
  }
};

Carousel = Class.create({
  initialize: function() {
    $$("#carousel img").each(function(img, index){
      img.observe("click", this.change.bind(this, img, index));
    }.bind(this));
    this.icons      = $$("#carousel img");
    this.references = $$("#reference .reference_details");
  },

  change: function(element, index) {
    this.icons.invoke("removeClassName", "active");
    this.icons[index].addClassName("active");

    this.references.invoke("hide");
    this.references[index].show();
  }
});


aktionen = Class.create({
  initialize: function() {
    this.prepare();
    new PeriodicalExecuter(this.moveThumbnails.bind(this), 2);
  },

  moveThumbnails: function() {
    // Safari fix until dom:loaded works fine with Safari !!
    if (this.width == 0)
      this.prepare();

    // Move
    this.firstThumbnail.morph("margin-left: -" + this.width + "px", {afterFinish: this.updateImageOrder.bind(this)});

    // Fade Out
    this.firstThumbnail.firstDescendant().fade();

    // Fade In
    this.lastThumbnail.firstDescendant().setOpacity(0);
    this.lastThumbnail.firstDescendant().appear();
  },

  updateImageOrder: function() {
    var next  = this.firstThumbnail.next();
    // Move hidden image to the end to loop on thumbnails
    this.container.insert({bottom: this.firstThumbnail});

    // Reset margin
    this.firstThumbnail.setStyle("margin-left: 0");

    // Update internal data
    this.firstThumbnail = next;
    this.lastThumbnail  = next.next(3);
  },

  prepare: function() {
    this.container = $$("#aktionen_carousel p").first();
    var elements   = this.container.childElements();

    this.firstThumbnail = elements.first();
    this.lastThumbnail  = elements[4];

    this.width  = this.firstThumbnail.getWidth();
  }
});

Effect.DefaultOptions.duration = 0.5;
