// BarackSlideshow from DevThought.com
window.addEvent('domready', function () {

  //set carousel height
  // var carouselHeight = 0;
  // $$("#pictures img").addEvent("load", function (el) {
  // var imgHeight = this.getDimensions().y;
  // if (imgHeight > carouselHeight) {      
  // $("slideshow").setStyle("height", imgHeight);
  // }
  // });

  // Possible settings:
  // new BarackSlideshow('menu', 'pictures', 'loading', {transition: '<transition here>', auto: true});
  // transitions can be 'slide-left', 'slide-right', 'slide-top', 'slide-bottom', 'fade'
  //var slideshow = new BarackSlideshow('menu', 'pictures', 'loading', { transition: 'fade', auto: true, autostart: true, autointerval: 7000, tween: 2000 });

  caroussel.init(4000);
});

var caroussel = {
  item: [],
  timeout: null,
  currentItem: null,
  currentItemIndex: 0,
  delay: 4000,
  previousBttn: null,
  nextBttn: null,

  init: function (delay) {
    this.delay = delay;
    this.items = $$("#pictures li");
    this.currentItem = this.items[this.currentItemIndex];
    this.items.fade("hide");
    this.currentItem.fade("show");

    this.previousBttn = $("previous");
    this.nextBttn = $("next");
    this.nextBttn.addEvent("click", this.bindToBttn);
    this.previousBttn.addEvent("click", this.bindToBttn);

    this.timeout = setTimeout(caroussel.run, this.delay);
  },

  run: function () {
    caroussel.currentItem.fade("out");
    caroussel.currentItemIndex++;
    if (caroussel.currentItemIndex == caroussel.items.length)
      caroussel.currentItemIndex = 0;
    caroussel.setAndFadeCurrentItem();
    caroussel.timeout = setTimeout(caroussel.run, caroussel.delay);
  },  

  bindToBttn: function () {
    clearTimeout(caroussel.timeout);
    caroussel.currentItem.fade("out");
    
    if (this.id == "next") {
      caroussel.currentItemIndex++;
      if (caroussel.currentItemIndex == caroussel.items.length)
        caroussel.currentItemIndex = 0;
      caroussel.setAndFadeCurrentItem();
    }

    else {
      caroussel.currentItemIndex--;
      if (caroussel.currentItemIndex == -1)
        caroussel.currentItemIndex = caroussel.items.length - 1;
      caroussel.setAndFadeCurrentItem();
    }
    return false;
  },
  
  setAndFadeCurrentItem: function () {
    caroussel.currentItem = caroussel.items[caroussel.currentItemIndex];
    $("pageCount").innerHTML = (caroussel.currentItemIndex + 1) + " / " + caroussel.items.length;
    caroussel.currentItem.fade("in");
  }
}
