//jquery.videoplayer.js
var adZoneTextDefault = 'home';
var adZoneText = adZoneTextDefault;
var platformReportsOwnerDefault = 'Outfitters';
var platformReportsOwner = platformReportsOwnerDefault;
jQuery(function($) {
    // ===== Carousel: If more than 6 images =====
    $tpIsPaging = false;
    $('div.inlineMediaContainer').each(function() {
        $(this).thumbnailcarousel({ pagination: true });
    });
    $('div.toutContainer').each(function() {
        $(this).toutcarousel({ pagination: true });
    });
    //Handle an Embed player
    if ($('#platformPlayerEmbed').length) {
        $('#platformPlayerEmbed').each(function() {
            $(this).createPlayer();
        });
    }
    //write out the video player
    if ($('#platformPlayerDiv').length) {
        if ($('#videoPlayerContainer').length) {
            if (false == $('#videoPlayerContainer').hasClass('hide')) {
                InjectPlayer();
            }
        } else {
            InjectPlayer();
        }
    }
}); 


// ===== InlineMediaContainer: Thumbnail Carousel ==================== 
(function($) {
	$.fn.thumbnailcarousel = function(options){
		// extend our default options with those provided
		var $options = $.extend({}, $.fn.thumbnailcarousel.defaults, options);
		var $this;
		
		return this.each(function() {
			$this = $(this);
			if(typeof($PlayerThumbnails) != "undefined") {
			    $options.visible = $PlayerThumbnails;
			}
			$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,
		visible: 6
	};
})(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', $this).css('display','none');
			    $($options.thumbs[0]).addClass('active');
			} else if($options.thumbs.length <= $options.visible){ // == no carousel ==
				$('a.previous,a.next', $this).css('display','none');
			} else { // == enable carousel ==
				// ~~~~~ parameters ~~~~~
				$('a.previous,a.next', $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();
			}
		});
		function animate(dir){
		    clearInterval($interval);
			$interval = setInterval(function(){animate('next');}, $scrollInterval);
			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;
			};
			
			// ~~~~~ 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);
		};
	};

	// default option
	$.fn.toutcarousel.defaults = {
		container: null,
		thumbs: null,
		visibleWidth:0,
		current: 0,
		total: 0,
		pageIcons:null
	};
})(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() {
			setCommManagerID();			
			printPlayer($options);
			printComManager();
			
			//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: null,
		AdZone: null,
		AdKW: null,
		AdPOS: null,
		AdURL: null,
		RandomFirst: false,
		ReloadClick: true
	};
})(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 printPlayer(options){
    tpRegisterID("playerwidget");
    var tile = '';
    if ((options.AdTile != '')&&(options.AdTile != null)){
        tile = 'tile%3D'+options.AdTile+'%3B';
    } 
    var pos = '';
    if ((options.AdPOS != '')&&(options.AdPOS != null)){
        pos = 'pos%3D'+options.AdPOS+'%3B';
    } 
   var kwVal = '';
    if ((options.AdKW != '')&&(options.AdKW != null)){
        kwVal = 'kw%3D'+options.AdKW+'%3B';
    } 
   
    //Allow javascript overrides of the share URL
    var baseUrl = location.protocol + "//" + location.hostname;
    
    var flashvars = [
        'ID='+'playerwidget', 
        'skinURL='+'/flash/theplatform/skinGlass.swf', 
        'backgroundColor='+'0xd9d4d1', 
        'controlBackgroundColor='+'0xd9d4d1', 
        'controlColor='+'0x4f4a3e',
        'controlFrameColor='+'0xd9d4d1', 
        '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='+'346', 
        'width='+'535', 
        'emailServiceURL='+'http://player.theplatform.com/ps/mail',
        'playerURL=' + baseUrl + '/video.aspx?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='+'/data/OutdoorChannelLayout4.xml', 
        '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'
    ];
    var adFlashVars = [];
    if(window.location.href.toLowerCase().indexOf("bypassads=true") == -1)
    {
        if ((options.AdService == 'Adap.tv')&&(options.AdZone.length > 0)) {
            adFlashVars = [ 'plugin0='+'type=overlay|URL=/flash/theplatform/AdapTV-PDK4.2.swf|debug=false|pkey=outdoorchannel|companionId=companionAdDiv|zid='+options.AdZone];
        } else if ((options.AdService == 'DART' && options.AdZone.length > 0)) {
            // SMIL plug-in triggers on ad.doubleclick.net in the URL

            // Ad wrapper plug-in allows preroll, postroll, and midroll URLs to be defined on the canvas
            // Works in conjunction with ad plug-ins (such as SMIL.swf) that rely on a playlist item to function
            adFlashVars = ['pluginSMIL='+'type=adcomponent|URL=/flash/theplatform/SMIL.swf|host=ad.doubleclick.net|priority=3',
            'pluginAdInsertion='+'type=adcomponent|URL=/flash/theplatform/adInsertionPlugin.swf|preRollUrls=http%3a%2f%2fad.doubleclick.net%2fadx%2f'+options.AdURL+'%2f'+options.AdZone+'%3b'+tile+pos+kwVal+'sz%3d535x300%3bord%3d'+ord];            
        }   
    } 
			
    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:535, height:346, 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,"&") };
            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
        $('#companionAd').show();
        $('.toutContainer').hide();
    }
}
function hideCompanionDiv(){
    if( $('#companionAd').is(':visible') ) {
        // it's visible, do something
        $('#companionAd').hide();
        $('.toutContainer').show();
    }
}
/* END Companion banner Region */

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://release.theplatform.com/content.select?pid=" + PID ;

    if (adZoneText != undefined && adZoneText.length > 0) {
        releaseURLText += "&player=" + adZoneText;
    } else if (adZoneTextDefault != undefined) {
        releaseURLText += "&player=" + adZoneTextDefault
    } else {
        releaseURLText += "&player=home"
    }
    
    if (platformReportsOwner != undefined && platformReportsOwner.length > 0) {
        releaseURLText += "&Affiliate=" + platformReportsOwner;
    } else if (platformReportsOwnerDefault != undefined) {
        releaseURLText += "&Affiliate=" + platformReportsOwnerDefault
    } else {
        releaseURLText += "&Affiliate=Outfitters"
    }
    

    //console.log("~~~~ adZoneText.length: "+ adZoneText.length + " - adZoneText: "+adZoneText + " - ownerThePlatformReporting: " + platformReportsOwner);    

    releaseURLText += "&MBR=True&format=SMIL&Tracking=true&Embedded=true";

    setTimeout(function(){
            tpController.setReleaseURL(releaseURLText);      
    }, 10);
}

function errorEvent(clip) {
    //NOTE: If there is an error durring play, this event will be fired
}

function startEvent(pdkEvent) {
    var baseClip = pdkEvent.data.baseClips[0];
    var thisIDString = "#contentID"+baseClip.contentID;
    var currentItem = $('.thumbnailBar .media_thumbs ul li').find(thisIDString);
          
    //set the description
    $('#clipinfoHTMLDiv').html("<span>"+baseClip.title+"</span>")
    
    //set all video thumbs to inactive
    $('.thumbnailBar .media_thumbs ul li a.active').removeClass('active');
    //highlight this video
    currentItem.addClass('active');
    
    //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 endEvent(pdkEvent) {    
    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); 
        }
    }
}

// ===== Inject The Player =========
function InjectPlayer() {
    //write out the video player
    var options = {'PID':$('#videoIDList').html()};
    var configInfo = $('#AdInfo').html().split(',');

    //Only need to declare boolean items for their defautl 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 adZone and ReportOwner text
    adZoneText = options.AdZone;
    platformReportsOwner = options.ReportOwner;
    
    $('#platformPlayerDiv').videoPlayerThePlatform(options);
}
