//*************************************************************
//					   jw player functions
//*************************************************************
/*================================================//
//NAME: initPlayer
//This function executes once all of the DOM elements have loaded
//variables,dependencies & why: none
//functions used & why: none
//================================================*/
function initPlayer(){
    createPlayer(); //create the player
}

//used to get how long they've been listening to the same song
//timeOnSiteCounter=setInterval("updateTimeOnSiteCounter();",1000);
var durationOfSecondsPlayed=0;
var percentOfSongListenedTo=0;
var percentOfSkippedListenedTo=0;

var setListenedToStat=false;
var vkfm_currentplayer_trackID;


/*================================================//
//NAME: playerReady
//This function executes once all of the DOM elements have loaded
//variables,dependencies & why: none
//functions used & why: none
//================================================*/
function playerReady(thePlayer) { 
	//player = window.document[thePlayer.id];
	vkfm_player = window.document[thePlayer.id];
	addListeners(); //add js listeners
	setPlayerNotLoadMessage('no tracks selected');
}

/*================================================//
//NAME: createPlayer
//This function executes once all of the DOM elements have loaded
//variables,dependencies & why: none
//functions used & why: none
//================================================*/
function createPlayer(){
    
    deletePlayer();
    
    var flashvars = {
       file:"", 
       autostart:"false",      
       shuffle:"false", 
       playlist:"none", //bottom   
       controlbar:"none",  //bottom
       repeat:"list",
       plugins:"spectrumvisualizer-1"
       //,plugins:"revolt-1"
       
   }
   var params = {
	allowfullscreen:"true", 
	allowscriptaccess:"always"
   }
   var attributes = {
	id:"vokoPlayer",
	name:"vokoPlayer"
   }
//   swfobject.embedSWF("/lib/app/controller/jwplayer_javascript_controller/player.swf", "vkfm_playerPlaceHolder", "100%", "100%", "9.0.115", false, flashvars, params, attributes);
   swfobject.embedSWF("http://c1245162.cdn.cloudfiles.rackspacecloud.com/player.swf", "vkfm_playerPlaceHolder", "100%", "100%", "9.0.115", false, flashvars, params, attributes);

}

/*================================================//
//NAME: deletePlayer
//This function executes once all of the DOM elements have loaded
//variables,dependencies & why: none
//functions used & why: none
//================================================*/
function deletePlayer() { 
    swfobject.removeSWF("vokoPlayer");
    var tmp=document.getElementById("vkfm_playerPlaceHolder");
    if (tmp) { tmp.innerHTML = "<div id=\"vkfm_playerPlaceHolder\">.</div>"; }
}

/*================================================//
//NAME: loadPlaylist
//This function executes once all of the DOM elements have loaded
//variables,dependencies & why: none
//functions used & why: none
//================================================*/ 
function loadPlaylist(startIndex,newPlaylist,autostart)
{
	resetDurationCounter();

	previousItem = currentItem;
	currentItem = startIndex;

	if(vkfm_player!=null){
	   	vkfm_player.sendEvent('LOAD', newPlaylist);
		vkfm_player.sendEvent('ITEM', startIndex);
		if(autostart){
			vkfm_player.sendEvent('PLAY');
		}
		else{
			vkfm_player.sendEvent('STOP', startIndex);
		}
		//getPlaylistData();
		
		//set playlist to json playlist
		vkfm_playlistQueue.items=newPlaylist;
		//display it
		setTrackInformation(startIndex);
		
		
		removePlayerNotLoadMessage();
		
		return true;
	}
	else{
		return false;
	}   
}

function setTrackInformation(index){
	if(vkfm_player!=null){
		printItemData(index);
	}
}

function printItemData(theIndex) {
	var plst = null;
	if(vkfm_player!=null){
		plst = vkfm_player.getPlaylist();
	}
    
	if (plst) { 
//		setVokoderPlayerInformation(trackid,playingIndex,author,authorname,tracktitle,trackname)		
		setVokoderPlayerInformation( plst[theIndex].trackid, (theIndex+1) ,plst[theIndex].artist ,plst[theIndex].artistname ,plst[theIndex].title ,plst[theIndex].trackname);	
		
		vkfm_currentplayer_trackID = plst[theIndex].trackid;	
	}
}

// *********************************************************************************
// *********************************  LISTENERS  **********************************
// *********************************************************************************

