/* 
Application Name: YouTube Video Library
Description: A script used to access data from version 2 of the YouTube data API
Author: Bryan Miller, Practis Inc.
Version: 2.0 
Author URI: http://www.practisinc.com 
*/

function initializeVideoLibrary(playlist) {
	
	//generate the video library html containers
	$('#practis_video_library').html('<div class="left"><div id="video_player"></div></div><div class="right"><ul id="video_listing"></ul></div>');
		
	loadPlaylist(playlist);
		
	// check if a video id is selected
	// if so, load the video
	if ( $_GET('v') ) {
		loadVideo($_GET('v'),true);			
	}
	
}

// load a single playlist
function loadPlaylist(pl) {	
	$.ajax({
		url: 'https://gdata.youtube.com/feeds/api/playlists/'+pl+'?v=2&alt=json',
		dataType: 'jsonp',
		success: function (data) { showPlaylist(data); }
	});
}


// load a single video
function loadVideo(v,autoplay) {
	$.ajax({
		url: 'http://gdata.youtube.com/feeds/api/videos/'+v+'?v=2&alt=json',
		dataType: "jsonp",
		success: function (data) { showVideo(data,autoplay); }
	});
}

function showPlaylist(data) {
	var feed = data.feed;
	var entries = feed.entry || [];
	var html = [];
	
	var totalResults = feed.openSearch$totalResults.$t;
	var playlistId = feed.yt$playlistId.$t;
	var feedTitle = feed.title.$t;
		
	for (var i = 0; i < entries.length; i++) {
		var entry = entries[i];		
		var title = entry.title.$t.substr(0, 50);
		if ( entry.title.$t.length > 50 ) { title += '...'; }
		var thumbnailUrl = entry.media$group.media$thumbnail[0].url;	
		var videoId = entry.media$group.yt$videoid.$t;
		var videoLink = location.href.split('?')[0] + '?pl='+ playlistId +'&v=' + videoId;
		
		// push the video list item to the html array
		html.push('<li><a class="result" href="'+ videoLink +'" onclick="loadVideo(\''+videoId+'\',\'1\'); return false;"><span class="video-thumb"><img src="'+thumbnailUrl+'" /></span><span class="video-title">'+title+'</span></a></li>');
		
	}
	
	if ( totalResults >= 1 ) {
		$('#video_listing').html(html.join(''));
		if ( !$_GET('v') ) {
			loadVideo(entries[0].media$group.yt$videoid.$t,0);
		}
	}
	
}

// show the video and description
function showVideo(data,autoplay) {
	var videoId = data.entry.media$group.yt$videoid.$t;	
	$('#video_player').html('<iframe width="100%" height="100%" src="https://www.youtube.com/embed/'+videoId+'?rel=0&autoplay='+autoplay+'" frameborder="0" allowfullscreen></iframe>');		
}

// convert seconds to MM:SS format
function secondstominutes(secs) {
   var mins = Math.floor(secs / 60);
   secs = secs % 60;
   return mins
          + ":"
          + (secs < 10 ? "0" + secs : secs);
}

// access GET variables from the url
function $_GET(q,s) {
	s = s ? s : window.location.search;
	var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
	return (s=s.replace('?','&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
