/*global jQuery, Drupal, drupalSettings*/
/*jslint white:true, multivar, this, browser:true*/

(function($, Drupal, drupalSettings)
{
	"use strict";

	function youtubeVideoEnable(context)
	{
		$(context).find(".youtube-player").once("youtube-video-enable").each(function()
		{
			var youtubeID, youtubePreview;

			youtubeID = $(this).attr("data-youtube-id");

			$(this).parent().removeClass("no-js");

			if(drupalSettings.urlToVideoFilter.autoload)
			{
				$(this).empty().append($("<iframe/>").attr("src", "//www.youtube.com/embed/" + youtubeID + "?autoplay=0&autohide=2&border=0&wmode=opaque&enablejsapi=1").attr("frameborder", "0").attr("class", "player-iframe youtube-iframe"));
			}
			else
			{
				if(drupalSettings.urlToVideoFilter.youtubeWebp)
				{
					youtubePreview = "//i.ytimg.com/vi_webp/" + youtubeID + "/sddefault.webp";
				}
				else
				{
					youtubePreview = "//i.ytimg.com/vi/" + youtubeID + "/hqdefault.jpg";
				}

				$(this).empty().append($("<span/>").append($("<div/>", {class:"player-thumb",style:"background-image:url(" + youtubePreview + ")"})).append($("<span/>", {class:"play-button"})).click(function(e)
				{
					e.stopPropagation();

					Drupal.detachBehaviors($(this).parent().parent());

					$(this).replaceWith($("<iframe/>").attr("src", "//www.youtube.com/embed/" + youtubeID + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1").attr("frameborder", "0").attr("class", "player-iframe youtube-iframe"));
				}));
			}
		});
	}

	Drupal.behaviors.urlToVideoFilterYoutube = {
		attach:function(context)
		{
			youtubeVideoEnable(context);
		},
		detach:function(context)
		{
			$(".youtube-player", context).unbind("click");
		}
	};	
}(jQuery, Drupal, drupalSettings));