function addListeners() {
	if (vkfm_player) {
                   
    vkfm_player.addControllerListener("ITEM", "itemListener"); //{index,id,client,version}. 
    vkfm_player.addControllerListener("MUTE", " muteListener"); //{state,id,client,version}. 
	vkfm_player.addViewListener("NEXT", "nextListener"); //{state,id,client,version}. 
//    vkfm_player.addControllerListener("PLAY", "doNothing"); //{state,id,client,version}. 
//    vkfm_player.addControllerListener("PLAYLIST", "doNothing"); //{playlist,id,client,version}. 
//    vkfm_player.addControllerListener("QUALITY", "doNothing"); //{state,id,client,version}. 
//    vkfm_player.addControllerListener("RESIZE", "doNothing"); //{fullscreen,height,width,id,client,version}. 
//    vkfm_player.addControllerListener("SEEK", "positionListener"); //{position,id,client,version}. 
//    vkfm_player.addControllerListener("STOP", "doNothing"); //{id,client,version}. 
    vkfm_player.addControllerListener("VOLUME", "volumeListener"); //{percentage,id,client,version}. 

// Model Listeners
//    vkfm_player.addModelListener("BUFFER", "doNothing"); //{percentage,id,client,version}. 
    vkfm_player.addModelListener("ERROR", "errorListener"); //{message,id,client,version}. 
    vkfm_player.addModelListener("LOADED", "loadedListener"); //{loaded,total,offset,id,client,version}. 
//    vkfm_player.addModelListener("META", "doNothing"); //{variable1,variable2,variable3,...,id,client,version}. 
    vkfm_player.addModelListener("STATE", "stateListener");//{newstate,oldstate,id,client,version}. 
    vkfm_player.addModelListener("TIME", "positionListener"); //{position,duration,id,client,version}. 

// View Listeners
//    vkfm_player.addViewListener("FULLSCREEN", "doNothing"); //{state,id,client,version}. 
//    vkfm_player.addViewListener("LINK", "doNothing"); //{index,id,client,version}. 
//    vkfm_player.addViewListener("LOAD", "doNothing"); //{object,id,client,version}. 
//    vkfm_player.addViewListener("MUTE", "doNothing"); //{state,id,client,version}. 
//    vkfm_player.addViewListener("NEXT", "doNothing"); //{id,client,version}. 
    vkfm_player.addViewListener("ITEM", "doNothing"); //{index,id,client,version}. 
//    vkfm_player.addViewListener("PLAY", "doNothing"); //{state,id,client,version}.
//    vkfm_player.addViewListener("PREV", "doNothing"); //{id,client,version}. 
//    vkfm_player.addViewListener("QUALITY", "doNothing"); //{state,id,client,version}. 
//    vkfm_player.addViewListener("RESIZE", "doNothing"); //{height,width,id,client,version}.  
//    vkfm_player.addViewListener("SEEK", "doNothing"); //{position,id,client,version}.
//    vkfm_player.addViewListener("STOP", "doNothing"); //{id,client,version}. 
//    vkfm_player.addViewListener("VOLUME", "volumeListener"); //{position,id,client,version}.e.		
		
	} 
	else {
		setTimeout("addListeners()",150);
	}
}

function errorListener(obj) { 
	//set the error message container html
	if(errorMessage!=""){
		setVokoderPlayerErrorDiv("<span style='text-decoration:blink; color:#f90;'>"+errorMessage+"</span>");
	}
	else{
		setVokoderPlayerErrorDiv('');
	}
}


function positionListener(obj) { 
//	setCorrectionPlayerMode();
	

	currentPosition = Math.floor(obj.position);  
	listenTo=currentPosition;
    var duration = Math.floor(obj.duration);
	
	//calculate listened to percentage
	percentOfSongListenedTo = (currentPosition/duration);
	percentOfSkippedListenedTo = (currentPosition/duration);
	                 
	//display total time
	totalMins=Math.floor(duration/60);  
	if(totalMins<1){
		totalMins=0;
	}
	totalSecs=Math.floor(duration%60);      
	if(totalSecs<1){
		totalSecs='00';
	}                  
	else if(totalSecs<10){
		totalSecs='0'+totalSecs;
	}
	setPlayerTotalTimeMessage(totalMins+':'+totalSecs);
	
	//display current time
	curMins=Math.floor(currentPosition/60);  
	if(curMins<1){
		curMins=0;
	}
	curSecs=Math.floor(currentPosition%60);      
	if(curSecs<1){
		curSecs='00';
	}                  
	else if(curSecs<10){
		curSecs='0'+curSecs;
	}
	setPlayerCurrentTimeMessage(curMins+':'+curSecs);
	
	//update the slider
	$('#vkfm_playerSlider').slider( 'value' , currentPosition );
	$('#vkfm_playerSlider').slider( 'option' , 'max' , duration );
}



