var Slideshow = new Class({
    initialize: function() {
        this.holder = $('photo-holder');
        this.duration = {
            slide: 1500,
            show: 7500
        },
        this.duration.slideshow = this.duration.slide + this.duration.show;
        this.slides = this.holder.getElements('div.photo');
        this.limit = this.slides.length;
        this.buttons = {
            previous: $('photo-previous'),
            next: $('photo-next')
        };
        this.caption = $('photo-caption');
        this.is_playing = false;
        this.current = 0;
        this.target = 0;
        var beginEvent = function() { this.begin(); };
        var boundBeginEvent = beginEvent.bind(this);
        window.addEvent('load', boundBeginEvent);
    },

    begin: function() {
        var buttonPrevious = function(e) {
            new Event(e).stop();
            this.proceed(-1);
        };
        var boundButtonPrevious = buttonPrevious.bind(this);
        var buttonNext = function(e) {
            new Event(e).stop();
            this.proceed(1);
        };
        var boundButtonNext = buttonNext.bind(this);
        // Button events
        this.buttons.previous.addEvent('click', boundButtonPrevious);
        this.buttons.next.addEvent('click', boundButtonNext);
        // Slide effects
        this.effects = new Array();
        $each(this.slides, function(slide, index) {
            this.effects[index] = new Fx.Tween(slide, {property: 'opacity', duration: this.duration.slide, wait: false, transition: Fx.Transitions.Quad.easeInOut});
            if (index > 0) this.effects[index].set(0);
        }, this);
        // Set initial caption
        this.head();
        // Start the show
        // this.playback(true);
    },

    playback: function(playing) {
        $clear(this.start);
        this.is_playing = playing;
        if (this.is_playing) this.progress();
    },

    progress: function() {
        this.start.delay(this.duration.slideshow, this);
    },

    start: function() {
        if (this.is_playing) this.proceed(1);
    },

    head: function() {
        var title = this.slides[this.current].getProperty('title');
        this.caption.set('html', title);
    },

    proceed: function(value) {
        if (!value) value = 1;
        this.target += parseInt(value);
        if (this.target >= this.limit) this.target = 0;
        if (this.target < 0) this.target = (this.limit - 1);
        this.effects[this.target].start(1);
        this.effects[this.current].start(0);
        this.current = this.target;
        this.head();
        if (this.is_playing) this.progress();
    }
});
