Event.observe(window, 'load',
	function(){
		new slideShow();
	}
);


var slideShow = Class.create({
    initialize: function() {
		this.slides = new Array();
        this.slidesTotal = 0;
        this.currentID = -1;

		this.container = $$('td.slideshow').find(function(el) {
			return el.id;
		});

		this.showID = parseInt(this.container.id.substr(this.container.id.lastIndexOf('-') + 1));
		this.container.insert({before:'<div id="preloader"></div>'});

        new Ajax.Request('/welcometest/init_sshow/'+this.showID, {
            onSuccess: function(t) {
                if(t.responseText) {
                    var resp = t.responseText.evalJSON();

                    this.showID = resp.showID;
                    this.slidesTotal = resp.slidesTotal;
                    this.currentID = -1;

                    if(this.slidesTotal) {
                        this._showNext();

                        new PeriodicalExecuter(this._showNext.bind(this), 8);
                    }
                }
            }.bind(this)
        });
    },

    _showNext: function() {
        this.currentID = this.currentID + 1;
        if(this.currentID == this.slidesTotal)
            this.currentID = 0;

		if(typeof this.slides[this.currentID] == 'undefined') {
			new Ajax.Request('/welcometest/slide/'+this.showID+'/'+this.currentID, {
				onSuccess: function(t) {
					if(t.responseText) {
						var resp = t.responseText.evalJSON();

						this.slides[this.currentID] = resp.current;

						//$('slide').setStyle({ width: resp.current.width+'px' });
						//$('slide').update(resp.current.slide).hide().appear({ duration: 3.0 });
						$('ss-'+this.showID).setStyle({ backgroundImage: 'url('+resp.current.slide+')' });
						$('preloader').update(resp.next.slide);
					}
				}.bind(this)
			});
		} else {
			//$('slide').setStyle({ width: this.slides[this.currentID].width+'px' });
			//$('slide').update(this.slides[this.currentID].slide).hide().appear({ duration: 3.0 });
			$('ss-'+this.showID).setStyle({ backgroundImage: 'url('+this.slides[this.currentID].slide+')' });
		}
    }
});
