/***
*	StationController 0.0.1
*
*	A controller class for the Multimedia Station 
*
*	(c) 2006 Tachometry Corporation.  
*	contact: support@tachometry.com
*
*	Licensed under the Apache License (v. 2.0)
*	http://www.apache.org/licenses/LICENSE-2.0
*/                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
/**
*	Constructor
*/
function StationController( player, playlist )
{
	this.init( player, playlist );
}

/**
*	Initializor
*/ 
StationController.prototype.init = function( player, playlist ) 
{    
	this.player = player;
	this.player_element = "player";
	this.playlist = playlist;
	this.playlist_element = "playlist";
	this.callback = "controller.changeTrack"; // the name of the controller method of linking playlist with player
	this.listen_rate = "5000"; // how often should the listener check status in milliseconds
	this.messages = new Object(); // holds any messages for the user in form "CSS_CLASS"=>"Messaage" (e.g. "error"=>"no available plug-ins")
	// this.message_element = "messages";
	this.message_element = null;
	this.min_clip_length = 60000; // Millisecond value of the minimum length a clip must be to render the playlist. (Allows for short ad clips w/o playlist)
	
	
	//this.cookie_name = "player_pref";
	//this.cookie = new Cookie();
}

StationController.prototype.getPlayer= function()
{
	return this.player;
};

StationController.prototype.setPlayer = function( Player )
{
	this.player = Player;
};

// Returns the playlist, or null if the playlist is not valid
StationController.prototype.getPlaylist= function()
{	if (this.playlist == null)
	{
		return null;
	}	else
	{
		if (typeof this.playlist != "object" || !this.playlist.getList() ) {
			return null;
		}
		return this.playlist;
	}
};

StationController.prototype.setPlaylist = function( Playlist )
{
	this.playlist = Playlist;
};

StationController.prototype.getPlaylistElement= function()
{
	return this.playlist_element;
};

StationController.prototype.setPlaylistElement = function( id )
{
	this.playlist_element = id;
};

StationController.prototype.getPlayerElement= function()
{
	return this.player_element;
};

StationController.prototype.setPlayerElement = function( id )
{
	this.player_element = id;
};

StationController.prototype.getMessageElement= function()
{
	return this.message_element;
};

StationController.prototype.setMessageElement = function( id )
{
	this.message_element = id;
};

StationController.prototype.getCallback= function()
{
	return this.callback;
};

StationController.prototype.setCallback = function( name )
{
	this.callback = name;
};

StationController.prototype.getListenRate= function()
{
	return this.listen_rate;
};

StationController.prototype.setListenRate = function( rate )
{
	this.listen_rate = rate;
};

StationController.prototype.getMinClipLength= function()
{
	return parseInt( this.min_clip_length );
};

StationController.prototype.setMinClipLength = function( mcl )
{
	this.min_clip_length = mcl;
};

StationController.prototype.getMessage = function(name)
{
    return this.messages[name];
};

StationController.prototype.getMessages = function()
{
    return this.messages;
};

StationController.prototype.setMessage = function(name, value)
{
	this.messages[name] = value;
}

StationController.prototype.renderPlaylist = function()
{
	this.getPlaylist().render( this.getPlaylistElement(), this.getCallback() );
};


// Check to make sure that the playlist should be rendered.
// If so, render the playlist and start the stream listener
StationController.prototype.tryRenderPlaylist = function()
{
	// Does the playlist exist?
	if ( this.getPlaylist() != null ) { 
		// Is the clip length longer than the minimum required to render the playlist?
		if ( this.isMinClipLength() ) {
			// clip is long enough.  render the playlist.
			this.renderPlaylist();
			this.startStreamListener(0);
			initScrollLayer();
		}	else {
			// clip is too short. check back later.	
			var clipto = setTimeout("controller.tryRenderPlaylist()", this.getListenRate() ); 
		}
	}	
};


StationController.prototype.renderPlayer = function( )
{
	this.getPlayer().render( this.getPlayerElement() );
};

StationController.prototype.renderMessages = function( )
{
	if ( this.getMessageElement() )
	{
		if ( this.getMessageElement() != "") {
	        document.getElementById( this.getMessageElement() ).innerHTML = this.getMessageTags( );
   		}
	    else {
   	     document.write(this.getMessageTags( ));
   		}
	}
};

StationController.prototype.render = function( )
{
	this.renderMessages();
	this.renderPlayer();
	this.tryRenderPlaylist(); // this method contains the logic and state checking.
};

StationController.prototype.getMessageTags = function()
{
    var msgTags = "";
    for (var msg in this.getMessages()) {
        msgTags += '<div class="' + msg + '">' + this.getMessage(msg) + '</div>';
    }
    if (msgTags == "") {
        msgTags = null;
    }
    return msgTags;
};

StationController.prototype.setPlayerSrc = function( src )
{
	this.getPlayer().setSrc( src );
}; 

/* Retruns the entry index for a given position in milliseconds or -1 if position is out of range */
StationController.prototype.getEntryIndexByPosition = function( position )
{
	var pos = isNaN(position) ? this.getPlayer().getPosition() : parseInt(position);
	var duration = this.getPlayer().getLength();
	if ( pos < 0 || pos > duration  ) {
		return -1;
	} else {
		var start = 0;
		var end = 0; 
		for(i=0; i<this.getPlaylist().getNumEntries(); i++ )
		{
			start = this.getPlaylist().getStartInMillis( i );
			if ( i < (this.getPlaylist().getNumEntries() -1 ) ) { // are there more entries in the list?
				end = (this.getPlaylist().getStartInMillis( i+1 ) - 1 ); // 1 millisecond before the next start
			} else {
				end = duration; 
			}			
			if ( pos >= start && pos <= end ) {
				return ( i );
			}
		}
		return -1; // was not found
	}	
}

/* Checks the current position of the player.  If the index position has changed, update the playlist */
StationController.prototype.startStreamListener = function( cached_index )
{
	try {
		if ( typeof( this.getPlayer() ) == "object" && this.getPlayer().canPlayPause() ) { // protect initial load
			if ( this.hasTrackChanged( cached_index ) ) {
				this.getPlaylist().setCurrentEntryIndex( this.getEntryIndexByPosition() );
				this.renderPlaylist();
			}
		}
	} catch ( ex ) {
		throw new Error("Player is not at a legal state.  Error thrown is: "+ ex );
	}
	this.timer_id = setTimeout("controller.startStreamListener("+ this.getPlaylist().getCurrentEntryIndex() +")", this.getListenRate() ); 
};

StationController.prototype.hasTrackChanged = function( cached_index )
{
	return ( cached_index != this.getEntryIndexByPosition( this.getPlayer().getPosition() ) );
};

/* Call the setPosition on the player */
StationController.prototype.changeTrack = function( index )
{
	// Change the player position
	var position = this.getPlaylist().getMillisFromHMS( this.getPlaylist().getStart( index ) );
	this.getPlayer().setPosition( position );
	
	// Change the playlist
	this.getPlaylist().setCurrentEntryIndex( index );
	this.getPlaylist().render( "playlist", "controller.changeTrack" );
	
	// Start the listener
	this.startStreamListener( index );
};

StationController.prototype.isMinClipLength = function()
{
	return ( this.getMinClipLength() < this.getPlayer().getLength() ); 
}












