(function($) {

	$.fn.youtubePlaylist = function(options) {

		var $this = $(this),
			$player = $(".player", $this),
			$videoTemplate = $(".video-template", $this),
			$videosContainer = $(".videos", $this),
			$featuredVideoContainer = $(".featured-video", $this),
			$moreVideosContainer = $(".more-videos", $this),
			$loading = $(".loading", $this);

		if (!options.featuredVideoId) { $featuredVideoContainer.hide(); }

		// Truncate text to a certain character length without breaking on a word
		function shortenText(input, maxLength) {
			if (input.length <= maxLength) {
				return input;
			} else {
				for (var i = maxLength-1; input.charAt(i) !== " " && i>0; i--);
				return input.substr(0, i) + "&hellip;";
			}
		}

		// Detect if we're on iOS or Android
		// This isn't ideal.
		function isTouch() {
			return navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/);
		}

		// Resize the iframe to maintain the video's aspect ratio.
		// Add space for the controls on flash-based players
		$player.height($player.width() * 256/455 + (isTouch() ? 0 : 30));

		// Get the playlist data from youtube
		$.ajax({

			dataType: "jsonp",
			url: "https://gdata.youtube.com/feeds/api/playlists/" + options.channelId,
			data: { v: 2, alt: "json" },

			error: function() {
				throw "Could not get YouTube feed";
			},

			success: function(playlist) {
			
				$loading.hide();
				$moreVideosContainer.show();

				$.each(playlist.feed.entry, function(i, videoRaw) {
					var videoRaw = playlist.feed.entry[i];

					// YouTube's data structure is rather ugly. Collect the bits we need.
					var video = {
						thumbnailUrl: videoRaw.media$group.media$thumbnail[0].url,
						title: videoRaw.media$group.media$title.$t,
						description: shortenText(videoRaw.media$group.media$description.$t, 225),
						embedUrl: "http://www.youtube.com/embed/" + videoRaw.media$group.yt$videoid.$t,
						id: videoRaw.media$group.yt$videoid.$t
					};

					// Create the video DOM element
					var $video = $videoTemplate.tmpl(video);
					
					// Insert the video DOM element where appropriate
					if (video.id == options.featuredVideoId) {
						$video.appendTo($featuredVideoContainer.show());
					} else {
						$video.appendTo($moreVideosContainer);
					}

					// When a video is "shown," give it the active class and display it in the player
					function showVideo(autoplay) {
						$player.attr("src", video.embedUrl + (autoplay ? "?autoplay=1" : ""));
						$videosContainer.find(".video.video-active").removeClass("video-active");
						$video.addClass("video-active");
					}

					// If this video is to be displayed initially, show it
					if (options.featuredVideoId ? video.id == options.featuredVideoId : i == 0) {
						showVideo();
					}

					// Show this video when it is clicked on
					$video.click(function() {
						showVideo(true);
					});

				});

				// Add iOS momentum scrolling to the videos if we're on a touch device
				if (isTouch()) {
					$videosContainer.children().touchScroll();
				}
				
			}
		});

	}

})(jQuery);

		
