/**
 * Cycles through a list and displays the contents one by one
 * Paul Serby - paul.serby@clock.co.uk 16 November 2009
 */
RumbleUI.InnerSwap = Class.create();
RumbleUI.InnerSwap.prototype = {

  initialize: function(element, options) {

		this.element = $(element);
	  this.options = {
	    timeout: 5,
	    delay: 0.5,
	    startPosition: 0,
	    containerHeight: "auto",
	    transition: "fade"
	  };

	  this.items = [];
	  this.currentItem = 0;
	  Object.extend(this.options, options || {});

	 	switch (this.options.transition) {
	 		case "blind":
			  this.transition = this.blindTransition;
		 		break;
	 		case "swap":
			  this.transition = this.swapTransition;
		 		break;
	 		case "fade":
		 	default:
			  this.transition = this.fadeTransition;
		 		break;
		}
	  
	  this.setup();

		new PeriodicalExecuter(this.onCycle.bind(this), this.options.timeout);
  },

  setup: function() {
	  var zIndex = 1;
	  var first = this.element.down("li");
		this.element.setStyle({ "position": "relative", "height" : first.getHeight() + "px" });
		this.element.select("li").each((function(listItem) {
			listItem.setStyle({ "position": "absolute", "zIndex": zIndex++ });
			listItem.hide();
			this.items.push(listItem);
		}).bind(this));
		first.show();
	},

	onCycle: function() {

		var oldIndex = this.currentItem;
		
		this.currentItem++;

		if (this.currentItem >= this.items.length) {
			this.currentItem = 0;
		}
		if (this.items[oldIndex].style.zIndex > this.items[this.currentItem].style.zIndex) {
		
			var zIndex = this.items[oldIndex].style.zIndex;
			this.items[oldIndex].style.zIndex = this.items[this.currentItem].style.zIndex;
			this.items[this.currentItem].style.zIndex = zIndex;
		}
		this.transition(this.items[oldIndex], this.items[this.currentItem]);
	},

	fadeTransition: function(outItem, inItem) {
		Effect.Fade(outItem, { delay: this.options.delay });
		Effect.Appear(inItem, { delay: this.options.delay });
	},

	swapTransition: function(outItem, inItem) {
		outItem.hide();
		inItem.show();
	},
	
	blindTransition: function(outItem, inItem) {
		Effect.BlindDown(inItem, { delay: this.options.delay, afterFinish: function() { outItem.hide(); } });
	}
};
