/**
 * This script will find the element with ID "videoPlayer" and substitute it for the YouTube video player,
 * loaded remotely as a SWF from YouTube.com. The video player element must have the custom yt:videoId
 * attribute set to whatever video you want to play on page load.
 *
 * It will also find any anchors with class of "playVideo" and attach an onclick event to them to switch the video
 * currently being played in the player. The anchor specifies the video to be played by way of the custom attribute yt:videoId
 * 
 * It requires both the Jquery and SWFObject javascript libraries in order to work, so make sure they are loaded prior
 * to including this script.
 */

$(document).ready(function() {
	if($('#videoPlayer').length){
		var isIphone=navigator.userAgent.indexOf('iPhone')!=-1;
        var params = {
			allowScriptAccess: "always",
			wmode: "transparent"
		}; // because the SWF player comes from an external domain
        var atts = {id: "videoPlayer"};

        videoId = $('#videoPlayer').attr("yt:videoId");
        elementId = $('#videoPlayer').attr("id");
        var playerUrl = "http://www.youtube.com/v/" + videoId + "?enablejsapi=1&rel=0&playerapiid=" + elementId;

        // creates the actual video player element in the page
        swfobject.embedSWF(playerUrl, "videoPlayer", "521", "304", "8", null, null, params, atts);
		
		if(isIphone){
			$('#videoPlayer').html('<embed src="'+playerUrl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="521" height="304"></embed>');
		}
		
		// show description of the first video playing on page load
		if(desc = $('#playlist .description:eq(0)')){
			$('#videoDesc').html(desc.html());
		}
		// show title of the first video playing on page load
		if(title = $('#playlist .videoText a:eq(0)')){
			$('#videoTitle').html(title.html());
		}
        
        // wiring up the links to use the Youtube javascript API to switch videos
        if($('.playVideo')){
            $('.playVideo').click( function(event){
                var videoId = $(this).attr("yt:videoId");
                document.getElementById("videoPlayer").loadVideoById(videoId);

                // remove highlight from all other playlist items
                $('#playlist li').removeClass("nowPlaying");
                $(this).closest('#playlist li').addClass("nowPlaying"); // highlight the currently played video in the playlist

				// copy the title and description of the video thumbnail over to the player
				if(title = $(this).parents('.item').find('.videoText a:eq(0)')){
					$('#videoTitle').html(title.html());
				}
				if(desc = $(this).parents('.item').find('.description')){
					$('#videoDesc').html(desc.html());
				}

                event.preventDefault();
            });
        }
    }
});
