//recieve ooyala callback function
function receiveOoyalaEvent(playerId, eventName, p) {
	mySetupPlayer.receiveOoyalaEvent(playerId, eventName, p);
} 

var setupPlayer = new Class({
	initialize: function() {
		this.myPlayerReady	= false;
		this.myDomReady 	= false;
		this.runOnce 		= true;
	},
	receiveOoyalaEvent: function(playerId, eventName, p) {
		switch(eventName) { 
	    case 'playheadTimeChanged': 
			this.ooyalaLoaded(playerId);
			return; 
	    case 'stateChanged': 
	      	return; 
	    case 'playComplete': 
			this.continuous();
			return;
	    case 'currentItemEmbedCodeChanged':
	    	if (this.videosLineup) {
				this.updateDetails(p,this.videosLineup,'video');
	    	};
			return; 
	    case 'totalTimeChanged': 
			this.ooyalaLoaded(playerId);
			return; 
	    case 'embedCodeChanged': 
			return; 
	    case 'volumeChanged': 
			return; 
	    case 'loadComplete':  
	    	return;   
		} 
	}, 
	domReady: function(options) {
		
		//setup DOM elements
		this.myOptions 			= options;
		this.myDetails			= $(this.myOptions.detailsPane);
		this.myDetailsNav		= this.myDetails.getElements('ul.nav li a');
		this.myPlayerPane		= $(this.myOptions.playerPane);
		this.myEmbedPane 		= $(this.myOptions.embedPane);
		this.myEmbedField 		= this.myEmbedPane.getElement('textarea'); 
		this.myCategoriesPane 	= $(this.myOptions.categoriesPane);
		this.myCarouselPane 	= $(this.myOptions.carouselPane);
		this.myMediaSwitcher 	= $(this.myOptions.mediaSwitcher).getElements('li a');
		this.carouselContainer 	= this.myCarouselPane.getElement('.viewport');
		this.myContinuousBtn 	= $(this.myOptions.continuousBtn);
		this.iFramePath			= this.myOptions.iFramePath;
		this.myCategories		= this.myOptions.categoryObj;
		this.screensLineup		= this.myOptions.screensObj;
		this.fltrScreensLineup	= this.screensLineup;

		//default player parameters
		this.defaultMedia			= this.myOptions.defaultMedia;
		this.primaryLabel			= this.myOptions.primaryLabel;
		this.ooyalaOptions			= new Hash(this.myOptions.ooyalaOptions);
		this.ooyalaOptions.labels 	= this.primaryLabel;
		this.ooyalaOptions.callback = "receiveOoyalaEvent";

		if ($type(this.myOptions.defaultType)) {
			this.defaultType = this.myOptions.defaultType;
		} else {
			this.defaultType = 'video';
		}


		//default filmstrip parameters
		this.filmStripOptions	= this.myOptions.filmStripOptions;
		
		//get hash (if it exists)
		this.getHash();
		
		//build the player based on the default type 
		this.buildMedia(this.defaultType)
		
		//setup media type swicther
		this.myMediaSwitcher.each(function(item){
			if (item.rel == this.defaultType) {
				item.addClass('on');
			}
			item.addEvent('click', function(e) {
				e.stop();
				this.myMediaSwitcher.each(function(item){
					item.removeClass('on');
				}.bind(this));
				item.addClass('on');
				this.buildMedia(item.rel);
			}.bind(this));
		}.bind(this));
	},
	buildMedia: function(mediaType) {
		//reset runonce boolean
		this.runOnce = true;
		
		//make sure everything is empty
		this.myPlayerPane.empty();
		this.carouselContainer.empty();
		
		//build categories if it exists
		if ($type(this.myCategoriesPane)) {
			this.buildCategories(mediaType);
		}
		
		if (mediaType === "screen") {
			
			if ($type(this.myEmbedPane)) this.myEmbedPane.setStyle('display','none');
			this.myContinuousBtn.setStyle('display','none')
	
			//load current item - if none exists, load the first one.
			this.currentItem = this.screensLineup[0];
			this.screensLineup.each(function(item){
				if (item.embedCode === this.defaultMedia) {
					this.currentItem = item;		
				}
			}.bind(this));

			//draw screen + build carousel
			this.drawScreen(this.currentItem);
			this.buildCarousel(this.screensLineup,'screen');
			
			//setup prev + next buttons
			this.myDetailsNav.each(function(item, index){
				item.removeEvents('click');
				item.addEvent('click', function(e) {
					e.stop();
					this.changeMedia(this.fltrScreensLineup[item.getProperty('rel')],'screen',this.fltrScreensLineup);
				}.bind(this));
			}.bind(this));

		} else if (mediaType === "video") {
			//build iframe element for ooyala player	
			delete this.myPlayerIframe;
			this.myPlayerIframe = new IFrame({
				src: this.iFramePath + '?' + this.ooyalaOptions.toQueryString(),
				frameborder: '0',
				scrolling: 'no',
				styles: {
			        width: 640,
			        height: 360
			    }
			});		   
			this.myPlayerIframe.inject(this.myPlayerPane);
		
			//toggle looping
			if ($type(this.myContinuousBtn)) {
				this.myContinuousBtn.addEvent('click', function(e) {
					this.myContinuousBtn.toggleClass('on');
					e.stop();
				}.bind(this));
			}
			
			//setup prev + next buttons
			this.myDetailsNav.each(function(item){
				item.removeEvents('click');
				item.addEvent('click', function(e) {
					e.stop();
					this.changeMedia(this.videosLineup[item.getProperty('rel')],'video',this.videosLineup,true);
				}.bind(this));
			}.bind(this));
			
			if ($type(this.myEmbedPane)) this.myEmbedPane.setStyle('display','block');
			this.myContinuousBtn.setStyle('display','block')
		}
		
	},
	drawScreen: function(item) {
		var new_item = new Element('img', {
			'src': item.img,
			'alt': item.title,
			'width': 640,
			'height': 360
		});
		
		//create the element + setup the fx
		var myFX = new Fx.Tween(new_item, {duration:500});
		new_item.setStyle('opacity','0');
		new_item.inject(this.myPlayerPane);
		myFX.start('opacity','1').chain(function(){	 
			// if there's more than 2 imgs - remove the first one to save memory.
			if (this.myPlayerPane.getChildren().length > 2) {
				this.myPlayerPane.getFirst().destroy();
			}
		}.bind(this));
	},
	ooyalaLoaded: function(playerId) {
		//ooyala player is loaded and ready to build carousel + details
		if (this.runOnce) {
			this.runOnce 		= false;
			this.myPlayerId 	= playerId;
			
			//setup player elements
			this.myPlayer 		= window.frames[0].document.getElementById(this.myPlayerId);		
			this.videosLineup 	= this.myPlayer.getLineup();
			this.currentItem	= this.myPlayer.getCurrentItem();
			this.myPlayerIframe.setStyle('visibility','visible');
			this.buildCarousel(this.videosLineup,'video');
		}
	},
	buildCarousel: function(playlist,mediaType) {
		//make sure carousel is empty
		this.carouselContainer.empty();
		
		delete this.carouselList;
		this.carouselList = new Element('ul', {
			'class':'filmstrip'
		}).inject(this.carouselContainer);
		
		
		$each(playlist,function(item, index){
			//check to make sure item is actual item and not bogus item ooyala sometimes returns.
			if (item.embedCode) {
				
				//determine thumb image
				if (mediaType === 'video'){
					var thumb = this.myPlayer.getPromoFor(item.embedCode, 133, 78);
				} else {
					var thumb = item.promo;	
				}
				
				var new_item = new Element('li', {'html':
					'<a class="' + item.embedCode + '"  href="?'+mediaType+'Id='+item.embedCode+'">'+
						'<img width="133" height="78" class="pic" src="'+thumb+'" /><span class="ie6_png_fix"></span>'+
						'<h2>'+item.title+'</h2>'+
					'</a>'
				}).inject(this.carouselList);
				
				if (mediaType === 'video'){
					new_item.addClass("showPlay");
				}
				
				new_item.addEvent('click', function(e) {
					this.changeMedia(item,mediaType,playlist,true);
					e.stop();
				}.bind(this));
			}
			
		}.bind(this));
		
		//create filmstrip
		delete this.myFilmStrip;
		this.myFilmStrip = new FilmStrip(this.filmStripOptions);
		
		//update details
		this.updateDetails(this.currentItem,playlist,mediaType);
	},	
	buildCategories: function(mediaType) {
		
		//get filter elements
		var trigger 	= this.myCategoriesPane.getElement('.trigger');
		var filter 		= this.myCategoriesPane.getElement('.filter');
		var caption 	= this.myCategoriesPane.getElement('.caption span');
	
		//reset the filter
		caption.setProperty('html','All');
		filter.empty();
	
		//add some events
		this.myCategoriesPane.addEvent('mouseleave', function(e) {
			this.myCategoriesPane.removeClass('on');
		}.bind(this));
		
		trigger.addEvent('click', function(e) {
			e.stop();
			this.myCategoriesPane.addClass('on');
		}.bind(this));
		
		//add categories
		$each(this.myCategories[mediaType],function(item, index){
			var new_item = new Element('a', {
				'html': item[0],
				'rel': item[1]
			}).inject(filter);
			
			new_item.addEvent('click', function(e) {
				e.stop();
				caption.setProperty('html',new_item.getProperty('html'));
				this.myCategoriesPane.removeClass('on');
				this.updateCategory(new_item.rel,mediaType);
			}.bind(this));

		}.bind(this));	
	},
	updateCategory: function(category,mediaType) {
		//reset runonce boolean
		this.runOnce = true;
		
		//make sure carousel is empty
		this.carouselContainer.empty();
		
		if (mediaType === "video") {
			//send new video filter to ooyala - ooyala will do the rest 
			this.ooyalaOptions.labels = this.primaryLabel + "/" + category;
			this.myPlayerIframe.setProperty('src', this.iFramePath + '?' + this.ooyalaOptions.toQueryString());
		} else if (mediaType == "screen") {
			
			//filter screen lineup by category
			if (category === "") {
				this.fltrScreensLineup = this.screensLineup;
			} else {
				this.fltrScreensLineup = this.screensLineup.filter(function(item, index){
					return item.category.contains(category,",");
				});
			}
			
			//reset current item, build carousel and draw image 
			this.buildCarousel(this.fltrScreensLineup,'screen');
			if (this.fltrScreensLineup[0]) {
				this.currentItem = this.fltrScreensLineup[0];
				this.drawScreen(this.fltrScreensLineup[0])
				this.updateDetails(this.currentItem,this.fltrScreensLineup,'screen');
			}
		}
	},
	changeMedia: function(mediaItem,mediaType,playlist,autoplay) {
		if (mediaType === "video") {
			//send new video to ooyala player 
			this.myPlayer.changeCurrentItem(mediaItem.embedCode);
			if (autoplay) {
				this.myPlayer.playMovie();
			}
		} else if (mediaType === "screen") {
			//draw new screen
			this.updateDetails(mediaItem,playlist,mediaType)
			this.drawScreen(mediaItem);
		}
	},
	updateDetails: function(mediaItem,playlist,mediaType) {
		// for omniture
		buildContentType(mediaType,'Game Information::'+mediaType,mediaItem.title);
		//update the item details
		this.myDetails.getElement('h1').set('html',mediaItem.title);
		this.myDetails.getElement('p').set('html',mediaItem.description);
		
		//update embed (used for vidsos only)
		this.updateEmbed(mediaItem);
		
		//update the hash
		this.updateHash(mediaItem,mediaType);
		
		//determine the current index of the item for the carousel & prev + next buttons 
		var currentIndex = 0;
		$each(playlist,function(item, index){
			if (item.embedCode === mediaItem.embedCode) {
				currentIndex = parseInt(index);
			};
		});
		this.myDetailsNav[0].setProperty('rel',currentIndex-1);
		this.myDetailsNav[1].setProperty('rel',currentIndex+1);
		
		//hide next + prev if at end or beginning
		if (currentIndex < 1) {
			this.myDetailsNav[0].setStyle('visibility','hidden');
		} else { 
			this.myDetailsNav[0].setStyle('visibility','visible');
		}
		
		if (currentIndex >= playlist.length-1) {
			this.myDetailsNav[1].setStyle('visibility','hidden');
		} else {
			this.myDetailsNav[1].setStyle('visibility','visible');
		}
		
		var myCarouselItems = this.myCarouselPane.getElements('.filmstrip li a');
		
		myCarouselItems.each(function(item, index) {
			item.removeClass('on');
		});
		
		if (myCarouselItems[currentIndex]) {
			myCarouselItems[currentIndex].addClass('on');
		}
		
		//advance filmstrip to current item
		this.myFilmStrip.goToItem(currentIndex);
	},
	continuous: function() {
		//at end of each video check continous play flag
		if (($type(this.myContinuousBtn)) && (this.myContinuousBtn.hasClass('on') === false)) {
			this.myPlayer.pauseMovie().delay(1000);
		}
	},
	updateEmbed: function(item) {
		var myItem = item;
		var url =  window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + window.location.pathname + '?mediaId=' + myItem.embedCode;
		var embed 	= '&lt;div style="width:640px; height: 400px"&gt;'
		embed 		+= '&lt;script src="http://www.ooyala.com/player.js?hide=endscreen&height=340&amp;embedCode=' + myItem.embedCode + '&amp;autoplay=0&amp;width=592"&gt;&lt;/script&gt;'
		embed 		+= '&lt;a href="http://nhl.easports.com/home.action" style="color: black; font-size: 10px; text-decoration: none;"&gt;EA SPORTS NHL 10&lt;/a&gt;'
		embed 		+= '&lt;/div&gt;';
		
		if ($type(this.myEmbedPane)) {
			this.myEmbedField.set('html',embed)
			this.myEmbedField.addEvent('click', function(e) {
				this.focus();
				this.select();
			});
		}
	},
	getHash: function() {
		//extract embedCode for deep linking
		if (!window.location.hash == "") { 
			var hash = window.location.hash;

			//look for a video item in the hash - if it exists, load that item
			var searchString = '#videoId=';
			if (hash.test(searchString)) {
				this.defaultMedia = hash.substring(hash.lastIndexOf(searchString) + searchString.length);
				this.defaultType = 'video';
				
				//add embedCode to Ooyala options - if it exists 
				if (this.defaultMedia != "") {
					this.ooyalaOptions.embedCode = this.defaultMedia;
				} 
			}
			
			//look for a screen item in the hash - if it exists, load that item
			var searchString = '#screenId=';
			if (hash.test(searchString)) {
				this.defaultMedia = hash.substring(hash.lastIndexOf(searchString) + searchString.length);
				this.defaultType = 'screen';
			}
		} 
	},
	updateHash: function(item,mediaType) {
		document.title = item.title + ' | EA SPORTS NHL 10';
		window.location.hash = "#" + mediaType + "Id=" + item.embedCode;
	}
});   
