/* Player Interface */

var firstVideo = true;
var bcp;
var mPlayer;
var mExp;
var mContent; 
var playlistTabs;
    
// called when template loads, we use this to store a reference to the player and modules
// and add event listeners for the video load (when the user clicks on a video)
function onTemplateLoaded(expId) {
    bcp = brightcove.getExperience(expId);
   
    mExp = bcp.getModule(APIModules.EXPERIENCE);
    mPlayer = bcp.getModule(APIModules.VIDEO_PLAYER);
    mContent = bcp.getModule(APIModules.CONTENT);
    playlistTabs = mExp.getElementByID('playlistTabs');

    mContent.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad); 
    mExp.addEventListener('contentLoad', onContentLoad);

    mPlayer.addEventListener('videoStart', onVideoStart);
}

function onVideoStart(event) {
    if (firstVideo) {
        firstVideo = false;
    } else {
        Sundance.tracking.flashAction(getTrackDir(), 'watch', 1);
    } 
}

function onContentLoad(event) {
    if (playlist != '') {
        showPlaylist(playlist);
    }

}

function onVideoLoad(event) {
    mPlayer.loadVideo(event.video.id);
}

function playVideo(id) {
    mContent.getVideoAsynch(id);
}

function showPlaylist(id) {
    var i;    
    var data = playlistTabs.getData();

    for (i in data) {
        if (id == data[i].id) {
           playlistTabs.setSelectedIndex(i);
           mContent.getVideoAsynch(data[i].videoIds[0]); // play first video in selected playlist 
         }
    }

}

function getTrackDir() {
    var url = location.href.substring(7);
    url = url.substring(url.indexOf('/'));

    if (url[url.length - 1] == '/') {
        url = url.substring(0, url.length - 1);
    }


    return url;
}
