
/* Channel embed codes for the cboe channels.
 */
var EMBED_CODE_FOR_MOST_RECENT 		= "Z3bXJoOnhoqcg0w4kr5k-7Z62eVYtM-n";
var EMBED_CODE_FOR_MOST_POPULAR 	= "VzdnIwMTqWjN-DCOuzdAG-kyTLQ6qMsF";
var EMBED_CODE_FOR_DAILY_MARKET 	= "dhMnd2OvdllQ0hA47WuEfU4lQ9UXcf4d";
var EMBED_CODE_FOR_STRATEGY 		= "kwd3I2OkIBwcHV8h8eIasEroNckHx1zg";
var EMBED_CODE_FOR_NEWS 			= "5hZXEyOkIM7EUIgOL0Naxd2Vk0RUoCKA";
var EMBED_CODE_FOR_PRODUCTS 		= "lzNHd2OrxouTVkbsJyQ56bcKJsevVg4k";
var EMBED_CODE_FOR_PARTENER_CONTENT = "Ixd3I2OhTx-J-5xlKvwdZpGwfe9aKwUa";

var _currentChannelEmbedCode = "";
var _currentVideoEmbedCode = "";
var _searchActive = false;
var _auto_play_video = false;
var _no_of_times_in_api_ready = 0;
var _play_head_time = "0";
var _finished_ad = false;
var _activeVideoChannelEmbedCode = "";
var _player = "";

function calculateTabWidth () 
{
  elements = $("#tabsContainer li");
  var totalWidth = 0;
  for (var i = 0; i < elements.length; i++)
  {
    totalWidth += $(elements[i]).outerWidth();
  }
  $("ul#tabsContainer").css("width", totalWidth+2 + "px");
}

function scrollList(pixels) 
{ // JS For Scrolling Tabs at Top
  var container = $("#tabsContainer");
  var currentLeft = container.position().left;
  var newLeft = pixels + currentLeft;
  var padding = 24;
  var leftLimit = $("#tabsOuter").width() - container.attr("scrollWidth") - padding;
  var rightLimit = padding;
  if (newLeft < leftLimit) 
  {
    // Trying to scroll beyond the right side
    newLeft = leftLimit;
    // rightArrow.className =+ "gray";
  }
  else if (rightLimit < newLeft)
  {
    // Trying to scroll beyond the left side
    newLeft = rightLimit;
    // leftArrow.className =+ "gray";
  }
  container.animate({ left: newLeft }, 400);
}

$(document).ready(function() 
{ // Functions called after document has loaded
  calculateTabWidth();
  _player = document.getElementById("ooyalaPlayer");

  $("#next").click(function() {
    if($("#tabsContainer").width() > 875){
      scrollList(-400);
    }
  });
  
  $("#previous").click(function() {
    if($("#tabsContainer").width() > 875){
      scrollList(400);
    }
  });

  // Listen for the enter keystroke in the search box
  $("#searchBox").keydown(function(event) 
  {
    var enterKey = 13;
    if (event.keyCode == enterKey) 
    {
        searchVideos();
        return false;
    }
  });
  
  /* Set the current channel embed code and video etc depending on whether it is a deep linking case
   * etc.
   */
  initializeVideo();
});

function getUrlChannelEmbedCode()
{
  var ooid_value = getParam("ooid");
  if (ooid_value != null && ooid_value != '')
  {
    /* Deep linking url case. Hence set the channel code, video code, play ahead time etc
     * and set auto play to true.
    */

    /*
    Change requested by Ooyala 10/22/2010 RA
    var codes = ooid_value.split(',');
    return codes[0];
    */
    var codes = ooid_value.split(',');
    if (codes[0] == ooid_value) {
      codes = ooid_value.split('|');
    }
    return codes[0];
  }
  return EMBED_CODE_FOR_MOST_RECENT;
}

function getUrlVideoEmbedCode()
{
  var ooid_value = getParam("ooid");
  if (ooid_value != null && ooid_value != '')
  {
    /* Deep linking url case. Hence set the channel code, video code, play ahead time etc
     * and set auto play to true.
     */
    var codes = ooid_value.split(',');
    if (codes.length > 1)
    {
      return codes[1];
    }
  }
  return "";
}

function getUrlOoTime()
{
  var play_time = getParam("ootime"); 
  if (play_time != null)
  {
    try 
    {
		  return play_time.substring(0,play_time.indexOf('s'));
    }
	  catch(e) 
	  {
  		return 0;
	  }
  }
  return "0";
}

