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

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

	function vimeoVideoEnable(context)
	{
		$(context).find(".vimeo-player").once("vimeo-video-enable").each(function()
		{
			var vimeoID = $(this).attr("data-vimeo-id");

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

			if(drupalSettings.urlToVideoFilter.autoload)
			{
				$(this).empty().append($("<iframe/>").attr("src", "//player.vimeo.com/video/" + vimeoID + "?autopause=1&autoplay=0&badge=1&byline=1&loop=0&portrait=1&autopause=1&fullscreen=1").attr("frameborder", "0").attr("class", "player-iframe vimeo-iframe"));
			}
			else
			{
				$.ajax(
				{
					url:"//vimeo.com/api/v2/video/" + vimeoID + ".json",
					context:$(this),
					success:function(data)
					{
						if(data[0] && data[0].thumbnail_large)
						{
							$(this).empty().append($("<span/>").append($("<img/>", {class:"player-thumb", src:data[0].thumbnail_large})).append($("<span/>", {class:"play-button"})).click(function(e)
							{
								e.stopPropagation();

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

								$(this).replaceWith($("<iframe/>").attr("src", "//player.vimeo.com/video/" + vimeoID + "?autopause=1&autoplay=1&badge=1&byline=1&loop=0&portrait=1&autopause=1&fullscreen=1").attr("frameborder", "0").attr("class", "player-iframe vimeo-iframe"));
							}));
						}
						else
						{
							$(this).empty().append($("<span/>").append($("<span/>", {class:"play-button"})).click(function(e)
							{
								e.stopPropagation();

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

								$(this).replaceWith($("<iframe/>").attr("src", "//player.vimeo.com/video/" + vimeoID + "?autopause=1&autoplay=1&badge=1&byline=1&loop=0&portrait=1&autopause=1&fullscreen=1").attr("frameborder", "0").attr("class", "player-iframe vimeo-iframe"));
							}));
						}
					}
				});
			}
		});
	}

	Drupal.behaviors.urlToVideoFilterVimeo = {
		attach:function(context)
		{
			vimeoVideoEnable(context);
		},
		detach:function(context)
		{
			$(".vimeo-player", context).unbind("click");
		}
	};
}(jQuery, Drupal, drupalSettings));
