﻿var player;
var video, content, exp, menu, ads, social;
var tabBar;

function onTemplateLoaded(pPlayer) {

    player = bcPlayer.getPlayer(pPlayer);

    video = player.getModule(APIModules.VIDEO_PLAYER);
    content = player.getModule(APIModules.CONTENT);
    exp = player.getModule(APIModules.EXPERIENCE);
    menu = player.getModule(APIModules.MENU);
    ads = player.getModule(APIModules.ADVERTISING);
    social = player.getModule(APIModules.SOCIAL);


    exp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    video.addEventListener(BCMediaEvent.CHANGE, onMediaChange);

}

function onTemplateReady(e) {

    tabBar = exp.getElementByID("playlistTabs");
    updateLink(video.getCurrentVideo().id, video.getCurrentVideo().displayName, tabBar.getSelectedData().id);

}

function onMediaChange(e) {

    if (exp.getReady()) { // If template is Ready

        // Because TemplateReady has already fired we can now access the
        // currentVideo and currentPlaylist from the tabBar module

        updateLink(video.getCurrentVideo().id, video.getCurrentVideo().displayName, tabBar.getSelectedData().id);

    }

}

function updateLink(videoId, videoName, playlistId) {

    // Brightcove players published using the standard JavaScript publishing code 
    // automatically listen for bclid and bctid in order to select featured items. 
    // If your application is setup in another format, such as ActionScript, you can
    // choose to alter these key names to something compatible with your application.
    // Your application will be responsible for properly setting the featured content.
    var encodedName = videoName.replace(/[^a-zA-Z0-9]/g, '');
    var newLink = baseURL + '/' + encodedName + '/' + playlistId + '/' + videoId;
    social.setLink(newLink);
}