function initializeVideo()
{
    _currentChannelEmbedCode = getUrlChannelEmbedCode();
    _activeVideoChannelEmbedCode = getUrlChannelEmbedCode();
    _currentVideoEmbedCode = getUrlVideoEmbedCode();
    _play_head_time = getUrlOoTime();
    
  /* Set the active tab according to the deeplinking params if any or the embedCode from url etc.
   * Default is the recent tab.
   */ 
  var tab_name = "";
  switch (_currentChannelEmbedCode) 
  {
    case EMBED_CODE_FOR_MOST_RECENT:
    {
      tab_name = 'recent_channel';
    }
    break;
    case EMBED_CODE_FOR_MOST_POPULAR:
    {
      tab_name = 'popular_channel';
    }
    break;
    case EMBED_CODE_FOR_DAILY_MARKET:
    {
      tab_name = 'DMR_channel';
    }
    break;
    case EMBED_CODE_FOR_STRATEGY:
    {
      tab_name = 'strategy_channel';
    }
    break;
    case EMBED_CODE_FOR_NEWS:
    {
      tab_name = 'news_channel';
    }
    break;
    case EMBED_CODE_FOR_PRODUCTS:
    {
      tab_name = 'products_channel';
    }
    break;
    case EMBED_CODE_FOR_PARTENER_CONTENT:
    {
      tab_name = 'partner_content_channel';
    }
    break;
    default:
    {
      tab_name = 'recent_channel';
    }
    break;
  }
  switchtab(tab_name, _currentChannelEmbedCode); 
}

/* The callback method of the player.
 */
function nuplayerEventHandler(playerId, eventName, eventParams)
{
  if (eventName == 'companionAdsReady') 
  {
    document.getElementById("ad").style.visibility = "hidden";
    document.getElementById("google_in_stream_sdk_companion").style.visibility = "visible";
  } 
  else if (eventName == 'adCompleted') 
  {
    document.getElementById("ad").style.visibility = "visible";
    document.getElementById("google_in_stream_sdk_companion").style.visibility = "hidden";
  }
    
  if (eventName == "embedCodeChanged") 
  {
     _player = document.getElementById('ooyalaPlayer');
    
     /* Check if the player embed code is the same as that from the url. If not, change
      * the channel embed code. Otherwise, change the current item in the channel.
      */
     var channelEC = getUrlChannelEmbedCode();
     if (channelEC != _player.getEmbedCode() )
     {
        _currentChannelEmbedCode = channelEC;
        _player.setEmbedCode(channelEC);
     }
     else
     {
       var videoEC = getUrlVideoEmbedCode();
       if (videoEC != "")
       {
         _currentVideoEmbedCode = videoEC;
         _player.pauseMovie();
         var result = _player.changeCurrentItem(videoEC);
       }
     }
  }
  
  if(eventName == "adCompleted")
  {
    /* Need to set this flag to set the playhead time in deep linking case, since 
     * player.setPlayheadTime() can only be called after the ad completes.
     */
    _finished_ad = true;
  }

  if (eventName == 'currentItemEmbedCodeChanged')
  {
    _player = document.getElementById('ooyalaPlayer');
    var play_time = getUrlOoTime();
    if(_auto_play_video == true)
    {
     _player.playMovie();
    }
    else
    {
     _player.pauseMovie();
    }
  }
  if (eventName == 'stateChanged')
  {
    if (eventParams.state == "playing") 
    {
      /* When the page loads for the first time, by default the
       * 1st video from the recent channel should start playing and be highlighted. 
       * In this case, we dont know the embed_code of the actual video that is playing.
       * Hence need to highlight like this in the listner.
       */
      _player = document.getElementById('ooyalaPlayer');
      _currentVideoEmbedCode = _player.getCurrentItemEmbedCode();
      _activeVideoChannelEmbedCode = _player.getEmbedCode();
      $('.thumbnailOn').toggleClass('thumbnailOn', false);
      $('#' + _activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode + "_thumbnail").toggleClass('thumbnailOn', true);
      $('.videoTileOn').toggleClass('videoTileOn', false);
      $('#' + _activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode + "_videoDiv").toggleClass('videoTileOn', true);
      $('.greenText').toggleClass('greenText', false);
      $('#' + _activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode + "_title").toggleClass('greenText', true);
      
      if (_finished_ad && _play_head_time != "0")
      {
        /* Set the playhead time for deep linking case if the ad has finished.
         */
        _player.setPlayheadTime(_play_head_time);
	      _play_head_time = "0"; //so this happens only once.
      }

    }
    return;                     
  }
}

function setOoidParamsInUrl(channelEmbedCode, embedCode)
{
  /* Set the channel embed code and video embed code in the url. This will be used in 
   * the search case, to set the embed codes of the first video from the search results in the url.
   */
  var fullUrl = window.location.href;
  var length = window.location.href.length - window.location.hash.length;
  var url_without_hash = fullUrl.substring(0,length);
  window.location.href = url_without_hash + '#ooid=' + channelEmbedCode + "," + embedCode ;
}

/* This gets called we have no search results for their query.
 */
function showNoSearchResultsMessage() 
{
  $("#rightTV")[0].innerHTML = "<div class='searchError'>No videos found. Please search again.</div>";
}

