// no cache: 2418cfe0f22654c88563b068f5404a4b

// package: /js/canoe-video.js (41482) 


/**
 * BRIGHTCOVE API
 */

var experienceId;
var BigBoxAdContainer;
var BigBoxAd;

var bc_player, bc_experience, bc_video, bc_social, bc_advertising, bc_cuepoints;
var bc_videoIds = new Array();
var bc_currentVideo, bc_previousVideo, bc_startingVideo;
var bc_playbackStarted = false;
var bc_playerFullScreen = false;
var bc_playerLastTick = 0; 
var bc_playerAutostart = false;
var bc_playerDefinition = '';
var bc_debug = 0;
var bc_video_count = 0;
var bc_playerVolumeDefault = .5;
var bc_playerVolume = .5;
var bc_user_video_count = 0;

function onTemplateLoaded(experienceId)
{
  bc_player = brightcove.getExperience(experienceId);

  if ( bc_debug )
  {
    console.log('onTemplateLoaded w/ id: '+experienceId);
  }
  
  // Setup Modules
  bc_player      = brightcove.getExperience('canoePlayer');
  bc_experience  = bc_player.getModule(APIModules.EXPERIENCE);
  bc_video       = bc_player.getModule(APIModules.VIDEO_PLAYER);
  bc_social      = bc_player.getModule(APIModules.SOCIAL);
  bc_advertising = bc_player.getModule(APIModules.ADVERTISING);
  bc_cuepoints   = bc_player.getModule(APIModules.CUE_POINTS);

  // Setup Listeners
  
  // experience related
  bc_experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
  bc_experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
  bc_experience.addEventListener(BCExperienceEvent.ENTER_FULLSCREEN, onEnterFullScreen);
  bc_experience.addEventListener(BCExperienceEvent.EXIT_FULLSCREEN, onExitFullScreen);
  
  // video related
  bc_video.addEventListener(BCVideoEvent.VIDEO_CHANGE, onVideoChange);
  bc_video.addEventListener(BCVideoEvent.VIDEO_CONNECT, onVideoConnect);
  bc_video.addEventListener(BCVideoEvent.VIDEO_COMPLETE, onVideoComplete);
  bc_video.addEventListener(BCVideoEvent.VIDEO_PROGRESS, onVideoProgress);
  bc_video.addEventListener(BCVideoEvent.STREAM_START, onStreamStart);

  // social related
  bc_social.addEventListener(BCSocialEvent.EMBED_CODE_RETRIEVED, onEmbedCodeRetrieved);
  
  // advertising related
  bc_advertising.enableExternalAds(true);
  bc_advertising.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
  bc_advertising.addEventListener(BCAdvertisingEvent.AD_COMPLETE, onExternalAdComplete);
}

function onTemplateReady(evt) 
{
  if ( bc_debug )
  {
    console.log('onTemplateReady');
  }
  
  bc_playerVolume = getVolumePreference();
}

function onContentLoad()
{  
  if ( bc_debug )
  {
    console.log('onContentLoad');
  }
    
  bc_startingVideo = bc_currentVideo;
  
  Playlist.getAutoPlaybackPlaylist();
  
  // set volume
  bc_video.setVolume(bc_playerVolume);
}

function onVideoChange(pEvent)
{
  if ( bc_debug )
  {
    console.log('onVideoChange');
  }

  bc_currentVideo = bc_video.getCurrentVideo();

  // setting auto start
  bc_playerDefinition = bc_video.getDefinition();
  if ( bc_playerDefinition.indexOf('autoStart="true"') !== -1 )
  {
    bc_playerAutostart = true;
  }
  
  if ( bc_debug == 2 )
  {
    console.log('Current Video Info:');
    console.dir(bc_currentVideo);
  }
  
  updateVideoMetadata(bc_currentVideo);

  bc_advertising.resumeAfterExternalAd();

 	BigBoxAd.redrawCount = 0;
  BigBoxAd.setSynchedBanner(false);
  
  bc_user_video_count = bc_user_video_count + 1;
  
  if ( bc_debug )
  {
    console.log('incrementing bc_user_video_count = '+(bc_user_video_count-1));
  }

  if ( bc_debug )
  {
    console.log('reset BigBoxAd.redrawCount = 0');
  }
	
  if ( SiteParams.use_cue_points == 1 )
  {
    if ( bc_debug == 2 )
    {
      console.log('Setting Cue Point at: '+SiteParams.cue_point);  
    }
    
    bc_cuepoints.addCuePoints(bc_currentVideo.id,[{time: SiteParams.cue_point, name: 'mid', type: 'AD'}]); 
  }
}

function onVideoConnect(pEvent)
{
  if ( bc_debug )
  {
    console.log('onVideoConnect');
  }
  
  bc_video_count = bc_video_count + 1;

  bc_playerLastTick = 0;
  
  BigBoxAd.redrawAd();
}

function onStreamStart()
{
  if ( bc_debug )
  {
    console.log('onStreamStart');
  }
}

function onVideoProgress( pEvent )
{
  bc_playerThisTick = parseInt(pEvent.position,10);
  
  if ( bc_playerThisTick != bc_playerLastTick && bc_playerThisTick % BigBoxAd.interval == 0 && bc_playerThisTick != 0 )
  {
    if ( bc_debug == 2 )
    {
      console.log('time: '+bc_playerThisTick);
    }
    
    BigBoxAd.redrawAd();
  }
  
  bc_playerLastTick = bc_playerThisTick;
}

