var Switchteaser = Class.create({

    options: $H({
        fxDelay: 0.5
    }),

    initialize: function(container)
    {
        this.container = $(container);
        this.elements = this.container.childElements();
        this.current = 0;
        this.isActive = false;
        
        if(this.elements.length == 0)
        {
            return false;
        }
        
        this.container.setStyle({
            position: 'relative' 
        });
        
        this.elements.each(function(el, i){
            el.setStyle({
                left: 0,
                opacity: i > 0 ? 0 : 1,
                position: 'absolute',
                top: 0,
                zIndex: i > 0 ? 0 : 1
            });
        });
        
        this.build();
    },
    
    build: function()
    {
        // left arrow
        var l =  new Element('a', { href: '#' }).addClassName('switch_left').observe('click', function(e){
            Event.stop(e);
            this.change(0);
        }.bind(this));
        this.container.insert(l);
        
        // right arrow
        var r =  new Element('a', { href: '#' }).addClassName('switch_right').observe('click', function(e){
            Event.stop(e);
            this.change(1);
        }.bind(this));
        this.container.insert(r);
    },
    
    change: function(d)
    {
        if(this.isActive)
        {
            return false;
        }
        this.isActive = true;
        // back
        if(d == 0)
        {
            this.elements[this.current].fade({ duration: 1.5, from: 1, to: 0 });
            
            this.current = this.current - 1 > -1 ? this.current - 1 : this.elements.length-1;
        }
        // forward
        else
        {
            this.elements[this.current].fade({ duration: 1.5, from: 1, to: 0 });
            
            this.current = this.current + 1 < this.elements.length ? this.current + 1 : 0;
        }
        (function(){
            this.elements[this.current].setStyle({
                display: 'block',
                opacity: 0
            }).fade({ duration: 1.0, from: 0, to: 1 });
        }.bind(this)).delay(this.options.get('fxDelay'));
        (function(){
            this.isActive = false;
        }.bind(this)).delay(this.options.get('fxDelay')*2);
    }
    
});

Event.observe(window, 'load', function(){
    if($$('div.switchable')[0])
    {
        new Switchteaser($$('div.switchable')[0]);
    }
});