// ==UserScript==
// @name          FYTEPlayer: Fast YouTube Embedded Player
// @description   Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. HTML5 direct playback (720p max) is used when selected and available.
// @version       2.0
// @include       *
// @exclude       https://www.youtube.com/*
// @author        wOxxOm
// @namespace     wOxxOm.scripts
// @license       MIT License
// @grant         GM_getValue
// @grant         GM_setValue
// @grant         GM_addStyle
// @grant         GM_xmlhttpRequest
// @connect       www.youtube.com
// @connect       youtube.com
// @run-at        document-start
// ==/UserScript==

/* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */

var resizeMode = GM_getValue('resize', 'Fit to width');
if (typeof resizeMode != 'string')
	resizeMode = resizeMode ? 'Fit to width' : 'Original';

var resizeWidth = GM_getValue('width', 1280) |0;
var resizeHeight = GM_getValue('height', 720) |0;
updateCustomSize();

var playHTML5 = !!GM_getValue('playHTML5', false);
var skipCustom = !!GM_getValue('skipCustom', true);

var $ = function(selORnode, sel) { return sel ? selORnode.querySelector(sel) : document.querySelector(selORnode) };
var $$ = function(selORnode, sel) { return sel ? selORnode.querySelectorAll(sel) : document.querySelectorAll(selORnode) };

var embedSelector;
initEmbedSelector();

processEmbeds($$(embedSelector));

document.addEventListener('DOMContentLoaded', function(e) {
	adjustNodesIfNeeded(e);
	injectStylesIfNeeded();
});

window.addEventListener('resize', adjustNodesIfNeeded);

var mutQueue = [];
new MutationObserver(function(mutations) {
	if (mutations.length == 1) {
		// ricing: skip singular mutations with no ELEMENT_NODE added
		// (like removal of nodes or creation of TEXT_NODE)
		var added = mutations[0].addedNodes;
		if (added.length==0 || added.length==1 && added[0].nodeType!=1)
			return;
	}
	mutQueue.push(mutations);
	if (mutations.length < 100)
		processQueue();
	else
		setTimeout(processQueue, 0);
}).observe(document, {subtree:true, childList:true});

function processQueue() {
	while (mutQueue.length) {
		var mutationBatch = mutQueue.shift();
		for (var m=0, ml=mutationBatch.length, mutation; (m<ml) && (mutation=mutationBatch[m]); m++) {
			for (var n=0, nodes=mutation.addedNodes, nl=nodes.length, node; (n<nl) && (node=nodes[n]); n++) {
				if (node.nodeType != 1) // skip non-ELEMENT_NODE
					continue;
				if (node.localName == 'iframe' || node.localName == 'embed') {
					if (node.matches(embedSelector))
						processEmbeds([node]);
				}
				else if (node.children.length) {
					var embeds = $$(node, embedSelector);
					if (embeds.length)
						processEmbeds(embeds);
				}
			}
		}
	}
}