function onVideoComplete()
{
  Playlist.playNextVideo(bc_currentVideo.id);  
}

function onEmbedCodeRetrieved(pEvent)
{
  Social.updateEmbedCode(pEvent.args.snippet);
}

function onEnterFullScreen()
{
  //bc_cuepoints.clearAdCuePoints(bc_currentVideo.id);
  BigBoxAd.setFullScreen(true);
}

function onExitFullScreen()
{
  //bc_cuepoints.addCuePoints(bc_currentVideo.id,[{time: SiteParams.cue_point, name: 'mid', type: 'AD'}]); 
  BigBoxAd.setFullScreen(false);
  BigBoxAd.redrawAd();
}

function onExternalAd(pAdObject)
{
	var forcepreroll = false;
	
  if ( bc_debug )
  {
    console.log('onExternalAd');
  }

  if ( bc_debug == 2 )
  {
    console.dir(pAdObject);
  }
	
	if( typeof SiteParams.prerollfreq == 'undefined' ) {
	  var prerollfreq = 2;
	} else {
 	  var prerollfreq = SiteParams.prerollfreq;
	}
  
  if ( pAdObject.ad.indexOf("forcepreroll=1") != -1 ) {
    forcepreroll = true;
  }
	
	//it's good.  check user video count
  if ( forcepreroll == true || (bc_user_video_count - 1) % prerollfreq == 0 )
  {
    if ( bc_debug )
    {
      console.log('showing preroll on video number '+(bc_user_video_count-1)+' - frequency matched');
    }

    new ExternalAd(pAdObject,{expandedId: BigBoxAdContainer});  
  }
  else
  {
    if ( bc_debug )
    {
      console.log('ignoring preroll on video number '+(bc_user_video_count-1)+' - frequency capped');
    }        
    
    bc_advertising.resumeAfterExternalAd();
    BigBoxAd.setSynchedBanner(false);
    
    return false;
  }  
}

function onExternalAdComplete(pEvent)
{
  if ( bc_debug )
  {
    console.log('onExternalAdComplete');
  }
}

function updateVideoMetadata( pVideo )
{
  // set title 
  orig_title = document.title.split(' : ');  
  document.title = pVideo.displayName + ' : ' + orig_title[1] + ' : ' + orig_title[2];
  
  jQuery(jQuery('#current_video_metadata h1')[0]).text(pVideo.displayName);
  jQuery("#crumb_video").text(pVideo.displayName); // video title in the breadcrumb
  jQuery("#crumb_video").attr("title", pVideo.displayName); // video title attibute in the breadcrumb
  setCurrentDateAndSource(pVideo.id); // date
  jQuery(jQuery('#current_video_metadata p')[0]).text(pVideo.shortDescription);
  Playlist.highlightCurrentlyPlayingVideo(pVideo.id);
  Social.updateGetLink();
  bc_social.getEmbedCode(pVideo.id);	
	
}
	
function setCurrentDateAndSource(pVideoId)
{
	
  var additionalItems = (jQuery('#additional-videos td').length > 0) ? jQuery('#additional-videos td') : jQuery('#additional-videos li'); 
  jQuery.each(additionalItems, function()
  {
    var videoId = this.id.split('_')[1];
	
    if (videoId == pVideoId) {
      if (jQuery("#date"))
        jQuery('#date').html($('#'+this.id+' span').html());
      if (jQuery("#video_content_source"))
	jQuery("#video_content_source").html('<a href="'+$('#'+this.id+' a.source').attr('href')+'">'+$('#'+this.id+' a.source').html()+'</a>');
    }
  });  

}

function playVideo(pVideoId)
{
  bc_video.loadVideo(pVideoId);
}

function getCurrentVideo()
{
  return bc_video.getCurrentVideo();
}

function getVolumePreference()
{
  var volume = cookie('bc_volume');
  
  if ( volume != null )
  {
    return volume;
  }
  else
  {
    return bc_playerVolumeDefault;
  }  
}

function setVolumePreference( volume )
{
  cookie('bc_volume', volume, { expires: 7, path: '/', domain: '', secure: false });
}

function setUserVideoCount( bc_user_video_count )
{
  if ( bc_debug )
  {
    console.log('setUserVideoCount = '+bc_user_video_count);
  }
  
  cookie('bc_user_video_count', bc_user_video_count, { path: '/', domain: '', secure: false });
}

function getUserVideoCount()
{
  var count = cookie('bc_user_video_count');
 
  if ( bc_debug )
  {
    console.log('getUserVideoCount = '+count);
  }
  
  if ( count != null )
  {
    return parseInt(count);
  }
  else
  {
    return 0;
  }  
}

// --------------------------------------------------------------------- 

/**
 * Creates a new Ad object which handles the synched banner and basic 300x250
 * unit next to the player.
 * 
 * @classDescription Creates an ad object with the basic ad tag to be used.
 *                   Redraws the iframe with that ad tag as often as the class's
 *                   interval specifies. If a synched banner exists (associated
 *                   with a video ad), then the redrawing of the iframe won't
 *                   occur.
 * @param {pString}
 *          pAdTagURL ad tag to be used when there's just a regular 300x250 (not
 *          a synched banner).
 * @return {Object} Returns the current Ad object.
 */
