//jquery.videoplayer.js
var adZoneText = '';
var platformReportsAffiliate = 'Outdoor%20Channel';
var $thePlatformHTML5Player;
jQuery(function($) { 
// ===== Carousel: If more than 6 images =====    
    $tpIsPaging = false;
    
    //test to see if we need to display the thumbnails
    var showThumbs = $("#displayVideoThumbnail").html();
    if (showThumbs == 'false')
    {
	     $('.thumbnailBar').css('display','none');
	     $('div#videoPlayerWithTout').height(400);
	}
	
    $('div.inlineMediaContainer').each(function(){
		    $(this).thumbnailcarousel({});
	});
	
	$('div.toutContainer').each(function(){
		$(this).toutcarousel({});
	});
	//Handle an Embed player
    if($('#platformPlayerEmbed').length){
         $('#platformPlayerEmbed').each(function(){
		    $(this).createPlayer();
	    }); 
    } 
    
    //write out the video player
    if($('#platformPlayerDiv').length){
        if(typeof(holdPlayer)=='undefined' || holdPlayer==false) { 
            $(this).parseAndWritePlayer(); 
        }
	}
}); 

// ===== InlineMediaContainer: Thumbnail Carousel ==================== 
(function($) {
	$.fn.thumbnailcarousel = function(options){
		// extend our default options with those provideds
		var $options = $.extend({}, $.fn.thumbnailcarousel.defaults, options);
		var $this;
				
		return this.each(function() {
			$this = $(this);
			$options.visible = 6;
			$options.container = $('.media_thumbs ul',$this);
			$options.thumbs = $('li',$options.container);
			
			$options.thumbs.hover(function(e){
			       $('div.hoverDescription',$(this)).show();
			    },
			    function(){
			        $('div.hoverDescription',$(this)).hide();
			});
			
			$options.pages = 1;
			if($options.thumbs.length <= $options.visible){ // == no carousel ==
				$('a.previous,a.next', $this).css('display','none');
			} else { // == enable carousel ==
				// ~~~~~ parameters ~~~~~
				$options.total = $options.thumbs.length
				$options.pages = Math.ceil($options.total/$options.visible);
			}			
			
			// ~~~~~ controls ~~~~~
			$this.find("a.next").click(function(){
				animate("next");
				return false;
			});
			$this.find("a.previous").click(function(){
				animate("prev");
				return false;
			});
			$this.find("a.next").bind("pageTo", function(type, pg){
			    animate(pg);
			    return false;
			});
			
	        $("a.previous", $this).css({'opacity':'0.25','cursor':'default'});
			
		});
		function animate(dir){
			if(!isNaN(dir)){
				$options.current = dir;
			}
			else if(dir == "next"){
		        if($options.current >= $options.pages-1)
		            return;
				$options.current = parseInt($options.current)+1;
		    } else {
		        if($options.current <= 0)
		            return;
			    $options.current = parseInt($options.current)-1;
		    };	
		    
	        $("a.next, a.previous", $this).css({'opacity':'1','cursor':'pointer'});
	        if($options.current >= $options.pages-1) $("a.next", $this).css({'opacity':'0.25','cursor':'default'});
	        if($options.current <= 0) $("a.previous", $this).css({'opacity':'0.25','cursor':'default'});
			
	        var x=$options.current*$options.visible;
	        var xl=x+$options.visible;
	        
	        $options.thumbs.hide();
	        fadeThumb(x, xl);
		};
		function fadeThumb(pos, last){
		    $tpIsPaging = true;
		    if(pos<last){
	            $($options.thumbs[pos]).fadeIn(1, function(){fadeThumb(pos+1, last);});
	        }
	        else{
	            $tpIsPaging = false;
	        }
		};
	};

	// default option
	$.fn.thumbnailcarousel.defaults = {
		container: null,
		thumbs: null,
		visibleWidth:0,
		current: 0,
		total: 0,
		pageIcons:null
	};
})(jQuery);

