// no cache: 19fc3d05d535a02dde63856b990a3947

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

var bc_startingVideo = null;
var bc_videoIds = [];
var bc_playbackStarted = false;

function OnContentLoad()
{
  bc_startingVideo = player.getCurrentVideo();
  
  Playlist.getAutoPlaybackPlaylist();
}

function OnVideoChange(video_id) 
{
  //set title 
  var title = player.getVideoTitle();
  var desc = player.getVideoDescription();
  var orig_title = document.title.split(' : ');  
  document.title = title + ' : ' + orig_title[1] + ' : ' + orig_title[2];
  
  jQuery(jQuery('#current_video_metadata h1')[0]).text(title);
  jQuery("#crumb_video").text(title); // video title in the breadcrumb
  jQuery("#crumb_video").attr("title", title); // video title attibute in the breadcrumb
  setCurrentDateAndSource(video_id); // date
  jQuery(jQuery('#current_video_metadata p')[0]).text(desc);
  Playlist.highlightCurrentlyPlayingVideo(video_id);
  Social.updateGetLink();
  player.getSocialEmbedCode(video_id);  
}

function OnVideoComplete() 
{
  Playlist.playNextVideo();  
}

function OnEmbedCodeRetrieved(pEvent) 
{
  Social.updateEmbedCode(pEvent.args.snippet);
}
	
function playVideo(pVideoId)
{
  player.loadVideo(pVideoId);
}

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>');
      
      jQuery("#video_content_link").html(jQuery("#link_video_"+this.id));
      
    }
  });  

}

/**
 * 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 parent_id = $(this).parent().attr('id');
      if ( !$(this).hasClass('source') ) 
      {
        if ( typeof parent_id === 'undefined' || parent_id == '' ) 
        {
          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_',''));
    });
    
    // Log(bc_videoIds);
  },
    
  playNextVideo: function()
  {
		this.getAutoPlaybackPlaylist();
    var pVideoId = player.getVideoId();
		
    // 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]);
          //Log('playVideo: '+bc_videoIds[i+1]);
        }
        else
        {
          playVideo(bc_videoIds[0]);
          //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 button = jQuery('#search-button');
      button.attr('disabled','disabled');
    	
      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 != jQuery('#default_seach_text').attr('value').replace(/ /g,'+')  )
        {
          window.location = '/'+search_url+'/'+phrase+'/';
        }
        else
        {
          button.removeAttr("disabled");
          return false;
        }
      }
      else
      {
    	button.removeAttr("disabled");
        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(player.getVideoTitle())+'/'+player.getVideoId();
      var shareURL = player.getSocialLink(true);
      jQuery('#social-link').val(shareURL); // update the social link
      jQuery('#crumb_video').attr("href",newURL); // update the breadcrumb link
      //player.setSocialLink(newURL);
    },
    
    updateEmbedCode: function(pCode)
    {
      jQuery('#social-code').hide(); 
      jQuery('#lang_share_embed_code').hide();

      jQuery.each(player.getVideoTags(),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: player.getVideoTitle(),
        description: player.getVideoDescription()
      };
      
      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 });
    }
  }
} 

function Log ( mixed )
{
  if ( typeof console !== 'undefined' )
  {
    if ( typeof mixed !== 'object' || typeof mixed !== 'boolean' )
    {
      clonsole.log(mixed);
    }
    else
    {
      clonsole.dir(mixed);
    }
  }
  
  return true;
}

 /**
  * 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 ( jQuery('#archive_form').length > 0 )
   {
     Archive.init();
   }
   
   AdditionalVideosModule.init();  
   Navigation.init();
   Search.init();
   Social.init();  
});

$(window).unload(function () {    
  setUserTimeZone();   
});


