function playerReady(p){
	var player = window.document[p.id];
	if (player)
	{
		var list = $(player).parents('[icobalt=CobaltControls.Controls.VideoList]:first'),
			flashvars = list.find(".buildflash[_flashvars]").attr('_flashvars'),
			m = flashvars && /streamer=([^&]+)/.exec( flashvars ),
			rtmp = m && m[1];

		list.find('[_video]')
				.data('player',player)
				.data('list',list)
				.addClass('vl-video')
				.click(function(e){
					var item = $(this);
					if ( item.is('.active') ) {
						return;
					}
					var player = item.data('player');
					var list = item.data('list');
					var video = item.attr('_video');
					var image = item.attr('_image');
					if (player && video)
					{
						if ( !rtmp && video.substr(0,1) != '/' && video.substr(0,4) != 'http' && video.substr(0,4) != 'rtmp' ) {
							video = '/' + video;
						}
						player.sendEvent('STOP');

						if ( image ) {
							if ( !image.startsWith('/') && !image.startsWith('http') ) {
								image = '/' + image;
							}
						}
						player.sendEvent('LOAD', {
							streamer: rtmp || null,
							image: image || null,
							file: video
						});
						list.find('.playing').removeClass('playing');
						list.find('.active').removeClass('active');
						item.addClass('active');

						// Fire the video load event.
						var evt = {
							type: 'videoload',
							state: video
						};
						list.trigger(evt);

						if ( !$.toBool( list.attr('_loadonclick') ) ) {
							item.addClass('playing');
							player.sendEvent('PLAY');
						}
					}
				});

		// Bind the state change event.
		player.addModelListener( 'STATE', 'jwStateChange' );

		// Activate the first video and autoplay it if necessary.
		var first = list.find('.vl-video:first').addClass('active');
		if ( $.toBool( list.attr('_autoplay') ) ) {
			first.click();
		}
	}
}


// Play the next video when the previous is done.
function jwStateChange( obj ) {
	var player;
	if ( obj && 
		 obj.id && 
		 obj.oldstate &&
		 obj.newstate && 
		 (player = window.document[obj.id]) ) {

		// Trigger any special event.
		var list = $(player).parents('[icobalt=CobaltControls.Controls.VideoList]:first');
		var evt = {
			type: 'statechange',
			state: obj
		};
		list.trigger(evt);

		// If the event has been killed, stop here.
		if ( evt.isImmediatePropagationStopped() ) {
			return;
		}

		// Get the video list.
		if ( obj.oldstate === 'PLAYING' && 
			 obj.newstate === 'COMPLETED' && 
			 $.toBool( list.attr('_cascade') ) ) {

			var items = list.find('.vl-video');
			var active = items.filter('.active');

			// Find the next video and click on it.
			var pos = items.index(active) + 1;
			if ( pos < items.length ) {
				setTimeout(function(video){
					return function(){
						video.click().scrollIntoView();
						video = null;
					};
				}( items.eq(pos) ), 1);
			}
		}
	}
}
