/* ---------- jQuery Events ---------- */

jQuery(document).ready(function() {

	var collegeName = jQuery('#college_name').val();
	if (collegeName) {
		// fixed CCONF-583 on Sep 8 2009: YouTube does not exist on all pages that include this script
		performYouTubeSearch(jQuery('#college_name').val());

		jQuery('#ytSearch').submit(function(e) {
			e.preventDefault(); // block normal form submission
			performYouTubeSearch(jQuery('#ytsearchButton').val());
		});
	}
});


/* ---------- Functions ---------- */

/*
 * This is the JSON callback function for a YouTube search.
 * The first video is loaded into the player. All others are shown as thumbnails in the ytVideobar.
 */
function layoutYoutubeVideobar(data) {
	var feed = data.feed;
	var entries = feed.entry || [];

	if (entries.length == 0) {
		printNoYoutubeResults('No videos were found for the search provided.');

	} else {
		loadYoutubeVideo(entries[0].media$group.media$content[0].url, false);

		var domVideobar = jQuery('#ytVideobar');

		domVideobar.empty();

		var ulVideos = jQuery('<ul>').addClass('ytVideos');
		domVideobar.append(ulVideos);

		for (var i = 0; i < entries.length; i++) {
			var entry = entries[i];
			var title = entry.title.length < 23 ? entry.title : (entry.title.$t.substr(0, 25) + '...');

			var viewcount = "";
			try {
				viewcount = " (" + formatNumber(entry.yt$statistics.viewCount) + " views)";
			} catch (ignore) {
				// not all entries have this statistic
			}

			var rating = "";
			try {
				rating = entry.gd$rating.average;

				// round rating to nearest half
				rating = Math.round(rating * 2) / 2

				rating = " (" + rating + " stars)"

			} catch(ignore) {
				// not all entries have this statistic
			}

			var thumbnailUrl = entry.media$group.media$thumbnail[0].url;
			var playerUrl = entry.media$group.media$content[0].url;
			var tooltip = entry.content.$t + viewcount + rating;


			// do not allow double-quotes in comment to corrupt the HTML
			tooltip = tooltip.replace(/"/g, "'");

			var duration = entry.media$group.yt$duration.seconds;

			// construct DOM
			var liThumbnailContainer = jQuery('<li>').addClass('thumbnailContainer').attr('href', playerUrl).click(function() { loadYoutubeVideo(jQuery(this).attr('href'), true); });
			var imgThumbnail = jQuery('<img>').addClass('thumbnail').attr('src', thumbnailUrl).attr('alt', tooltip).attr('title', tooltip);
			var divDuration = jQuery('<div>').addClass('duration').text(formatDuration(duration));
			var divTitlec = jQuery('<div>').addClass('titlec').text(title);
			liThumbnailContainer.append(imgThumbnail);
			liThumbnailContainer.append(divDuration);
			liThumbnailContainer.append(divTitlec);
			domVideobar.append(liThumbnailContainer);
		} // end foreach entries
	} // end if-else zero entries
}

/*
 * Loads a video into the player. Typically called 
 */
function loadYoutubeVideo(playerUrl, autoplay) {
	swfobject.embedSWF(
			playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
			(autoplay?1:0), 'player', '415', '250', '9.0.0', false, 
			false, {allowfullscreen: 'true'});
}

/*
 * Encapsulates the formatting of 'durationInSec' to a 'min:sec' string, 0-padding where appropriate.
 */
function formatDuration(durationInSec) {
	var m = Math.floor(durationInSec / 60);
	var s = durationInSec % 60;

	if (s < 10) {
		s = "0" + s;
	}

	return m + ':' + s;
}

/*
 * Adds commands to a number.
 * Author: http://www.mredkj.com/javascript/numberFormat.html
 */
function formatNumber(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/*
 * Replace contents of <div id=ytVideobar> with a message indicating that no videos were found.
 */
function printNoYoutubeResults(message) {
	var domVideobar = jQuery('#ytVideobar');

	// no additional results available
	domVideobar.empty();

	var divNoResults = jQuery('<div>').addClass('ytNoResults').text(message);
	domVideobar.append(divNoResults);
}

/*
 * Performs a YouTube search and updates the page content to reflect this:
 *  - active video
 *  - ytVideobar
 *  - searh label (below the player) notifying user of current results being displayed
 * The search returns 20 results, with the first being automatically loaded into the player (all 20 available in video bar).
 * See the layoutYoutubeVideobar function for more details.
 * 
 * Parameters:
 * 		q - The search query string to be sent to YouTube (as 'q' parameter).
 */
function performYouTubeSearch(q) {
	var queryString = "q=" + escape(q) + "&alt=json-in-script&callback=?&max-results=20&format=5";
	jQuery.getJSON("http://gdata.youtube.com/feeds/api/videos", queryString, layoutYoutubeVideobar);
	
	// jQuery('#searchValue').clear();
	jQuery('#searchValue').text(q.length < 50 ? q : q.substr(0, 47) + "...");
}
