/* *** LISTEN FOR EVENTS *** */

c=null; //used for scrolling the carousel back once the playlist is completed

/* the player is now ready */
function playerReady(thePlayer) 
{
	player = document.getElementById(thePlayer.id);
	addListeners();
}

/* listen for events from the flash player */
function addListeners() 
{
	if (player) 
	{
		player.addModelListener("STATE", "stateListener");
	}
	else
	{
		setTimeout("addListeners()",500);
	}
}

//IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
function stateListener(obj) 
{
	currentState = obj.newstate; 
	previousState = obj.oldstate; 
	
   	if (currentState ==  "PLAYING") 
   	{
    	if(currentlyShowing == 'content')
    	{
      		lasKeys = contentArray[currentVideoIndex].Keywords;
           
           	if (lasKeys!=oldKeys)
            {
            	oldKeys=lasKeys; 
              	enviaDatos(lasKeys);
            }
      	}//final content
    
    	if(currentlyShowing == 'search')
    	{
    		lasKeys = searchContentArray[currentVideoIndex].Keywords;
   
            if (lasKeys!=oldKeys)
            {
            	oldKeys=lasKeys; 
              	enviaDatos(lasKeys);
            }
   		}//final search
    }

	if ((currentState == "IDLE")&&(previousState == "PLAYING")) 
	{
		//Lets do a timestamp check, in firefox the completed state fires twice.
		//so we check we are not the second event by skipping if we're a complete event in less than 5 seconds.
		var newD = new Date();
		var timestamp =  newD.getTime();
	
		timestamp = (timestamp - savedTimestamp);
		
		if(timestamp > 5000)
		{
			savedTimestamp = newD.getTime();
			//video has completed.
			videoPlayer_IsAutoStart = true;
			currentVideoIndex = currentVideoIndex +1;
			var contentLength = 0;
			
			if(currentlyShowing == 'content')
			{
				contentLength = contentArray.length;
			}
			
			if(currentlyShowing == 'search')
			{
				contentLength = searchContentArray.length;
			}
			
			if(currentVideoIndex >= contentLength)
			{
				//restarting the playlist, have we come to the end of the current playlist?
				currentVideoIndex = 0; // restart the playlist.
				playVideo(0, currentlyShowing);
					
      			c.scroll(1);    //restart the carousel

			}// end final de currentVideoIndex >= contentLength
			playVideo(currentVideoIndex, currentlyShowing);
		}
	}
}
