/*
BrightgCove 3 flash Player
 *@ Author Yufang Chang
 */

/************************************************
*  @JSON RESPONSE PARSER
*************************************************/

function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}

// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

/************************************************
*  @BC Player API Calls
*************************************************/
// called when template loads, this function stores a reference to the player and modules.
// Then event listeners will be added for when the template is ready and when a user
// clicks on a video.
function onTemplateLoaded(experienceID) {
    MAGNET.brightcove.player.initTemplate(experienceID);
}




var MAGNET = window.MAGNET || {};

if (typeof MAGNET.brightcove == "undefined") {
    MAGNET.brightcove = {};
}

/************************************************
*  @DRAW BC PLAYER
*************************************************/
MAGNET.brightcove.player = new (function() {
var oThis = this;
var playerContainer = 'brightcovePlayer';
var bgcolor= "#FFFFFF";
var publisherID = "1569970201";
var currentPage = document.location.href;

var host = "http://" + document.location.host + "/video";
var bcExp;
var modVP;
var modExp;
var modCon;
var modSoc;
var modMenu;


//Single PLayer
var widthSingle = 486;
var heightSingle = 455;

//Multi Channel Player
var widthMulti = 798;
var heightMulti = 603;
var videoIDFromSingle;
var playerIDFromSingle;
var playerTypeFromSingle;
var lineupIDFromSingle;
var featuredPlayList;

oThis.initTemplate = function(experienceID) {
    bcExp = brightcove.getExperience(experienceID);
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
    modSoc = bcExp.getModule(APIModules.SOCIAL);
    modMenu = bcExp.getModule(APIModules.MENU);
    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
    if (playerTypeFromSingle == "multi") {
    modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onSetLink);
    modVP.addEventListener(BCVideoEvent.VIDEO_LOAD, onSetLink);
    }
}


oThis.create = function(videoID, playerID, playerType, lineupID) {

  videoIDFromSingle = videoID;
  playerIDFromSingle = playerID;
  playerTypeFromSingle = playerType;
  lineupIDFromSingle = lineupID;

  var py = document.createElement('div');
  py.id = playerContainer;
  document.getElementById('videoscreen').appendChild(py);

  // if video id is passed in the url, generate the line up id on the fly
  if (playerType == 'multi' && videoID != '' && !queryString('lineupID')) {
     getPlaylists(playerID);
  } else if (document.getElementById(playerContainer)) {
     displayPlayer(videoID, playerID,playerType, lineupID);
  }

}

oThis.response = function(jsonData) {
          var items = jsonData["items"];

        for (var i = items.length - 1; i >= 0; i--) {
           for (var j = 0; j < items[i].videoIds.length; j++) {
                if (items[i].videoIds[j] == videoIDFromSingle) {
                  featuredPlayList = items[i].id;
                }
           }
        }
        displayPlayer(videoIDFromSingle, playerIDFromSingle,playerTypeFromSingle, featuredPlayList);
}

oThis.getVideoID = function() {
  return  videoIDFromSingle;
}


/**
*  @private CallBack for BC API
*/

function onTemplateReady(evt) {
}

function onContentLoad(evt) {
     var currentVideo = modVP.getCurrentVideo();
     modCon.getVideoAsynch(currentVideo.id);
     modSoc.setLink(vLink);
}

function onSetLink(evt) {
  if (playerTypeFromSingle == "multi") {
  var vLink = host + "?videoID=" + modVP.getCurrentVideo().id
  } else {
  var vLink = currentPage;
  }
  modSoc.setLink(vLink);
}

/**
*  @private getPlaylists function
*  make player read api call to bc
*/

function getPlaylists(playerID) {
       var token = "Dg0xWzNPf4PPwzVf6e_cGWHq2r6787maLj8KkFRk5CU.";
       var req = "http://api.brightcove.com/services/library?";
       req += "command=find_playlists_for_player_id&token=" + encodeURIComponent(token);  // tokens need to be URL-encoded
       req += "&player_id=" + playerID + "&fields=videoIds,id,name&page_size=10&callback=MAGNET.brightcove.player.response";

        // Create a new request object
        bObj = new JSONscriptRequest(req);
        // Build the dynamic script tag
        bObj.buildScriptTag();
        // Add the script tag to the page
        bObj.addScriptTag();
}


/**
*  @private displayPlayer function
*  create brightcove 3 html embeded codes
*/

function displayPlayer(videoID, playerID,playerType, lineupID) {
  if (playerID) {
        if (playerType == 'single') {
        document.getElementById('videoscreen').style.height = heightSingle + "px";
          document.getElementById('videoscreen').style.width = widthSingle + "px";
          document.getElementById(playerContainer).innerHTML = '<object id="myExperience' + videoID + '" class="BrightcoveExperience"><param name="bgcolor" value="' + bgcolor + '" /><param name="width" value="' + widthSingle + '" /><param name="height" value="' + heightSingle + '" /><param name="playerID" value="' + playerID + '" /><param name="publisherID" value="' + publisherID + '"/><param name="wmode" value="opaque" /><param name="isVid" value="true" /><param name="@videoPlayer" value="' + videoID + '" /><param name="linkBaseURL" value="' + currentPage + '" /></object>';
    } else {
      var videoContent = '';
      videoContent = '<object id="myExperience" class="BrightcoveExperience"><param name="bgcolor" value="' + bgcolor + '" /><param name="width" value="' + widthMulti + '" /><param name="height" value="' + heightMulti + '" /><param name="playerID" value="' + playerID + '" /><param name="publisherID" value="' + publisherID + '"/><param name="wmode" value="opaque" /><param name="isVid" value="true" /><param name="isUI" value="true" /><param name="linkBaseURL" value="' + currentPage + '" />';
          if (lineupID != '') {videoContent += '<param name="@playlistTabs.featured" value="' + lineupID + '" />';}
      if (videoID != '') {videoContent += '<param name="@videoList.featured" value="' + videoID + '" />';}
          videoContent += '</object>';
          document.getElementById(playerContainer).innerHTML = videoContent;
    }
        brightcove.createExperiences();
  }
}

});
// DRAW BC Player//
