$(document).ready(function(i){
	$("[icobalt='CobaltControls.Controls.VideoList'] div[icobalt='CobaltControls.Controls.VideoPlayer']").each(function(i){
		var div = $(this);
		if ( div.data('swf') ) {
			VideoListReady.apply(this,[]);
		} else {
			div.bind('swfready', VideoListReady);
		}
	});
});

// Set up the video list once the player is ready.
function VideoListReady(e){
	var div = $(this),
		player = div.data('swf'),
		list = div.closest("[icobalt='CobaltControls.Controls.VideoList']"),
		flashvars = div.attr('_flashvars'),
		m = flashvars && /streamer=([^&]+)/.exec( flashvars ),
		rtmp = m && m[1];

	if ( player ) {
		list.find('[_video]')
			.data('player',player)
			.data('list',list)
			.data('rtmp',rtmp)
			.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 rtmp = item.data('rtmp');
				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).closest('[icobalt=CobaltControls.Controls.VideoList]');
		var evt = $.Event('statechange');
		evt.state = obj;
		list.trigger(evt);

		// If the event has been killed, stop here.
		if ( evt.isImmediatePropagationStopped() ) {
			return;
		}

		// Get the video list.
		if ( obj.newstate === 'COMPLETED' && 
			 obj.newstate !== obj.oldstate &&
			 $.toBool( list.attr('_cascade') ) ) {

			var video, event,
				items = list.find('.vl-video'),
				active = items.filter('.active'),
				pos = items.index(active) + 1;

			// If we reach the end, wrap around to the beginning.
			if ( pos >= items.length && $.toBool( list.attr('_replay') ) ) {
				pos = 0;
			}

			video = items.eq(pos);
			if ( !video.length ) {
				return;
			}

			// Trigger the autoadvance event.
			evt = $.Event('autoadvance');
			evt.state = obj;
			evt.position = {
				index: pos,
				video: video
			};
			list.trigger(evt);

			if ( evt.isImmediatePropagationStopped() ) {
				return;
			} else {
				// Find the next video and click on it.
				setTimeout(function(_video){
					return function(){
						video.click().scrollIntoView();
						video = null;
					};
				}( video ), 1);
			}
		}
	}
}
