var SimpleGallery = new Class({
    Implements: [Options, Events],    
    
    options: {
        canvas: 'canvas',
        duration: 1000,
        delay: 5000,
        fps: 20,
        images: []
    },
    
    _img: [],
    _fade_out: [],
    _fade_in: [],
    _timer: '',
    
    initialize: function(options) {
    
        this.setOptions(options);
        this.options.canvas = $(this.options.canvas);
        
        // Inject 2 img tags into canvas
        var img = new Element('img', {
            styles: {
                display: 'block',
                position: 'absolute'
            }
        });
        
        this._img[0] = img;
        this._img[1] = img.clone();
        
        this._img.each(function(ele, index) { 
            if(index == 0) ele.set('rel', 'active');
            ele.inject(this.options.canvas); 
        }.bind(this));
        
        this.changeImage(0);
        
    },
    
    changeImage: function(index) {
    
        if(index >= this.options.images.length) index = 0;
        
        $clear(this._timer);
        
        var newEle = '';
        this._fade_out = new Array();
        this._fade_in = new Array();
        
        // Get current image in front
        this._img.each(function(ele, i) {
        
            var t = new Fx.Tween(ele, {
                duration: this.options.duration,
                fps: this.options.fps
            });
            
            if(ele.get('rel') == 'active') {
            
                this._fade_out[this._fade_out.length] = t;
                
            } else {
            
                this._fade_in[this._fade_in.length] = t;
                
                ele.removeEvents('load');
                ele.addEvent('load', function() {
                    this._fade_out.each(function(fo) {
                        fo.start('opacity', 0);
                    });
                    
                    this._fade_in.each(function(fi) {
                        fi.start('opacity', 1);
                    });
                    
                    this.fireEvent('imageChange', index);
                    
                }.bind(this));
                
                newEle = ele;
                
                
            }
        }.bind(this));
        
        this._img.each(function(ele) { ele.set('rel', ''); }.bind(this));
        newEle.set('rel', 'active');
        
        if(typeof this.options.images[index] == 'object') {
            newEle.set('src', this.options.images[index].get('href'));
        } else {
            newEle.set('src', this.options.images[index]);
        }
        
        this._timer = (function() { 
            this.changeImage(index + 1); 
        }.bind(this)).delay(this.options.delay);
        
    }
    
});


