jhawins / Stackexchange HTML 5 Youtube Enabler

// ==UserScript==
// @name         Stackexchange HTML 5 Youtube Enabler
// @namespace    http://stackoverflow.com/users/1596138/jhawins
// @version      0.2
// @description  Replaces embed tags with iFrames and uses the Youtube Iframe API
// @author       jhawins
// @include      http://*stackexchange.com/questions/*
// @include      http://*stackoverflow.com/questions/*
// @grant        none
// ==/UserScript==

(function(){
	var embeds = document.getElementsByTagName("embed");

	var tubeOpts = {}, toBeTubed = {};

	// check for youtube links
	for (var i = 0; i < embeds.length; i++) {
		if (embeds[i].src.indexOf("youtube") > -1) {

			tubeOpts = {
				'videoId': youtube_parser(embeds[i].src),
				'width': embeds[i].width,
				'height': embeds[i].height
			};

			toBeTubed[i] = {
				options: tubeOpts,
				oldTube: embeds[i]
			}

		}	
	}

	// check if there were any videos to convert 
	if (Object.keys(toBeTubed).length > 0) createIframes(toBeTubed);

	function createIframes(newtubes) {
		window.onYouTubeIframeAPIReady = function() {
			for (var k in newtubes) {
				player = new YT.Player(newtubes[k].oldTube, {
					width: newtubes[k].options.width,
					height: newtubes[k].options.height,
					videoId: newtubes[k].options.videoId,
					playerVars: {
						html5: 1
					}
				});
			}
		}
      // Add Youtube iFrame API
      var tag = document.createElement('script');
      tag.id = "YTIframeAPI";
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
	}

	function youtube_parser(url) {
		var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
		var match = url.match(regExp);
		if (match && match[7].length == 11) {
			return match[7];
		} else {
			return false;
		}
	}

}());