/**
 * @author Dave Stein
 * @author Chris Henry
 */



mediaTheater = Class.create();
mediaTheater.prototype = {
	_theater : null,
	_items : null,
	_itemIndex : 0,
	
	initialize : function (the_id, options) {
		this._theater = $(the_id);
		
		this._path = options.path;

		this._items = options.items;		//TODO: add a check to ensure that the items member is an array or hash...or whatever
		this._itemIndex = this.findIndex();

		this.preload();

		this._nextArrow = $(options.nextArrow);
		this._previousArrow = $(options.previousArrow);
		
		this.nextMediaListener = this.mediaNext.bindAsEventListener(this);
		this.mediaPreviousListener = this.mediaPrevious.bindAsEventListener(this);
		
    Event.observe(this._nextArrow, "click", this.nextMediaListener);
    Event.observe(this._previousArrow, "click", this.mediaPreviousListener);
		
		
	},
	
	preload : function() {
		var self = this;
		this._items.each(function(i) {
			  pic1= new Image(); 
				//console.log(self._path + i);
			  pic1.src=self._path + i; 
		});		
	},
	
	findIndex : function() {
		//look for the tag that will display the actual media.
		if(!this._mediaTag) this._mediaTag = this._theater.down('img');
		var mediaTagSrc = this._mediaTag.readAttribute('src').replace(this._path, "");
		
		return this._items.indexOf(mediaTagSrc);
	},
	
	mediaNext : function() {

		this._itemIndex++;

		if(this._itemIndex == (this._items.length)) {
			this._itemIndex = 0;
		}

		var newMedia = this._items[this._itemIndex];
		this.changeMedia(newMedia)
	},
	
	mediaPrevious : function() {
		
		this._itemIndex--;
		
		if(this._itemIndex == -1) {
			this._itemIndex = this._items.length-1;
		}
		
		var newMedia = this._items[this._itemIndex];
		this.changeMedia(newMedia)
		
	},
	
	changeMedia : function(newMedia) {
		if(!this._mediaTag) this._mediaTag = this._theater.down('img');
		var self = this;
		new Effect.Fade(this._mediaTag, {
					duration: 1.0,
					from : 1.0,
					to: 0.0,
					queue : 'end',
					afterFinish: function(obj) {
						self._mediaTag.src = self._path + newMedia;
					}
			});
		new Effect.Appear(this._mediaTag, { 
					duration: 1.0,
					from : 0.0,
					to: 1.0,
					queue: 'end'
			});
	}
	
}