function Ad( container, url )
{
  this.url = url;
  //this.container = container;
  this.containers = container;
  this.interval = 30; // 30 seconds timeout
  this.fullscreen = false;
  this.synchedBanner = false;
  this.timeout;
  this.params = {size: 'sz=300x250', adkeys: ''};
	this.redrawCount = 0;

  /**
   * Creates an iFrame with the ad tag as it's source, and uses the DOM API to
   * add it to the page
   * 
   * @method
   * @param {String}
   *          pInsertionPoint The id of the HTML element where the ad should be
   *          inserted.
   * @param {String}
   *          pURL The ad tag URL to use
   */
  createAd = function( container, url, opt )
  {
		
		var width = 300;
		var height = 250;
		
		if(typeof opt.width !== 'undefined') {
			width = opt.width;
		}
		
 		if(typeof opt.height !== 'undefined') {
 	 	  height = opt.height;
		}
		
		
    if ( bc_currentVideo.adKeys )
    {
      this.params.adkeys = bc_currentVideo.adKeys;
    }
    else
    {
      this.params.adkeys = '';
    }
    
    if ( bc_debug == 2 )
    {
      console.log('ad keys: '+bc_currentVideo.adKeys);
    }
    
    // add params to url
		// Look for params 
    jQuery.each(this.params, function(i,val) {
      
      if ( val != '' )
      {
				if(typeof opt[i] !== 'undefined') {
	 			  val = opt[i];
				}
        url += val+';';
      }
      
    });

    // add cache bustin random number to url
    url += 'ord='+(Math.random()*10000000000000000)+'?';
    
    // write to the container
    try
    {
      if ( bc_debug == 2 )
      {
        console.log('calling bigbox ad url: '+url);  
      }
			
      var iframeElem = document.createElement('iframe');
      iframeElem.setAttribute('width', width);
      iframeElem.setAttribute('height', height);
      iframeElem.setAttribute('scrolling', 'no');
      iframeElem.setAttribute('frameborder', '0');
      iframeElem.setAttribute('src',url);
      
      jQuery(container).empty();
      jQuery(container).html(iframeElem);
			
    }
    catch( e )
    {
      if ( bc_debug == 2 )
      {
        console.log('Could not create the big box ad. Error: '+e);
      }
      
      return false;
    }
    
    return true;
  };
  
  /**
   * If the video is not in fullscreen and there's currently no synched banner,
   * the createAd() method is called again and a timeout is set to call
   * redrawAd() again after the class's interval.
   * 
   * @method
   */
  redrawAd = function()
  {
    if ( !this.getFullScreen() && (!this.getSynchedBanner() || this.redrawCount > 1) )
    {
      this.createAd(this.containers.ad, this.url, {width: 300, height: 250});
			
			// Only if the tag is synchedBanner728
      //this.createAd(this.containers.banner, this.url, {width: 728, height: 90, size: 'sz=728x90'});
    }
 		this.redrawCount++;
  };
  
  /**
   * @method
   * @return {Boolean} Whether or not the player is currently in fullscreen mode
   */
  getFullScreen = function()
  {
    return this.fullscreen;
  };
  
  /**
   * @method
   * @param {Boolean}
   *          Sets whether or not the player is currently in fullscreen mode
   */
  setFullScreen = function(pToggle)
  {
    if(typeof pToggle == 'boolean') this.fullscreen = pToggle;
    else console.debug("Can't toggle the fullscreen property. Value was not a Boolean");
  };
  
  /**
   * @method
   * @param {Boolean}
   *          Sets whether or not a synched banner is currently on the page
   */
  setSynchedBanner = function(pToggle)
  {  
    if(typeof pToggle == 'boolean') this.synchedBanner = pToggle;
    else console.debug("Can't toggle the synched banner property. Value was not a Boolean");
  };
  
  /**
   * @method
   * @return {Boolean} Whether or not there's currently a synched banner on the
   *         page
   */
  getSynchedBanner = function()
  {
    return this.synchedBanner;
  };
  
  return this;
};

var _brightcoveAd = new Object();
var _BigBoxAds = new Object();

/**
 * Takes care of parsing the XML that comes back from the ad server, building
 * the ad object, and displaying the ads in both the player and on the page. It
 * should be noted that the ad XML that comes back from the ad server needs to
 * be one of the supported Rich Media templates that Brightcove distributes for
 * use with DFP and other ad serving platforms.
 * 
 * @param {String}
 *          pXML The XML string that gets returned from the ad server. Needs to
 *          be one of the templates supported by Brightcove.
 * @param {Object}
 *          pOptions An object that contains options for further customization.
 *          By default, this function will render the expanded banner (eg type:
 *          "expandedBanner") and also write out the banner to a div with the id
 *          of "expandedBanner" (eg writeTo: "expandedBanner"). For the type
 *          option, you can also choose "collapsedBanner". For the writeTo
 *          option, a user can specify the ID of any element they'd like.
 */