// ===== .toutContainer - Tout Carousel =================================================
(function($) {
	$.fn.toutcarousel = function(options){
		// extend our default options with those provided
		var $options = $.extend({}, $.fn.toutcarousel.defaults, options);
		var $this;
		var $interval;
		
		return this.each(function() {
			$this = $(this);
			$scrollInterval = 10000; //In Millieconds
			$options.visible = 1;
			$options.container = $('.media_thumbs ul',$this);
			$options.thumbs = $('a',$options.container);
			    
			if($options.thumbs.length === 1){
				$('a.previous,a.next,a.previous_center,a.next_center', $this).css('display','none');
			    $($options.thumbs[0]).addClass('active');
			} else if($options.thumbs.length <= $options.visible){ // == no carousel ==
				$('a.previous,a.next,a.previous_center,a.next_center', $this).css('display','none');
			} else { // == enable carousel ==
				// ~~~~~ parameters ~~~~~
				$('a.previous,a.next,a.previous_center,a.next_center', $this).css('display','inline');
				$options.total = $options.thumbs.length;
				
				// ~~~~~ controls ~~~~~
				$this.find("a.next").click(function(){
					animate("next");
					return false;
				});
				$this.find("a.previous").click(function(){		
					animate("prev");
					return false;
				});
				createPagination();
				
				//these controls are found on OutdoorChannelNews page.
				if ($this.find("a.next_center").length > 0)
				{
				    $this.find("a.next_center").click(function(){
					    animate("next");
					    return false;
				    });
				    $this.find("a.previous_center").click(function(){		
					    animate("prev");
					    return false;
				    });
    				
				    createPaginationCenter();
				}
			}
		});
		function animate(dir){
			if(!isNaN(dir)){
				$options.current = parseInt(dir);
			} else if(dir == "next"){
				$options.current = (parseInt($options.current)+1 >= $options.total) ? 0 : parseInt($options.current)+1;
			} else {
				$options.current = (parseInt($options.current) <= 0) ? $options.total-1 : parseInt($options.current)-1;
			};
			var $si = $('.tout_ScrollInterval');
			$scrollInterval = parseInt($si[$options.current].innerHTML);
			if ( isNaN($scrollInterval) || $scrollInterval <= 0)
			{
			    $scrollInterval = 10000; //In Millieconds
			}
		    clearInterval($interval);
			$interval = setInterval(function(){animate('next');}, $scrollInterval);
			
			// ~~~~~ page icons ~~~~~
			$options.pageIcons.removeClass('active');
			$($options.pageIcons[$options.current]).addClass('active');
			$options.thumbs.removeClass('active');
			$($options.thumbs[$options.current]).addClass('active');
		};
		
		function createPagination(){
			var ul = $('ul.controls', $this);
						
			// ===== Add Pagination =====
			if($options.pagination){
				var pages = [];
				for(var x=0,xl=$options.total;x<xl;x++){
					pages.push('<li><a href="#" rel="'+x+'" class="page"><span>'+(x+1)+'</span></a></li>');
				};
				ul.html(pages.join(''));
				$options.pageIcons = $this.find('ul.controls li a.page');
				$options.pageIcons.click(function(e){ e.preventDefault(); animate($(this).attr('rel')); });
			};
			$interval = setInterval(function(){animate('next');}, $scrollInterval);
			animate(0);
		};
		
		function createPaginationCenter(){
		    //this is for tout within content area like on OutdoorChannelNews page
			//need to center controls, next & previous
			ul = $('ul.controls_center', $this);
			nt = $('a.next_center', $this);
			pv = $('a.previous_center', $this);
			tt = 540;
						
			if($options.pagination){
				var pages = [];
				for(var x=0,xl=$options.total;x<xl;x++){
					pages.push('<li><a href="#" rel="'+x+'" class="page"><span>'+(x+1)+'</span></a></li>');
				};
				ul.html(pages.join(''));
				//center control 
				var ulWidth = $options.total * 22;
				var ulLeftPadding = (tt-ulWidth)/2;
				var ulRightPadding = ulLeftPadding+ulWidth;
				ul.css('width',ulWidth);				
				ul.css('left', ulLeftPadding );
				//move previous to left side of centered control
				pv.css('left', ulLeftPadding - 45);
				//move next to right side of centered control
				nt.css('left', ulRightPadding - 18);
				
				$options.pageIcons = $this.find('ul.controls_center li a.page');
				$options.pageIcons.click(function(e){ e.preventDefault(); animate($(this).attr('rel')); });
			};
			$interval = setInterval(function(){animate('next');}, $scrollInterval);
			animate(0);
	    }
		
	};

	// default option
	$.fn.toutcarousel.defaults = {
		container: null,
		thumbs: null,
		visibleWidth:0,
		current: 0,
		total: 0,
		pageIcons:null,
		pagination:true
	};
})(jQuery);

