/*

  America.gov Site JavaScript: Video Page Functions
  
  America.gov Web Site
  United States Department of State

*/

//Swaps out brightcove media elements (such as a video or photo gallery component)
$.fn.brightcoveToggleVideo = function() {

  var loc = location.href;
  var videoId = new Array();
  videoId = loc.split("=");
  videoId = videoId[1];

  if ( !(videoId) && ($(".player").attr("class")) ) {
    var videoId = ($(".collection-box li a:eq(0)").attr("href")).substring(1);
    $.fn.brightcoveToggleVideo.swapVideo(videoId);
  }

  this.each(function() {
    $(this).find(".collection-box li").click(function () {
      var videoId = ($(this).find("a:eq(0)").attr("href")).substring(1);
      $.fn.brightcoveToggleVideo.swapVideo(videoId);
      return false;
    });
  });

  var videoCurrent = $("a[href=#" + videoId + "]:eq(0)").parent();
  var vTitle = $(videoCurrent).find("h5 a").text();
  var vDetail = $(videoCurrent).find("span").text();
  var vDesc = $(videoCurrent).find(".description").text();

  $(".player").find(".about .content").html("<h5>" + vTitle + " <span class='detail'>" + vDetail + "</span></h5><div class='description'>" + vDesc + "</div>");

};

$.fn.brightcoveToggleVideo.swapVideo = function(videoId) {
  var loc = location.href;
  if (loc.indexOf('?videoId=') !=-1) {
    var redirectURL = new Array();
    redirectURL = loc.split("?");
    redirectURL = redirectURL[0];
  } else {
    redirectURL = loc;
  }

  window.location = redirectURL + "?videoId=" + videoId;

};

$.fn.activeHighlight = function() {
  var loc = location.href;
  var itemId = new Array();
  itemId = loc.split("=");
  itemId = itemId[1];

  if(itemId) {;
    $(".collection-nav").find("li").removeClass();
    $(".collection-box").find(".elements").hide();
    $(".collection-box").find("li").removeClass("active");
    
    var matchContent = $("a[href=#" + itemId + "]:eq(1)").text();    
    var tabName = $(".collection-box ul:contains('" + matchContent + "')").attr("title");
    
    $(".collection-box ul:contains('" + matchContent + "')").show();
    $(".collection-box li:contains('" + matchContent + "')").addClass("active");
    $(".collection-nav li:contains('" + tabName + "')").addClass("active");
  }
};

$(function() {
  $("#video").find(".tabbed-collection").brightcoveToggleVideo();
  $(".tabbed-collection").activeHighlight();  
});