/**
 * Funktionen fuer die Brightcove-Integration
 */

var bcPlayer;

/**
 * Schreibt den Brightcove-Player
 */
function writeBrightcovePlayer(elem, brightcoveId, playerId, playerWidth, aspectRatio, adTags, noAds) {
  // Element und Brightcove-ID sind zwingend notwendig und muessen uebergeben werden!
  if ('undefined' == typeof elem || '' == elem || 'undefined' == typeof brightcoveId || '' == brightcoveId) {
    return false;
  }
  
  // Falls keine Player-ID uebergeben wird nehmen wir den Standard-Player
  if ('undefined' == typeof playerWidth || '' == playerWidth) {
    var playerId = '704781425001';
  }

  // Wenn keine Breite uebergeben wurde einen Standard definieren
  if ('undefined' == typeof playerWidth || '' == playerWidth) {
    var playerWidth = 580;
  }

  // Wenn ein Seitenverhaeltnis uebergeben wurde kann die Playerhoehe dynamisch bestimmt werden
  if ('undefined' != typeof aspectRatio) {
  	var ratios = {
      '4:3'   : playerWidth / 4 * 3,
      '16:9'  : playerWidth / 16 * 9,
      '16:10' : playerWidth / 16 * 10,
      '1,85:1': playerWidth / 1.85,
      '2,35:1': playerWidth / 2.35
    };
    // Zusaetzlich noch 44 Pixel fuer die Menueleiste hinzufuegen
    var playerHeight = ratios[aspectRatio] + 44;
  }

  // Fallback falls keine Hoehe definiert wurde (z.B. weil kein oder ein ungueltiges Seitenverhaeltnis uebergeben wurde)
  if ('undefined' == typeof playerHeight) {
    // Passend fuer 4:3-Videos
    var playerHeight = playerWidth / 4 * 3 + 44;
  }


  if (true != noAds && !frn046adxtra) {
    var frn046adxtra = "";
    var frn046enrich = (typeof pt027bw == 'undefined') ? "&amp;band=256"+frn046adxtra : "&amp;band="+pt027bw+frn046adxtra;
    var frn046enrich = (typeof frn046tie == 'undefined') ? "&amp;tie=free"+frn046enrich : "&amp;tie="+frn046tie+frn046enrich;
  }

  var htmlString = '<object id="myExperience' + brightcoveId + '" class="BrightcoveExperience">'
  + '<param name="bgcolor" value="#FFFFFF" />'
  + '<param name="width" value="' + playerWidth + '" />'
  + '<param name="height" value="' + playerHeight + '" />'
  + '<param name="playerID" value="' + playerId + '" />'
  + '<param name="publisherID" value="66995324001" />'
  + '<param name="isVid" value="true" />'
  + '<param name="isUI" value="true" />'
  + '<param name="optimizedContentLoad" value="true" />'
  + '<param name="wmode" value="transparent" />';

  if (true != noAds) {
    htmlString += '<param name="additionalAdTargetingParams" value="' + adTags + frn046enrich + '" />';
  }

  htmlString += '<param name="@videoPlayer" value="' + brightcoveId + '" /></object>';
  
  jQuery(elem).html(htmlString);
  
  brightcove.createExperiences();
  
  return true;
}

/**
* Called when players loads. Sets up listener for TEMPLATE_READY.
*
* @param  id  The HTML object ID of the player element.
*/
function onTemplateLoaded(id) {
  bcPlayer = brightcove.getExperience(id);
  bcPlayer.getModule(APIModules.EXPERIENCE).addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
}

/**
* Handler for TEMPLATE_READY event. Sets callback for when additional media need to be accessed.
*
* @param  event  Event dispatched by ExperienceModule.
*/
function onTemplateReady(event) {
  bcPlayer.getModule(APIModules.EXPERIENCE).removeEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
  var menuModule = bcPlayer.getModule(APIModules.MENU);
  menuModule.setAdditionalMediaCallback(getAdditionalMedia);
}

/**
* Callback for when the player needs to request additional media.
*
* @param  type  The type of additional media that is being requested. These correspond with the types passed in the initial
*               setAdditionalMediaCallback() call, or if no custom types were passed, those specified as constants of MenuModule.
* @param  media  The media for which the additional media is being requested.
*
* @return  True is this callback will handle the specified type, or if the player is to handle the type with its default search algorithm.
*/
function getAdditionalMedia(type, media) {
  if (type == BCMenuAdditionalMedia.RELATED_VIDEOS) {
      requestRelatedForMedia(media.id);
      return true;
  }
  return false;
}

/**
* Calls to third party recommendation engine to retrieve list of Brightcove media IDs to be used in related videos list.
*
* @param  id  The id of the media that is currently being viewed in the player and for which the related media
*             is being requested.
*/
function requestRelatedForMedia(id) {
  jQuery.getJSON('http://api.brightcove.com/services/library?command=find_playlist_by_id&token=bWnJB7uUWLw_SI_5cAkUlF6KLUeEk_36_Honr0pEeqtUCJ1lR7TH2A..&playlist_id=' + OdcVars.bcPlaylistId + '&fields=videoIds&callback=?', function(ids) {
    onRelatedRequestComplete(null, ids.videoIds);
  });
}

/**
* Handler for the response from the third party recommendation engine. This should hold list of Brightcove media IDs.
*
* @param  event  Event dispatched by URLLoader (probably, depending on the implementation of the request).
* @param  ids  Array with Video-IDs
*/
function onRelatedRequestComplete(event, ids) {
  var contentModule = bcPlayer.getModule(APIModules.CONTENT);
  contentModule.addEventListener(BCContentEvent.MEDIA_COLLECTION_LOAD, onMediaCollectionLoad);
  contentModule.getMediaInGroupAsynch(ids);
}

/**
* Handler for the getMediaInGroupAsynch() request.
* This should hold a MediaCollectionDTO with the IDs of the media metadata that was loaded.
*
* @param  event  Event dispatched by ContentModule.
*/
function onMediaCollectionLoad(event) {
  var mediaIds = event.mediaCollection.mediaIds;
  var mediaDTOs = [];
  for (var i in mediaIds) {
    mediaDTOs.push({id:mediaIds[i]});
  }
  var menuModule = bcPlayer.getModule(APIModules.MENU);
  menuModule.setAdditionalMediaForType(mediaDTOs, BCMenuAdditionalMedia.RELATED_VIDEOS);
}
