/**
 * @author POP: G.S.
 * @version 1.0
 * @lastmodified 8/06/2009
 * @classDescription A class for dynamically loading SilverLight video/audio assets based on a collection of thumbnails
 * @return {Object}	Returns a new instance of the class.
 * @projectDescription Forza Motorsport
 * 
 * Dependencies:
 * - Prototype 1.6.0.3+
 * - Scriptaculous 1.8.2+
 */
var ForzaMediaWidget = Class.create({
	initialize: function(elMetaDataWrapper, elThumbnails, options){
		// -----------------------------------------------------------------------------
		// Element References:
		// -----------------------------------------------------------------------------
		this.elMetadataWrapper = elMetaDataWrapper;
		this.elThumbnails = elThumbnails;
		this.elMetadata = elMetaDataWrapper.select('div.metadata');

		this.options = Object.extend({
			mediaType: 'media',
			silverlightObjID: 'SilverLightMediaPlayer'
		}, options || {});
		
		
		// -----------------------------------------------------------------------------
		// Properties:
		// -----------------------------------------------------------------------------

		// Contains the unique IDs of each media item for easily figuring out their index:
		this.mediaIDs = {};

		this.elMetadata.each(function(el,index){
			//console.log(index + " - " + el.select('div.resources ul li')[2].innerHTML);
			this[el.select('div.resources ul li')[2].className] = index;
		},this.mediaIDs);
		
		this.mediaCount = this.elThumbnails.length;
		this.currentMedia = this.getHash() || 0;
		this.previousMedia = this.currentMedia;
		
		this.pageTitle = document.title;
				
		// -----------------------------------------------------------------------------
		// Page Setup:
		// -----------------------------------------------------------------------------		
		this.setHash(this.currentMedia);		
		this.highlightThumbnail(this.currentMedia);
		this.showMetadata(this.currentMedia);
		
		this.loadMedia(false);
		
		// -----------------------------------------------------------------------------
		// Event Handlers:
		// -----------------------------------------------------------------------------
		this.elThumbnails.invoke('observe','click',this.__thumbClick.bind(this));
	},
	
	__thumbClick: function(e) {
		e.stop();
		
		this.previousMedia = this.currentMedia;
		this.currentMedia = e.element().up().previousSiblings().length;
		//console.log(e.element());
		//console.log("Loading Video: " + this.currentMedia);
		
		this.highlightThumbnail(this.currentMedia);
		this.scrollUp();
		this.showMetadata(this.currentMedia, true);
		this.loadMedia(true);		
		this.setHash(this.currentMedia);
	},
	
	highlightThumbnail: function(index) {
		this.elThumbnails.invoke('removeClassName','on');
		this.elThumbnails[index].addClassName('on');
	},
	
	showMetadata: function(index,animate) {
		this.targetMargin = (-359 * index)+'px';
		
		//console.log("Sliding metadata_wrapper to : "+ this.targetMargin);
		
		// Adds the ability to suppress animation for initial page load :
		if(animate) {
			new Effect.Morph(this.elMetadataWrapper,{
				style:{'margin-left':this.targetMargin},
				duration:0.4
			});
		} else {
			this.elMetadataWrapper.setStyle({marginLeft:this.targetMargin});
		}
	},
	
	loadMedia: function(autoplay) {
		var audioExt = $w('.mp3 .wma .aac');
		var videoExt = $w('.wmv .mov .mp4');
		
		if(this.options.mediaType == 'audio') {
			var ext = this.elMetadata[this.currentMedia].select('div.resources ul li')[4].className;
			if(audioExt.member(ext)){
				this.loadAudio(this.currentMedia, autoplay, 0);
			} else{
				this.loadVideo(this.currentMedia, autoplay, 0);
			}
			//this.loadAudio(this.currentMedia, autoplay, 0);
		} else {
			this.loadVideo(this.currentMedia, autoplay, 0);
		}
	},
	
	loadVideo: function(index, autoplay, count) {
		var silverlightObj = $(this.options.silverlightObjID);
		if (!silverlightObj || !silverlightObj.Content || !silverlightObj.Content.MainPage) {
			if (!count)
				count = 0;
			count++;
			console.log('Trying to load video...attempt ' + count + ' of 20');
			if (count > 20)
				throw 'Unable to load video';
			var callbackObj = this;
			setTimeout(function() {
				callbackObj.loadVideo(index, autoplay, count);
			}, 500);
			return;
		}

		var videoUrl = this.elMetadata[index].select("div.resources ul li")[0].select('a')[0].readAttribute('href');
		var imgUrl = this.elMetadata[index].select("div.resources ul li")[1].select('a')[0].readAttribute('href');		
		
		try{
			console.log("loading video:", videoUrl, imgUrl, autoplay);
			silverlightObj.Content.MainPage.LoadVideo(videoUrl, imgUrl, autoplay);
		} catch(e){
			console.error(e);
			//throw new Error("Silverlight failed to respond");
		}
		
		
	},
	
	loadAudio: function(index, autoplay, count) {
		var silverlightObj = $(this.options.silverlightObjID);
		if (!silverlightObj || !silverlightObj.Content || !silverlightObj.Content.MainPage) {
			if (!count)
				count = 0;
			count++;
			console.log('Trying to load video...attempt ' + count + ' of 20');
			if (count > 20)
				throw 'Unable to load video';
			var callbackObj = this;
			setTimeout(function() {
				callbackObj.loadAudio(index, autoplay, count);
			}, 500);
			return;
		}
		var audioUrl = this.elMetadata[index].select("div.resources ul li")[0].select('a')[0].readAttribute('href');
		var imgUrl = this.elMetadata[index].select("div.resources ul li")[1].select('a')[0].readAttribute('href');
		try{
			console.log("loading audio:", audioUrl, imgUrl, autoplay);
			silverlightObj.Content.MainPage.LoadVideo(audioUrl, imgUrl, autoplay);
		} catch(e){
			console.error(e);
			//throw new Error("Silverlight failed to respond");
		}	
	},
	
	scrollUp: function() {	
		if(document.viewport.getScrollOffsets()[1] > 173)
			Effect.ScrollTo('content',{duration:0.2});
	},
	
	setHash: function(index) {
		location.hash = '/'+this.options.mediaType+'/' + this.elMetadata[index].select('div.resources ul li')[2].className + '/';
		
		var title = this.pageTitle;
		
		// For IE's benefit (Using 10ms delay for temporal bug) :
		setTimeout(function() { document.title = title; }, 10);
	},
	
	// Gets the current hash (unique media ID) and returns the index of the media
	getHash: function() {
		this.hash = Math.floor(location.hash.split('/')[2]);
		this.index = this.mediaIDs[this.hash];
				
		if(this.index == undefined) {
			//console.log("Referenced media does not exist.");
			return false;
		} else {
			return Math.floor(this.index);	// Prevents a string from being returned
		}
	}
});