/* searchVideos via title and description and returns them as current channel result
*/
function searchVideos() 
{ 
  _searchActive = true;
  _play_head_time = "0";
  _auto_play_video = false;
  $("li.tab a").css({ 'color': '#FFF' });

  var value = encodeURIComponent(document.getElementById("searchBox").value);

  /* Get the search results and load that html in #rightTV
  */
  $('#rightTV').load('SearchResults.aspx', value, function(response, status, xhr) 
  {
    /**
    * Load is complete. So now check if we got any results etc and set the 1st video in player
    */

    /**
    * Apply scrolling to the search results
    */
    $('#rightTV').jScrollPaneRemove();

    var needsToBeScrolled = $("#rightTV").height() < $("#rightTV")[0].scrollHeight;
    if (needsToBeScrolled) 
    {
      $("#rightTV").css("overflow", "auto");
      $('#rightTV').jScrollPane({ scrollbarWidth: 15, scrollbarMargin: 0, dragMaxHeight: 156 });
    } 
     
    _player = document.getElementById("ooyalaPlayer");

    if ($("#txtSearchResultsResponse")[0].innerHTML != 'success')
    {
      showNoSearchResultsMessage();
     _player.pauseMovie();
    }
    else
    {
      _currentVideoEmbedCode = $("#firstResultVideoCode")[0].innerHTML;
      var firstVideoChannelCode = $("#firstResultChannelCode")[0].innerHTML
      _currentChannelEmbedCode = firstVideoChannelCode;
      setOoidParamsInUrl(_currentChannelEmbedCode,_currentVideoEmbedCode);
      if (_player.getEmbedCode() != firstVideoChannelCode)
      {
        /* The first video's channel embed code is different than the 
         * player's current channel. So change the channel
         */
        _player.setEmbedCode(firstVideoChannelCode);
      }
      else
      {
        /* The channel of player and 1st video is same, so change the video
         * to be played to the 1st video.
         */
        _player.changeCurrentItem(_currentVideoEmbedCode);
        _player.pauseMovie();
      }
    }
  });
}

/**
 * Called when whatever tab is clicked
 * Affects the UI by changing the selected tab
 * 
 * @param @name : name of the clicked tab
 */
function switchtab(name, channel_embed_code)
{
  _searchActive = false;

  $("li.tab a").css({ 'color': '#FFF' });
  $('li#' + name + " a").css({ 'color': '#99cc00' });

  /* Copy the contents of relevant div to the active div
   */
  $('#rightTV').html($('#hidden_' + name).html());

  $('#rightTV').jScrollPaneRemove();

  var needsToBeScrolled = $("#rightTV").height() < $("#rightTV")[0].scrollHeight;
  if (needsToBeScrolled) 
  {
    $("#rightTV").css("overflow", "auto");
    $('#rightTV').jScrollPane({ scrollbarWidth: 15, scrollbarMargin: 0, dragMaxHeight: 156 });
  } 

  if (_currentVideoEmbedCode != "")
  {
    /* Everytime we switch tab, we overwrite the visible div
     * with the html for that tab. Hence need to again highlight
     * the correct playing video.
     */
    $('.thumbnailOn').toggleClass('thumbnailOn', false);
    $('#' + _activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode + "_thumbnail").toggleClass('thumbnailOn', true);
    $('.videoTileOn').toggleClass('videoTileOn', false);
    $('#' + _activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode + "_videoDiv").toggleClass('videoTileOn', true);
    $('.greenText').toggleClass('greenText', false);
    $('#' + _activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode + "_title").toggleClass('greenText', true);
    scrollDiv(_activeVideoChannelEmbedCode+ '_' + _currentVideoEmbedCode) ;
  }

  _currentChannelEmbedCode = channel_embed_code;
}

/* Returns the value for the passed in key from the url hash parameters.
 */
function getParam(key) {
  try {
    //get querystring(s) without the # 
    var urlParams = window.location.hash.substring(1, window.location.hash.length);
    if (urlParams == false | urlParams == '') return null;
    //get key/value pairs 
    var pairs = urlParams.split("&");
    var keyValue_Collection = {};
    for (var i = 0; i < pairs.length; i++) {
      //let's get the position of the first occurrence of "=", in case value has "=" in it 
      var equalsignPosition = pairs[i].indexOf("=");

      if (equalsignPosition == -1) //in case there's only the key, e.g: http://cboe.com/#ooid
      {
        keyValue_Collection[pairs[i]] = '';
      }
      else {
        keyValue_Collection[pairs[i].substring(0, equalsignPosition)] = pairs[i].substring(equalsignPosition + 1);
      }
    }
    return keyValue_Collection[key];
  }
  catch (e) {
    return "";
  }
};
 
/**
* Make the highlighted video visible to user
*/ 
function  scrollDiv(divId)
{
  if ($(".videoTileOn", $("#rightTV")).length > 0)
  { 
     var position =  $('#'+divId).position();
     var top=  position.top;
     var scrollableDiv = document.getElementById("rightTV"); 
     scrollableDiv.scrollTo(top);  
   }
}
