var player;
var video, content, exp, menu, ads, social;
var tabBar;

function onTemplateLoaded(pPlayer) {
	trace("templateLoaded");

	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.CONTENT_LOAD, onContentLoad);
	exp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	video.addEventListener(BCVideoEvent.VIDEO_CHANGE, onVideoChange);

}

function onContentLoad(e) { trace(e.type); }

function onTemplateReady(e) {
	trace(e.type);

	tabBar = exp.getElementByID("playlistTabs");
	updateLink(video.getCurrentVideo().id, tabBar.getSelectedData().id);

}


function onVideoChange(e) {
	trace(e.type);

	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, tabBar.getSelectedData().id);

	}

}

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. If your application is setup
	// in another format, such as Actionsript, 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 playlistKey = "bclid";
	var videoKey = "bctid";


	var currentLink = social.getLink();
	trace("Original Link: " + currentLink);

	// Get the current URL and remove any existing URL parameter
	if(currentLink.indexOf("?") != -1) {
		currentLink = currentLink.substring(0,currentLink.indexOf("?"));
	}

	var newLink = currentLink + "?" + playlistKey + "=" + playlistId + "&" + videoKey + "=" + videoId;
	trace("New Link: " + newLink);
	social.setLink(newLink);

}