function nextListener(obj) { 
	resetDurationCounter();

	if (vkfm_player) {		
		plst = vkfm_player.getPlaylist();
		updateTrackListenedToCount(vkfm_currentplayer_trackID,percentOfSkippedListenedTo);
		percentOfSkippedListenedTo=0;
	}
}

function loadedListener(obj) { 
	currentLoaded = obj.loaded; 
	currentRemain = obj.total - currentLoaded;
	
	perecentLoaded = (obj.loaded/obj.total)*100;
	
	if(perecentLoaded<95){
		$('#vkfm_playerLoadedStatus').html(' - '+parseInt(perecentLoaded)+'% loaded');
	}
	else{
		$('#vkfm_playerLoadedStatus').html('');
	}
}

function volumeListener(obj) { 
	currentVolume = obj.percentage;   
	$('#vkfm_playerVolLevel').html(currentVolume+'%');
    //var tmp = document.getElementById("volumeSliderText");
    //if (tmp) { tmp.innerHTML = "Volume " + currentVolume + "%"; }
}      


function muteListener(obj) { 
//     
	if(obj.state){
		$('.tpUnmute').html('un-mute');
	}                                  
	else{
		$('.tpUnmute').html('');
	}
}


function itemListener(obj) { 
	
	if (obj.index != currentItem) {
 		previousItem = currentItem;
		currentItem = obj.index;
		
		setTrackInformation(currentItem);
		resetDurationCounter();
		
		setListenedToStat=false;
	}
}


function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentPlayerState = obj.newstate;
	currentState = obj.newstate; 
	previousState = obj.oldstate;  
	
	playerGlobalState=currentState;
	

	//if player is not playing don't increment playing timer	
	if(currentState!="PLAYING"){
		//stop the listened to seconds counter
		clearInterval(durationTimer);	
	}
	
	if(currentState=="PLAYING"){
		//set keep count of how many seconds listened
		durationTimer=setInterval("updateDurationCounter();",1000);
		$('#vkfm_playerPlayPauseButton').removeClass('vkfm_playerPlayButton');
		$('#vkfm_playerPlayPauseButton').addClass('vkfm_playerPauseButton');
		setPlayerStatusMessage('');	
	}
	else if(currentState=="BUFFERING"){

		setPlayerStatusMessage("<span style='text-decoration:blink; color:#66ff00;'> "+currentState+"</span>");	
	}
	else if(currentState=="PAUSED"){
		$('#vkfm_playerPlayPauseButton').removeClass('vkfm_playerPauseButton');
		$('#vkfm_playerPlayPauseButton').addClass('vkfm_playerPlayButton');
		setPlayerStatusMessage("<span style='text-decoration:blink; color:#663300;'> "+currentState+"</span>");
	}
	else{
		setPlayerStatusMessage(' '+currentState);	
	}
}
/*================================================//
//NAME: stateListener
//This function executes once all of the DOM elements have loaded
//variables,dependencies & why: none
//functions used & why: none
//================================================*/ 

function updateDurationCounter(){
	durationOfSecondsPlayed++;
	
	//document.title='number of seconds listened to current song: '+durationOfSecondsPlayed+' which is '+(percentOfSongListenedTo*100)+'%';
	
	if((percentOfSongListenedTo*100)>80 && setListenedToStat==false){
		updateTrackListenedToCount(vkfm_currentplayer_trackID,percentOfSongListenedTo);
		setListenedToStat=true;
	}
}
function resetDurationCounter(){
	durationOfSecondsPlayed=0;
	percentOfSongListenedTo=0;
}

// ********************************************************

function addSong(changeIndex,newSongs){                                         
	for(var i = 0; i<newSongs.length; i++){
		currentPlaylist.splice(changeIndex,0,newSongs[i]);     
	}
}

function addSongToPlaylistQueue(changeIndex,newSong){                                         
	playlistQueue.items.splice(changeIndex,0,newSong);
	loadPlaylist(0,playlistQueue.items,false);
	setNowPlayingHTML();
}

function removeSong(index)
{
	currentPlaylist.splice(index,1);
}

function moveSong(oldIndex,newIndex)
{
	var song = currentPlaylist.slice(oldIndex,1);
	var array = new Array();
	array[0] = song;
	removeSong(oldIndex);
	addSong(newIndex,array);
}     