/* jquery.youtube_replace.js */

// Youtube Link Replacement 1.0 - CMS Version
// Will Rosenberg
// Digital Surgeons

// This script uses jQuery and it must be included before this script is called.

// This script will rewrite all anchor tags with class="youtube_replace" as YouTube 
// embeds.  The href of the anchor must contain the URL of a YouTube page (with 
// parameter 'v' as the video ID) or this script will insert a blank embed.  If 
// Javascript is disabled, users will be able to click your link to view the video.

// This version provides CMS support -- with some CMS solutions, you cannot edit the
// class of a link.  This solves that problem by allowing you append your YouTube
// link with "&class=youtube_replace".  This works the same as adding a class to the
// anchor tag.

$(document).ready(function(){

	$("a").each(function(index, element){
	
		var href = $(this).attr('href');
		if (typeof href != "undefined") {

			var query = href.substring( href.indexOf("?") + 1 ); 
			if (has_ytr_class(query) || $(this).hasClass("youtube_replace")) {
				var ytid = getYoutubeID(query);
			
				var youtube_replace = '<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/' + ytid + '" frameborder="0"></iframe>';
			
				$(this).replaceWith(youtube_replace);
			}
		}
	});

});

// this function uses code from http://www.idealog.us/2006/06/javascript_to_p.html
function getYoutubeID (query) {
	var vars = query.split("&"); 
	for (var i=0;i<vars.length;i++) { 
		var pair = vars[i].split("="); 
		if (pair[0] == "v") { 
			return pair[1]; 
		}
	}
}
function has_ytr_class (query) {
	var vars = query.split("&"); 
	for (var i=0;i<vars.length;i++) { 
		var pair = vars[i].split("="); 
		if (pair[0] == "class") { 
			if (pair[1] == "youtube_replace") {
				return true;
			}
		}
	}
	return false;
}