// ===== Embed the Platform Video Player  ==================== 
(function($) {
	$.fn.videoPlayerThePlatform = function(options){
		// extend our default options with those provided
		var $options = $.extend({}, $.fn.videoPlayerThePlatform.defaults, options);
	    
		return this.each(function() {
			
		    if(useFlashPlayer()){		
			    setCommManagerID();	
			    printPlayer($options);
			    printComManager();
			}
			else{
			    readyHtmlPlayer($options);
			}
			
			//Set the video ID - use the passed in variable, if it exists; otherwise, find the first in the list.
			if($options.PID==null || $options.PID.length==0)
			{
			   setFirstVideo($options.RandomFirst);
			}
			else
			{
			    setVideo($options.PID);
			}
			
            if(!($options.ReloadClick))
            {
                //Capture clicks and load via JS
                $('.thumbnailBar .media_thumbs ul li a').click(function(e){
                    e.preventDefault();
                    var href = $(this).attr("href");
                    var PID = href.substring(href.lastIndexOf("pid=")+4);
                    
                    tpController.removeEventListener("OnReleaseEnd", "endEvent"); 
                    setTimeout(function(){
                        setVideo(PID);
                    }, 100);       
                    setTimeout(function(){
                        tpController.addEventListener("OnReleaseEnd", "endEvent"); 
                    }, 500);                    
                });
            }
		});		
		
	};

	// default option
	$.fn.videoPlayerThePlatform.defaults = {
		PID: null,
		AdService: 'Adap.tv',
		AdZone: '',		
		RandomFirst: false,
		ReloadClick: true,
		PlayerWidth: 535,
		PlayerHeight: 346,		
        LayoutURL: '/data/OutdoorChannelLayout4.xml',
        ControlBackground: '0xd9d4d1',
        AdFrequency: '1|3'
	};
})(jQuery);

// ===== Create the tags necessary to process the video player from an embedded DIV =========
(function($) {
	$.fn.createPlayer = function(){
		var $this = $(this);
		var PID = $this.attr("PID");
		
		if(PID!=null && PID.length>0) { //Make sure we have a valid PID...
		    $this.html('<div id="platformPlayerDiv"><span id="videoIDList" style="display: none">' + PID + '</span><div id="pdkHolder"><div class="commmanager"><div id="commmanagerDiv"></div></div><div class="player"><div id="playerDiv"><p style="font: 10pt Verdana; color: #bebebe">To view this site, you need to have Flash Player 9.0.115 or later installed. Click <a href="http://www.macromedia.com/go/getflashplayer/" target="_blank" style="color: #bebebe">here</a> to get the latest Flash player.</p></div></div><div class="clipinfoHTML" id="clipinfoHTMLDiv"></div><div id="AdInfo" style="display:none;">'+$("#AdInfo").html()+'</div></div></div>');
		} 
	};
})(jQuery);

function setCommManagerID(){
    tpSetCommManagerID("commmanagerwidget");
    //tpLoadExternalMediaJS("http://tpplayer.comcastcim.edgesuite.net/PDK/4.2/js/tpExternal_WMP.js", "http://tpplayer.comcastcim.edgesuite.net/PDK/4.2/js/tpExternal_QVT.js");
    tpController.addEventListener("OnReleaseStart", "startEvent");
    tpController.addEventListener("OnReleaseEnd", "endEvent"); 
    tpController.addEventListener("OnMediaStart", "populateAdBanners");
    tpController.addEventListener("OnMediaError", "errorEvent");

}
 
function useFlashPlayer() {
    var testVideoTag = document.createElement("video");
//	if (testVideoTag.canPlayType)
//      //TODO: Check if it's an iPhone/iPad
//		return false;
//	else
		return true;
}
function getPlayerFormat() {
    var testVideoTag = document.createElement("video");
	var format = "MPEG4";
	if (testVideoTag.canPlayType)
	{
		if (testVideoTag.canPlayType("video/webm"))
			format = "Unknown";
		else if (testVideoTag.canPlayType("video/mp4"))
			format = "MPEG4";
		else if (testVideoTag.canPlayType("video/ogg"))
			format = "Ogg";
	}
	return format;
}

