
var slideViewer = new Class({
    options: {
		slides: [],
		back: 0,
		next: 0,
		autotime: 6000
      },

	initialize: function(options){
    	this.setOptions(options);
    	this.intControls(this.options.back,this.options.next,this.options.play,this.options.pause);
		if(this.options.slides.length) {this.showSlide(0);}
		this.autoTimer = this.nextSlide.periodical(this.options.autotime, this);
    },
    autoTimer: 0,
    intControls: function(back,next,play,pause){
		if (back) {
			back.addEvent('click',function(e){
				e = new Event(e).stop();
				$clear(this.autoTimer);
				this.backSlide();
			}.bind(this));
		}
		if (next) {
			next.addEvent('click',function(e){
				e = new Event(e).stop();
				$clear(this.autoTimer);
				this.nextSlide();
			}.bind(this));
 		}
		if (play) {
			play.addEvent('click',function(e){
				e = new Event(e).stop();
				$clear(this.autoTimer);
				this.autoTimer = this.nextSlide.periodical(this.options.autotime, this);
			}.bind(this));
		}
		if (pause) {
			pause.addEvent('click',function(e){
				e = new Event(e).stop();
				$clear(this.autoTimer);
			}.bind(this));
 		}
    },

    nextSlide: function(){
        if (this.fading) return;
        if($chk(this.now)) {
			var newSlide = 0;
			if (this.now < this.options.slides.length-1) {
				newSlide = parseInt(this.now, 10) + 1
			}
			this.showSlide(newSlide);
		}
        else if(!$defined(this.now)) {this.showSlide(this.options.startSlide);}

    },

    backSlide: function(){
		if (this.fading) return;
		var newSlide = this.options.slides.length - 1;
		if (this.now > 0) {
			newSlide = parseInt(this.now, 10) -1;
		}
		this.showSlide(newSlide);
    },

    showSlide: function(iSlide){
        var now = this.now;
        var currentSlide = this.options.slides[now];
        var slide = this.options.slides[iSlide];

        var fadeIn = function (s){
			this.fading = true;
            s.setStyles({
            	display:'block',
            	position:'absolute',
            	top:0,
            	left:0,
                visibility: 'visible',
                opacity: 0
            });
			var fxfadeIn = new Fx.Style(s, 'opacity', {duration: 700} ).start(1).chain(function(){
				this.fading = false;
                this.fireEvent('onShow', [slide, iSlide]);
            }.bind(this));
        }.bind(this);

		var fadeOut = false;
		if(slide) {
        	if($chk(now)) {
				fadeOut = (now != iSlide);
			}
			if (fadeOut) {
            	this.fading = true;
            	var fxfadeOut = new Fx.Style(currentSlide, 'opacity', {duration: 300} ).start(0).chain(function(){
                	currentSlide.setStyle('display', 'none');
            	}.bind(this));
        	}
        	fadeIn(slide);
        	this.now = iSlide;
        }
    }
});

slideViewer.implement(new Options(), new Events());