// set file up to run as an include, this will make life easier for other
// brightcove players that need deeplinking abilities.

// global brightcove VARS
var player;
var video, content, exp, menu, ads, social;
var playlist;

function onTemplateLoaded(pPlayer) {
	// called by brightcove player once it has loaded.
	// using this to set all vars and add event listeners.
	
	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) {
	// fires when template is ready.
	playlist = content.getAllMediaCollectionIDs("playlist");
	updateLink(video.getCurrentVideo().id, playlist);
}

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, playlist);
	}
}

function updateLink(videoId, playlistId) {
	// Brightcove players published using the standard JavaScript publishing code 
	// automatically listen for bclid and bctid in order to select featured items. 
				
	var playlistKey = "bclid";
	var videoKey = "bctid";
	var newLink = "";
	
	// Get the current URL and remove any existing URL parameters from the search.
	if(window.location.search.length > 0) {
		newLink = window.location.href.substring(0,window.location.href.indexOf("?"));
	}else{
		newLink = window.location.href;
	}
	
	// sets/overwrites the link values in the brightcove player for any link backs (ie getlink, getcode, etc.)
	social.setLink(newLink + "?" + playlistKey + "=" + playlistId + "&" + videoKey + "=" + videoId);
}