function readyHtmlPlayer($options){
    tpRegisterID("playerDiv");
    $thePlatformHTML5Player = new Player("playerDiv", $options.PlayerWidth, $options.PlayerHeight);
    
    //Allow javascript overrides of the share URL
    var thisShareUrl = location.href.substring(0,location.href.indexOf("?")>0?location.href.indexOf("?"):location.href.length)
    if(typeof(shareURL) != "undefined") {
        if(shareURL != null && shareURL.length>0) {
            thisShareUrl = shareURL;
        }
    }
    if(typeof(controlBackground) != "undefined") {
        if(controlBackground != null && controlBackground.length>0) {
            $options.ControlBackground = controlBackground;
        }
    }
    
//    $thePlatformHTML5Player.backgroundColor=$options.ControlBackground; 
//    $thePlatformHTML5Player.controlBackgroundColor=$options.ControlBackground; 
//    $thePlatformHTML5Player.controlFrameColor=$options.ControlBackground; 
//    $thePlatformHTML5Player.controlColor='0x4f4a3e';
//    $thePlatformHTML5Player.controlHighlightColor='0x837b66'; 
//    $thePlatformHTML5Player.controlHoverColor='0x9db030'; 
//    $thePlatformHTML5Player.controlSelectedColor='0x9db030'; 
//    $thePlatformHTML5Player.frameColor='0xd9d4d1'; 
//    $thePlatformHTML5Player.loadProgressColor='0xbfb5a4'; 
//    $thePlatformHTML5Player.pageBackgroundColor='0xd9d4d1'; 
//    $thePlatformHTML5Player.playProgressColor='0xaabe3b'; 
//    $thePlatformHTML5Player.textBackgroundColor='0xd9d4d1'; 
//    $thePlatformHTML5Player.textColor='0x4f4a3e'; 
//    $thePlatformHTML5Player.scrubberColor='0xbfb5a4'; 
//    $thePlatformHTML5Player.scrubberFrameColor='0xbfb5a4'; 
//    $thePlatformHTML5Player.scrubTrackColor='0xbfb5a4'; 
//    $thePlatformHTML5Player.emailServiceURL='http://player.theplatform.com/ps/mail'; 
//    $thePlatformHTML5Player.playerURL=thisShareUrl+'?pid={releasePID}'; 
//    //$thePlatformHTML5Player.embeddedPlayerHTML='<embed src=\"http://player.theplatform.com/ps/player/pds/s6acvcZ3DD&pid={releasePID}\" width=\"640\" height=\"360\" type=\"application/x-shockwave-flash\" allowFullScreen=\"true\" bgcolor=\"#131313\"/>'; 
//    $thePlatformHTML5Player.allowFullScreen='true'; 
//    $thePlatformHTML5Player.layoutURL=$options.LayoutURL; 
//    $thePlatformHTML5Player.autoPlay='true'; 
//    $thePlatformHTML5Player.showNav='true';         
//    //$thePlatformHTML5Player.plugin1='type=tracking|URL=/flash/theplatform/googleAnalytics.swf|TrackAds=false|pattern=thePlatform%2F%7Bplaylist.player%7D%2F%7BisAd%7D%2F%7Btitle%7D%2F%7Bhistogram%7D|Histograms=10|ID=UA-3702351-1'; 
//    $thePlatformHTML5Player.plugin2='type=tracking|URL=/flash/theplatform/comScore.swf|c6Field=|c2=6034630|c5Field=|c3Field=|c4=tpvideo%7Btitle%7D';
//    $thePlatformHTML5Player.logLevel='debug';
//    //$thePlatformHTML5Player.adPattern='count:'+$options.AdFrequency;
//    if(window.location.href.toLowerCase().indexOf("bypassads=true") == -1) {
//        if ($options.AdService == 'Ads247') {
//            $thePlatformHTML5Player.pluginSMIL='type=adcomponent|URL=/flash/theplatform/SMIL.swf|host=oascentral.outdoorchannel.com|priority=3';
//            $thePlatformHTML5Player.pluginAdInsertion='type=adcomponent|URL=/flash/theplatform/adInsertionPlugin.swf|preRollUrls=http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/@x10,http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/@x11';
//        }
//    } 
   
   ////$thePlatformHTML5Player.write();
}

