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

var clicked_element = '';

function OnContentLoad()
{
  bc_startingVideo = player.getCurrentVideo();
  
  Playlist.getAutoPlaybackPlaylist();
	
	if(location.hash != '') {
	  //var custhash = location.hash.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
 	 	var tag = location.hash.replace("#","");
		//  return tag;
		//});
	  if(!isNaN(parseInt(tag)) && isFinite(tag)) {
		  playVideo(tag);
		}
	}
	
}

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) {

  jQuery.each(jQuery('.playlist li'), function()
  {
		if(this.id.split('-')[0] == 'general') {
		  var videoId = this.id.split('-')[1];
		} else {
      var videoId = this.id.split('_')[1];
		}
	
    if (videoId == pVideoId) {
      if (jQuery("#date"))
        jQuery('#date').html(jQuery('#'+this.id+' .video-time').html());
      if (jQuery("#video_content_source"))
        jQuery("#video_content_source").html('<a href="'+jQuery('#'+this.id+' a.source').attr('href')+'">'+jQuery('#'+this.id+' a.source').html()+'</a>');
			
			var href = jQuery('#'+this.id+' .video-text a').attr('href');
			var inner = jQuery('#' + this.id + ' .video-text a').html();
			if (jQuery('#related-video-link') && href != 'null' && href != null && inner != 'null' && inner != 'null')
			  jQuery('#related-video-link').html('<a href="' + jQuery('#'+this.id+' .video-text a').attr('href') + '">' + jQuery('#' + this.id + ' .video-text a').html() + '</a>');

      
      jQuery("#video_content_link").html(jQuery("#link_video_"+this.id));
      
    }
  });  

}

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

  init: function()
  {
		jQuery('#related-videos a,#popular-videos a').bind('click', function() {
		  if(typeof jQuery(this).attr('rel') != 'undefined' && jQuery(this).attr('rel') != '') {
			  clicked_element = jQuery(this).closest('li').attr('id').split('-')[0];
			  location.hash = jQuery(this).attr('rel');
		    playVideo(jQuery(this).attr('rel'));
	 			return false;
			}
		});
  },
    
  switchModules: function( module )
  {
    var apply_switch = false;
		
    if ( module == 'related' ) {
	    apply_switch = !jQuery('#tab-related').hasClass('active');
			clicked_element = 'related';
      jQuery('#related-videos').show();
      jQuery('#popular-videos').hide();
    } else {
      apply_switch = !jQuery('#tab-popular').hasClass('active');
			clicked_element = 'popular';
      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');
    }
	}
};

var Navigation = 
{
  init: 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();
      
		jQuery('#navigation h3').bind('click', function() {
      if ( !jQuery(this).hasClass('highlight') ) {
        jQuery(this).addClass('highlight');
        jQuery(this).next().show();
      } else {
        jQuery(this).removeClass('highlight');
        jQuery(this).next().hide();
      }
		});
  }
};

