;window.jQuery && (window.jQuery.fn.mediaCatchup || (function($, window, undefined) {

	jQuery.plugins = {
		 mimetypeDetect: function(types) {
			for (i=0; i<types.length; i++) {
				if(navigator.mimeTypes) {
					if (navigator.mimeTypes[types[i]]) {
						if (navigator.mimeTypes[types[i]].enabledPlugin)
							return true;
						else
							return false;
					}
				}
			}
		}

		,pluginDetect: function(type) {
			var plugin = jQuery.plugins.pluginOptions[type].plugin;
			var mimetypes = jQuery.plugins.pluginOptions[type].mimetypes;
			var activex = jQuery.plugins.pluginOptions[type].mimetypes;

			var hasPlugin = false;
			var hasActiveX = false;
			var atx = null;

			try {
				if (window.ActiveXObject) {
					atx = new ActiveXObject(activex);
				}
				else if (window.GeckoActiveXObject) {
					atx = new GeckoActiveXObject(activex);
				}

				if (atx.versionInfo) {
					hasActiveX = true;
				}
			}
			catch(e) {}

			if (navigator.plugins && navigator.plugins.length > 0) {
				for (i = 0; i < navigator.plugins.length; i++) {
					if (navigator.plugins[i].name.match(plugin)) {
						hasPlugin = true;
						break;
					}
				}
			}

			if (jQuery.plugins.mimetypeDetect(mimetypes) && !hasPlugin) {
				hasPlugin = true;
			}

			if (hasPlugin || hasActiveX) {
				return true;
			}
			return false;
		}

		,pluginOptions: {
			 flash: {
				plugin: "Shockwave Flash",
				activex: "",
				mimetypes: []
			}
			,quicktime: {
				plugin: "QuickTime Plug-in",
				activex: "",
				mimetypes: []
			}
			,winmedia: {
				plugin: "Windows Media Player",
				activex: "WMPlayer.OCX.7",
				mimetypes: [
					"video/x-ms-asf",
					"application/x-drm-v2",
					"application/x-ms-wmp",
					"application/x-ms-wmd"
				]
			}
			,flip4mac: {
				plugin: "Flip4Mac Windows Media Plugin",
				activex: "",
				mimetypes: []
			}
			,npmswmp: {
				plugin: "Microsoft® Windows Media Player Firefox Plugin",
				activex: "",
				mimetypes: []
			}
		}

		,pluginError: function(error) {
			var errorScreen = [
				 '<div class="pluginErrorMsg">'+
				'<p class="alerte">Vous ne possédez pas le plugin permettant de profiter au maximum des vidéos.</p>'+
				'<p class="telecharger"><a href="'+
				'http://medias2.francetv.fr/videosread/externe/wmv-firefox-plugin/WindowsMedia-Firefox-Plugin.exe'+
				'" class="targBlank"><span>Cliquez-ici pour le télécharger</span></a></p>'+
				'<p class="continue"><span>Afficher la vidéo tout de même</span></p>'+
				'</div>'

				,'<div class="pluginErrorMsg">'+
				'<p class="alerte">Vous ne possédez pas le plugin permettant lire cette vidéo.</p>'+
				'<p class="telecharger"><a href="'+
				'http://dynamic.telestream.net/downloads/download-flip4macwmv.htm'+
				'" class="targBlank"><span>Cliquez-ici pour télécharger FLIP4MAC</span></a></p>'+
				'<p class="continue"><span>Afficher la vidéo tout de même</span></p>'+
				'</div>'
			];
			return errorScreen[error];
		}
	};


	var mediaCatchup = (function() {
		var pathLogo = '/layoutftv/arches/common/images/video/ecran-PORTAIL.jpg'
		,pathPluginErrorCss = '/layoutftv/arches/common/stylesheets/jquery.mediaCatchup.css'

		,wmpTestPattern = /\.(asf|avi|wma|wmv|wsx|asx|m3u|php)($|\?)/
		,wmpCtrlFuncPattern = /^play|pause|stop|fastForward|fastReverse$/
		,wmpCtrlVarPattern = /^current(Position(Timecode)?|Item|Marker|AudioLanguage(Index)?)$/

		,clsLogoBlk = 'mediaLogoBlk'
		,clsPubBlk = 'mediaPubBlk'
		,clsRebourBlk = 'mediaRebour'
		,clsWrapperBlk = 'mediaPlayerBlk'

		,hauteurs = {
			 france2	: 285
			,france5	: 285
		}

		,portail = typeof ftvi_portail == 'string' ? ftvi_portail : 'france2'

		,pluginError = function(errornum) {
			var oObj = this
			,oMsg = $(jQuery.plugins.pluginError(errornum));
			oMsg
				.prependTo(this.wrapper())
				.find('.continue')
					.click(function() {
						oMsg.remove();
						oObj.wrapper().trigger('continue');
						return false;
					})
				.end()
				.find('.targBlank')
					.attr('target', '_blank');
			return false;
		}

		,rebourText = function(secondes) {
			var pluriel = secondes > 1;
			return secondes+' seconde' + (pluriel ? 's':'') + ' avant votre vidéo';
		}

		,defaultOptions = {
				 selectorBlockPub	: '#adMiddle03'
				,width				: 384
				,height				: hauteurs[portail] || 357
				,activeLogo			: true
				,timeLogo			: 2
				,portail			: portail
				,activePub			: false
				,timePub			: 5
				,activeMedia		: true
				,soustitre			: false
				,samiNode			: false
				,samiId				: 'soutitre'
				,initAction			: false
				,callback			: false
				,rebourText			: rebourText
				,activePluginError	: true
				,pluginError		: pluginError
				,pluginErrorCss		: pathPluginErrorCss
		}

		,defaultOptionsMedia = {
				 autoplay		: true
				,caption		: false
				,bgColor		: 'transparent'
				,params			: {
					 showstatusbar		: '1'
					,wmode				: 'transparent'
				}
		};

		return function(element, opt) {
			var $this = this
			,interval, mediaElement, mediaInitTime, wmpControl
			,options = $.extend(
				 {}
				,defaultOptions
				,opt
				,((typeof activepub == 'boolean') && activepub) ? {activePub: true} : {}
				,(typeof timepub == 'number') ? {timePub: timepub + 1} : {}
				,{forcePluginError: ($.browser.mozilla && typeof forcepluginerror == 'boolean' && forcepluginerror)}
			)
			,optionsMedia = $.extend(
				 {}
				,{width: options.width, height: options.height}
				,defaultOptionsMedia
				,options.optionsMedia
			)
			,chrono = options.timePub
			,isMedia = (options.activeMedia && element.is('a'))
			,isWmp = (isMedia && wmpTestPattern.test(element.attr('href') || ''))
			,doPreload = (function() {return isWmp && !$.browser.msie;})()
			,urlLogo = pathLogo.replace('PORTAIL', options.portail)

			,initAction = function() {
				if(typeof options.initAction == 'function'
					&& options.initAction.call($this) === false) {
						return;
				}
				wrapper.trigger('continue');
			}

			,continueAction = function() {
				if(!options.activePub) {
					initDisplayContent();
				}
				else if(!options.activeLogo) {
					displayPub();
				}
				else {
					window.setTimeout(displayPub, (options.timeLogo * 1000));
				}
			}

			,displayPub = function() {
				pub.show();
				logo.hide();
				interval = window.setInterval(rebourPub, 1000);
			}

			,rebourPub = function() {
				if(--chrono <= 0) {
					window.clearInterval(interval);
					initDisplayContent();
					return;
				}
				timeLine.html(options.rebourText(chrono));
			}

			,initDisplayContent = function() {
				pub.remove();
				logo.remove();
				wrapper.one('continue', continueDisplayContent);

				if(isWmp && (options.activePluginError || options.forcePluginError)) {
					if(navigator.appVersion.indexOf("Win") > 0 && $.browser.mozilla && !jQuery.plugins.pluginDetect('npmswmp')) {
						showPluginError(0);
						return;
					}
					else if(navigator.appVersion.indexOf("Mac") > 0 && !jQuery.plugins.pluginDetect('flip4mac')) {
						showPluginError(1);
						return;
					}
				}
				wrapper.trigger('continue');
			}

			,showPluginError = function(errornum) {
				if(options.pluginErrorCss) {
					$('head').append('<link type="text/css" media="screen" href="'+options.pluginErrorCss+'" rel="stylesheet" />');
				}
				if(	typeof options.pluginError == 'function'
					&& options.pluginError.call($this, errornum) === false) {
					return;
				}
				wrapper.trigger('continue');
			}

			,continueDisplayContent = function() {
				if(isMedia && !doPreload) {
					mediaStart();
				}
				else {
					var delta = (new Date().getTime()) - mediaInitTime;
					if(isWmp && delta < 500) {
						window.setTimeout(continueDisplayContent, 600 - delta);
						return;
					}
				}
				(isMedia ? mediaElement : element).show();
				if( typeof options.callback == 'function') {
					options.callback.call($this);
				}
			}

			,traitesoustitre = function() {
				var samiId, idx, st = String.prototype.match.call($.isFunction(options.soustitre) ? options.soustitre.call(element) : options.soustitre, /^(sami):(.*)$/i);
				if(!st) {
					return;
				}
				switch(st[1]) {
					case 'sami':
						soustitre = $.isFunction(options.samiNode) ? options.samiNode.call(element) : options.samiNode;
						if(!soustitre || $(soustitre).length === 0) {
							soustitre = $('<div />').insertAfter(element);
						}
						if(!(samiId = $(soustitre).attr('id'))) {
							idx = 1;
							samiId = options.samiId;
							while($('#'+samiId).length > 0) {
								samiId = options.samiId + idx++;
							}
							$(soustitre).attr('id', samiId);
						}

						if(optionsMedia.params === undefined) {
							optionsMedia.params = {};
						}
						$.extend(optionsMedia.params, {
							 SAMIFileName: st[2]
							,captioningID: samiId
							,SAMIStyle: 'Small Print'
							,SAMILang: 'French'
						});
						break;
					default:
						break;
				}
			}

			,mediaStart = function() {
				traitesoustitre();
				element.media(optionsMedia);
				mediaInitTime = new Date().getTime();
				wrapper
					.children()
					.not(logo)
					.not(pub)
					.not(soustitre || false)
					.hide()
					.each(function() {
						mediaElement = $(this);
						if(isWmp) {
							wmpControl = function(event, data) {
								mediaElement
									.children('object, embed')
									.each(function() {
											try {
												if(wmpCtrlFuncPattern.test(event.type)) {
													this.controls[event.type]();
												}
												else if(wmpCtrlVarPattern.test(event.type)) {
													this.controls[event.type] = data;
												}
											} catch (ex) {}
									});
							};
							mediaElement
								.bind('play', wmpControl)
								.bind('pause', wmpControl)
								.bind('stop', wmpControl)
								.bind('fastForward', wmpControl)
								.bind('fastReverse', wmpControl)
								.bind('currentPosition', wmpControl);

							element
								.bind('play', wmpControl)
								.bind('pause', wmpControl)
								.bind('stop', wmpControl)
								.bind('fastForward', wmpControl)
								.bind('fastReverse', wmpControl)
								.bind('currentPosition', wmpControl);
						}
					});
			}

			,logo = $('<div class="'+clsLogoBlk+'" />')
				.css({
					 position		: 'relative'
					,display		: 'block'
					,width			: options.width+'px'
					,height			: options.height+'px'
					,background		: 'black'
				})
				.append(
					$('<img src="'+urlLogo+'" alt="Logo '+options.portail+'" />')
						.css({
							 position		: 'absolute'
							,top			: '50%'
							,left			: '50%'
							,margin			: '-108px 0 0 -116px'
						})
				)

			,pub = $('<div class="'+clsPubBlk+'" />')
				.css({
					 position		: 'relative'
					,display		: 'none'
					,width			: options.width+'px'
					,height			: options.height+'px'
					,background		: 'black'
					,'text-align'	: 'center'
				})
				.append((function() {
					if(!$.browser.msie) {
						return $(options.selectorBlockPub).children().not('script').clone();
					}
					var wrapper = $('<div />')
						.append(
							$(options.selectorBlockPub)
								.children()
								.not('script')
						)
					,html = wrapper.html()
					,at = parseFloat($.fn.jquery) < 1.3 ? '@' : ''
					,flashvars =
						wrapper.find('param['+at+'name=flashvars]').attr('value') ||
						wrapper.find('param['+at+'name=FlashVars]').attr('value');
					wrapper
						.children()
							.appendTo(options.selectorBlockPub);
					wrapper = undefined;
					return html
							.replace(
								 /<param( name="flashvars"| value="[^"]*"){2}>/ig
								,'<param name="flashvars" value="' + flashvars + '">'
							);
				})())
				.bind('displayContent', initDisplayContent)

			,timeLine = $('<div class="'+clsRebourBlk+'">'+options.rebourText(options.timePub)+'</div>')
				.css({
					 position		: 'absolute'
					,bottom			: '2px'
					,left			: '0'
					,width			: '100%'
					,color			: 'white'
					,'font-weight'	: 'bold'
					,'line-height'	: '1em'
				})
				.appendTo(pub)

			,soustitre

			,wrapper = $('<div class="'+clsWrapperBlk+'" />')
				.insertAfter(element)
				.append(logo)
				.append(pub)
				.append(element.hide())
				.one('continue', continueAction);

			$.extend(this, {
				 content: function(original) {
					return (isMedia && (original !== true)) ? mediaElement : element;
				}
				,wrapper: function() {
					return wrapper;
				}
				,pub: function() {
					return pub;
				}
				,logo: function() {
					return logo;
				}
				,soustitre: function() {
					return soustitre;
				}
				,options: function() {
					return options;
				}
				,optionsMedia: function() {
					return optionsMedia;
				}
				,chrono: function() {
					return chrono;
				}
				,isMedia: function() {
					return isMedia;
				}
				,isWmp: function() {
					return isWmp;
				}
			});

			if(typeof forceactivepub == 'boolean') {
				options.activePub = forceactivepub;
			}
			else if(pub.children().length === 0) {
				options.activePub = false;
			}

			if(doPreload) {
				mediaStart();
			}

			initAction();
		};
	})();

	$.fn.mediaCatchup = function(options) {
		return this.each(function() {
			new mediaCatchup($(this), options);
		});
	};
})(window.jQuery, this));