//$options.AdService,$options.AdZone,$options.AdKW,$options.AdPOS, $options.AdTile,$options.AdURL
function printPlayer($options){//todo add extra ad paarmas to dart
    tpRegisterID("playerwidget");
     
   
    //Allow javascript overrides of the share URL
    var thisShareUrl = location.href.substring(0,location.href.indexOf("?")>0?location.href.indexOf("?"):location.href.length)
    if(typeof(shareURL) != "undefined") {
        if(shareURL != null && shareURL.length>0) {
            thisShareUrl = shareURL;
        }
    }
    if(typeof(controlBackground) != "undefined") {
        if(controlBackground != null && controlBackground.length>0) {
            $options.ControlBackground = controlBackground;
        }
    }
    
    var flashvars = [
        'ID='+'playerwidget', 
        'skinURL='+'/flash/theplatform/skinGlass.swf', 
        'backgroundColor='+$options.ControlBackground, 
        'controlBackgroundColor='+$options.ControlBackground, 
        'controlFrameColor='+$options.ControlBackground, 
        'controlColor='+'0x4f4a3e',
        'controlHighlightColor='+'0x837b66', 
        'controlHoverColor='+'0x9db030', 
        'controlSelectedColor='+'0x9db030', 
        'frameColor='+'0xd9d4d1', 
        'loadProgressColor='+'0xbfb5a4', 
        'pageBackgroundColor='+'0xd9d4d1', 
        'playProgressColor='+'0xaabe3b', 
        'textBackgroundColor='+'0xd9d4d1', 
        'textColor='+'0x4f4a3e', 
        'scrubberColor='+'0xbfb5a4', 
        'scrubberFrameColor='+'0xbfb5a4', 
        'scrubTrackColor='+'0xbfb5a4', 
        'height='+$options.PlayerHeight, 
        'width='+$options.PlayerWidth, 
        'emailServiceURL='+'http://player.theplatform.com/ps/mail', 
        'playerURL='+thisShareUrl+'?pid={releasePID}', 
        //'embeddedPlayerHTML='+'<embed src=\"http://player.theplatform.com/ps/player/pds/s6acvcZ3DD&pid={releasePID}\" width=\"640\" height=\"360\" type=\"application/x-shockwave-flash\" allowFullScreen=\"true\" bgcolor=\"#131313\"/>', 
        'allowFullScreen='+'true', 
        'layoutURL='+$options.LayoutURL, 
        'autoPlay='+'true', 
        'showNav='+'true',         
       // 'plugin1='+'type=tracking|URL=/flash/theplatform/googleAnalytics.swf|TrackAds=false|pattern=thePlatform%2F%7Bplaylist.player%7D%2F%7BisAd%7D%2F%7Btitle%7D%2F%7Bhistogram%7D|Histograms=10|ID=UA-3702351-1', 
        'plugin2='+'type=tracking|URL=/flash/theplatform/comScore.swf|c6Field=|c2=6034630|c5Field=|c3Field=|c4=tpvideo%7Btitle%7D',
        'logLevel='+'debug' /*,
        'adPattern='+'count:'+$options.AdFrequency*/
    ];
    var adFlashVars = [];
    if(window.location.href.toLowerCase().indexOf("bypassads=true") == -1) {
        if ($options.AdService == 'Ads247') {
            adFlashVars = ['pluginSMIL='+'type=adcomponent|URL=/flash/theplatform/SMIL.swf|host=oascentral.outdoorchannel.com|priority=3',
            'pluginAdInsertion='+'type=adcomponent|URL=/flash/theplatform/adInsertionPlugin.swf|preRollUrls=http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/'+ord+'@x10(LA==)http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/'+ord+'@x11|priority=2'];
        }//pdk\4.4.2/custom_outdoor/outdoor_custom_adinsertionplugin.swf
        if ($options.AdService == 'Ads247PreRollOnly') {
            adFlashVars = ['pluginSMIL='+'type=adcomponent|URL=/flash/theplatform/SMIL.swf|host=oascentral.outdoorchannel.com|priority=3',
            'pluginAdInsertion='+'type=adcomponent|URL=/flash/theplatform/adInsertionPlugin.swf|preRollUrls=http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/'+ord+'@x10|priority=2'];
        }
        if ($options.AdService == 'Ads247OverlayOnly') {
            adFlashVars = ['pluginSMIL='+'type=adcomponent|URL=/flash/theplatform/SMIL.swf|host=oascentral.outdoorchannel.com|priority=3',
            'pluginAdInsertion='+'type=adcomponent|URL=/flash/theplatform/adInsertionPlugin.swf|preRollUrls=http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/'+ord+'@x11|priority=2'];
        }
        if ($options.AdService == 'Ads247Vast') {
            adFlashVars = ['plugin0='+'type=ad|URL=/flash/theplatform/vast.swf|mimeTypes=video%2Fx-flv|hosts=oascentral.outdoorchannel.com|priority=3',
            'pluginAdInsertion='+'type=ad|URL=/flash/theplatform/adInsertionPlugin.swf|urlPattern=http%3a%2f%2foascentral.outdoorchannel.com/RealMedia/ads/adstream_sx.ads/'+$options.AdZone+'/'+ord+'@x14|priority=2'];
        }
    } 
			
    var sFlashVars = adFlashVars.concat(flashvars);
   
    if (swfobject) {
        // load the video player
        if (swfobject.hasFlashPlayerVersion("9.0.115.0")) {
            var att = { data:"/flash/theplatform/flvPlayer.swf", width:$options.PlayerWidth, height:$options.PlayerHeight, menu:"false", id:"playerwidget", name:"playerwidget" };
            var par = { quality:"high", scale:"noscale", salign:"tl", wmode:"transparent", allowScriptAccess:"always", allowfullscreen: "true", bgcolor:"#d9d4d1", flashvars: sFlashVars.toString().replace(/[,]/gi,"&").replace(/\(LA==\)/g, ",") };
            var id = "playerDiv";
            var so = swfobject.createSWF(att, par, id);
        } else {
             $('#playerDiv').html('<center><br /><h2><b>Please <a href="http://www.adobe.com/products/flashplayer/" target="blank">upgrade your Flash Player</a><br /> to experience this site to its fullest.</b></h2></center>');			

        }
    } 
}

