var bcExp; //brightcove experience
var modVP; //video player module
//var modAP; //Audio player module. Not used
var modExp; //brightcove experience module
var modCon; //Content module
//var modMenu; //Menu module. Not used
var expID; //ID of the experience, player, googlePreview, welcomePlayer
var startedAt; // position when the video starts / when a new calulation has been made.
var timePlayed = 0; // var used to calculate the duration that has passed from startedAt to the current position.

//function to create a player. currently playerID is ignored and we use one player for all.
/**
* playerID ID of the player to play videos
* videoID Id of video to be loaded into the player
* containerDIV container div for the player.
* playerContainerID ID of the object element that contains player.
*/
function createFlashPlayer(playerID, videoID, containerDiv, playerContainerID){
	playerID = "1042515689001";
	var params = {};
	params.playerID =  playerID;
	params.videoId = videoID;
	params.isVid = "true"; // conent is video.
	params.isUI = "true"; // needed for chromeless players
	params.bgcolor = "#000000";
	params.wmode = "transparent"; // to make sure we can show html element above the player.
	params.autoStart = "true"; // we want to autostart content
  
	var player = brightcove.createElement("object");
	player.id = playerContainerID;
	var parameter;
	for (var i in params) {
		 parameter = brightcove.createElement("param");
		 parameter.name = i;
		 parameter.value = params[i];
		 player.appendChild(parameter);
	}
	
	var playerContainer = document.getElementById(containerDiv);
	brightcove.createExperience(player, playerContainer, true); // create the 'experience'
}
	
// when the templade has been loaded
function onTemplateLoaded(experienceID) {
	expID = experienceID;
	bcExp = brightcove.getExperience(experienceID);
     	 
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);

	//modAP = bcExp.getModule(APIModules.AUDIO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
	//modMenu = bcExp.getModule(APIModules.MENU);

  
    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
    modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad); 
	
	modVP.addEventListener(BCMediaEvent.PLAY, onVideoPlay); // playback has started
	modVP.addEventListener(BCMediaEvent.STOP, onVideoStop); // video has stopped / paused
	modVP.addEventListener(BCMediaEvent.COMPLETE, onVideoComplete);
	modVP.addEventListener(BCMediaEvent.PROGRESS, onVideoProgress);
	
	//modVP.addEventListener(BCMediaEvent.SEEK, onVideoSeek);
	modVP.addEventListener(BCMediaEvent.BUFFER_BEGIN, onMediaBufferBegin); // video buffering has started
	modVP.addEventListener(BCMediaEvent.BUFFER_COMPLETE, onMediaBufferComplete); //video buffering has been completed
	
	//modVP.setRenditionSelectionCallback(selectBestRendition);
	
	//The following code is not needed since we removed it in the brightcove player.
	//Code to remove the overlay that happens when the video is paused. Also to remove the menu when a video has completed.
	/*modMenu.addEventListener(BCMenuEvent.MENU_PAGE_OPEN, onMenuPageOpen);
	modMenu.addEventListener(BCMenuEvent.OVERLAY_MENU_OPEN, onMenuOverlayOpen);
	modMenu.addEventListener(BCMenuEvent.OVERLAY_MENU_PLAY_CLICK, onMenuOverlayClick);*/
}

var checkTimeLeftTimer = null; // timer used to update  

/*function selectBestRendition(content) {
    var renditions = content.renditions;

	var size = 0;
	var returnIndex = 0;
	for (var i = 0; i < renditions.length; i++) {
		if(renditions[i].size > size){
			size = renditions[i].size;
			returnIndex = i;
		}
	}
	return returnIndex;
}*/

//function to start a 10 sec timer to update time played.
function checkTimeleft(){
	checkTimeLeftTimer = setTimeout(function (){
		if(AMOSTV.currView === "Play" && modVP.isPlaying()){
			timePlayed = (modVP.getVideoPosition() - startedAt);
			AMOSTV.views[AMOSTV.currView].updateAmosPlayTimeLeft(timePlayed);
			startedAt = modVP.getVideoPosition();
			this.checkTimeleft();
		}
	}.bind(this),10000);
}

