﻿var SlideShow = new Class({

    Implements: Options,

    options: { index: 0, items: 0, slideSelector: '', controller: null },

    initialize: function (element, options) {
        this.element = document.id(element);
        this.setOptions(options);
        this.slides = this.element.getElements(this.options.slideSelector);
        this.slides.setStyle('opacity', 0)[this.options.index].setStyle('opacity', 1);
        this.slides.set('tween', {duration: 1000})
        this.attach();
    },

    attach: function () {
        //Bind the controller if available
        if ($chk(this.options.controller)) {
            var _pause = this.pause.bind(this);
            var _jump = this.jump.bind(this);

            this.element.getElement(this.options.controller + ' .play').addEvent('click', function (e) {
                this.toggleClass('pause');
                _pause();
                e.stop();
            });
            this.element.getElements(this.options.controller + ' li a').addEvent('click', function (e) {
                _jump(this.getParent('ul').getElements('li a').indexOf(this));
                e.stop();
            });
        }

        this.play({ stop: $empty });
    },

    play: function () {
        this.stop();
        this.loop = this.showNext.periodical(5000, this);
    },

    stop: function () {
        $clear(this.loop);
        this.loop = null;
    },

    pause: function () {
        if ($chk(this.loop)) this.stop();
        else this.play();
    },

    showNext: function () {
        if (this.options.index < this.options.items - 1)
            this.options.index++;
        else
            this.options.index = 0;
        this.slides.setStyle('z-index', 1).fade(0)[this.options.index].setStyle('z-index', 5).fade(1);
        if ($chk(this.options.controller))
            this.element.getElements(this.options.controller + ' li a').removeClass('sel')[this.options.index].addClass('sel');
    },

    showPrevious: function () {
    },

    jump: function (jumpIndex) {
        //if you are looping show carry on looping after jump
        var mustResume = false;
        if ($chk(this.loop)) {
            this.stop();
            mustResume = true;
        }
        this.options.index = jumpIndex;
        this.slides.setStyle('z-index', 1).fade(0)[jumpIndex].setStyle('z-index', 5).fade(1);
        if ($chk(this.options.controller))
            this.element.getElements(this.options.controller + ' li a').removeClass('sel')[jumpIndex].addClass('sel');
        if (mustResume) this.play();
    }

});
