var Slideshow = new Class({
  slideWidth: 950,
  cache: {},
  timeoutId: null,
  currentIndex: 0,
  interval: 5100,

  initialize: function (element) {
    this.element = element;
    this.setEventHandlers();
    this.timeoutId = this.goToIndex.delay(this.interval, this, 0);
  },

  /**
   * UPDATES THE SLIDESHOW HTML EITHER FROM CACHE OR AJAX REQUEST
   */
  updateSlideshow: function (section, category, filter) {
    var xhr;

    if (section != 'webstore') {
      this.element.set('html', '');
      window.clearTimeout(this.timeoutId);
      this.timeoutId = null;
      return;
    }

    if (this.cache[section] && this.cache[section][category] && this.cache[section][category][filter]) {
      this.element.set('html', this.cache[section][category][filter]);
      this.goToIndex(0);
    } else {
      xhr = new Request.HTML({
        url: '/slideshow/get',
        onSuccess: (function (tree, elements, html) {
          this.element.set('html', html);
          this.cacheHTML(section, category, filter, html);
          this.goToIndex(0);
        }).bind(this),
        method: 'post'
      });

      xhr.send('section=' + section + '&category=' + category + '&filter=' + filter);
    }
  },


  /**
   * CACHE FETCHED HTML FOR CURRENT SECTION/CATEGORY/FILTER combination
   */
  cacheHTML: function (section, category, filter, slideshowHTML) {
    if (this.cache[section]) {
      if (!this.cache[section][category]) {
        this.cache[section][category] = {};
      }
    } else {
      this.cache[section] = {};
      this.cache[section][category] = {};
    }

    this.cache[section][category][filter] = slideshowHTML;
  },


  /**
   * SETS ALL THE EVENT HANDLERS FOR USER INTERACTION
   */
  setEventHandlers: function () {
    this.element.addEvent('click', (function (evt) {
      var clickedElm = $(evt.target),
          numPrevChilds;

      if (clickedElm.hasClass('label')) {
        numPrevChilds = clickedElm.getAllPrevious().length;
        this.goToIndex(numPrevChilds);
      }
    }).bind(this));
  },


  /**
   * PROCEDES TO THE SLIDESHOW TO THE GIVEN INDEX
   */
  goToIndex: function (index) {
    var currentActiveLabel = this.element.getElement('.label.active'),
        nextActiveLabel = this.element.getElements('.label')[index];

    if (this.element.getElements('.slides li').length == 0) {
      return;
    }

    if (index >= this.element.getElements('.slides li').length) {
      index = 0;
    }

    window.clearTimeout(this.timeoutId);

    this.element.getElement('.slides').tween('margin-left', index * this.slideWidth * -1);
    this.currentIndex = index;

    if (currentActiveLabel) {
      currentActiveLabel.removeClass('active');
    }

    if (nextActiveLabel) {
      nextActiveLabel.addClass('active');
    }

    this.timeoutId = this.goToIndex.delay(this.interval, this, index+1);
  }
});

window.addEvent('domready', function () {
  Denham.slideshow = new Slideshow($('slideshow'));
});
