var Gallery = Class.create();
Gallery.prototype = {
    initialize: function( elem ) {
        this.images = $A();
        var images = $(elem).getElementsByTagName( 'img' );
        for( var i = 0; i < images.length; i++ ) {
            this.images.push( new fx.Opacity( images[i], { duration: 600 } ) );
            this.images[i].hide();
        }
        this.current = 0;
        this.images[ this.current ].toggle();
    },
    next: function() {
        if( this.timer != null ) this.stop();
        this.doNext();
    },
    doNext: function() {
        this.images[this.current].hide();
        this.current = (this.current + 1) % this.images.length;
        this.images[this.current].toggle();
        this.updateCounter();
    },
    prev: function() {
        if( this.timer != null ) this.stop();
        this.images[this.current].hide();
        if( this.current <= 0 ) {
            this.current = this.images.length;
        }
        this.current--;
        this.images[this.current].toggle();
        this.updateCounter();
    },
    hook: function( nextElement, prevElement, counter ) {
        this.nextElement = nextElement;
        this.prevElement = prevElement;
        
        if( this.nextClick == null ) {
            this.nextClick = this.next.bindAsEventListener(this);
        }
        
        if( this.prevClick == null ) {
            this.prevClick = this.prev.bindAsEventListener(this);
        }
        
        Event.observe( this.nextElement, 'click', this.nextClick );
        Event.observe( this.prevElement, 'click', this.prevClick );

        // Event.observe( slideshow, 'click', this.toggle.bindAsEventListener(this) );

        this.counter = $(counter);
        this.updateCounter();
    },
    unhook : function() {
        Event.stopObserving( this.nextElement, 'click', this.nextClick );
        Event.stopObserving( this.prevElement, 'click', this.prevClick);
    },
    start: function() {
        this.timer = setInterval( this.doNext.bind(this), 3000 );
    },
    stop: function() {
        if( this.timer != null ) {
            clearInterval( this.timer );
            this.timer = null;
        }
    },
    toggle: function() {
        if( this.timer == null ) {
            this.start();
        } else {
            this.stop();
        }
    },
    updateCounter: function() {
        if( this.counter ) {
            this.counter.innerHTML = (this.current + 1) + ' of ' + this.images.length;
        }
    }
};