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

var setupPlayer = new Class({
	initialize : function() {
		this.myPlayerReady = false;
		this.myDomReady = false;
		this.runOnce = true;
	},
	domReady : function(options) {

		//setup DOM elements
		this.myOptions = options;
		this.enableComments = this.myOptions.enableComments;
		this.myDetails = $(this.myOptions.detailsPane);
		this.myDetailsNav = this.myDetails.getElements('ul.nav li a');
		this.myPlayerPane = $(this.myOptions.playerPane);
		this.myEmbedPane = $(this.myOptions.embedPane);
		//console.log(this.myEmbedPane);
		this.myCategoriesPane = $(this.myOptions.categoriesPane);
		this.myCarouselPane = $(this.myOptions.carouselPane);
		this.carouselContainer = this.myCarouselPane.getElement('.viewPort');
		this.myContinuousBtn = $(this.myOptions.continuousBtn);
		this.iFramePath = this.myOptions.iFramePath;

		// default video player parameters
		this.defaultVideo = this.myOptions.defaultVideo;
		this.primaryLabel = this.myOptions.primaryLabel;
		this.ooyalaOptions = new Hash(this.myOptions.ooyalaOptions);
		this.ooyalaOptions.labels = this.primaryLabel;
		this.ooyalaOptions.callback = 'receiveOoyalaEvent';

		// default filmstrip parameters
		this.filmStripOptions = this.myOptions.filmStripOptions;

		// extract embedCode for deep linking
		var searchString = '#mediaId=';
		var hash = window.location.hash;
		if (hash.test(searchString)) {
			this.defaultVideo = hash.substring(hash.lastIndexOf(searchString) + searchString.length);
		}

		//add embedCode to Ooyala options - if it exists 
		if (this.defaultVideo != "") {
			this.ooyalaOptions.embedCode = this.defaultVideo;
		}

		//build iframe element for ooyala player	
		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));
		}

		this.myDetailsNav.each( function(item, index) {
			item.addEvent('click', function(e) {
				e.stop();
				this.changeMedia(this.myPlaylist[item
						.getProperty('rel')], true);
			}.bind(this));
		}.bind(this));

		// build player if player ready is also true
		this.myDomReadyReady = true;
		if (this.myPlayerReady) {
			this.myDomReadyReady = false;
			this.buildPlayer();
		}

	},
	playerLoaded : function(playerId) {
		if (this.runOnce) {
			this.runOnce = false;
			this.myPlayerId = playerId;
			this.myPlayerLoaded = true;

			// setup player elements
			this.myPlayer = window.frames[0].document.getElementById(this.myPlayerId);
			this.myPlaylist = this.myPlayer.getLineup();
			this.currentItem = this.myPlayer.getCurrentItem();

			// build player if domready is also true
			this.myPlayerReady = true;
			if (this.myDomReadyReady) {
				this.myPlayerReady = false;
				this.buildPlayer();
			}
		}
	},
	receiveOoyalaEvent : function(playerId, eventName, p) {
		switch (eventName) {
		case 'playheadTimeChanged':
			this.playerLoaded(playerId);
			return;
		case 'stateChanged':
			return;
		case 'playComplete':
			this.continuous();
			return;
		case 'currentItemEmbedCodeChanged':
			if (this.videosLineup) {
				this.updateDetails(p);
			};
			return;
		case 'totalTimeChanged':
			this.playerLoaded(playerId);
			return;
		case 'embedCodeChanged':
			return;
		case 'volumeChanged':
			return;
		case 'loadComplete':
			return;
		}
	},
	buildPlayer : function() {
		this.myPlayerIframe.setStyle('visibility', 'visible');
		this.buildCarousel();
		if ($type(this.myCategoriesPane)) {
			this.buildCategories();
		}
	},
	buildCarousel : function() {
		this.carouselContainer.empty();
		var carouselDiv = new Element('div', {
			'class' : 'filmStrip'
		}).inject(this.carouselContainer);

		var carouselList = new Element('ul').inject(carouselDiv);

		$each(
				this.myPlaylist,
				function(item, index) {
					//check to make sure item is actual item and not bogus item ooyala sometimes returns.
					if (item.embedCode) {
						var tmpClass = '';
						if(index%4 == 0){
							tmpClass = 'first_item';
						}
					
						var new_item = new Element(
								'li',
								{
									'class' : tmpClass,
									'html' : '<a class="'
											+ item.embedCode
											+ '"  href="?mediaId='
											+ item.embedCode
											+ '">'
											+ '<img width="143" height="80" class="pic" src="'
											+ this.myPlayer
													.getPromoFor(
															item.embedCode,
															143, 80)
											+ '" />' + '<h3>'
											+ item.title + '</h3>'
											+ '<span>'
											+ item.description
											+ '</span>' + '</a>'
								}).inject(carouselList);

						new_item.addEvent('click', function(e) {
							this.changeMedia(item, true);
							e.stop();
						}.bind(this));
					}

				}.bind(this));

		// create filmStrip
		this.myFilmStrip = new FilmStrip(this.filmStripOptions.id,
				this.filmStripOptions);

		this.updateDetails(this.currentItem);
	},
	buildCategories : function() {
		var trigger = this.myCategoriesPane.getElement('.trigger');
		var links = this.myCategoriesPane.getElements('.filter a');
		var caption = this.myCategoriesPane.getElement('.caption span');

		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));

		links.each( function(item, index) {
			item.addEvent('click', function(e) {
				e.stop();
				caption.innerHTML = item.innerHTML;
				this.myCategoriesPane.removeClass('on');
				this.ooyalaOptions.labels = this.myOptions.primaryLabel
						+ "/" + item.rel;
				this.myPlayerIframe.setProperty('src', this.iFramePath
						+ '?' + this.ooyalaOptions.toQueryString());
				this.runOnce = true;
			}.bind(this));
		}.bind(this));
	},
	changeMedia : function(mediaItem, autoplay) {
		this.myPlayer.changeCurrentItem(mediaItem.embedCode);
		if (autoplay) {
			this.myPlayer.playMovie();
		}
		this.updateDetails(mediaItem);
	},
	updateDetails : function(mediaItem) {
		//this.myDetails.set('html',mediaItem.title);
		//this.myDetails.getElement('p').set('html',mediaItem.description);
		this.updateEmbed(mediaItem);
		this.updateHash(mediaItem);
		var currentIndex = 0;

		$each(this.myPlaylist, function(item, index) {
			if (item.embedCode === mediaItem.embedCode) {
				currentIndex = parseInt(index);
			}
		});

	//checking if Comments are enabled
	if(this.enableComments == "true"){
		loadComments(mediaItem.embedCode, "commentsTarget")
	}
		// 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 >= this.myPlaylist.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');
		});
		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 (this.myContinuousBtn.hasClass('on') === false)
		//alert(this.myPlayer.id)
		this.myPlayer.pauseMovie();
	},
	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://fifa.easports.com/" style="color: black; font-size: 10px; text-decoration: none;"&gt;EA SPORTS FIFA 10&lt;/a&gt;'
		embed += '&lt;/div&gt;';

		if ($type(this.myEmbedPane)) {
			this.myEmbedPane.set('html', embed)
			this.myEmbedPane.addEvent('click', function(e) {
				this.focus();
				this.select();
			});
		}
	},
	updateHash : function(item) {
		document.title = item.title + ' : FIFA 10 : EA SPORTS';
		window.location.hash = "#mediaId=" + item.embedCode;
	}
});
