var bcExp;
var modVP;
var modContent;
var modSocial;
var modAd;
var modExp;

var debugIVW;
var removeOverlaymenu;
var firstAutoloadedVideo;
var traceReport;
var player;
var adServerUrl;

function onTemplateLoaded(pEvent)
{
  bcExp      = brightcove.getExperience(pEvent);
  modVP      = bcExp.getModule(APIModules.VIDEO_PLAYER);
  modContent = bcExp.getModule(APIModules.CONTENT);
  modSocial  = bcExp.getModule(APIModules.SOCIAL);
  modExp     = bcExp.getModule("experience");
  
  modVP.addEventListener(BCVideoEvent.STREAM_START, getCurrentDetails);
  modContent.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad);
  modExp.addEventListener("templateReady", onTemplateReady);

  if (adServerUrl)
  {
    var brightcovePlayer   = brightcove.getExperience(pEvent);
    var brightcoveAdModule = brightcovePlayer.getModule(APIModules.ADVERTISING);
    var brightcoveAdPolicy = new Object();
    
    brightcoveAdPolicy.adServerURL = adServerUrl;
    brightcoveAdPolicy.prerollAds  = true;
    brightcoveAdPolicy.midrollAds  = true;
    brightcoveAdPolicy.postrollAds = true;
    brightcoveAdModule.setAdPolicy(brightcoveAdPolicy);
  }
  
  if (removeOverlaymenu == 1)
  {
    modMenu = bcExp.getModule(APIModules.MENU);
    modMenu.removeOverlayMenu();
  }
}

/**
* Event handler for when the player is ready for interaction.
*
* @param  event  Event dispatched by player experience module.
*/
function onTemplateReady(event)
{
  modExp.removeEventListener("templateReady", onTemplateReady);
  var videoPlayer = bcExp.getModule("videoPlayer");
  if (videoPlayer)
  {
      // set callback function for rendition selection
      videoPlayer.setRenditionSelectionCallback(selectRendition);
  }
}

function getCurrentDetails (evt)
{
  var currentVideo = modVP.getCurrentVideo();
  var videoRef     = currentVideo.referenceId.toString();
  var titleName    = currentVideo.displayName.toString();
  var titleTagArr  = currentVideo.tags;
  /* old solution, tag: simple integer value */
  var titleTag     = mapPlaylist(currentVideo.tags[0].toString());
  /* new solution, tag: lineup=xxx */
  for(var p=0;p<titleTagArr.length;p++)
  {
    temp = titleTagArr[p].split('=');
    if (temp[0] == 'lineup')
    {
      titleTag = temp[1].toString();
      break;
    }
  }
  ivw_add = "Video,"+ player + "," + titleTag + "," + titleName + "";
  trackingManager.count(ivw_add, '1023280', null, videoRef, firstAutoloadedVideo);
  firstAutoloadedVideo = 0;
}

function loadVideoInPlayer(data)
{
  if ($('div_article_headline'))
  {
    $('div_article_headline').innerHTML  = '<span class="dateline">'+data.spitzmarke+'<span>:</span></span>';
    $('div_article_headline').innerHTML += data.headline;
  }
  if ($('div_article_intro'))
  {
    $('div_article_intro').innerHTML = data.teaser;
  }
  modContent.getVideoAsynch(data.id);
}

function loadVideoIdInPlayer(id)
{
  modContent.getVideoAsynch(id);
}

function onVideoLoad(evt)
{
  /* Play video that was just loaded */
  modVP.loadVideo(evt.video.id);
  modSocial.setLink("http://www.stern.de/" + evt.video.referenceId + ".html");
}

