var SlideShow = new Class({

    initialize: function(element) {
        this.container = element;
        this.canvas = this.container.getElement('.canvas');
        this.left_arrow = this.container.getElement('.left-arrow');
        this.right_arrow = this.container.getElement('.right-arrow');

        this.canvas_width = this.canvas.getStyle('width').toInt();
        this.wrapper_width = this.container.getElement('.wrapper').getStyle('width').toInt();
        this.image_width = this.canvas.getElement('.column').getStyle('width').toInt();
        this.max_index = Math.ceil((this.canvas_width - this.wrapper_width) / this.image_width);

        this.left_arrow.addEvent('click', function(e) {
            this.scroll_left();
        }.bind(this));
        this.right_arrow.addEvent('click', function(e) {
            this.scroll_right();
        }.bind(this));

        this.period = null;
        if (!this.container.hasClass('noauto')) {
            this.start();
        }
    },

    start: function() {
        this.period = this.scroll_right.bind(this).pass(true).periodical(3000);
    },

    stop: function() {
        this.period = $clear(this.period);
    },

    scroll_right: function() {
        var periodical = arguments[0];
        if (!periodical && this.period != null) {
            this.stop();
        }
        var current = Math.floor(Math.abs(this.canvas.getStyle('left').toInt() / this.image_width));
        if (current < this.max_index) {
            current++;
            this.canvas.tween('left', -(current * this.image_width));
            if (current == this.max_index) {
                this.right_arrow.setStyle('display', 'none');
                if (this.period != null) {
                    this.stop();
                }
            }
            if (current > 0) {
                this.left_arrow.setStyle('display', 'block');
            }
        }
    },

    scroll_left: function() {
        var periodical = arguments[0];
        if (!periodical && this.period != null) {
            this.stop();
        }
        var current = Math.floor(Math.abs(this.canvas.getStyle('left').toInt() / this.image_width));
        if (current > 0) {
            current--;
            this.canvas.tween('left', -(current * this.image_width));
            if (current < this.max_index) {
                this.right_arrow.setStyle('display', 'block');
            }
            if (current == 0) {
                this.left_arrow.setStyle('display', 'none');
            }
        }
    }

});

var setup_slideshows = function() {
    $$('.slideshow').each(function(e) {
        new SlideShow(e);
    });
}

window.addEvent('domready', setup_slideshows);
