/**
 * bam.vpp : Supporting object for the Video Playback Page
 *
 */

bam.vpp = (function(){

	var _IGNORE_KEYWORD_REGEX = new RegExp("^[A-Z_0-9]*$");
	var _log                  = function(msg){ if (typeof console!="undefined" && _settings.debugMode){ console.log("bam.vpp: " + msg); } };
	var _getPrerollUrl        = function(){ return _settings.adUrl + "ord=" + (new Date).getTime(); };	

	var _userInitiatedPlay    = false; // flag used by playClip() to track user requested clips separately from auto plays.
	
	var _$event = $({}); // for custom events
	
	var _settings = {
	
		debugMode  : false,
		adUrl      : null,  // null for no preroll
		playlist   : [],

		contentUrlBase : "/media/video.jsp?content_id=",

		autostart          : true,
		autostartTimeoutId : null,
		autostartDelay     : 10000,
		
		index: {itemsPerPage: 12, maxItems: 60},
		
		autoplaylist : false,
		currentIndex : 0,
		prerollIndex : 0,  // prerolls are not in playlist, but each item has a preroll request (ad call)
		
		isPrerollPlaying       : false,
		isPlaylistComplete     : false,
		anotherPrerollRequired : false,
		
		psKeys        : ["FLASH_1000K_640X360", "FLASH_800K_640X360", "MLB_FLASH_800K_STREAM_VPP", "MLB_FLASH_800K_STREAM", "MLB_FLASH_1000K_PROGDNLD", "MLB_FLASH_800K_PROGDNLD", "FLASH_800K_512X288", "v2_url"],
		prodPageUrl   : "http://mlb.mlb.com/media/video.jsp", // used for Facebook link
		shareVideoUrl : "/media/email/send.jsp",
		searchPageUrl : "/search/media.jsp",
		
		playerSkin    : "/flash/video/y2009/skins/mlb_compact_full_feature.swf",
		videoAlign    : "top",
		endPosterPath : "/images/000000.gif",
		companionSize : "300x60",
		
		commentsAreDisplayed : false,
		
		curClipData : {},
		playerProps : {}
		
	};
	
	
	/**
	 * Utility function for sorting JSON objects based on a property (or sub.property) 
	 * @param {array} objArray
	 * @param {array|string} prop Dot-delimited string or array of (sub)properties
	 * @TODO move this to a lib
	 */	
	function _sortJsonArrayByProp(objArray, prop){  
		if (arguments.length<2){
			throw new Error("sortJsonArrayByProp requires 2 arguments");  
		}  
		if (objArray && objArray.constructor===Array){
			var propPath = (prop.constructor===Array) ? prop : prop.split(".");
			objArray.sort(function(a,b){
				for (var p in propPath){
					if (a[propPath[p]] && b[propPath[p]]){
						a = a[propPath[p]];
						b = b[propPath[p]];
					}
				}
				// convert numeric strings to integers
				a = a.match(/^\d+$/) ? +a : a;
				b = b.match(/^\d+$/) ? +b : b;
				return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
			});
		}
	}	

	var _self = {	 
		
		flashPlayer: null,

		bind: function(/* eventName, dataOrFn, fnOrUndefined */){
			_$event.bind.apply(_$event, arguments);
		},
		
		unbind: function(/* eventName, fn */){
			_$event.unbind.apply(_$event, arguments);
		},
			
		index: { // support for Related/Topic index
		
			contentIds  : [],
			currentPage : null,
			totalPages  : 1,
			loadedPages : [],  // keeps track of pages which were displayed (prevents unnecessary loading of thumbnails)			
			
			pageNavInitialized : false,


			showPage: function(p){ // pagination handler
				if (p != _self.index.currentPage){
					var curIndex = null;
					var $items   = $("#vppIndex li");
					var $curItem; 					
					if (p >= 0 && p < Math.ceil($items.length/_settings.index.itemsPerPage)){
						$items.hide().each(function(i, curItem){
							curIndex = parseInt($(curItem).attr("index"));
							if ( (p*_settings.index.itemsPerPage <= curIndex) && (curIndex < ((p+1)*_settings.index.itemsPerPage)) ){ 
								$curItem = $(curItem);
								if (!_self.index.loadedPages[p]){
									$curItem.find("img").attr({src:$curItem.attr("thumb")}).css({visibility:"visible"});
								}
								$curItem.show();
							}
						});
						$("#vppIndexNav button").removeClass("current");
						$("#vppIndexNav button:eq("+p+")").addClass("current");
						_self.index.currentPage    = p;
						_self.index.loadedPages[p] = true;
					}
				}
			},			
			
			
			initPageNav: function(){
				try { _self.index.totalPages = Math.ceil($("#vppIndex li").length/_settings.index.itemsPerPage); }
				catch (err) {}
				_log("initPageNav(): _self.index.totalPages: " + _self.index.totalPages);
				var $pageLink;
				if (_self.index.totalPages > 1){
					for (var i=0; i<_self.index.totalPages; i++){
						$pageLink = $("<button>"+(i+1)+"</button>").click(function(buttonPage){ 
							return function(){ 
								bam.tracking.track({
									async:{
										isDynamic    : false, 
										compName     : "Video Playback Playlist", 
										compActivity : "Video Playlist Page " + (buttonPage+1), 
										actionGen    : true
									}
								});
								if (_self.index.currentPage != buttonPage){
									_self.index.showPage(buttonPage);
								}
							}; 
						}(i));
						$("#vppIndexNav").append($pageLink);		
					}
				}
				_self.index.pageNavInitialized = true;
			},
						
			
			goToPageWithIndex: function(index){
				if (_self.index.pageNavInitialized){
					var newPage = _self.index.currentPage || 0;
					for (var p=0; p<_self.index.totalPages; p++){
						if ( (index >= p*_settings.index.itemsPerPage) && (index < (p+1)*_settings.index.itemsPerPage) ){
							newPage = p;
							break;
						}
					}
					_log("index " + index + " is on page: " + newPage);
					_self.index.showPage(newPage);
				}
				else {
					_log("goToPageWithIndex(): page nav has not been initialized yet. doing nothing");
				}
			},
			
			
			loadSearchResults: function(props){
				var callback = function(){
					// $("ul#vppIndex").height( $("#indexWrap").height()+"px" ); // TODO: ensure that height of related clips area is same for every sub-page						
					if (typeof props['callback'] == "function") props.callback();
				};
				// store existing contentIds from index or request
				$("#vppIndex li").each(function(i, curLi){
					_self.index.contentIds.push($(curLi).find("a").attr("rel"));
				});
				
				if (_self.index.contentIds.length >= _settings.index.maxItems){
					_log(_self.index.contentIds.length + " results already displayed.  search not required.  executing callback and exiting.");
					callback();
					return;  // don't show more items than maxItems
				}
				else {
					_log("need more results from search...");
				}

				var searchParams = "type=json&src=vpp&start=0";
				if (props.searchParams)                       { searchParams += props.searchParams; }
				if (searchParams.indexOf("sort=") === -1)     { searchParams += "&sort=desc"; }
				if (searchParams.indexOf("sort_type=") === -1){ searchParams += "&sort_type=custom"; }

				$.ajax({
					url      : _settings.searchServiceUrl+"?"+searchParams,
					type     : "GET", 
					async    : false,
					cache    : true, 
					dataType : "json",
					// timeout  : 3000, // timeout doesn't work when async = false
					error    : function(request, errorType, errorThrown){ 
						_log("error getting results.  error type: " + errorType + " resuming...");
						callback();
					},
					success  : function(searchData){
						_log("loadSearchResults(): got search results!");
						if (searchData.mediaContent && searchData.mediaContent.constructor==Array){
							
							// if searchQuery contains sort_type=date, then sort searchData.mediaContent by content_id
							if (searchParams.indexOf("sort_type=date")){
								_sortJsonArrayByProp(searchData.mediaContent, "contentId");
								searchData.mediaContent.reverse();
							}
							
							$.each(searchData.mediaContent, function(i, obj){
								if ( (_self.index.contentIds.length < _settings.index.maxItems) && obj.contentId && obj.title && !_self.index.itemAlreadyExists(obj.contentId) ){
									var thumbnailSrc = "/images/trans.gif";
									if (obj['thumbnails'] && obj.thumbnails.constructor==Array){
										$.each(obj.thumbnails, function(i, thumb){ 
											if (thumb.type == "7"){ 
												thumbnailSrc = thumb.src;
												return false;
											}
										});
									}
									var itemHtml = "\
										<li index='"+_self.index.contentIds.length+"' thumb='"+thumbnailSrc+"'>\
											<div>\
												<a href='"+_settings.contentUrlBase+obj.contentId+"' rel='"+obj.contentId+"'><img src='' style='visibility:hidden;'/><div class='videoText'>"+obj.blurb+"</div></a>\
												<div class='dateAdded'>Added: "+obj.date_added.replace(/\d{2}(\d{2})/, "$1") +"</div>\
												<div class='duration'>"+_self.formatDuration(obj.duration)+"</div>\
											</div>\
										</li>";
									$("#vppIndex").append(itemHtml);
									_self.index.contentIds.push(obj.contentId);
								}
							});
						}
						callback();
					}
				});
			},
			
			
			itemAlreadyExists: function(content_id){
				return ($.inArray(content_id, _self.index.contentIds) >= 0);
			}
		},
		
		
		initPage: function(){
			_self.initPlaylist();
			$("#initMsg").remove();			
			_self.createFlvPlayer();
	//	_self.initPlaylist(true);  // init with preserveExisting switch set to true
			_self.index.initPageNav();
			_self.index.showPage(0);
			$("#vppIndex").css({"height":"auto"}); // reset height to show full page of clips
		},
		
		
		// Flash Player Support -------------------------------------------------------
		createFlvPlayer: function(){
			_log("creating flvPlayer");
			_self.flashPlayer = new bam.FlvPlayer({
				hideControls       : false,
				skin               : _settings.playerSkin, // "/flash/video/y2009/skins/mlb_media_landing_full.swf",
				endPosterPath      : _settings.endPosterPath,
				self               : "bam.vpp.flashPlayer",
				width              : _settings.playerProps.w,
				height             : _settings.playerProps.h,
				elemId             : "flashPlayer",
				containerId        : "flvContainer",
				volume             : 65,
				videoScaleMode     : "noScale",
				videoAlign         : _settings.videoAlign,
				debugMode          : _settings.debugMode,
				onPlayerLoaded     : _self.onFlvPlayerLoaded,
				onPlaylistComplete : _self.handlePlayComplete,
				companionSize      : _settings.companionSize,
				showCompanionAd    : function(adStr){ var adUrl = adStr.replace(/companionAd-/,""); $("#companionAd").attr("src",adUrl); }
			});
		},


		onFlvPlayerLoaded: function(){
			_log("flvPlayer.onFlvPlayerLoaded(). AUTOSTART is: " + _settings.autostart);		
			if (_settings.autostart){
				$("#flvContainer, #clipData").removeClass("collapsed");	
				_self.playCurrentItem();
			}
			else {
				var delayedStart = function(){
					_log("delayedStart()");
					$("#buttonWatch").hide();					
					$("#flvContainer, #clipData").removeClass("collapsed");	
					_self.playCurrentItem();
					_self.clearAutostartTimeoutId();
				};
				_settings.autostartTimeoutId = setTimeout(delayedStart, _settings.autostartDelay);
			}
		},
		
		
		clearAutostartTimeoutId: function(){
			_log("clearAutostartTimeoutId()");
			clearTimeout(_settings.autostartTimeoutId); // clear id for delayed start 			
		},


		highlightCurrentItem: function(){
			_self.resetHighlight();
			$("ul#vppIndex li:eq("+_settings.currentIndex+")").addClass("current");
			_self.index.goToPageWithIndex(_settings.currentIndex);
		},
	
		
		resetHighlight: function(){
			$("ul#vppIndex li").each(function(i, curElem){
				$(curElem).removeClass("current");
			});
		},
	
					
		getCurrentPlaylistItem: function(){
			if (_settings.currentIndex < _settings.playlist.length){
				return _settings.playlist[_settings.currentIndex];
			} 
			else {
				_self.endPlaylist();
				return false;
			}
		},
		
		
		endPlaylist: function(){
			_self.isPlaylistComplete = true;
		},
	
		
		clearPlaylist: function(){
			_log("clearPlaylist(): Setting currentIndex and prerollIndex to 0 (zero).");
			_settings.playlist = [];
			_settings.currentIndex = _settings.prerollIndex = 0;
		},
		
		
		addToPlaylist: function(newItems){
			if (newItems.constructor==Array){
				for (var i=0; i<newItems.length; i++){
					_settings.playlist.push(newItems[i]);
				}
			}
			else {
				_settings.playlist.push(newItems);
			}
		},

	
		showMessage: function(msg){
			$("#playlistMessage").text(msg);
		},
		
		
		/**
		 * 
		 */
//		playPreroll: function(){
//			_log("playPreroll(): " + _getPrerollUrl());			
//			_self.showMessage("");
//			_settings.prerollIndex = _settings.currentIndex;
//			// Preserve Dart for SOE sites. (FW for MLB domains)
//			var dcDomains = ["yesnetwork.com", "sny.tv", "mlsnet.com", "tigerwoods.com"],
//				isSOE = false,
//				adPlatform = bam.FlvPlayer.prerollPlatform || _self.flashPlayer.adPlatform;
//			for (var i=0; i<dcDomains.length; i++){
//		    if (location.host.indexOf(dcDomains[i]) > -1){
//					isSOE = true;
//					break;
//				}
//			}
//			if (isSOE || adPlatform==="dc"){
//				_log("playing Dart PreRoll");
//				_self.flashPlayer.startPlaylist([{type:'dartPreroll', path:_getPrerollUrl()}]);
//			}
//			else {
//				_log("playing FreeWheel preroll for content_id: " + _settings.curClipData.content_id + ", duration is: " + bam.media.getDurationInSeconds(_settings.curClipData.duration));
//				_self.flashPlayer.startPlaylist([{type:'freewheelAd', content_id:_settings.curClipData.content_id, duration:bam.media.getDurationInSeconds(_settings.curClipData.duration)}]);				
//			}
//			_settings.isPrerollPlaying = true;			
//		},
//		
		
		setIndexes: function(index){
			_log("setIndexes() to " + index);			
			_settings.prerollIndex = _settings.currentIndex = index;
		},
	
		
		/**
		 * Plays next (now current) playlist item. This may be a DC (or early FW) preroll,
		 * or the actual video clip. (In the new FW implementation, preroll is never a separate item.)
		 */
		playCurrentItem: function(){
			if (_settings.commentsAreDisplayed) return;
			_log("playCurrentItem(): preroll=" + _settings.prerollIndex + " curIndex=" + _settings.currentIndex);
			_self.highlightCurrentItem();
			
			var dataLoaded     = true,
					dataIsGood     = true,
					curItemMediaId = _self.getCurrentPlaylistItem();
					
			_$event.trigger("playCurrentItem", [curItemMediaId]);
			
			if (curItemMediaId != _settings.curClipData["content_id"]){
				_log("loading data for item: " + curItemMediaId);
				dataLoaded = _self.loadClipData(curItemMediaId);
				dataIsGood = _self.displayClipData();
			}
			else {
				_log("curClipData is already loaded");
			}
			if (!(dataLoaded && dataIsGood)){
				_log("data is bad. exiting");
				return; // data is bad, so exit
			}
//			if (_settings.adUrl && _settings.isPrerollPlaying){
//				_self.showMessage("Your video selection will begin shortly.");
//				_log("Video will play after this preroll, and as well as the one for requested video.");
//				_settings.anotherPrerollRequired = true;
//				return true;
//			} 
//			else {
				if (curItemMediaId){ // if there are more items in playlist
//					if (_settings.adUrl && _settings.prerollIndex==_settings.currentIndex){ // if Ad hasn't been shown before this clip, show it
//						_log("playCurrentItem(): showing preroll...");
//						_self.playPreroll();
//					}
//					else { // if preroll was shown, show clip
						_log("playCurrentItem(): showing clip...");
						_self.playClip(curItemMediaId);
						_log("playCurrentItem(): clearing curClipData");
						_settings.curClipData = {}; // clear this.
//					}
				}
				else _log("playCurrentItem(): End of Playlist.");
//			}
		},
		
		
		handlePlayComplete: function(){
			_log("handlePlayComplete()");
//			var prerollWasPlaying = _settings.isPrerollPlaying;
//			if (!prerollWasPlaying){
				_log("Preroll wasn't playing so tracking playback complete.");
				bam.tracking.track({videoComplete:{playerContext:"Video Playback Page"}});
//			}
//			if (_settings.adUrl && _settings.isPrerollPlaying){
//				_settings.isPrerollPlaying = false;
//				if (!_settings.anotherPrerollRequired){
//					_log("Another preroll is NOT required. Incrementing preroll index.");
//					_settings.prerollIndex++;  // force next clip
//				}
//				else {
//					_log("Another preroll IS required, so not incrementing preroll index.");
//					_settings.anotherPrerollRequired = false;
//				}
//			}
//			else { 
			_log("Incrementing currentIndex");
			_settings.currentIndex++;
//			}
//			_log("currentIndex is " + _settings.currentIndex + " autoplaylist is: " + _settings.autoplaylist + " and prerollWasPlaying is: " + prerollWasPlaying);
			if (_settings.autoplaylist){ // || prerollWasPlaying){
				_log("calling playCurrentItem()");
				_self.playCurrentItem();
			}
			else {
				_log("stoping playback.  executing exitFullScreen and calling endPlaylist()");
				_self.flashPlayer.execute("exitFullScreen");				
				_self.endPlaylist();
			}
		},


		// initPlaylist: used to initialize and reset the playlist
		initPlaylist: function(preserveExisting){
			_log("initPlaylist("+preserveExisting+")");
			if (!preserveExisting){
				_log("full init. not preserving existing playlist and highlight");
				_self.clearPlaylist();
				_self.resetHighlight();
			}
			else {
				// _log("keeping old stuff");
			}
			_settings.playlist = []; // reset playlist since we'll repopulate it fully below
			// assign new onclick handlers for playlist items
			$("ul#vppIndex li a").each(function(i, curItem){
				_self.addToPlaylist($(curItem).attr("rel"));
				// _log("assigning handler to playlist item: " + $(curItem).attr("rel") + " at index: " + i);
				$(curItem).unbind("click");
				$(curItem).click(function(){
					_log("Playlist item " + $(this).attr("rel") + " selected.  Setting indexes to " + i);
					_settings.currentIndex = _settings.prerollIndex = i;
					_self.playCurrentItem();
					_userInitiatedPlay = true; // user initiated play - set flag
					bam.tracking.track({
						async:{
							isDynamic    : false, 
							compName     : "Video Playback Playlist", 
							compActivity : "Video Playback Thumbnail " + (_settings.currentIndex+1), 
							actionGen    : true
						}
					});					
					return false;
				});
			});		
		},

		
		/**
		 * Plays video clip itself.
		 */ 
		playClip: function(content_id){
			if (typeof _settings.curClipData.curVideoFlashUrl == "undefined"){
				_log("playClip("+content_id+"): URL IS UNDEFINED.  NO PLAYBACK.");
				return;
			}
			_log("playClip("+content_id+"): startingPlaylist: " + _settings.curClipData.curVideoFlashUrl);
//			_self.flashPlayer.startPlaylist([{type:'video', path:_settings.curClipData.curVideoFlashUrl}]);
			_self.flashPlayer.startPlaylist([{
				type       : 'video',
				path       : _settings.curClipData.curVideoFlashUrl,
				content_id : content_id,
				duration   : bam.media.getDurationInSeconds(_settings.curClipData.duration)
			}]);
			bam.tracking.track({
				async_media:{
					mediaID        : content_id+"|"+_settings.curClipData.playbackScenario,
					playerType     : "Flash",
					playerContext  : "Video Playback Page",
					playerFlavor   : _settings.topicName,
					contextVersion : "3.0",
					streamType     : "Progressive Download",
					bitRate        : _settings.curClipData.bitRate,
					actionGen      : _userInitiatedPlay
				}
			});
			_userInitiatedPlay = false; // reset switch
		},

		
		// Clip Data Support -----------------------------------------------------------
		displayClipData: function(){
			_log("displayClipData().");
			if ( (typeof _settings.curClipData.content_id=="undefined") || (typeof _settings.curClipData.curVideoFlashUrl=="undefined") ){ // bad data.  handle display
				_log("bad data. (content_id or URL undefined)");
				$("#clipTitle").text("This video is temporarily unavailable");
				$("#clipBlurb").text("Please make another selection.");
				$("#clipThumb").html("<img src='" + $("#vppIndex li.current img").attr("src") + "'/>");
				$("#clipDate,#clipDuration").text("N/A");
				$("#clipTags div").html("");
				$("#share,#comment,#facebook,#digg").unbind("click");
				_self.showMessage("");
				return false;
			}
			$("#clipTitle").text(_settings.curClipData.headline);
			$("#clipDate").text(_self.formatDate(_settings.curClipData.date));
			$("#clipDuration").text(_self.formatDuration(_settings.curClipData.duration));
			$("#clipThumb").html("<img src='"+_settings.curClipData.thumb+"'/>");
			$("#clipBlurb").text(_settings.curClipData.bigBlurb);
			_self.loadKeywords(_settings.curClipData);
			
			$("#share").unbind("click").click(function(clipData){
				return function(){
					bam.tracking.track({
						async:{
							isDynamic    : false, 
							compName     : "Video Playback Distribution/Comments", 
							compActivity : "Video Playback Email Video Link Click", 
							actionGen    : true
						}
					});																								 
					_self.shareVideo(clipData.content_id, clipData.content_id, clipData.headline);
					return false;
				};
			}(_settings.curClipData));
			
			if (_settings.curClipData.commentsAreClosed){
				$("#comment").unbind("click").click(function(evt){ evt.preventDefault(); }).find("a").text("Closed");
			}
			else {
				$("#comment").unbind("click").click(function(){
					bam.tracking.track({
						async:{
							isDynamic    : false, 
							compName     : "Video Playback Distribution/Comments", 
							compActivity : "Video Playback Comment Link Click", 
							actionGen    : true
						}
					});																								 
					_self.showComments();
					return false;
				}).find("a").text("COMMENTS");
			}

			$("#facebook").unbind("click").click(function(content_id){ 
				return function(){
					bam.tracking.track({
						async:{
							isDynamic    : false, 
							compName     : "Video Playback Distribution/Comments", 
							compActivity : "Video Playback Facebook Link Click", 
							actionGen    : true
						}
					});					
					window.open("http://www.facebook.com/sharer.php?u="+encodeURIComponent(_settings.prodPageUrl+"?affiliateId=CommentWidget&affiliateId=facebook_share&content_id="+content_id)+"&t=","vppsharefb","width=626,height=436");
					return false;
				};
			}(_settings.curClipData.content_id));
			
			$("#digg").unbind("click").click(function(content_id, title, bodytext){
				return function(){
					bam.tracking.track({
						async:{
							isDynamic    : false, 
							compName     : "Video Playback Distribution/Comments", 
							compActivity : "Video Playback Digg Link Click", 
							actionGen    : true
						}
					});
					var diggUrl = "http://digg.com/submit?url="+encodeURIComponent(_settings.prodPageUrl +"?affiliateId=digg_share&content_id="+content_id)+"&title="+encodeURIComponent(title)+"&bodytext="+encodeURIComponent(bodytext);
					window.open(diggUrl,"vppsharedigg");
					return false;
				};
			}(_settings.curClipData.content_id, _settings.curClipData.headline, _settings.curClipData.bigBlurb));
			return true;
		},


		loadClipData: function(content_id){
			_settings.curClipData = bam.media.getMetaData(content_id);
			if (_settings.curClipData && typeof _settings.curClipData.urls != "undefined"){
				_log("loadClipData(): populated curClipData. Going through URLs");
				var urlNode = {};
				var psMap   = {};
				$.each(_settings.curClipData.urls, function(i, url){ // load available playback scenarios into a hash for easy reference
					if (url.getAttribute("playback_scenario")){
						psMap[url.getAttribute("playback_scenario")] = url;
					}
					else if (url.getAttribute("speed")=="800" && url.getAttribute("type")=="flash-video"){
						psMap["v2_url"] = url;
					}
				});
				
				_log("loadClipData() is looking for URL node...");
				$.each(_settings.psKeys, function(i, psKey){
//					_log("checking key: " + psKey);
					if (psMap[psKey]){
						_log("found it: " + psKey);
						urlNode = psMap[psKey]; // get the first match and exit
						return false;
					}
//					else { _log("not it: " + psKey + ". continuing..."); }
				});

				if (urlNode && urlNode.firstChild && urlNode.firstChild.nodeValue){
					_settings.curClipData.curVideoFlashUrl = urlNode.firstChild.nodeValue;
					_settings.curClipData.curVideoFlashId  = urlNode.getAttribute("id");
					_settings.curClipData.playbackScenario = urlNode.getAttribute("playback_scenario");
					var bitRateArr = _settings.curClipData.playbackScenario.match(/(\d+K)/);
					_settings.curClipData.bitRate = (bitRateArr) ? bitRateArr[1] : "";
					_log("loadClipData(): found url: " + _settings.curClipData.curVideoFlashUrl);
				}
				else {
					_log("loadClipData(): playbackScenario (or v2 data) is missing.");
					return false;
				}
			}
			else {
				_log("loadClipData(): Meta data is not available or bad.  Returning false.");
				return false;
			}
			return true;
		},
		

		loadKeywords: function(videoData){
			var wsGameToTopicMap = { // map of game_pk to topic_id for World Series 09 game topics
				"263181":"7224330",
				"263182":"7223768",
				"263183":"7224332",
				"263184":"7223232",
				"263185":"7224002",
				"263186":"7224214",
				"263187":"7223770"
			};
			
			_settings.curClipData.commentsAreClosed = false; // custom keyword for disabling commenting
			
			if ($("#clipTags").length){ // if elem #clipTags exists
				var type         = "",
						taxTypes     = {"mlbtax":"mlbtax_key", "yes_tax":"yes_tax_key", "tiger_tax":"tiger_tax_key", "mlstax":"mlstax_key", "sny_tax":"sny_tax_key"},
						display      = "", 
						value        = "", 
						param        = "", 
						keywordsHtml = "";
				$("#clipTags div").empty();
				$.each(videoData.keywords, function(i, keyword){
					type = keyword.getAttribute("type");
					if (taxTypes[type]){
						param = taxTypes[type];						
						type  = "tax";
					}
					switch (type){
						case "tax" : 
							display = keyword.getAttribute("displayName").replace(/\"/g,"");
							if ( !(_IGNORE_KEYWORD_REGEX.test(display)) ){
								value = keyword.getAttribute("value");
							}
							break;
						case "team_id" :
							param   = "team_id";
							value   = keyword.getAttribute("value");
							display = keyword.getAttribute("displayName");
							break;
						case "mlb_team_id" :
							param   = "mlb_team_id";
							value   = keyword.getAttribute("value");
							display = keyword.getAttribute("displayName");
							break;							
						case "player_id" :
							param   = "player_id";
							value   = keyword.getAttribute("value");
							display = keyword.getAttribute("displayName");
							break;
						case "mlb_player_id" :
							param   = "mlb_player_id";
							value   = keyword.getAttribute("value");
							display = keyword.getAttribute("displayName");
							break;
						case "game_pk" :
							param   = "game_pk";
							value   = keyword.getAttribute("value");
							display = "More From This Game";
							break;
						/**
						* Hack for hiding the comments when video doesn't support them.
						* Its here, rather than in displayClipData() since we don't want
						* to iterate keywords twice.
						*/
						case "mmtax" :
							if (keyword.getAttribute("value")==="comments_closed"){
								_settings.curClipData.commentsAreClosed = true;
							}
							break;
					}
					if (param!="" && value!="" && display!=""){
						if (param==="game_pk" && wsGameToTopicMap[value]){ // point to WS2009 games to topic pages
							keywordsHtml += "<a href='/media/video.jsp?topic_id="+wsGameToTopicMap[value]+"'>"+ display +"</a>, ";
						}
						else {
							keywordsHtml += "<a href='"+_settings.searchPageUrl+"?"+param+"="+escape(value)+"'>"+ display +"</a>, ";
						}
					}
					param = ""; // reset parameter
				});
				if (keywordsHtml.length > 0){
					$("#clipTags div").html(keywordsHtml.substring(0, keywordsHtml.length-2)); // remove trailing comma and space
				}
				$("#clipTags div a").unbind().click(function(){
					bam.tracking.track({
						async:{
							isDynamic    : false, 
							compName     : "Video Search Option", 
							compActivity : "Video Playback Search Tag Click", 
							actionGen    : true
						}
					});																					 
				});
			}
		},
		
		
		formatDuration: function(duration){ // converts HH:MM:SS to MM:SS
			var minSec = "";
			if (typeof(duration)=="string" && duration.length > 7){ minSec = duration.substring(3,8); }
			return minSec;
		},
	
		
		formatDate: function(dateLong){ // converts YYYY-MM-DDTHH:MM:SS-???? to MM/DD/YY
			var displayDate = "";
			if (typeof(dateLong)=="string" && dateLong.length > 8){
				displayDate = dateLong.substring(5,7) + "/" + dateLong.substring(8,10) + "/" + dateLong.substring(2,4);
			}
			return displayDate;
		},


		showComments: function(){
//			if (_settings.isPrerollPlaying) return;
			var curId = $("ul#vppIndex li.current a").attr("rel");
			bam.comments_init();
			bam.comments.overrideLoginLinkParams({content_id:curId, topic_id:_settings.topicId});
			bam.comments.getComments(curId);
			$("#indexWrap").hide();
			$("#comments").show();
			_settings.commentsAreDisplayed = true;
		},
		
		
		setCommentsAreDisplayed: function(boolValue){ // public setter.  used when overriding showComments method.
			_settings.commentsAreDisplayed = boolValue;
		},
		
		
		closeComments: function(){
			$("#comments").hide();
			$("#indexWrap").show();
			_settings.commentsAreDisplayed = false;
		},


		shareVideo: function(content_id, metaId, title){
			var url    = _settings.shareVideoUrl + "?content_id=" + content_id + "&metaId=" + metaId + "&title=" + escape(title);
			var width  = 500;
			var height = 470;
			if (width > screen.availWidth-12) width = screen.availWidth-12;
			if (height > screen.availHeight-48) height = screen.availHeight-48;
			var left = (screen.availWidth - width - 12) / 2;
			var top  = (screen.availHeight - height - 48) / 2;
			void( window.open(url, name, "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top) );
		},
		
		
		// expose private settings for debugging
		getSettings: function(prop){
			if (prop && _settings["prop"]) return _settings["prop"];
			else return _settings;	
		},

		
		init: function(props){
			$.extend(_settings, props);
		}
		
	};
	
	return _self;
	
})();