/**
* The callback invoked whenever the player reaches a point when a new selection can be selected. This will occur on initial playback
* as well, for streaming videos, when there are multiple buffering events or when the screen size changed, as when going full screen.
* This method must take an object as an argument and return an int value that represents the index of the rendition to play.
*
* @param  context  The context that the player uses to select a new rendition. This object includes the following properties:
*           video  The video currently playing to which the renditions belong.
*           currentRendition  The currently selected rendition for the video.
*           renditions  An Array of renditions for the video to choose from.
*           detectedBandwidth  The last detected bandwidth value.
*           screenWidth  The pixel width of the video screen in which the rendition will play.
*           screenHeight  The pixel height of the video screen in which the rendition will play.
*
* @returns  The index of the rendition in the renditions list for the video player to play.
*/
function selectRendition(context)
{
  var renditions = context.renditions.slice();
  var heightMatch;
  var currentRendition;
  var selectedRendition;
  var bandwidth = context.detectedBandwidth;
  var height = 350;//context.screenHeight;
  for (var i = 0; i < renditions.length; i++) {
      currentRendition = renditions[i];
    //console.log(currentRendition.frameHeight);
      if (isNaN(currentRendition.frameHeight)) continue;
      if (isNaN(currentRendition.encodingRate) && bandwidth > -1) continue;
      // bandwidth hasn't yet need detected, look at height
      //console.log("bandwidth " + bandwidth);
      if (bandwidth == -1 || isNaN(bandwidth)) {
          // set the rendition that most closely matches screen height
          if (heightMatch == null
              || Math.abs(currentRendition.frameHeight-height) < Math.abs(heightMatch.frameHeight-height)
          ) {
              heightMatch = currentRendition;
              //console.log("matching " + currentRendition.frameHeight);
          }
      // if bandwidth has been detected, look at encoding rate;
      // only look at renditions that have encoding rate and height that is less than
      // the current bandwidth and screen height, within a tolerance setting
      } else if (bandwidth > -1
                  && currentRendition.encodingRate <= bandwidth*ENCODING_RATE_TOLERANCE
                  && currentRendition.frameHeight <= height*FRAME_HEIGHT_TOLERANCE
      ) {
          // check whether current rendition being evaluated is closer match than last one assigned to selectedRendition
          if (selectedRendition != null) {
              // if this rendition is closer than previous assigned, use it
              if (Math.abs(currentRendition.frameHeight-height) < Math.abs(selectedRendition.frameHeight-height)) {
                  selectedRendition = currentRendition;
              } else {
                  // since renditions are sorted descending, we will not get a closer match than the current
                  break;
              }
          } else {
              selectedRendition = currentRendition;
          }
      }
  }
  // if we couldn't find anything under the current bandwidth and size...
  if (selectedRendition == null) {
      // bandwidth has been detected, so find the closest encoding
      if (bandwidth > -1) {
          // sort renditions first by encoding, then by height
          renditions = sortRenditions(renditions);
          var bandwidthMatch;
          for (var i = 0; i < renditions.length; i++) {
              currentRendition = renditions[i];
              if (isNaN(currentRendition.encodingRate)) continue;
              if (bandwidthMatch == null) {
                  bandwidthMatch = currentRendition;
              // if this rendition is closer in desired encoding than the previous, use it
              } else if (Math.abs(currentRendition.encodingRate-bandwidth*ENCODING_RATE_TOLERANCE) < Math.abs(bandwidthMatch.encodingRate-bandwidth*ENCODING_RATE_TOLERANCE)) {
                  bandwidthMatch = currentRendition;
              }
          }
          selectedRendition = bandwidthMatch;
      } else if (heightMatch != null) {
          // just grab the closest in height since we have no bandwidth data
          selectedRendition = heightMatch;
      }
  }
  // find the index in the initial list
  var renditionIndex = -1;
  for (var i = 0; i < context.renditions.length; i++) {
      if (selectedRendition == context.renditions[i]) {
          renditionIndex = i;
          break;
      }
  }
//  describeRendition(context.renditions[renditionIndex]);
  return renditionIndex;
}

/**
* Sorts renditions first by bandwidth, then by frame height.
*
* @param  renditions  The list of renditions to sort.
*
* @returns  The sorted renditions in a new array.
*/
function sortRenditions(renditions)
{
  // first, sort by encoding
  renditions.sort(sortByEncoding);
  // run through sorted list and place same encodings into their own arrays
  var encodingRenditions = {};
  for (var i = 0; i < renditions.length; i++) {
      if (encodingRenditions[renditions[i].encodingRate] == null) {
          encodingRenditions[renditions[i].encodingRate] = [];
      }
      encodingRenditions[renditions[i].encodingRate].push(renditions[i]);
  }
  // now sort all nested arrays and put them back into single array
  var sortedRenditions = [];
  for (var i in encodingRenditions) {
      encodingRenditions[i].sort(sortByFrameHeight);
      sortedRenditions = sortedRenditions.concat(encodingRenditions[i]);
  }
  return sortedRenditions;
}

