(function() {
	if(typeof IMVU.util == 'undefined') {
			IMVU.util = {};		
	}

	IMVU.util.SlideShow = new function() {		
		var slideshow = this;
		var container = null;
		var timer = {};
		
		this._index = 0;
		this._next = 1;
		this._greatestWidth = 0;
		this._greatestHeight = 0;
		this._cache = [];
		
		this.containerId = '';		
		this.displayDuration = 3;
		this.fadeDuration = .5;
		this.onTransitionComplete = new YAHOO.util.CustomEvent("onTransitionComplete");
		
		this.start = function() {			
			container = YAHOO.util.Dom.get(this.containerId);
			container.appendChild(this._cache[this._index]);
			YAHOO.util.Dom.setStyle(this._cache[this._index + 1], 'opacity', 0);
			container.appendChild(this._cache[this._index + 1]);
			timer = setTimeout(
				function() { 
					slideshow.loop(); 
				}, 
				(this.displayDuration * 1000)
			);
		};
		
		this.getNext = function() {	
			return this._next = (this._index + 1 == this._cache.length) ? 0 : this._index + 1; 
		};
		
		this.loop = function() {			
			this.getNext();
			var anim = new YAHOO.util.Anim(
				this._cache[this._next], 
				{opacity : {to : 1}}, 
				this.fadeDuration, 
				YAHOO.util.Easing.easeOut
			);
			anim.onComplete.subscribe(
				function() {
					slideshow.onTransitionComplete.fire();
					container.removeChild(slideshow._cache[slideshow._index]);
					slideshow._index = slideshow._next;
					slideshow.getNext();
					YAHOO.util.Dom.setStyle(slideshow._cache[slideshow._next], 'opacity', 0);
					container.appendChild(slideshow._cache[slideshow._next]);
					slideshow.loop();		
				}
			);
			clearTimeout(timer);
			timer = setTimeout(
				function() {
					anim.animate();
				},
				(this.displayDuration * 1000)
			);
		};
		
		this.initCache = function() {
			for(var i = 0, obj, el; obj = this.imageList[i]; ++i) {				
				var img = document.createElement('img');				
				var a = document.createElement('a');
				for(var attr in obj) {
					if(attr == 'href') {
						a.setAttribute(attr, obj[attr]);
					} else {
						img.setAttribute(attr, obj[attr]);
						if(img.height > this._greatestHeight) {
							this._greatestHeight = img.height;
						}
						if(img.width > this._greatestWidth) {
							this._greatestWidth	= img.width;
						}						
					}
				}
				if(a.href) {
					a.appendChild(img);
					el = a;
				} else {
					el = img;
				}
				this._cache.push(el);
			}
		};
		
		this.init = function(config) {			
			for(var prop in config) {
				this[prop] = config[prop];
			}
			this.initCache();

			if(config.runOnLoad) {
				YAHOO.util.Event.on(window, 'load', slideshow.start());
			}
		};
	};
})();