/*global $ Class Element setTimeout */

/**
 * Generate an image and caption rotator.
 */
var ImageRotator = Class.create({
  initialize: function(image_target, caption_target, options) {
		if (!options) { options = {}; }
		this.image_target   = image_target;
		this.caption_target = caption_target;
		this.images         = [];
		this.display_time   = options.display_time ? options.display_time : 10;
		this.fade_time      = options.fade_time ? options.fade_time : 0.5;
		this.current_image_index = 0;
		this.current_img    = null;
		
		if (this.image_target) { $(this.image_target).innerHTML = ""; }
		if (this.caption_target) { $(this.caption_target).innerHTML = ""; }
	},
	/**
	 * Add an image to the rotation list.
	 */
	add: function(url, caption) {
	  this.images.push({url: url, caption: caption});
		var i = new Image();
		i.src = url;
	},
	/**
	 * Start rotating image.
	 */
	start: function() {
	  var myThis = this;
		
		var image_fader;
		image_fader = function() {
		  var target_img = new Element("img");
			target_img.setOpacity(0);
			target_img.style.position = "absolute";
			target_img.src = myThis.images[myThis.current_image_index].url;
			Element.insert($(myThis.image_target), target_img);
			
			if (myThis.caption_target) {
				var target_caption = new Element("span");
				target_caption.innerHTML = myThis.images[myThis.current_image_index].caption;
				Element.insert($(myThis.caption_target), target_caption);
			}
			
			myThis.current_image_index = (myThis.current_image_index + 1) % myThis.images.length;
			
  		var current_step = 0;
			var total_steps = 20;
			var fader;
			fader = function() {
				if (myThis.current_img) {
					var current_opacity = 1 - (current_step / total_steps);
					myThis.current_img.setOpacity(current_opacity);
    			if (myThis.caption_target) {			
						myThis.current_caption.setOpacity(current_opacity);
					}
				}
				
				var target_opacity = (current_step / total_steps);
				target_img.setOpacity(target_opacity);
   			if (myThis.caption_target) {			
					target_caption.setOpacity(target_opacity);
				}

				current_step++;
				if (current_step <= total_steps) {
					setTimeout(fader, (myThis.fade_time * 1000) / total_steps);
				}	else {
				  if (myThis.current_img) {
					  Element.remove(myThis.current_img);
	    			if (myThis.caption_target) {			
						  Element.remove(myThis.current_caption);
						}
					}

				  myThis.current_img = target_img;
    			if (myThis.caption_target) {			
					  myThis.current_caption = target_caption;
					}
					setTimeout(image_fader, myThis.display_time * 1000);
				}
			};
			fader();
		};		
		
		image_fader();
	}
});