var Playlist = {  
    
  getAutoPlaybackPlaylist: function()
  {
		bc_videoIds = new Array();
		if(clicked_element) {
		  var list = clicked_element;
      jQuery.each(jQuery('#playlist_' + list + ' li h4 a'), function() {
        bc_videoIds.push(jQuery(this).attr('rel'));
      });
		} else {
      jQuery.each(jQuery('#playlist_general li'), function() {
		      bc_videoIds.push(this.id.replace('general-',''));
      });
		}
  },
    
  playNextVideo: function() {
		this.getAutoPlaybackPlaylist();
    var pVideoId = player.getVideoId();
		
    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] ) {
					location.hash = bc_videoIds[i+1];
          playVideo(bc_videoIds[i+1]);
        } else {
					location.hash = bc_videoIds[0];
          playVideo(bc_videoIds[0]);
        }
        break;
      }
    }
  },
    
  highlightCurrentlyPlayingVideo: function(pVideoId) {
    // main playlist
    jQuery.each(jQuery('#playlist_general li'), 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
    jQuery.each(jQuery('#additional-videos li'), 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() {
      jQuery(this).val('');
      jQuery(this).addClass('search_active');
    });
      
    search_field.blur(function() {
      if ( jQuery(this).val() == '' ) {
        jQuery(this).val(jQuery('#search_box_text').text()); 
      }
        
      jQuery(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 = SiteParams.base_url + '/' + 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');
      
    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;
			  jQuery(this).addClass('active');
      }
    });
				
    jQuery('#social-friend-email').focus(function() {
      if(!socialFriendClear) {
        jQuery(this).val('');
        socialFriendClear = true;
			  jQuery(this).addClass('active');
      }
    });
		
    jQuery('#social-message').focus(function() {
      if(!socialMessageClear) {
        jQuery(this).val('');
        socialMessageClear = true;
  			jQuery(this).addClass('active');
      }
    });
  },
    
  updateGetLink: function() {
    var crumbURL = jQuery('#crumb_video').attr('href');
    //var newURL = 'http://' + SiteParams.domain;
    var 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

		var FacebookLang = 'en_US';
		if(SiteParams.language == 'fr') {
			var FacebookLang = 'fr_FR';
		}
		
		jQuery('.facebook_like').attr('src', 'http://www.facebook.com/plugins/like.php?locale=' + FacebookLang + '&href=' + encodeURIComponent(shareURL) + '&layout=button_count&show_faces=false&width=130&action=like&font=arial&colorscheme=light&height=21');
	  //jQuery('.facebook_share').attr('src', 'http://widgets.fbshare.me/files/fbshare.php?locale=' + FacebookLang + '&size=small&url=' + encodeURIComponent(shareURL));
		jQuery('.twitter-share-button').attr('src', 'http://platform0.twitter.com/widgets/tweet_button.html?_=1292949871405&count=right&lang=' + SiteParams.language + '&text=' + encodeURIComponent(player.getVideoTitle()) + '&url=' + encodeURIComponent(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 = SiteParams.base_url + '/email';
      
    jQuery('form.share_box .share_box_container').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 .share_box_container').fadeIn('fast');
  }
};

var Archive = {
  init: function() {
		
  },
    
  getContent: function() {
	  var source   = jQuery('select.archive_sources').val();
		var category = jQuery('select.archive_categories').val();
		var year     = jQuery('select.archive_years').val();
		var month    = jQuery('select.archive_months').val();
		var day      = jQuery('select.archive_days').val();
      
    var url = SiteParams.base_url + '/archive';
    if(category && category != '0') url += '/category/'+category;
    if(source && source != '0')     url += '/source/'+source;
		if(year && year != '0')         url += '/year/'+year;
		if(month && month != '0')       url += '/month/'+month;
		if(day && day != '0')           url += '/day/'+day;

    window.location = url;
  }
};

var SelectBox = {
	archivesources: '',
	selectedcategory: '',
	selectedsource: '',
	
	changearchives: function() {
	 
	  var sources = this.archivesources;
	  var category = this.selectedcategory;
	 
	  if(!category || category == '0') {
		  category = 'all';
		}
	
	  if(typeof sources[category] === 'undefined') {
			 return false;
		}
	 
    jQuery('.archive_sources option').remove();
  	jQuery('.archive_sources').append('<option value="' + jQuery('.archive_categories option')[0].value + '">' + jQuery('.archive_categories option')[0].text + '</option>');
  	jQuery.each(sources[category], function(k, v) {
	  	jQuery('.archive_sources').append('<option value="' + k + '">' + v + '</option>');
  	});
	 
	},
	
	SetSourceValues: function(v) {
	  this.archivesources = v;
	}
	
};

/**
 * 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().ready(function() {

  if ( typeof jQuery('#archive_form') != 'undefined' ) {
    Archive.init();
  }
   
  AdditionalVideosModule.init();  
  Navigation.init();
  Search.init();
  Social.init();  

  jQuery('#video_search_form').bind('submit', function() {
	  Search.onSearchSubmit(jQuery(this).attr('rel'));
 	  return false;
	});
	
	jQuery('#archive_form').bind('submit', function() {
	  Archive.getContent();
 	  return false;
	});
	
	jQuery('#archive_form #form_button a').bind('click', function() {
	  jQuery('#archive_form').submit();
	  return false;
	});
	
	jQuery('.share_box').bind('submit', function() {
 	  Social.sendEmail();
	  return false;
	});
	
	jQuery('.switch_module').bind('click', function() {
	  var selectedModule = jQuery(this).attr('id').substr(14);
	  AdditionalVideosModule.switchModules(selectedModule);
	  return false;
	});
	
	jQuery('.archive_categories').bind('change', function() {
	  SelectBox.selectedcategory = jQuery(this).val();
	  SelectBox.changearchives();
	});
	
});



/*****************************
Global Functions
******************************/
function url_title(pTerm) {
  // mimmicks the url_title() function from codeigniter
  if (pTerm) {
		pTerm = pTerm.toLowerCase();
		var trimer = {
		  'a': new RegExp(/[àáâãäå]/gi),
		  'o': new RegExp(/[òóôõöø]/gi),
		  'e': new RegExp(/[éèêë]/gi),
		  'c': new RegExp(/[ç]/gi),
		  'i': new RegExp(/[ìíîï]/gi),
		  'u': new RegExp(/[ùúûü]/gi),
		  'y': new RegExp(/[ÿ]/gi),
		  'n': new RegExp(/[ñ]/gi)
		};
		//for(var i = 0; i < accent.length; i++) {
		jQuery.each(trimer, function(e, b) {
		  pTerm = pTerm.replace(b, e);
		});

		return pTerm.replace(/[^a-z0-9]+/gi, '-').replace(/^-*|-*jQuery/g, '');
  }

  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;
}

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