function printComManager(){
    if (swfobject){
        if (swfobject.hasFlashPlayerVersion("9.0.115.0")) {
            var att = { data:"/flash/theplatform/commManager.swf", width:1, height:1, menu:"false", id:tpGetCommManagerID(), name:tpGetCommManagerID() };
            var par = { wmode:"transparent", allowScriptAccess:"always" };
            var id = "commmanagerDiv";
            var so = swfobject.createSWF(att, par, id);
        }
    }
}


/* ~~~~~~~~~~~~~ Companion AD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * Adap.tv functions for displaying prerolls
 * These functions are called by the adapt.tv plugin (pdk.swf) to the pdk player. 
 */ 
function adaptv_jsstartBreak(object){    
   /* setTimeout(function(){
        dimControls();
    }, 1);*/
}

function adaptv_jscompanion(object){    
    setTimeout(function(){        
        showCompanionDiv();
    }, 1);
}
function adaptv_jsbreakEnded(){
    setTimeout(function(){
       // unDimControls();        
        hideCompanionDiv();
        
    }, 1);
}
/* display Buy Now */
function displayBuyNow(url){
    if ((url != '')&&(url != null))
    {
        $('#platformPlayerDiv #BuyNow').html("<a href='"+ url +"' target='_blank' style='padding-left:10px;cursor:hand;'><img src='/images/btn_buynow.gif' /></a>");
    }
   else
   {
        $('#platformPlayerDiv #BuyNow').html("");
   } 
}
/* ~~~~ DART functions ~~~~~~~~~~~ */
function populateAdBanners(pdkEvent) {
    //dump(pdkEvent);
    displayBuyNow(pdkEvent.data.baseClip.contentCustomData.BuyNowLink)
    if (pdkEvent.data.baseClip.isAd) {
        for ( var i=0; i<pdkEvent.data.baseClip.banners.length; i++) {
            var bannerRegionName = pdkEvent.data.baseClip.banners[i].region;
            var bannerURL = pdkEvent.data.baseClip.banners[i].src;
            var bannerHREF = pdkEvent.data.baseClip.banners[i].href;
            
            if ((!(bannerURL==null || bannerURL.length==0))&&( bannerRegionName == 'Banner300x250')) {
                setTimeout(function(){
                    $('#companionAdDiv').html("<a href='"+ bannerHREF +"' target='_blank'><img src='" + bannerURL + "'/></a>");
                  //  dimControls();
                    showCompanionDiv();
                }, 1);
            } else {
               /* setTimeout(function(){
                    dimControls();
                }, 1);*/
            }
        }
    } else {
        setTimeout(function(){
            //unDimControls();        
            hideCompanionDiv();            
        }, 1);
    }
}
/* ~~~ shared ad functions ~~~~~~~~~~~*/
function dimControls(){
    /*
    $(".thumbnailBar ul").addClass("videoDark");
    $("#toutCarouselCell .toutContainer").addClass("videoDark");
    $(".thumbnailBar ul.videoDark").bind("click.vidDark", function(){return false;});
    $("#toutCarouselCell .toutContainer .media_thumbs .carousel-thumbs a").bind("click.vidDark", function(){return false;});
   */ 
}
function unDimControls(){
    /*
    $(".thumbnailBar ul.videoDark").unbind(".vidDark");
    $("#toutCarouselCell .toutContainer .media_thumbs .carousel-thumbs a").unbind(".vidDark");
    $(".thumbnailBar ul").removeClass("videoDark");
    $("#toutCarouselCell .toutContainer").removeClass("videoDark");
   */ 
}
function showCompanionDiv(){
    if( $('#companionAd').is(':hidden') ) {
        // it's invisible, do something
        $('#ToutOverride').hide();
        $('#companionAd').show();
        $('.toutContainer').hide();
        
        if($('.thumbnailBar .media_thumbs ul li a.active').length>0) {
            logVideo('',$('.thumbnailBar .media_thumbs ul li a.active').attr('ID').replace("contentID",""),"ShowCompanion");
        }
    }
}
function hideCompanionDiv(){
    if( $('#companionAd').is(':visible') ) {
        // it's visible, do something
        $('#companionAd').hide();
        $('.toutContainer').show();
    }   
   
    showCompanionTout(); 
}
/* END Companion banner Region */

function showCompanionTout() {
   var activeItem = $('.thumbnailBar .media_thumbs ul li a.active');
   if ((typeof(activeItem.attr('companion')) != "undefined") && (activeItem.attr('companion').length > 0))
   {
        $('#ToutOverride').html('<a href="' + activeItem.attr('companionURL') + '"><img src="' + activeItem.attr('companion') + '"/></a>');
        $('.toutContainer').hide();
        $('#ToutOverride').show()
   }
}