/**
* Sorts two renditions by encoding rate value.
*/
function sortByEncoding(a, b)
{
  var x = a.encodingRate;
  var y = b.encodingRate;
  return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

/**
* Sorts two renditions by frame height value.
*/
function sortByFrameHeight(a, b)
{
  var x = a.frameHeight;
  var y = b.frameHeight;
  return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

/**
* Traces out the values of rendition for testing.
*
* @param  rendition  The rendition to traces values for.
* @param  index  The index in the renditions array where this rendition is found.
*/
function describeRendition(rendition)
{
  if (rendition == null )
  {
    return;
  }
  
  var message = ("size: " + rendition.size);
  message += ("\nframeWidth: " + rendition.frameWidth);
  message += ("\nframeHeight: " + rendition.frameHeight);
  message += ("\nencodingRate: " + rendition.encodingRate);
  console.log(message);
}

function mapPlaylist(playlistNumber)
{
  /* Old: lineup as id, mapping here for hbx, bad */
  /* New: lineups as name, no mapping needed any more (to enable multiple tags), 27.11.2008 */
  output = '';
  switch (playlistNumber) {
    case "1":
      output = 'reuters';
      break;
    case "8":
      output = 'single';
      break;
    case "9":
      output = 'reuters';
      break;
    case "11":
      output = 'einstein';
      break;
    case "12":
      output = 'politik';
      break;
    case "13":
      output = 'panorama';
      break;
    case "14":
      output = 'wissenschaft';
      break;
    case "15":
      output = 'sport';
      break;
    case "16":
      output = 'kultur';
      break;
    case "17":
      output = 'technik';
      break;
    case "18":
      output = 'lifestyle';
      break;
    case "21":
      output = 'sneak';
      break;
    case "22":
      output = 'klatsch';
      break;
    case "23":
      output = 'kuehn';
      break;
    case "24":
      output = 'starmag';
      break;
    case "25":
      output = 'Tests';
      break;
     case "26":
      output = 'Bellstedts_Ballshow';
      break;
    case "27":
      output = 'Look';
      break;
    case "114":
      output = 'EM-Weisen';
      break;
    case "117":
      output = 'EM-Buntes';
      break;
    case "116":
      output = 'Bellstedts_Ballshow_EM';
      break;
    case "118":
      output = 'EM-News';
      break;
    case "33":
      output = 'Reise';
      break;
    case "34":
      output = 'Vorfahrt';
      break;
    case "120":
      output = 'Olympia-News';
      break;
    case "121":
      output = 'Olympia-Buntes';
      break;
    case "122":
      output = 'Olympia-Kolumnen';
      break;
    case "28":
      output = 'Auto';
      break;
    case "29":
      output = 'Witz_der_Woche';
      break;
    case "30":
      output = 'Die_witzigsten_Werbespots';
      break;
    case "31":
      output = 'Best_of_Jon_Stewart';
      break;
    case "32":
      output = 'Cartoonisten';
      break;
    case "35":
      output = 'Games Check';
      break;
    case "36":
      output = 'Tronic';
      break;
    case "37":
      output = 'Bohlen liest';
      break;
    case "38":
      output = '60_Sekunden';
      break;
    case "39":
      output = 'Southpark';
      break;
    case "40":
      output = 'Stars_von_morgen';
      break;
    case "41":
      output = 'Klimaserie';
      break;
    case "126":
      output = 'Abgeltungssteuer';
      break;
    case "127":
      output = 'US-Wahl';
      break;
    case "128":
      output = 'Klimaserie';
      break;
    case "129":
      output = 'Bildungsreport';
      break;
    case "130":
      output = 'Musik';
      break;
    case "132":
      output = 'Wahl 2009';
      break;
    case "43":
      output = 'Joerges';
      break;
    case "44":
      output = 'Wirtschaft';
      break;
    case "45":
      output = 'Release';
      break;
    case "47":
      output = 'Blank_vs_Sander';
      break;
    case "48":
      output = 'Kochen';
      break;
    case "49":
      output = 'Energiesparen';
      break;
  }
  
  return output;
}