function ExternalAd(pAdObject, pOptions)
{  
  if (pOptions) 
  {
    _brightcoveAd.expandedId = (pOptions.expandedId) ? pOptions.expandedId : "expandedBanner";
    _brightcoveAd.collapsedId = (pOptions.collapsedId) ? pOptions.collapsedId : "collapsedBanner";
    _brightcoveAd.type = (pOptions.type) ? pOptions.type : "expandedBanner";
  }
  else
  {
    _brightcoveAd.expandedId = "expandedBanner";
    _brightcoveAd.collapsedId = "collapsedBanner";
    _brightcoveAd.type = "expandedBanner";
  }
  
  /**
   * Parses the XML from the ad server 
   * @param {Object} pXML The XML returned from the ad server.
   */
  this.parseAd = function( pAdObject )
  {
    // check for basic ad xml structure
    if ( typeof pAdObject != 'object' || pAdObject.ad.indexOf("<SynchedBanner") === -1 ) 
    {
      if ( bc_debug == 2 )
      {
        console.log('bad preroll ad');
      }

      return false;
    }
      
    if ( window.ActiveXObject )
    {
      try
      {
        // parses the XML for IE browsers
        this.adXML = new ActiveXObject("Microsoft.XMLDOM");
        this.adXML.async = false;
        this.adXML.loadXML(pAdObject.ad);
      }
      catch ( e )
      {
        if ( bc_debug == 2 )
        {
          console.log('loadXML Error');
          console.dir(e);
        }

        return false;
      }

    }
    else if ( window.XMLHttpRequest )
    {
      try
      {
        this.adXML = (new DOMParser()).parseFromString(pAdObject.ad, "text/xml"); // parses the XML for Mozilla browsers
      }
      catch ( e )
      {
        if ( bc_debug == 2 )
        {
          console.log('DOMParser Error');
          console.dir(e);
        }

        return false;
      }
    }

    return true;
  };

  /**
   * Builds the ad object
   * 
   */
  this.buildAd = function()
  {  
    adXML = this.adXML;

    var ad = new Object();
    ad.type = "videoAd";

    var nodeItems = adXML.firstChild.childNodes.length;
    var currentNode = adXML.firstChild.firstChild;
    
    // get the root node attributes
    ad.duration = (adXML.firstChild.getAttribute("duration") !== "") ? Number(adXML.firstChild.getAttribute("duration")) : 15;
    if(adXML.firstChild.getAttribute("trackStartURLs") !== "") ad.trackStartURLs = adXML.firstChild.getAttribute("trackStartURLs").split(",");
    if(adXML.firstChild.getAttribute("trackMidURLs") !== "") ad.trackMidURLs = adXML.firstChild.getAttribute("trackMidURLs").split(",");
    if(adXML.firstChild.getAttribute("trackEndURLs") !== "") ad.trackEndURLs = adXML.firstChild.getAttribute("trackEndURLs").split(",");
    if(adXML.firstChild.getAttribute("trackPointURLs") && (adXML.firstChild.getAttribute("trackPointURLs") !== "")) ad.trackPointURLs = adXML.firstChild.getAttribute("trackPointURLs").split(",");
    ad.trackPointTime = (adXML.firstChild.getAttribute("trackPointTime") && (adXML.firstChild.getAttribute("trackPointTime") !== "")) ? Number(adXML.firstChild.getAttribute("trackPointTime")) : 0;
  
    for ( var i = 0; i < nodeItems; i++ )
    {
      //checks to see if the current nodes are in our Rich Media Templates and assigns them if they exist
      if ( currentNode.firstChild )
      {
        if ( currentNode.nodeName == "videoURL" )
        {  
          ad.videoURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "videoClickURL" ) 
        {
          ad.videoClickURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "expandedBannerURL" )
        {
          _BigBoxAds.expandedBannerURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "expandedBannerClickURL" )
        {
          _BigBoxAds.expandedBannerClickURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "collapsedBannerURL" )
        {
          _BigBoxAds.collapsedBannerURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "collapsedBannerClickURL" )
        {
          _BigBoxAds.collapsedBannerClickURL = currentNode.firstChild.nodeValue;
        }
      }

      currentNode = currentNode.nextSibling;
    }
    
    if ( i == 0 )
    {
      return false;
    }
    else
    {
      return ad;
    }
  };
  
  this.createSwf = function(pURL, pClickThrough, pId)
  {
    var objectTag = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="300" height="250" id="'+pId+'" align="middle">\n';
    objectTag += '\t<param name="allowScriptAccess" value="always" />\n';
    objectTag += '\t<param name="movie" value="' + pURL + '" />\n';
    objectTag += '\t<param name="quality" value="high" />\n';
    objectTag += '\t<param name="bgcolor" value="#ffffff" />\n';
    objectTag += '\t<param name="wmode" value="transparent" />\n'; 
    objectTag += '\t<param name="FlashVars" value="clickTag=' + pClickThrough + '" />\n';
    objectTag += '\t<embed src="' + pURL + '" quality="high" bgcolor="#ffffff" width="300" height="250" name="expandedBanner" align="middle" allowScriptAccess="always" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="clickTag='+pClickThrough+'" />\n';
    objectTag += '</object>\n';
    
    if(document.getElementById(pId)) document.getElementById(pId).innerHTML = objectTag;
  };
  
  this.createImage = function(pURL, pClickThrough, pId)
  {
    if(document.getElementById(pId)) document.getElementById(pId).innerHTML = "<a href='" + pClickThrough + "' target='_blank' ><img src='" + pURL + "' /></a>\n";
  };
  
  /**
   * Writes the banner out to the page, and determines wheter or not it's a swf or regular image so that the correct tags are written to the page.
   * @param {Object} pAd The ad object containing all of the information to display an ad in the player and render an ad on the page.
   */
  this.createBanner = function(pAd)
  {
    var externalAds = {};
    
    if ( (_brightcoveAd.type == "expandedBanner" || _brightcoveAd.type == "both") && pAd.expandedBannerURL )
    {
      externalAds["expandedBanner"] = {clickURL: pAd.expandedBannerClickURL, srcURL: pAd.expandedBannerURL, id: _brightcoveAd.expandedId, type: "expandedBanner"};
    }
    
    if ( (_brightcoveAd.type == "collapsedBanner" || _brightcoveAd.type == "both") && pAd.collapsedBannerURL )
    {
      externalAds["collapsedBanner"] = {clickURL: pAd.collapsedBannerClickURL, srcURL: pAd.collapsedBannerURL, id: _brightcoveAd.collapsedId, type: "collapsedBanner"};
    }

    for ( var i in externalAds )
    {
      var banner = externalAds[i];

      var iframeElem = document.createElement('iframe');
      iframeElem.setAttribute('width', '300');
      iframeElem.setAttribute('height', '250');
      iframeElem.setAttribute('scrolling', 'no');
      iframeElem.setAttribute('frameborder', '0');
      iframeElem.setAttribute('src', banner.srcURL);
      
      try
      {
        jQuery(banner.id).empty();
        jQuery(banner.id).html(iframeElem);
      }
      catch( e )
      {
        if ( bc_debug == 2 )
        {
          console.log('Could not create the big box ad. Error: '+e);
        }
        
        return false;
      }
    }

    return true;
  };

  this.recover = function()
  {
    bc_advertising.resumeAfterExternalAd();
    BigBoxAd.setSynchedBanner(false);
  };
  
  if ( this.parseAd(pAdObject) )
  {
    var ad = this.buildAd();

    if ( typeof ad == 'object' && this.createBanner(_BigBoxAds) )
    {
      BigBoxAd.setSynchedBanner(true);
      bc_advertising.showAd(ad);
    }
    else
    {
      this.recover();
    }
  }
  else
  {
    this.recover();
  }
}

