var default_scollsize = 6;
var scrollable_attributes = {size: default_scollsize, speed: 500};

$(document).ready(function(){

	$("#ytapiplayer").fadeOut("fast");

	//pick up the default playtlistId and set the matching filter to active
	default_playlist_id = $("#defaultPlaylist").html();
	$("#filter #"+default_playlist_id).addClass("active");
		
	//find the first video id to load as the default
	default_video = $(".items span img").first().attr("id");
	
	var video_width = "945";
	var video_height = "556"
	var params = { allowScriptAccess: "always", hd: 1 };
	var atts = { id: "myytplayer" };
	swfobject.embedSWF("http://www.youtube.com/v/"+default_video+"?enablejsapi=1&playerapiid=video_player&hd=1", "ytapiplayer", video_width, video_height, "9.0.115", "/swfs/expressInstall.swf", null, params, atts);

	//wire up click events for each playlist
	$("#filter li a").each(function(){
		$(this).click(function(e){
			//only fire if NOT the active playlist
			if(!$(this).hasClass("active")){
				loadVideoThumbs($(this).attr("id"));
				$("#filter li a").removeClass("active");
				$(this).addClass("active");				
			}
			e.preventDefault();
		});
	});
	
	attachThumbnailClickEvent();

	//initialize scrollable
	$(".scrollable").scrollable(scrollable_attributes);
			
});

function loadVideoThumbs(playlist_id){

	//pull in all the videos for the supplied playlist_id
	url = '/videos/get/'+playlist_id;
	$.get(url, function(data){
		
		$(".items").fadeOut("fast", function(){
			//empty the div
			$(".items").empty();			
			//filll it up with the new thumbs
			$(".items").append(data);
					
			images = attachThumbnailClickEvent();
			
			var api = $(".scrollable").scrollable({api: true});
			api.reload().begin();
			
			$(".items").fadeIn("fast");
			
			if(images.length > default_scollsize){
				$("a.nextPage").removeClass("disabled");
			} else {
				$("a.nextPage").addClass("disabled");
			}
			
		});

	});


}

function loadVideo(youtube_key){
	video_player = document.getElementById("myytplayer");
	video_player.loadVideoById(youtube_key,0);
}

function attachThumbnailClickEvent(){
	 /* loop the thumbnails to attach the video action to them */
	var images = $(".items span img");			
	images.each(function() {				
		 $(this).click(function(e){
		 	loadVideo($(this).attr("id"));
		 	e.preventDefault();
		 });
	});
	return images;
}

function onYouTubePlayerReady() {
	$("#loading").fadeOut("fast");
}


