
function displayThumbSet( thumbIndex ) {
    
    /* Hide all thumbnail sets */
    $('#thumb-pane table').each( function() { $(this).hide() } );

    $('#thumb-set-' + thumbIndex).fadeIn('fast');
}

function setVideo( id ) {

    /* I had an implementation that just changed the necessary attributes, but
     * that didn't work in Safari. So, brute force it by replacing the whole
     * damn things.
     */
    $('#movie-pane').html( 
	'<object width="425" height="344">'
	    + '<param name="movie" value="http://www.youtube.com/v/' + id + '&hl=en&fs=1&rel=0&color1=0x0044DD&color2=0x0044DD"></param>'
	    + '<param name="allowFullScreen" value="true"></param>'
	    + '<param name="allowscriptaccess" value="always"></param>'
	    + '<embed src="http://www.youtube.com/v/' + id + '&hl=en&fs=1&rel=0&color1=0x0044DD&color2=0x0044DD" '
	    + 'type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>'
	    + '</object>' );
}

$(document).ready(function () {

    /* Auto-generate thumbnail set ids */
    $('#thumb-pane table').each( function( index ) {
	$(this).attr( 'id', 'thumb-set-' + (index+1) );
    });

    /* Generate click handlers that will load the requested video */
    $('#thumb-pane img').each( function() {
	/* Extract the YouTube video ID from the URL */
	var videoId = $(this).attr("src").split(/[\/.]/)[3];
	$(this).bind( 'click', function() {
	    setVideo( videoId );
	});

	/* Add event handlers that will display a video's title in a
	 * preview area, above the media playing area. */
	$(this).bind( 'mouseover', function() { $('#video_title').text( $(this).attr("alt") ); } );
	$(this).bind( 'mouseout',  function() { $('#video_title').text('') } );
    });

    /* Install handlers for movies thumbnail-set links. I.e. change which
     * set of videos to display */
    $('#thumb-pagination span').each( function() {
	$(this).bind( 'click', function() {
	    displayThumbSet( $(this).text() );
	});
    });

    /* Bind event handlers for the thumbnail set buttons */
    $('.nav-buttons span').each( function() {
	$(this).bind( 'mouseover', function() {$(this).toggleClass('on'); } );
	$(this).bind( 'mouseout',  function() {$(this).toggleClass('on'); } );
    });

    /* Check whether someone has actually requested a specific video */

    var url = document.location.toString();

    if ( url.match('#') ) {
	/* Show the video with the requested ID. If the ID isn't valid,
	 * then the click() call won't happen. */
	var videoId = url.split('#')[1];
	$('img#' + videoId).click();

	/* We also want to show the corresponding thumnails set. Find the
	 * first ancestor node of this <img> that is a table and extract
	 * the final numeric part, so that we can plug it into the
	 * appropriate helper function. */
	var tableId = $('img#' + videoId).parents('table:eq(0)').attr('id').split('-')[2];

	displayThumbSet( tableId );
    }

});