/**
 * Site Interactions
 */
var AdditionalVideosModule = {

  init: function()
  {
    this.replaceHref(jQuery('#related-videos a'));
    this.replaceHref(jQuery('#popular-videos a'));
  },
    
  switchModules: function( module )
  {
		var apply_switch = false;
		
    if ( module == 'related' )
    {
			apply_switch = !jQuery('#tab-related').hasClass('active');
      jQuery('#related-videos').show();
      jQuery('#popular-videos').hide();
    }
    else
    {
			apply_switch = !jQuery('#tab-popular').hasClass('active');
      jQuery('#related-videos').hide();
      jQuery('#popular-videos').show();        
    }

		if(apply_switch) {
      AdditionalVideosModule.switchTab(jQuery('#related_videos'));
      AdditionalVideosModule.switchTabs(jQuery('#tab-related'));
      AdditionalVideosModule.switchTabs(jQuery('#tab-popular'));
		}
		
  },

  switchTab: function(pTab)
  {
    if(pTab.hasClass('related'))
    {
      pTab.removeClass('related');
      pTab.addClass('popular');
    }
    else if(pTab.hasClass('popular'))
    {
      pTab.removeClass('popular');
      pTab.addClass('related');
    }
  },

  switchTabs: function(pTab)
  {
    if(pTab.hasClass('active'))
    {
      pTab.removeClass('active');
      pTab.addClass('inactive');
    }
    else if(pTab.hasClass('inactive'))
    {
      pTab.removeClass('inactive');
      pTab.addClass('active');
    }
  },

  replaceHref: function(pAnchorTags)
  {
    //loops through all of the related videos
    jQuery.each(pAnchorTags, function()
    {
      var parentt = $(this).parent().attr('id');
      if ( !$(this).hasClass('source') ) 
      {
        if ( typeof parentt === 'undefined' || parentt == '' ) 
        {
          var videoId = $(this).parent().parent().attr('id').split('_')[1];
        } 
        else 
        {
          var videoId = $(this).parent().attr('id').split('_')[1];
        }
        
        jQuery(this).attr('href', 'javascript:playVideo(' + videoId + ')');
      }
    });
  }
};

var Navigation = 
{
  init: function()
  {
    this.showNav();
    this.crumbTrailInit();
  },
    
  showNav: function()
  {
    if ( jQuery('#navigation ul li.highlight').length > 0) jQuery('#navigation ul li.highlight:first').parent().prev().addClass('highlight');
    if ( jQuery('#navigation h3.highlight').length > 0) jQuery('#navigation h3.highlight:first').next().toggle();
      
    var categories = jQuery('#navigation h3');
      
    jQuery.each(categories, function()
    {     
      var cat = $(this);
        
      cat.hover(
        function()
        {
          if ( cat.hasClass('highlight') )
          {
            cat.addClass('over');
          } 
        },
        function()
        {
          cat.removeClass('over'); 
        }
      );
        
      cat.click(function()
      {
        if ( !cat.hasClass('highlight') ) 
        {
          cat.addClass('highlight');
          cat.next().show();
        } 
        else 
        {
          cat.removeClass('highlight');
          cat.next().hide();
        }
      });
    });
  },
    
  crumbTrailInit: function()
  {
    /****
    jQuery.each(jQuery('#navigation h3'), function()
    { 
      if(url_title(jQuery(this).html()) == url_title(jQuery('#crumb_section').html()))
      {
        jQuery('#crumb_section').html(jQuery(this).html());
        jQuery('#crumb_section').attr('href', jQuery(this).next().children()[0].firstChild.href);
      }
    });
    ***/
  }
};

