/**
 Austereo Now Playing Functionality
 CHANGELOG:
 20091102 - Born.
 20100625 - Added function to handle Ooyala events
 **/

var nextVideoInPlaylistUrl = '';
var autoplay = false;

/*
 Do Nielson Impression
 */
function refreshSession() {
    FD.doNielsonImpression(location.href);
}

/** ------------------------------ These methods are used by Brightcove Video Player ------------------------------ **/

function onVideoPlay(event) {
    this.refreshSession();
}

function onVideoStop(event) {
    this.refreshSession();
    if (autoList != undefined && autoList.length > 0) {
        var player = document.getElementById("featurePlayer");
        var currentEmbedCode = player.getEmbedCode();
        for (var i = 0; i < autoList.length - 1; i++) {
            if (autoList[i] == currentEmbedCode) {
                var newEmbedCode = autoList[i+1];
                player.setEmbedCode(newEmbedCode);
                autoplay = true;
            }
        }
    } else if (nextVideoInPlaylistUrl != '') {
        window.location = nextVideoInPlaylistUrl;
    }
}

/*
 Note: onTemplateLoaded is a Brightcove method that gets called when the video loaded is on the page.
 We override this method with our own to listen for play and stop methods.
 Refer to this API: http://support.brightcove.com/en/docs/player-api-mediaevents
 */
function onTemplateLoaded(experienceID) {
    try {
        //Brightcove3
        player = bcPlayer.getPlayer(experienceID);
        video = player.getModule(APIModules.VIDEO_PLAYER);
        video.addEventListener(BCMediaEvent.PLAY, onVideoPlay);
        video.addEventListener(BCMediaEvent.STOP, onVideoStop);
    } catch (e) {
        //Brightcove2
        addBrightcove2Events();
    }
}

function addBrightcove2Events() {
    try {
        callFlash("addEventListener", "streamStart", "onVideoPlay");
        callFlash("addEventListener", "mediaStop", "onVideoStop");
    } catch (e) {
        //error with Brightcove 2 video.
    }
}

/** ------------------------------ These methods are used by Ooyala Video Player ------------------------------ **/

/*
* Function to handle Ooyala Play Events.
* Note: The Media Player, Now Playing Player and DAB Player javascripts will need to have this function defined.
*/
function receiveOoyalaEvent(playerId, eventName, eventArgs) {
    if (eventName == "stateChanged") {
        //make nielson impression when video starts playing
        if (eventArgs.state == "playing") {
            onVideoPlay();
        }
    }
    if (eventName == "playComplete") {
            onVideoStop();
    }
    if (eventName == "apiReady") {
        var player = document.getElementById(playerId);
        if (autoplay) {
            player.playMovie();
        }
    }
}