function hideCompanionTout() {
    $('#ToutOverride').hide()
    $('.toutContainer').show();
}

function setFirstVideo(Random) {
    var thumbnailItems = $('.thumbnailBar .media_thumbs ul li a');
    if(thumbnailItems.length > 0) {  
        var length = (thumbnailItems.length>6) ? 6 : thumbnailItems.length;
        var item = (Random) ? Math.floor(Math.random()*length) : 0;
        
        var href = $($('.thumbnailBar .media_thumbs ul li a')[item]).attr("href");
        var firstPID = href.substring(href.lastIndexOf("pid=")+4);
        
        setVideo(firstPID);
    } 
} 

function setVideo(PID) {
    var releaseURLText = "http://link.theplatform.com/s/MTQ3NTE2MjMwOA/" + PID + "?feed=" + getFeedName();
    
    if (adZoneText.length > 0) {
        releaseURLText += "&player=" + adZoneText;
    } 
    if (platformReportsAffiliate.length > 0) {
        releaseURLText += "&Affiliate=" + platformReportsAffiliate;
    }
    releaseURLText += "&MBR=True&format=SMIL&Tracking=true&Embedded=true";
    setTimeout(function(){
            tpController.setReleaseURL(releaseURLText);      
            logVideo(PID,'',"Requested"); 
    }, 10);
}

function getFeedName() {
    var $videoList = $('div.thumbnailBar');
    
    if($videoList.length>0) {
        var name = $videoList.attr('FeedName');
        if(name!=null && name.length>0) {
            return name;
        }
    }
    
   //Can't find a name - use default... 
    return "Outdoor%20Channel%20Master%20Feed";
}

function errorEvent(clip) {
    //NOTE: If there is an error durring play, this event will be fired
}

function startEvent(pdkEvent) {
    //tpController.clearAdCookie();
    var baseClip = pdkEvent.data.baseClips[0];
    var thisIDString = "#contentID"+baseClip.contentID;
    var currentItem = $('.thumbnailBar .media_thumbs ul li').find(thisIDString);
   
   logVideo('',baseClip.contentID,"Start"); 
          
    //set the description
    $('#clipinfoHTMLDiv').html("<span>"+baseClip.title+"</span>")
    if(document.title.indexOf("$TITLE$")>0) {
        document.title = document.title.replace("$TITLE$",baseClip.title);
    }
    else if (parent.location.href.indexOf("pid=") != -1) {
        //check to see if we have a pid for video and if so parse out the title for updating the video title
        var title = document.title;
        if ( title.indexOf(baseClip.title) != -1)
        {
            var pipeIdx1 = title.indexOf("|");
            var pipeIdx2 = title.lastIndexOf("|");
            //check to see if we have a '|' or not.  if not then set to -2 so it will substring correctly
            if ( pipeIdx1 < 0)
                pipeIdx1 = -2;
            if ( pipeIdx2 < 0)
                pipeIdx2 = -2;        
            var endIdx = pipeIdx2 + 2;
            var titleBegin = title.substring(0, pipeIdx1 + 2);
            var titleEnd =  title.substring(endIdx);
            
            document.title = baseClip.title + " | " + titleBegin + titleEnd;
        }
    }
    
    //set all video thumbs to inactive
    $('.thumbnailBar .media_thumbs ul li a.active').removeClass('active');
    //highlight this video
    currentItem.addClass('active');
    hideCompanionTout();
    
    //if this thumbnail isn't visible, find the page it's on and make it visible...
    if (!$tpIsPaging && !(currentItem.is(':visible'))){
	    var currentPage = Math.floor(currentItem.attr("p")/6); //6 is the number of visible options
	    if (!isNaN(currentPage) && currentPage > 0) {
	        $('div.inlineMediaContainer').find('a.next').trigger('pageTo', currentPage);	
	    }
	    else {
	        //Default to page 0
	        $('div.inlineMediaContainer').find('a.next').trigger('pageTo', 0);	
	    }
    }
}

