var CE_Slideshow_Controller = new Class({
    options: {
		id: null,
		gallery_id: null,
		datasource: null,
		container: null,
		application_webroot: null,
		fx_duration: 300,
		resize_image_width: 0, // set to zero to use the image's natural width/height
		slideshow_interval: 5000
    },

    initialize: function(options) {
		this.setOptions(options);
		this.ajax = null;
		this.interval = null;
		
		this.container = $(this.options.container);
		
		this.images = [];
		this.current_image = 0;
		this.tallest_image_height = 0;
		
		this.init();
	},
	
	init: function() {
		pars = "method=get_images&target=" + this.options.id + "&id=" + this.options.gallery_id;

		this.ajax = new Request({
			url: this.options.datasource,
			data: pars,
			onSuccess: this.populate.bind(this)
		}).send();
	},

	populate: function(request) {
		var r = JSON.decode(request);

		this.images = r.images;
		for (var x = 0; x < this.images.length; x++) {
			var image_container = new Element("div", {
				"id": "image_container_" + x
			});
		
			if (x !== 0) {
				image_container.setStyle("display", "none");
			}
			
			var image = new Element("img", {
				"src": this.options.application_webroot + this.images[x].path
			});
			
			if (this.options.resize_image_width === 0) {
				image.setStyles({
					"width": this.images[x].width,
					"height": this.images[x].height
				});
			} else {
				image.setStyles({
					"width": this.options.resize_image_width,
					"height": this.options.resize_image_width * this.images[x].height / this.images[x].width
				});
			}
			
			image.inject(image_container);
			image_container.inject(this.container);
		}

		this.container.removeClass("loading");
		this.play();
	},
	
	do_image: function(which) {
		if (this.current_image !== which) {	
			this.transition("image_container_" + this.current_image, "image_container_" + which);
			this.current_image = which;
		}
	},
	
	transition: function(from, to) {
		var f = new Fx.Tween(from, { duration:this.options.fx_duration, onComplete:function(elem) { elem.style.display = "none"; } });
		var t = new Fx.Tween(to, { duration:this.options.fx_duration });
		
		f.start("opacity", 1, 0).chain(
			function() {
				$(to).setStyles({ opacity: 0, display:"block" });
				t.start("opacity", 0, 1);
			}
		);
	},
	
	next: function() {
		if (this.current_image == (this.images.length - 1)) {
			this.do_image(0);
		} else {
			this.do_image(this.current_image + 1);
		}
	},
	
	previous: function() {
		if (this.current_image == 0) {
			this.do_image(this.images.length - 1);
		} else {
			this.do_image(this.current_image - 1);
		}
	},
	
	play: function() {
		//this.next();
		this.interval = setInterval(this.options.id + ".next()", this.options.slideshow_interval);
	},
	
	pause: function() {
		clearInterval(this.interval);
	}
});

CE_Slideshow_Controller.implement(new Options);
