/**
 * This file handles the external Ad Integration with the Brightcove Player.
 * 
 * @author Jesse Streb
 */

var player = null;
var experience = null;
var adModule = null;

/**
 * An event fired by the Brightcove Player.  Since we have a custom ad integration we register the correct ad formats.
 * @param {Object} message
 */
 function onTemplateLoaded(pId) 
 {
 	player = brightcove.getExperience(pId);
 	experience = player.getModule(APIModules.EXPERIENCE);
 	
    experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoaded);
    
    adModule = player.getModule(APIModules.ADVERTISING);
    adModule.enableAdFormats(0, 2, 14);
}

/*
 * onContentLoaded is a function fired by the player when the content is ready to interacted with.
 */
function onContentLoaded() 
{
    adModule.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
}

/*
 *  Once the player has finished loading we can then interact with the player to enable external ads.
 *  If this is not turned on then our player would simply skip the ad since it would not know how to
 *  handle the ad.
 */
function onTemplateReady() 
{
    try 
	{
        adModule.enableExternalAds(true);
    } catch (e) 
	{
		//gulp
    }
}

/************************************************************************************
 * Functions to handle the custom ad integration
 ************************************************************************************/

/*
 * The onExternalAd function is called by player when it doesn't understand how to playback an ad.
 * In this case this is we create the external ad object and then call into it to get the ad object 
 * to show in the player and then handle the external ad code.  We also include this in a try catch
 * so that if anything goes wrong we can resume the playback of the video.  This is because once the 
 * player calls into external ad we need to either call showAd or resumeAfterExternalAd otherwise
 * the player will hang.
 */

function onExternalAd(pXML) {
    try {
        var externalAd = new External_Ad(pXML.ad);
        var ad = externalAd.getPlayerAd();
        adModule.showAd(externalAd.getPlayerAd());
        if(externalAd.getExpandedAd() != "") document.getElementById('300x250').innerHTML = externalAd.getExpandedAd();
    
    } catch (e) {
        adModule.resumeAfterExternalAd();
    }
}