//video startplay
function onVideoPlay(evt){

	// IE9 Hacks
	if(expID === 'googlePreview'){
		$('googlePreview').setStyle({
		width: '547px',
		height: '308px'
		});
	}
	if(expID ==='welcomePlayer'){
		$('welcomePlayer').setStyle({
			width: '627px',
			height: '399px'
		});
	}
	// End IE9 Hacks


	if(expID === 'player'){
		//modMenu.closeMenuPage();
		startedAt = evt.position;
		clearTimeout(checkTimeLeftTimer);
		checkTimeleft();
	}
}

//video stop/pause
function onVideoStop(evt){
	
	if(expID === 'player'){
		clearTimeout(checkTimeLeftTimer);
		timePlayed = (evt.position - startedAt);
		AMOSTV.views[AMOSTV.currView].updateAmosPlayTimeLeft(timePlayed);
	}
}

//buffering start
function onMediaBufferBegin(event){
	if(expID === 'player' && event.position > 0){
		clearTimeout(checkTimeLeftTimer);
		timePlayed = (evt.position - startedAt);
		AMOSTV.views[AMOSTV.currView].updateAmosPlayTimeLeft(timePlayed);
	}
}

//buffering completes
function onMediaBufferComplete(event){
	if(expID === 'player'){
		//modMenu.closeMenuPage();
		startedAt = evt.position;
		clearTimeout(checkTimeLeftTimer);
		checkTimeleft();
	}
	
	if(expID == 'welcomePlayer' || expID == 'googlePreview'){
		AMOSTV.stopLoading();
	} 
}

//function to rescale the vpreviewarea and show the preview done overlay
function previewDone(){
	$('googlePreview').setStyle({
		width: '547px',
		height: '308px'
	});
	$('previewVideoArea').className = 'previewDone';
	$('previewOverlay').show();
}

// video completes playback
function onVideoComplete(evt){
	//console.log('DEBUG: onVideoComplete')
	//console.log(evt);
	if(expID === 'player'){
		AMOSTV.views[AMOSTV.currView].playNextVideo();
		//AMOSTV.views[AMOSTV.currView].bcLoadVideo();
	} else if(expID === 'welcomePlayer'){
		brightcove.removeExperience("welcomePlayer");
            AMOSTV.loadView('Menu');
            AMOSTV.currView = null;
            AMOSTV.loadView('viewingOptions');
            VIEWS.viewingOptions.show();
			AMOSTV.loadView('Menu');
	} else if(expID === 'googlePreview'){
		previewDone();
	}
}

//event that happens on video time progress
function onVideoProgress(evt){
	if(expID === 'googlePreview'){
		if(evt.position > 60){
			modVP.pause(true);
			previewDone();
		}
	}
}

function onVideoSeek(evt){
	//don't need to do anything here, stop event fixes the timePlayed value
}

function onTemplateReady(evt) {
}
	
function onContentLoad(evt) {
	var currentVideo = modVP.getCurrentVideo();  
	modCon.getMediaAsynch(currentVideo.id);
}

function onVideoLoad(evt) {
   if(expID === 'player'){
		AMOSTV.views[AMOSTV.currView].loadNextVideo();
		AMOSTV.stopLoading();
	}
	
	/*
	if(expID === 'googlePreview'){
		//modVP.loadVideo(evt.video.id);
	} else if(expID === 'player'){
		AMOSTV.views[AMOSTV.currView].bcLoadVideo();
		//AMOSTV.views[AMOSTV.currView].loadNextVideo();
	} else if(expID === 'welcomePlayer'){
		//modVP.loadVideo(evt.video.id); 
	}*/
}

function onMediaError(event){
}

function onMenuPageOpen(){
	modMenu.closeMenuPage();
}

function onMenuOverlayOpen(){
	modMenu.setOverlayMenuVisible(false);
}