function logVideo(PID, ContentID, Type) {
//    if(window.location.pathname==="/Shooting.aspx"){
//        var requestURL = "/TrackVideo.aspx" ;
//        var postData = { }; 
//       
//        var $activeItem = $('.thumbnailBar .media_thumbs ul li a.active');
//        
//        if($activeItem.length==0) {
//            if( $('.thumbnailBar .media_thumbs ul li').length>0) {
//                if(PID!=undefined && PID.length>0) {
//                    $('.thumbnailBar .media_thumbs ul li a').each(function() {
//                        if($(this).attr('href').indexOf("pid="+PID)!=-1) {
//                             $activeItem = $(this);
//                        }  
//                    });
//                }
//                else if(ContentID!=undefined && ContentID.length>0) {
//                    $activeItem = $('.thumbnailBar .media_thumbs ul li').find("#contentID"+ContentID);
//                }
//            }
//            else {
//                //No thumbnail bar - we can't track by title - just get out.
//                return;
//            }
//        }
//        
//        if(PID==undefined || PID.length==0) {
//            if($activeItem.length==0) {
//                $activeItem = $('.thumbnailBar .media_thumbs ul li').find("#contentID"+ContentID);
//            }
//            PID = $activeItem.attr('href').replace(/.*pid=(.{32})/,'$1');
//        }
//        else if(ContentID==undefined || ContentID.length==0) {
//            if($activeItem.length==0) { 
//                $('.thumbnailBar .media_thumbs ul li a').each(function() {
//                    if($(this).attr('href').indexOf("pid="+PID)!=-1) {
//                         $activeItem = $(this);
//                    }  
//                });
//            }
//            ContentID = $activeItem.attr('ID').replace("contentID","");
//        }
//       
//        var title = 'Not in Video Carousel';
//        try{ 
//            title = $activeItem.parent().find('div.videoTitle').contents()[0].nodeValue;
//        } catch(e){} 
//       
//        postData.PID = PID;
//        postData.ContentID = ContentID;
//        postData.Title = title;
//        postData.Player=adZoneText;
//        postData.Affiliate=platformReportsAffiliate;
//        postData.Type = Type;
//        postData.Companion = $('#AdInfo').html();
//            
//        $.post(requestURL, getPostString(postData), function(){}, "html"); 
//    }
}

function getQueryParameter ( parameterName ) 
{
    var param = null;
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    param = vars[parameterName];
    return param;
} 

function getPostString(data) {
    var postString = "";
   
    for(var param in data)
    {
        postString+=param + "="+escapeHTML(data[param]) + "&"
    }
   
    postString =  postString.substring(0,postString.length-1);
    
    return postString; 
}

function escapeHTML(str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}

function endEvent(pdkEvent) {    
    hideCompanionTout();
    var thisIDString = "#contentID"+pdkEvent.data.baseClips[0].contentID;
    var currentItem = $('.thumbnailBar .media_thumbs ul li').find(thisIDString);
             
   if(currentItem.length > 0) {
        if($(currentItem[currentItem.length-1]).parent().next().length > 0) { 
            var href =  $(currentItem[currentItem.length-1]).parent().next().find('a').attr("href");
            var nextPID = href.substring(href.lastIndexOf("pid=")+4);
            setVideo(nextPID);
        }
        //If there is no next sibling, then show the first movie...
        else if(true) {  //NOTE: Conditions for repeating the playlist would go here...
           setFirstVideo(false); 
        }
    }
}

(function($) {
	$.fn.parseAndWritePlayer = function(){
	    var videoID = getQueryParameter("pid");
	    if ( videoID == "null" || videoID == undefined )
	        videoID = $('#videoIDList').html();
        var options = {'PID':videoID};
        var configInfo = $('#AdInfo').html().split(',');
       
        //Only need to declare boolean items with default values 
	    var thisRandomFirst=false;
	    var thisReloadClick=true;
        
        jQuery.each(configInfo, function() {
          var thisArray = this.split(':');
              try{
                  switch($.trim(thisArray[0]))
                    {
                    //boolean values
                    case "RandomFirst":
                    case "ReloadClick":
                        //Set to 'true' if "true", set to the default found above if blank, set to 'false' otherwise
                        eval("this"+$.trim(thisArray[0])+"=($.trim(thisArray[1])=='true') ? true : ($.trim(thisArray[1]).length==0) ? this"+$.trim(thisArray[0])+" : false");     
                      break;
                    //All other value types
                    default:
                        //Set to the value contained in thisArray[1]
                        eval("this"+$.trim(thisArray[0])+"=$.trim(thisArray[1])");
                      break;
                    }
                    //Add the new variable to the 'options' array
                    options[$.trim(thisArray[0])] = eval("this"+$.trim(thisArray[0]));
              }catch(e){;}
        });
        
        //set adZoneText
        if ((typeof(options.AdZone) != "undefined") && (options.AdZone.length >0)){
            adZoneText = options.AdZone;
        }
        if ((typeof(options.PlatformReportsAffiliate) != "undefined") && (options.PlatformReportsAffiliate.length >0)){
            platformReportsAffiliate=options.PlatformReportsAffiliate;
        }
        $('#platformPlayerDiv').videoPlayerThePlatform(options);
	};
})(jQuery);
