$( document ).ready( function()
{	
	$( '#categories a, #all a, #videoList li a' ).live( 'click', function( e )
	{
		e.preventDefault();
		if( $( this ).parent().is( '.active' ) ) return;
		ajaxLoad( $( this ).attr( 'href' ) );
	});
	
	$( '.searchForm' ).submit( function( e )
	{
		e.preventDefault();
		ajaxLoad( $.BD +'search/'+ $( '.searchInput' ).val() );
	});
});

function ajaxLoad( url )
{
	jwplayer().stop();
	hideVideo();
	
	$.ajax
	({
		url: $.BD +'ajax.php',
		type: 'POST',
		data: { url: url },
		dataType: 'json',
		success: ajaxLoaded
	});
}

function ajaxLoaded( data )
{
	if( data.messages.length > 0 )
		showMessages( data.messages );
		
	if( data.success )
	{
		if( data.type == 'category' || data.type == 'search' )
		{
			$( '#mainNav .active' ).removeClass( 'active' );
			
			if( data.type == 'category' )
			{
				if( data.activeCategory == false ) $( '#all' ).addClass( 'active' );
				else $( '#cat-'+ data.activeCategory ).addClass( 'active' );
			}
			
			emptyVideoList();
			populateVideoList( data.videoList );					
		}
		
		removeMessages();
		
		jwplayer().load( data.activeVideo.src );	
		
		$( '#mainHead' ).text( data.activeVideo.title );
		$( '#mainContent .description' ).text( data.activeVideo.description );
		$( '#embedCode' ).val( data.activeVideo.embedCode );
	}
	else
	{
		showVideo();
	}
}

function showMessages( messages )
{
	removeMessages();
	$ul = $( '<ul />' ).addClass( 'feedbackList messagesOuter' )
	
	for( i in messages )
		$ul.append( $( '<li />' ).text( messages[ i ] ) );
		
	$ul.appendTo( $( '#feedbackCon' ) );
}

function removeMessages(){ $( '#feedbackCon' ).find( 'ul' ).remove(); }

function emptyVideoList(){ $( '#videoList li' ).remove(); }
function populateVideoList( items )
{
	$t = $( $.ajax
	({
		url: $.BD +'li.tpl',
		dateType: 'html',
		async: false
	}).responseText );
	
	for( i in items )
	{
		$li = $t.clone();

		$li.find( '.thumb' ).attr({ href: items[ i ].link });
		
		$li.find( '.thumb' ).append
		(
			$( '<img />' )
				.attr({ src: items[ i ].thumbSrc })
				//.css({ opacity: 0 })
		);
			
		$li.find( '.title' )
			.text( items[ i ].title )
			.attr({ href: items[ i ].link });
		
		$li.find( 'dd.vidViews' ).text( items[ i ].views );
		
		if( items[ i ].runtime == '' ) $li.find( '.vidRuntime' ).remove();
		else $li.find( 'dd.vidRuntime' ).text( items[ i ].runtime );

		$( '#videoList' ).append( $li );
		
		$thumb = $li.find( '.thumb img' );

		/*if( $thumb.attr( 'complete' ) ) $thumb.animate({ opacity: 1 });
		else $thumb.load( function(){ $( this ).animate({ opacity: 1 }); })*/
	}
}