function processEmbeds(nodes) {
	for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
		var np = n.parentNode, npw;
		if (!np ||
			np.localName == 'object' && !np.parentNode ||
			n.className.indexOf('instant-youtube-') >= 0 ||
			n.src.indexOf('autoplay=1') > 0 ||
			n.onload && getComputedStyle(np).display == 'none' // skip some retarded loaders
		)
			continue;

		var id = n.src.match(/(?:embed\/|v[=\/])([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
		if (!id)
			continue;
		id = id[1];

		var div = document.createElement('div');
		div.className = 'instant-youtube-container';
		div.srcEmbed = n.src.replace(/&$/, '');
		div.videoID = id;

		div.originalWidth = n.width|0 || n.clientWidth;
		div.originalHeight = n.height|0 || n.clientHeight;

		var divSize = calcThumbSize(n);
		div.style.maxWidth = divSize.w + 'px';
		div.style.height = divSize.h + 'px';

		var wrapper = div.appendChild(document.createElement('div'));
		wrapper.className = 'instant-youtube-wrapper';

		var img = wrapper.appendChild(document.createElement('img'));
		img.className = 'instant-youtube-thumbnail';
		img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
		img.style.cssText = important('transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0;');

		img.title = 'Shift-click to use alternative player';
		img.onload = function(e) {
			var img = e.target;
			if (img.naturalWidth <= 120)
				return img.onerror(e);
			var fitToWidth = true;
			if (img.naturalHeight) {
				var ratio = img.naturalWidth / img.naturalHeight;
				if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
					img.style.cssText += important('width:auto; height:100%;');
					fitToWidth = false;
				}
			}
			if (fitToWidth) {
				img.style.cssText += important('width:100%; height:auto;');
			}
			if (img.videoWidth)
				fixThumbnailAR(div);
			img.style.opacity = 1;
		};
		img.onerror = function(e) {
			var img = e.target;
			if (img.src.indexOf('maxresdefault') > 0)
				img.src = img.src.replace('maxresdefault','hqdefault');
		};

		GM_xmlhttpRequest({
			method: 'GET',
			url: div.srcEmbed.replace(/\/(embed\/|v[=\/])/, '/watch?v='),
			context: div,
			onload: parseWatchPage
		});

		wrapper.insertAdjacentHTML('beforeend', '\
			<svg class="instant-youtube-play-button"><path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>\
			<span class="instant-youtube-link">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
			<div class="instant-youtube-options-button">Options</div>\
		');

		if (n.parentNode.localName == 'object')
			n = n.parentNode;
		n.parentNode.insertBefore(div, n);
		n.remove();

		div.addEventListener('click', clickHandler);
	}

	injectStylesIfNeeded();
	return true;
}

function adjustNodesIfNeeded(e) {
	if (resizeMode != 'Original' && !adjustNodesIfNeeded.scheduled)
		adjustNodesIfNeeded.scheduled = setTimeout(function() {
			adjustNodes(e);
			adjustNodesIfNeeded.scheduled = 0;
		}, 16);
}

function adjustNodes(e, clickedContainer) {
	var force = !!clickedContainer;
	var nearest = force ? clickedContainer : null;

	var vids = [].slice.call($$('div.instant-youtube-container'));

	if (!nearest && e.type != 'DOMContentLoaded') {
		var minDistance = window.innerHeight*3/4 |0;
		var nearTargetY = window.innerHeight/2;
		vids.forEach(function(n) {
			var bounds = n.getBoundingClientRect();
			var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
			if (distance < minDistance) {
				minDistance = distance;
				nearest = n;
			}
		});
	}

	if (nearest) {
		var bounds = nearest.getBoundingClientRect();
		var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
	}

	var resized = false;

	vids.forEach(function(n) {
		var size = calcThumbSize(n);
		var w = size.w, h = size.h;

		if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
			return;

		if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
		if (n.style.height != h + 'px')   n.style.height = h + 'px';

		var video = $(n, 'video');
		if (video) {
			video.width = w;
			video.height = h;
		}

		fixThumbnailAR(n);
		resized = true;
	});

	if (resized && nearest)
		setTimeout(function() {
			var bounds = nearest.getBoundingClientRect();
			var h = bounds.bottom - bounds.top;
			var projectedCenterY = nearestCenterYpct * window.innerHeight;
			var projectedTop = projectedCenterY - h/2;
			var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
			window.scrollBy(0, bounds.top - safeTop);
		}, 16);
}

function calcThumbSize(node) {
	var w, h;
	switch (resizeMode) {
		case 'Original':
			w = node.originalWidth;
			h = node.originalHeight;
			break;
		case 'Custom':
			w = resizeWidth;
			h = resizeHeight;
			break;
		case '1080p':
		case '720p':
		case '480p':
		case '360p':
			h = parseInt(resizeMode);
			w = Math.round(h / 9 * 16 + 0.49);
			break;
		default: // fit-to-width mode
			do {
				node = node.parentElement;
				// find parent node with nonzero width (i.e. independent of our video element)
			} while (node && !(w = node.clientWidth));
			if (w)
				h = Math.round(w / 16 * 9 + 0.49);
			else {
				w = node.clientWidth;
				h = node.clientHeight;
			}
	}
	return {w:w, h:h};
}

function parseWatchPage(response) {
	var div = response.context;
	var txt = response.responseText;

	// parse width & height to adjust the thumbnail
	var w = txt.match(/<meta property="og:video:width" content="(\d+)">/);
	var h = txt.match(/<meta property="og:video:height" content="(\d+)">/);
	if (w && h)
		fixThumbnailAR(div, w[1]|0, h[1]|0);

	// parse video sources
	var m = txt.match(/ytplayer\.config\s*=\s*(\{.+?\});\s*ytplayer\.load/);
	var videoInfo = [];
	if (m) {
		var cfg = JSON.parse(m[1]), streams = {};
		cfg.args.url_encoded_fmt_stream_map.split(',').forEach(function(stream) {
			var params = {};
			stream.split('&').forEach(function(kv) {
				params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
			});
			streams[params.itag] = params;
		});
		cfg.args.fmt_list.split(',').forEach(function(fmt) {
			var itag = fmt.split('/')[0];
			var dimensions = fmt.split('/')[1];
			var stream = streams[itag];
			if (stream) {
				videoInfo.push({
					src: stream.url,
					title: stream.quality + ', ' + dimensions + ', ' + stream.type
				});
			}
		});
	} else {
		var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
		var text = txt.split('url_encoded_fmt_stream_map')[1];
		while (m = rx.exec(text)) {
			videoInfo.push({
				src: decodeURIComponent(decodeURIComponent(m[1]))
			});
		}
	}

	var title = txt.match(/<title>(.+?)(?:\s*-\s*YouTube)?<\/title>/);
	if (title) {
		var duration = txt.match(/<meta itemprop="duration" content="\D*(\d+.*?)S?">/);
		var a = div.firstElementChild.appendChild(document.createElement('a'));
		a.className = 'instant-youtube-persistent-title';
		a.innerHTML = '<strong>' + title[1] + '</strong>' +
			(duration ? '<span>' + duration[1].replace(/[HM]/, ':0').replace(/\b0(\d\d)/, '$1') + '</span>' : '');
		a.href = 'https://www.youtube.com/watch?v=' + div.videoID;
		a.target = '_blank';
		['animation', 'webkitAnimation', 'mozAnimation'].some(function(prop) {
			if (prop in a.style) {
				a.style[prop] = 'instant-youtube-fadein 1s ease-in';
				setTimeout(function() { a.style[prop] = '' }, 1000);
				return true;
			}
		});
	}

	if (videoInfo.length)
		div.videoInfo = videoInfo;

	injectStylesIfNeeded();
}

function fixThumbnailAR(div, w, h) {
	var img = $(div, 'img');
	var thw = img.naturalWidth, thh = img.naturalHeight;
	if (!thw || !thh) {
		// thumbnail is still loading
		img.videoWidth = w;
		img.videoHeight = h;
		return;
	} else if (!w || !h) {
		w = img.videoWidth;
		h = img.videoHeight;
	}
	var divw = div.clientWidth, divh = div.clientHeight;
	// if both video and thumbnail are 4:3, fit the image to height
	if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
		img.style.cssText = img.style.cssText.replace(/\bheight:.*?;/, 'height:' + img.clientHeight + 'px!important;');
		if (!img.videoWidth) // skip animation if thumbnail is already loaded
			img.style.transition = 'height 1s ease, margin-top 1s ease';
		setTimeout(function() {
			img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
			setTimeout(function() {
				img.style.transition = '';
			}, 1000);
		}, 0);
	}
}

function clickHandler(e) {
	if (e.target.href)
		return;
	if (e.target.matches('.instant-youtube-options-button'))
		return showOptions(e);
	if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
		return;
	div = e.target.closest('.instant-youtube-container');
	div.removeEventListener('click', clickHandler);
	$(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';

	var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
	if (div.videoInfo && (!!playHTML5 + !!alternateMode == 1))
		playDirectly(div);
	else
		switchToIFrame.call(div);
}

function playDirectly(div) {
	$(div, '.instant-youtube-options-button').style.display = 'none';
	$(div, '.instant-youtube-link').style.display = 'none';

	var video = document.createElement('video');
	video.controls = true;
	video.autoplay = true;
	video.style.cssText = important('width:'+div.clientWidth+'px; height:'+div.clientHeight+'px;');
	video.className = 'instant-youtube-embed';
	video.volume = GM_getValue('volume', 0.5);

	div.videoInfo.forEach(function(src) {
		var srcdom = video.appendChild(document.createElement('source'));
		Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
		srcdom.onerror = switchToIFrame.bind(div);
	});


	if (window.chrome) {
		video.addEventListener('click', function(e) {
			this.paused ? this.play() : this.pause();
		});
	}
	video.interval = (function() {
		return setInterval(function() {
			if (video.volume != GM_getValue('volume', 0.5))
				GM_setValue('volume', video.volume);
		}, 1000);
	})();
	var title = $(div, '.instant-youtube-persistent-title');
	if (title) {
		video.onpause = function() { title.removeAttribute('hidden') };
		video.onplay = function() { title.setAttribute('hidden', true) };
	}
	video.onloadeddata = function(e) {
		pauseOtherVideos(this);
		div.style.cssText += 'contain:none!important'; // allow fullscreen
		div.firstElementChild.appendChild(this);
		this.style.cssText = 'opacity:1!important';
		var img = $(div, 'img');
		img.style.transition = 'opacity 1s';
		img.style.opacity = 0;
	};
}

function switchToIFrame(e) {
	var div = this;
	var wrapper = div.firstElementChild;
	if (e) {
		console.log('Direct linking failed on %s, switching to IFRAME player', div.srcEmbed);
		var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
		while (video.lastElementChild)
			video.lastElementChild.remove();
	}

	wrapper.insertAdjacentHTML('beforeend',
		'<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
		div.srcEmbed.replace('http:', 'https:').replace('/v/', '/embed/') +
		(div.srcEmbed.indexOf('?') > 0 ? '&' : '?') +
		'html5=1' +
		'&autoplay=1' +
		'&autohide=2' +
		'&border=0' +
		'&controls=1' +
		'&fs=1' +
		'&showinfo=1' +
		'&ssl=1' +
		'&theme=dark' +
		'&enablejsapi=1' +
		'" frameborder="0" allowfullscreen width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>');

	wrapper.lastElementChild.onload = function() {
		pauseOtherVideos(this);
		this.style.opacity = 1;

		var div = this.closest('.instant-youtube-container');
		div.setAttribute('iframe', '');
		div.style.cssText += 'contain:none!important'; // allow fullscreen
		setTimeout(function() {
			$(div, 'img').style.display = 'none';
			var title = $(div, '.instant-youtube-persistent-title');
			if (title)
				title.remove();
		}, 2000);
	};
}

function pauseOtherVideos(activePlayer) {
	[].forEach.call(activePlayer.ownerDocument.getElementsByClassName('instant-youtube-embed'), function(v) {
		if (v == activePlayer)
			return;
		switch (v.localName) {
			case 'video':
				if (!v.paused)
					v.pause();
				break;
			case 'iframe':
				try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
				break;
		}
	});
}

function showOptions(e) {
	var optionsButton = e.target;
	optionsButton.insertAdjacentHTML('afterend', '\
		<div class="instant-youtube-options">\
			<label>Size:<br>\
				<select data-action="size-mode">\
					<option>Original</option>\
					<option>Fit to width</option>\
					<option>360p</option>\
					<option>480p</option>\
					<option>720p</option>\
					<option>1080p</option>\
					<option value="Custom">Custom...</option>\
				</select>\
			</label>\
			<label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
				<input type="number" min="320" max="9999" placeholder="width" step="10" value="' + (resizeWidth||'') + '">\
				x\
				<input type="number" min="240" max="9999" placeholder="height" step="10" value="' + (resizeHeight||'') + '">\
			</label>\
			<label title="Tip: shift-clicking thumbnails will use alternative player">\
				<input data-action="direct" type="checkbox" ' + (playHTML5 ? 'checked' : '') + '>\
				Play directly\
			</label>\
			<label title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
				<input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
				Safe\
			</label>\
			<span data-action="buttons">\
				<button>OK</button>\
				<button>Cancel</button>\
			</span>\
		</div>\
	');
	var options = optionsButton.nextElementSibling;

	options.addEventListener('keydown', function(e) {
		if (e.target.localName == 'input' &&
			!e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
			return false;
	});

	$(options, '[data-action="size-mode"]').value = resizeMode;
	$(options, '[data-action="size-mode"]').addEventListener('change', function() {
		var v = this.value != 'Custom';
		var e = $(options, '[data-action="size-custom"]');
		e.children[0].disabled = e.children[1].disabled = v;
		v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
	});

	$(options, '[data-action="buttons"]').addEventListener('click', function(e) {
		if (e.target.textContent != 'OK') {
			options.remove();
			return;
		}
		var v, shouldAdjust;
		if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
			GM_setValue('resize', resizeMode = v);
			shouldAdjust = true;
		}
		if (resizeMode == 'Custom') {
			var w = $(options, '[placeholder="width"]').value |0;
			var h = $(options, '[placeholder="height"]').value |0;
			if (resizeWidth != w || resizeHeight != h) {
				updateCustomSize(w, h);
				GM_setValue('width', resizeWidth);
				GM_setValue('height', resizeHeight);
				shouldAdjust = true;
			}
		}
		if (playHTML5 != (v = $(options, '[data-action="direct"]').checked)) {
			GM_setValue('playHTML5', playHTML5 = v);
			[].forEach.call($$('.instant-youtube-container .instant-youtube-link'), function(e) {
				e.textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
			});
		}
		if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
			GM_setValue('skipCustom', skipCustom = v);
			initEmbedSelector();
		}

		options.remove();

		if (shouldAdjust)
			adjustNodes(e, e.target.closest('.instant-youtube-container'));
	});
}

function updateCustomSize(w, h) {
	resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
	resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
}

function initEmbedSelector() {
	embedSelector = 'iframe[src*="youtube.com/embed"]~~~, embed[src*="youtube.com/v"]~~~'
		.replace(/~~~/g, skipCustom ? ':not([src*="enablejsapi=1"])' : '');
}

function important(cssText) {
	return cssText.replace(/;/g, '!important;');
}

function injectStylesIfNeeded() {
	if (document.head.innerHTML.indexOf('.instant-youtube-container') > 0)
		return;
	GM_addStyle(important('\
		.instant-youtube-container {contain:strict; position:relative; overflow:hidden; cursor:pointer; background-color:black; padding:0; margin:0; font:normal 14px/1.0 sans-serif,Arial,Helvetica,Verdana; text-align:center;}\
		.instant-youtube-container .instant-youtube-wrapper {width:100%; height:100%;}\
		.instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px;}\
		.instant-youtube-container .instant-youtube-loading-button {position:absolute; left:0; right:0; top:0; bottom:0; padding:0; margin:auto; display:block; width:20px; height:20px; background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");}\
		.instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E;}\
		.instant-youtube-container .instant-youtube-link {\
			position:absolute; top:50%; left:0; right:0; width:20em; height:20px; margin:60px auto; padding:0; border:none; \
			display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
		}\
		.instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px;}\
		.instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent;}\
		.instant-youtube-container .instant-youtube-embed {position:absolute; left:0; top:0; padding:0; margin:0; height:inherit; opacity:0; transition:opacity 2s;}\
		.instant-youtube-container iframe {z-index:10;}\
		.instant-youtube-container .instant-youtube-persistent-title {\
			display:block; z-index:9; background-color:rgba(0,0,0,0.5); color:white;\
			width:100%; top:0; left:0; right:0; position:absolute; z-index: 9;\
			color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
			margin:0; padding:7px; border:none;\
		}\
		.instant-youtube-container .instant-youtube-persistent-title strong:after {content:" - watch on Youtube"; font-weight:normal; margin-right:1ex;}\
		.instant-youtube-container .instant-youtube-persistent-title span {color:inherit;}\
		.instant-youtube-container .instant-youtube-persistent-title span:before {content:"(";}\
		.instant-youtube-container .instant-youtube-persistent-title span:after {content:")";}\
		\
		@-webkit-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1}	}\
		@-moz-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1}	}\
		@keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1}	}\
		\
		.instant-youtube-container:not(:hover) .instant-youtube-persistent-title[hidden] {display:none; margin:0;}\
		.instant-youtube-container .instant-youtube-persistent-title:hover {text-decoration:underline;}\
		.instant-youtube-container .instant-youtube-persistent-title strong {color:white;}\
		\
		.instant-youtube-container .instant-youtube-options-button {position:absolute; right:0; bottom:0; color:white; font-size:11px; text-shadow:1px 1px 2px black; padding:1.5ex 2ex; margin:0; opacity:0.6;}\
		.instant-youtube-container .instant-youtube-options-button:hover {opacity:1; background:rgba(0,0,0,0.5);}\
		\
		.instant-youtube-container .instant-youtube-options {position:absolute; right:0; bottom:0; color:white; background:black; padding:2ex 1ex 2ex 2ex; margin:0; opacity:1; display:flex; flex-direction:column; align-items:flex-start; line-height:1.5; text-align:left;}\
		.instant-youtube-container .instant-youtube-options * {display:inline; color:white; background:black; font:inherit; font-size:13px; vertical-align:middle; padding:0; margin:0; height:auto; width:auto; text-transform:none; text-align:left; border-radius:0; text-decoration:none;}\
		.instant-youtube-container .instant-youtube-options > label {margin-top:1ex;}\
		.instant-youtube-container .instant-youtube-options select {-webkit-appearance:menulist;}\
		.instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {width:9ex; border:1px solid #666; padding:.5ex .5ex .4ex;}\
		.instant-youtube-container .instant-youtube-options [data-action="buttons"] {margin-top:1em;}\
		.instant-youtube-container .instant-youtube-options button {padding:.5ex 2ex; margin:0 1ex 0 0; border:2px solid gray; font-weight:bold;}\
		.instant-youtube-container .instant-youtube-options button:hover {border-color:white;}\
		.instant-youtube-container .instant-youtube-options > [disabled] {opacity:0.25;}\
	'));
}