var ss_dir = root+'upload/slideshow_dept/';

Event.observe(window,'load',function() {
	if(obj = $('ssobj')) {
		new SlideShow(obj,0,'sscaps',ss_dir,ss_pics,ss_caps);
	}
	
	$$('div.slideshow').each(function(obj){
		new Ajax.Request(root+'solo/solo.getPictureArrays.php',{
			parameters:{slideshow_id:obj.title},
			onFailure:function(r) {
				alert('HTTP Error status '+r.status);
			},
			onSuccess:function(r) {
				var json = r.responseText.evalJSON(true);
				var ss_caps = [], ss_pics = [];
				json.each(function(item){
					ss_pics.push(item[0]+'/'+item[1]);
					ss_caps.push(item[2]);
				});
				obj.insert({before:new Element('div')});
				obj.insert(imgobj = new Element('img'));
				new SlideShow(imgobj,0,obj.previous(),root+'upload/slideshows/',ss_pics,ss_caps);
			}
		});
	});
});

var SlideShow = Class.create({
	initialize: function(objid, start, captionid, ss_dir, ss_pics, ss_caps) {
		/* load vars */
		this.obj = $(objid);
		this.caption = $(captionid);
		this.start = start;
		this.ss_dir = ss_dir;
		this.ss_pics = ss_pics;
		this.ss_caps = ss_caps;
		this.numpics = ss_pics.length;
		this.preloadImage = new Image();

		/* Set the first picture */
		this.obj.src = this.ss_dir + escape(this.ss_pics[this.start]);
		this.caption.innerHTML = this.ss_caps[this.start];

		if( this.numpics < 2 ) return;

		/* start cycling */
		new PeriodicalExecuter(this.cycle.bind(this), 5);

		/* Preload the image after this one */
		this.preloadImage.src = this.ss_dir + escape(this.ss_pics[ (this.start+1) % this.numpics ]);
	},
	cycle: function() {
		/* Preload the image after this one */
		this.preloadImage.src = this.ss_dir + escape(this.ss_pics[ (this.start+2) % this.numpics ]);
		var albumobj = this;
		
		/* Fade effects */
		new Effect.Fade(albumobj.obj, {
			duration: 1,
			fps: 50,
      		afterFinish: function() {
      			albumobj.start = (albumobj.start+1) % albumobj.numpics;
				albumobj.obj.src = albumobj.ss_dir + escape(albumobj.ss_pics[albumobj.start]);
				new Effect.Appear(albumobj.obj, {
					duration: 1,
					fps: 50,
					beforeStart: function() {
						albumobj.caption.innerHTML = albumobj.ss_caps[albumobj.start];
					}
				})
			}
		});
	}
});