var Carousel = new Class({
  Implements: [Options, Events],
  options: {},

  initialize: function (element, options) {
    var nextBtn = new Element('div', {'class': 'next-btn'}),
        prevBtn = new Element('div', {'class': 'prev-btn'}),
        firstItem = element.getElement('li:first-child'),
        lastItem  = element.getElement('li:last-child'),
        secondItemOffset,
        options = options || {},
        slideLength = 0;

    this.setOptions(options)

    firstItem.clone().inject(firstItem.getParent(), 'bottom');
    lastItem.clone().inject(lastItem.getParent(), 'top');

    this.element = element;
    this.items = element.getElements('li');
    this.currentIndex = 1;
    this.lastItemIndex = this.items.length - 1;
    this.viewport = element.getElement('.viewport');

    element.adopt(nextBtn, prevBtn);

    secondItemOffset = 0;
    
    this.items[this.currentIndex].getAllPrevious().each(function (element) {
      secondItemOffset += element.getSize().x;
    });

    this.items.each(function (slideItem) {
      slideLength += slideItem.getSize().x;
    });

    this.viewport.getElement('ul').setStyles({
      'margin-left': secondItemOffset * -1,
      'width': slideLength
    });

    $$(prevBtn, nextBtn).addEvent('click', this.buttonClick.bind(this));
    this.viewport.addEvent('click', this.viewportClick.bind(this));

    document.fireEvent('carouselReady', this);

    if (options.autoprogress == true) {
      this.interval = this.moveToNext.delay(options.interval, this);
    }
  },

  viewportClick: function (evt) {
    var target     = $(evt.target),
        listItem   = target.get('tag') == 'li' ? target : $(evt.target).getParent('li'),
        actionLink = listItem.getElement('a'),
        poster     = listItem.getElement('img'),
        itemUrl    = actionLink.get('href'),
        width      = poster.getSize().x,
        height     = poster.getSize().y;

    if (actionLink.get('rel') == 'videolightbox') {
      this.showVideo(itemUrl, width, height);

    } else if (itemUrl != null) {
      document.location = itemUrl;
    }

    evt.stop();
  },

  buttonClick: function (evt) {
    var element = $(evt.target);

    if (element.hasClass('prev-btn')) {
      this.moveToPrevious();

    } else if (element.hasClass('next-btn'))  {
      this.moveToNext();

    } else {
      throw new Error('Unknown button clicked');
    }

    evt.preventDefault();
  },

  moveToPrevious: function () {
    if (this.currentIndex == 0) {
      this.currentIndex = this.lastItemIndex - 1;
    }

    this.moveToIndex(this.currentIndex - 1);
  },

  moveToNext: function () {
    if (this.currentIndex == this.lastItemIndex) {
      this.currentIndex = 1;
    }

    this.moveToIndex(this.currentIndex + 1);
  },

  moveToIndex: function (index) {
    var currentItemOffset = this.items[this.currentIndex].getPosition(this.viewport.getElement('ul')).x,
        nextItemOffset    = 0;

    this.items[index].getAllPrevious().each(function (element) {
      nextItemOffset += element.getSize().x;
    });

    this.viewport.getElement('ul').tween('margin-left', [currentItemOffset*-1, nextItemOffset*-1]);

    this.currentIndex = index;

    if (this.options.autoprogress == true) {
      clearInterval(this.interval);
      this.interval = this.moveToNext.delay(this.options.interval, this);
    }
  },

  showVideo: function (videoUrl, width, height) {
    var backdrop   = new Element('div', {'id': 'backdrop'}),
        videoPanel = new Element('div', {'id': 'videopanel'}),
        container  = new Element('div', {'id': 'videocontainer'}),
        closeBtn   = new Element('p', {'id': 'close-video', 'html': 'x Close'});

    $$('body')[0].adopt(backdrop, videoPanel);

    videoPanel.adopt(closeBtn, container);

    closeBtn.addEvent('click', this.hideVideo);

    new Swiff('/flash/player-licensed.swf', {
      container: 'videocontainer',
      width: 745,
      height: 420 + 19, // 19 is the height of the controls
      vars: {
        file: videoUrl,
        autostart: true
      }
    });

    videoPanel.setStyles({
      'width': container.getSize().x,
      'margin-left': 745 / -2
    });
    
    window.scrollTo(0,0);
  },

  hideVideo: function () {
    var backdrop = $('backdrop'),
        videoPanel = $('videopanel');

    if (backdrop) {
      backdrop.destroy();
    }

    if (videoPanel) {
      videoPanel.destroy();
    }
  }
});

window.addEvent('domready', function () {
  var options = {},
      defaultOptions,
      looping,
      delay,
      dataAutoProgress,
      dataInterval,
      xhr = new Request.JSON({'async': false});

  xhr.get('/carousel/config');

  defaultOptions = JSON.decode(xhr.response.text);

  $$('.carousel').each(function (element) {
    dataConfig       = JSON.decode(element.get('data-config'));
    autoProgress     = dataConfig.auto_progress ? dataConfig.auto_progress : defaultOptions.auto_progress;
    interval         = dataConfig.interval ? dataConfig.interval.toInt() : defaultOptions.interval;

    options = {
      autoprogress: autoProgress,
      interval: interval
    }

    new Carousel(element, options);
  });
});