var Playlist = {  
    
  getAutoPlaybackPlaylist: function()
  {
    if ( jQuery('#playlist li').length > 0  )
    {
        var Tags = jQuery('#playlist li');
    }
    else
    {
      var Tags = jQuery('#playlist td');
    }
      
    jQuery.each(Tags, function()
    {
      bc_videoIds.push(this.id.replace('video_',''));
    });
    
    // console.dir(bc_videoIds);
  },
    
  playNextVideo: function( pVideoId )
  {
    // console.log('play next video: '+pVideoId);
    
    for ( var i = 0; i < bc_videoIds.length; i++)
    {
      if ( bc_videoIds[i] == pVideoId )
      {
        if ( bc_startingVideo.id == pVideoId && bc_playbackStarted )
        {
          break;
        }
        else if ( bc_startingVideo.id == pVideoId && !bc_playbackStarted )
        {
          bc_playbackStarted = true;
        }

        if ( bc_videoIds[i+1] )
        {
          playVideo(bc_videoIds[i+1]);
          //console.log('playVideo: '+bc_videoIds[i+1]);
        }
        else
        {
          playVideo(bc_videoIds[0]);
          //console.log('playVideo: '+bc_videoIds[0]);
        }
        
        break;
      }
    }
  },
    
  highlightCurrentlyPlayingVideo: function(pVideoId)
  {
    // main playlist
    var playlistItems = (jQuery('#playlist td').length > 0) ? jQuery('#playlist td') : jQuery('#playlist li'); 
    jQuery.each(playlistItems, function()
    {
      jQuery(this).removeClass('highlight');
      /**
       * This regex allows the code to work on search and archive pages where
       * the id is prefixed by "video_"
       */ 
      var videoID = /(\d+)/.exec(this.id);
        if(videoID[0] == pVideoId) jQuery(this).addClass('highlight');
    });
      
    // additional videos
    var additionalItems = (jQuery('#additional-videos td').length > 0) ? jQuery('#additional-videos td') : jQuery('#additional-videos li'); 
    jQuery.each(additionalItems, function()
    {
      jQuery(this).removeClass('highlight');
      var videoId = this.id.split('_')[1];
      if(videoId == pVideoId) jQuery(this).addClass('highlight');
    });
  }
};

