﻿/*
/*
* jQuery Plugin to launch media from a link in another target
* Requires the jQuery.media plugin
*/

function targetMediaLink(config) {

	var $target = jQuery("div[id=" + config.targetId + "]");

	if (config.event) {
		jQuery.Event(config.event).preventDefault();
	}

	if (window.suppressTabRotations && config.suppressTabs) {

		var hasSuppressedSpecificTabs = false;
		var $tabContainer = $target.parents("div[id^=tabContainer]:first");
		if ($tabContainer.size() == 1) {

			var $tabMenuOuter = $tabContainer.find("div[class='element-tabs-menu-outer']:first");
			if ($tabMenuOuter.size() == 1) {

				var tabMenuOuterId = $tabMenuOuter.attr("id");
				var tabMenuOuterIdParts = tabMenuOuterId.split("_");
				var tabIdentifier = "tabs_esctl_" + tabMenuOuterIdParts[1]; // Should be tabs_esctl_XXXX where XXXX is the esctl number

				window.suppressTabRotations(tabIdentifier);
				hasSuppressedSpecificTabs = true;
			}
		}

		if (!hasSuppressedSpecificTabs) {

			window.suppressTabRotations(); // Suppress all tabs on the page
		}
	}

	jQuery.fn.media.defaults.flvPlayer = "/EasysiteWeb/Easysite/SupportFiles/FlashVideo/flvplayer.swf";
	jQuery.fn.media.defaults.mp3Player = "/EasysiteWeb/Easysite/SupportFiles/FlashVideo/flvplayer.swf";

	if ($target.size() > 0) {

		var autoplay = (config.autoplay != null) ? config.autoplay : true;
		var assetId = config.assetId;

		jQuery.ajax({
			type: "POST",
			url: "/EasySiteWeb/EasySite/SupportFiles/ContentEditor/Services/ResolveAssetDetails.ashx",
			data: {
				assetId: assetId,
				forceLicenceAsset: true 
			},
			dataType: "json",
			success: function(assetDetails) {
				if (assetDetails.success) {

					var url = assetDetails.asset.path;

					// Special case for YouTube movies in order to autoplay them
					if (url.match(new RegExp("http://.*\\.youtube\\..*/v/")) && autoplay) {
						url += "&autoplay=1";
					}

					var extension = assetDetails.asset.extension;
					if (extension == "") {
						extension = "swf"; // Assume flash where no extension specified
					}
					
					var width = $target.width();
					var height = $target.height();
					var $media = jQuery("<a>").attr("href", url);
					$target.empty().append($media);
					$media.media({
					    autoplay: autoplay,
						caption: false,
						width: width,
						height: height,
						type: extension,
						params: {
							allowfullscreen: "true"
						},
						flashvars: {
							type: extension,
							autostart: autoplay,
							allowfullscreen: "true"
						}
					});
				}
				else {

					alert(assetDetails.errorMessage);
				}
			}, // end success: function
			error: function(XMLHttpRequest, textStatus, errorThrown) {

				alert("Error in request: " + errorThrown);
			}
		});    // end $.ajax
	}
	else {
		alert("Error: Cannot find the target container id that you have specified");
	}
}