var Search = 
{
  init:function()
    {
      var search_field = jQuery('#search-field');
      
      search_field.focus(function()
      {
        $(this).val('');
        $(this).addClass('search_active');
      });
      
      search_field.blur(function()
      {
        if ( $(this).val() == '' )
        {
          $(this).val(jQuery('#search_box_text').text()); 
        }
        
        $(this).removeClass('search_active');
      });
      
      jQuery.each(jQuery('#playlist li'), function()
      {
        jQuery(this).hover(
          function()
          {
            jQuery(this).addClass('highlight');
          },
          function()
          {
            jQuery(this).removeClass('highlight');
          }
        );
      });
    },
    
    onSearchSubmit: function(search_url)
    {
      var phrase = jQuery('#search-field').attr('value');
			
      // clean term
      phrase = phrase.replace(/<(?:.|\s)*?>/g,'');
			phrase = phrase.replace(/([?#&%])+/g, '');
      
      // trim whitespace
      phrase = jQuery.trim(phrase);
      
      // replace spaces with underscores
      phrase = phrase.replace(/ /g,'+');
      
      if ( phrase.length > 2 )
      {
        if ( phrase != 'Rechercher-toutes-les-vidéos' && phrase != 'Search-All-Videos' )
        {
          window.location = '/'+search_url+'/'+phrase+'/';
        }
        else
        {
          return false;
        }
      }
      else
      {
        return false;
      }
    }

  };

  var Social = 
  { 
    init: function()
    {
      jQuery('#add_this a').attr('target', '_blank');
      
      // update text fields if section sponsor image isn't there
      if(jQuery('td.share_right').length <= 0) jQuery('.share_box td.share_middle .box').width('315px');
      
      var socialUserClear = false;
      var socialFriendClear = false;
      var socialMessageClear = false;
      
      jQuery('#social-link').focus(function() {
        this.select();
      });
      jQuery('#social-code').focus(function() {
        this.select();
      });
      
      jQuery('#social-user-email').focus(function() {
        if(!socialUserClear) 
        {
          jQuery(this).val('');
          socialUserClear = true;
					$(this).addClass('active');
        }
      });
				
      jQuery('#social-friend-email').focus(function() {
        if(!socialFriendClear) 
        {
          jQuery(this).val('');
          socialFriendClear = true;
					$(this).addClass('active');
        }
      });
      jQuery('#social-message').focus(function() {
        if(!socialMessageClear) 
        {
          jQuery(this).val('');
          socialMessageClear = true;
					$(this).addClass('active');
        }
      });
    },
    
    updateGetLink: function()
    {
      var crumbURL = jQuery('#crumb_video').attr('href');
      var newURL = 'http://' + SiteParams.domain;
      newURL += jQuery("span#get_link_url").text() + url_title(bc_currentVideo.displayName)+'/'+bc_currentVideo.id;
 
      jQuery('#social-link').val(newURL); // update the social link
      jQuery('#crumb_video').attr("href",newURL); // update the breadcrumb link
      bc_social.setLink(newURL);
    },
    
    updateEmbedCode: function(pCode)
    {
      jQuery('#social-code').hide(); 
      jQuery('#lang_share_embed_code').hide();

      jQuery.each(bc_currentVideo.tags,function(id,value) 
      {
        if ( value == 'embed=true' )
        {
          jQuery('#social-code').show();  
          jQuery('#lang_share_embed_code').show();
        }  
      });
			if(pCode == null || pCode == 'null' ) {
		    pCode = '';
			}
      jQuery('#social-code').val(pCode);
    },
    
    sendEmail: function()
    {
      var params = 
      {
        from: jQuery('#social-user-email').val(),
        to: jQuery('#social-friend-email').val(),
        message: jQuery('#social-message').val(),
        link: jQuery('#social-link').val(),
        title: bc_currentVideo.displayName,
        description: bc_currentVideo.shortDescription
      };
      
      var url = 'http://' + SiteParams.domain + '/email';
      
      jQuery('form.share_box table').fadeOut('fast', function()
      {
        jQuery.post(url, params, function(pResponse)
        {
          if(pResponse.error) jQuery('form.share_box').prepend("<h2 class='notification'>"+jQuery('#email_invalid_error_notification').html()+"</h2>");
          else jQuery('form.share_box').prepend("<h2 class='notification'>"+jQuery('#email_sent_notification').html()+"</h2>");
          setTimeout("Social.fadeInForm()", 2300);  
        }, "json");
      });
    },
    
    removeLoadingGraphic: function()
    {
      jQuery('img.loader').remove();
    },
    
    fadeInForm: function()
    {
      // bring the share form back
      jQuery('form.share_box h2.notification').remove();
      jQuery('form.share_box table').fadeIn('fast');
    }
  };

  var Archive = 
  {
    init: function()
    {
      var formDefaults = 
      {
        year: jQuery('select.archive_years option:first').text(),
        month: jQuery('select.archive_months option:first').text()
      };
      
      Archive.preSelect();
      
      jQuery('select.archive_months').attr('disabled', 'disabled');
      jQuery('select.archive_days').attr('disabled', 'disabled');
      
      jQuery('select.archive_years').change(function()
      {
        if ( jQuery('select.archive_years option:selected').text() !== formDefaults.year )
        {
          jQuery('select.archive_months').removeAttr('disabled');
        }
        else
        {
          jQuery('select.archive_months').attr('disabled', 'disabled');
          jQuery('select.archive_days').attr('disabled', 'disabled');
        }
      });
      
      jQuery('select.archive_months').change(function()
      {
        if (jQuery('select.archive_months option:selected').text() !== formDefaults.month)
        {
          Archive.updateDays(jQuery('select.archive_months option:selected').val());
          jQuery('select.archive_days').removeAttr('disabled');
        }
        else
        {
          jQuery('select.archive_days').attr('disabled', 'disabled');
        }
      });
			
    },
    
    preSelect: function()
    {
      if(jQuery('#category').text().length > 0) jQuery('select.archive_categories option[value='+jQuery('#category').text()+']').attr('selected', 'selected');
      if(jQuery('#source').text().length > 0) jQuery('select.archive_sources option[value='+jQuery('#source').text()+']').attr('selected', 'selected');
      if(jQuery('#year').text().length > 0) jQuery('select.archive_years option[value='+jQuery('#year').text()+']').attr('selected', 'selected');
      if(jQuery('#month').text().length > 0) jQuery('select.archive_months option[value='+jQuery('#month').text()+']').attr('selected', 'selected');
      if(jQuery('#day').text().length > 0) jQuery('select.archive_days option[value='+jQuery('#day').text()+']').attr('selected', 'selected');
    },
    
    updateDays: function(pMonth)
    {
      // if february was previously selected, these need to be reset
      jQuery('select.archive_days option[value=29]').removeAttr('disabled');
      jQuery('select.archive_days option[value=30]').removeAttr('disabled'); 
      
      if ( pMonth == 2 ) // feb
      {
        jQuery('select.archive_days option[value=29]').attr('disabled', 'disabled');
        jQuery('select.archive_days option[value=30]').attr('disabled', 'disabled');
        jQuery('select.archive_days option[value=31]').attr('disabled', 'disabled');
      }
      else if (pMonth == 9 || pMonth == 4 || pMonth == 6 || pMonth == 11) 
      {
        jQuery('select.archive_days option:last').attr('disabled', 'disabled');
      }
      else
      {
        jQuery('select.archive_days option:last').removeAttr('disabled'); 
      }
    },
    
    getContent: function()
    {
      var source = (jQuery('select.archive_sources option:selected').val() != '0') ? jQuery('select.archive_sources option:selected').val() : null;
      var category = (jQuery('select.archive_categories option:selected').val() != '0') ? jQuery('select.archive_categories option:selected').val() : null;
      var year = (jQuery('select.archive_years option:selected').val() != '0') ? jQuery('select.archive_years option:selected').val() : null;
      var month = (jQuery('select.archive_months option:selected').val() != '0') ? jQuery('select.archive_months option:selected').val() : null;
      var day = (jQuery('select.archive_days option:selected').val() != '0') ? jQuery('select.archive_days option:selected').val() : null;
      
      var url = 'http://' + SiteParams.domain + '/archive';
      if(category) url += '/category/'+category;
      if(source) url += '/source/'+source;
			if(year || month || day) {
		    if(year && month && day) {
          url += '/year/'+year;
          url += '/month/'+month;
          url += '/day/'+day;
				} else {
	 			  alert(jQuery('#filter_invalid_date_format').html());
			    return false;
				}
			}

      window.location = url;
    }
  };

  function url_title(pTerm)
  {
    // mimmicks the url_title() function from codeigniter
    if (pTerm)
    {
      return pTerm.replace(/ /g, '-').toLowerCase();
    }

    return pTerm;
  }


/**
 * Cookie read and write function.
 * @param name
 * @param value
 * @param options
 * @return
 */

function cookie(name, value, options) 
{
  if ( typeof value != 'undefined') // name and value given, set cookie
  { 
    options = options || {};
    if ( value === null ) 
    {
      value = '';
      options.expires = -1;
    }
    
    var expires = '';
    
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) 
    {
      var date;
      if ( typeof options.expires == 'number' ) 
      {
        date = new Date();
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } 
      else 
      {
        date = options.expires;
      }
      expires = '; expires=' + date.toUTCString(); 
    }
    
    /** 
     * CAUTION: Needed to parenthesize options.path and options.domain
     * in the following expressions, otherwise they evaluate to undefined
     * in the packed version for some reason...
     */
    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } 
  else // only name given, get cookie
  { 
    var cookieValue = null;
    if (document.cookie && document.cookie != '') 
    {
      var cookies = document.cookie.split(';');
      for ( var i = 0; i < cookies.length; i++ ) 
      {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) 
        {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    
    return cookieValue;
  }
}
 
/**
 * Timezone extraction
 * 
 */
function setUserTimeZone()
{
  var now = new Date();
  var later = new Date();
 
  // Set time for how long the cookie should be saved
  later.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);

  // Set cookie for the time zone offset in minutes
  cookie('time_zone_offset',now.getTimezoneOffset(),{ expires: later, path: '/', domain: '', secure: false });
 
  // Create two new dates
  var d1 = new Date();
  var d2 = new Date();
  // Date one is set to January 1st of this year
  // Guaranteed not to be in DST for northern hemisphere,
  // and guaranteed to be in DST for southern hemisphere
  // (If DST exists on client PC)
  d1.setDate(1);
  d1.setMonth(1);
  // Date two is set to July 1st of this year
  // Guaranteed to be in DST for northern hemisphere,
  // and guaranteed not to be in DST for southern hemisphere
  // (If DST exists on client PC)
  d2.setDate(1);
  d2.setMonth(7);
  // If time zone offsets match, no DST exists for this time zone
  if ( parseInt(d1.getTimezoneOffset()) == parseInt(d2.getTimezoneOffset()) )
  {
    cookie('time_zone_dst','0',{ expires: later, path: '/', domain: '', secure: false });
  }
  // DST exists for this time zone - check if it is currently active
  else 
  {
    // Find out if we are on northern or southern hemisphere
    // Hemisphere is positive for northern, and negative for southern
    var hemisphere = parseInt(d1.getTimezoneOffset())-parseInt(d2.getTimezoneOffset());
    // Current date is still before or after DST, not containing DST
    if ( (hemisphere > 0 && parseInt(d1.getTimezoneOffset()) == parseInt(now.getTimezoneOffset()) ) || (hemisphere<0 && parseInt(d2.getTimezoneOffset())==parseInt(now.getTimezoneOffset())))
    {
      cookie('time_zone_dst','0',{ expires: later, path: '/', domain: '', secure: false });
    }
    // DST is active right now with the current date
    else 
    {
      cookie('time_zone_dst','1',{ expires: later, path: '/', domain: '', secure: false });
    }
  }
} 

 /**
  * This function fires when the DOM is ready, but before window.onload and
  * initializes anything that's required as well as specific page
  * initializations.
  */
 jQuery(document).ready(function()
 {
   if ( bc_debug )
   {
     console.log('Document Ready');
   }
   
   experienceId = SiteParams.experience;
   BigBoxAdContainer = SiteParams.ad_container;
   BannerAdContainer = SiteParams.banner_container;

   if ( jQuery('#archive_form').length > 0 )
   {
     Archive.init();
   }
   
   AdditionalVideosModule.init();  
   Navigation.init();
   Search.init();
   Social.init();  
	 
	 var containers = {ad: SiteParams.ad_container, banner: SiteParams.banner_container};
     
   BigBoxAd = Ad(containers, SiteParams.ad_url);
   BigBoxAd = Ad(containers, SiteParams.ad_url);
   
   bc_user_video_count = getUserVideoCount();
 });

 $(window).unload(function () 
 { 
   if ( typeof bc_video !== 'undefined' )
   {
     if ( bc_video.getVolume() != bc_playerVolume )
     {
       bc_playerVolume = bc_video.getVolume();
       setVolumePreference(bc_playerVolume);
     }
   }
   
   setUserTimeZone();
   setUserVideoCount(bc_user_video_count);
   
 });
 


