$.getScript('/dl/js/jquery/plugin/jquery.touchwipe.min.js');

var rnd = new Date();
rnd = rnd.getTime();

var isIpad = (navigator.userAgent.match(/iPad/i));
var isIphone = (navigator.userAgent.match(/iPhone/i));
var isAndroid = (navigator.userAgent.match(/android/i));

var MediaItem = MediaItem || {};

MediaItem.popupAvailable = true;
MediaItem.playerExpandable = true;

MediaItem.startTime = false;

MediaItem.enableDebug = false;
MediaItem.enableTrace = false;
MediaItem.forceUniPlayer = false;
MediaItem.isLive = false;
MediaItem.type = MediaItem.type || false;
MediaItem.autoplay = true;
if ( /refresh_ce/.test(''+document.location.search) ) {
	MediaItem.autoplay = false;
}

MediaItem.opts = {};

MediaItem.WMV = {};
MediaItem.RAM = {}; // non usato: servono funzioni globali... :(
MediaItem.Audio = {}; // parzialmente usato: pure qui ci sono parecchie funzioni globali... :(
MediaItem.WMA = {}; // e' diverso da un ram! quindi non bisogna fare le stesse cose :P
MediaItem.FLV = {};
MediaItem.RSS = {};
MediaItem.Photo = {};

var mediaItemSilverlightCreated = false;

/*** Modifica per Barra Player Firefox 3.6.6 ***/
var windowless = 'true';
// if(navigator.userAgent.indexOf("Firefox/3.6") > 0) {
if(jQuery.browser.mozilla) {
	// windowless = 'false';
	try {
		var v = navigator.userAgent.match(/Firefox\/([0-9a-zA-Z.]*)/i);
		v = v[1];
		var Vmin = '3.6'; // problema con il windowless, nelle versioni successive alla 3.6
		// var Vmax = '3.6.10'; // il problema non si verifica piu' con la 3.6.10
		// sigh, alcuni utenti ancora hanno problemi con i pulsanti... altri (come me) no :'(
		//
		// if (v>Vmin && v<Vmax) {
		if (v>Vmin) {
			windowless = 'false';
		}
	} catch(e) {
		windowless = 'true';
	}
}

MediaItem.willReloadBannersAtPlayerCreation = function() {
	var isSilverlightUniplayer, isAutoPlay, hasBannerSpot;

	isSilverlightUniplayer = false;
	isAutoPlay = MediaItem.autoplay;
	hasBannerSpot = false;

	if (MediaItem.type == 'SmoothStreamingLive' ||
			MediaItem.type == 'SmoothStreaming') {
		isSilverlightUniplayer = true;
	} else if (MediaItem.type == 'WMV') {
		if (/http:\/\/tales.2lifecast.com/.test(videoURL)) {
			isSilverlightUniplayer = false;
		} else if (typeof(codificaVideo) != 'undefined' && codificaVideo == "MP4V3") {
		} else if (isIpad || isIphone || isAndroid) {
			isSilverlightUniplayer = false;
		} else {
			isSilverlightUniplayer = true;
		}
	} else if (MediaItem.type == 'Audio') {
		if ((typeof(formatoAudio) != 'undefined' && formatoAudio == 'WMA') ||
				!$('#Player .realRadio .controlliPlay .Play,.Player .realRadio .controlliPlay .Play').is(':visible')) {
			if (/mediapolis\.rai\.it/.test(url)) {
				isSilverlightUniplayer = true;
			}
		}
	}
	if (isSilverlightUniplayer &&
			typeof(videoBannerSL) != 'undefined' && videoBannerSL != '') {
		hasBannerSpot = true;
	}

	return isSilverlightUniplayer && isAutoPlay && hasBannerSpot;
};

function createMediaItemSilverlight() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	var rv = true;

	if ((typeof(window.videoBannerSL) == 'undefined' ||
			window.videoBannerSL == '')) {
		var bsp = '';
		if (typeof(window.parentSet) == 'object') {
			bsp = window.parentSet.bsp || '';
		} else if (typeof(window.parentPage) == 'object') {
			bsp = window.parentPage.bsp || '';
		}
		if (bsp != '') {
			window.videoBannerSL = ',pathbanner=http://ad2.neodatagroup.com/ad/' +
					'load_ndgruler.jsp?sid=49&loc=' + bsp +
					'&bt=n&wt=n&jsvar=&rnd=';
			bsp = new Date();
			bsp = bsp.getTime();
			window.videoBannerSL += bsp;
		}
	}

	if (typeof(window.forceBannerSpotSL) != 'undefined') {
		window.videoBannerSL = window.forceBannerSpotSL;
	}
	if (typeof(window.forceBannerSpot) != 'undefined') {
		window.videoBanner = window.forceBannerSpot;
	}
	if (typeof(stopBannerSL) != 'undefined' && stopBannerSL == 'noBanner') {
		window.videoBannerSL = '';
		window.videoBanner = '';
	}
	try {
		if (MediaItem[MediaItem.type].createMediaItemSilverlight) {
			rv = MediaItem[MediaItem.type].createMediaItemSilverlight();
		}
	} catch (e) {
		rv = false;
		try {
			console.log(e);
		} catch (e1) {
		}
	}
	return rv;
};
// questa la metto alla fine del file, quando tutti i metodi di creazione saranno definiti
// $(createMediaItemSilverlight);


MediaItem.getInitParams = function(params) {
	if (typeof (params.overrideConfig) == 'object') {
		var p = [];
		// extend UniPlayer.additionalConfig
		for (var type in params.overrideConfig) {
			if (type == 'Part') {
				for (var id in params.overrideConfig[type]) {
					var typeId = 'Part;id$'+id;
					var t = [];
					for (var par in params.overrideConfig[type][id]) {
						t.push(par+'$'+params.overrideConfig[type][id][par]);
					}
					p.push('type$'+typeId+';'+t.join(';'));
				}
			} else /* if (type == 'Startup' || type == 'CommandBar') */ {
				var t = [];
				for (var id in params.overrideConfig[type]) {
					t.push(id+'$'+params.overrideConfig[type][id]);
				}
				p.push('type$'+type+';'+t.join(';'));
			}
		}
		params.overrideConfig = p.join('|');
	}

	var initParams = [];
	for (var i in params) {
		if (params[i] != '') {
			initParams.push(i+'='+params[i]);
		}
	}
	initParams = initParams.join(',');

	return initParams;
};

/* *** WMV *** */


/** TODO verificare se e dove vengono utilizzare queste variabili */
var logoIMG = "http://www.rai.tv/dl/RaiTV/silverlight1.0/logo_rai.png";
var liveMode = "0";

MediaItem.WMV.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;

	videoURL = videoURL.replace(/&amp;/g, '&');
	if (!/\?/.test(videoURL) && !/\.csm$/.test(videoURL)) {
		videoURL += '?v';
	}

	if (/http:\/\/tales.2lifecast.com/.test(videoURL)) {
		window.refreshByJS = false;
		$('#silverlightControlHost').html(QT_GenerateOBJECTText(videoURL, '640', '388', '',
				'autoplay', ''+MediaItem.autoplay,
				'emb#bgcolor', 'black',
				'align', 'middle'));
		return true;
	}

	var altHtml = false;

	if (isIpad || isIphone || isAndroid) {
		if (typeof(window.videoURL_MP4) != 'undefined') {
			// per iPhone e iPad usiamo il tag html5 video con la versione mp4
			// altHtml = '<video width="640" height="360" controls autobuffer>';
			// altHtml = '<video width="100%" height="100%" controls autobuffer>';

			// <video id="VideoPlayer" src="http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=180354" autoplay="autoplay" controls="controls"> html 5 video not supported </video>
			altHtml = '<video width="100%" height="100%" controls="controls"'+(MediaItem.autoplay?' autobuffer="autobuffer" autoplay="autoplay"':'')+' src="'+window.videoURL_MP4+'">';
			// altHtml += '<source src="'+window.videoURL_MP4+'" type="video/mp4" />';
			altHtml += '<h3>Video non ancora disponibile per dispositivi mobili</h3></video>';
		} else {
			altHtml = '<h3>Video non ancora disponibile per dispositivi mobili</h3>';
		}
		$('#silverlightControlHost').html(altHtml);
		window.refreshByJS = false;
		if (isAndroid) {
			$('#silverlightControlHost video').click(function() {
				this.play();
			});
		}
	} else if (typeof(codificaVideo) != 'undefined' && codificaVideo == "MP4V3") {
		// formato video non supportato da silverlight ma solo da windows media player.
		window.refreshByJS = false;
		var playerHtml = '<object classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6"\n'+
			'	width="100%" height="100%"\n'+
			'	codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"\n'+
			'	standby="Loading Microsoft Windows Media Player components..."\n'+
			'	type="application/x-oleobject">\n'+
			'	<param name="URL" value="'+videoURL+'" />\n'+
			'	<param name="animationatStart" value="true" />\n'+
			'	<param name="transparentatStart" value="true" />\n'+
			(MediaItem.autoplay?'	<param name="autoStart" value="true" />\n':'')+
			'	<param name="controls" value="imagewindow" />\n'+
			'	<param name="ShowControls" value="true" />\n'+
			'	<param name="ShowStatusBar" value="true" />\n'+
			'	<param name="ShowDisplay" value="true" />\n'+
			'	<param name="bgcolor" value="#B4BBCA"/>\n'+
			'	<!-- mostra la barra di stato -->\n'+
			(altHtml?altHtml:'')+
			'	<embed type="application/x-mplayer2" pluginspage = "http://www.microsoft.com/windows/mediaPlayer/"\n'+
			'		src="'+videoURL+'"\n'+
			'		animationatStart="true"\n'+
			'		transparentatStart="true"\n'+
			(MediaItem.autoplay?'		autoStart="true"\n':'')+
			'		controls="imagewindow"\n'+
			'		ShowControls="true"\n'+
			'		ShowStatusBar="true"\n'+
			'		ShowDisplay="true"\n'+
			'		bgcolor="#B4BBCA"\n'+
			'		width="100%"\n'+
			'		height="100%" />\n'+
			'</object>';
		$('#silverlightControlHost').html(playerHtml);

	} else {
		// video con player silverlight

		var slParams = {};

		if (MediaItem.enableDebug === true) {
			if (MediaItem.enableTrace === true) {
				slParams.configUri = '/dl/objects/silverlight/uniplayer/Config.smooth.trace.xml';
			} else {
				slParams.configUri = '/dl/objects/silverlight/uniplayer/Config.smooth.debug.xml';
			}
		} else {
			slParams.configUri = '/dl/objects/silverlight/uniplayer/Config.smooth.xml';
		}
		// initParams.push("overrideConfig=type$Part;id$10;initiallyVisible$false;refreshInterval$0|type$CommandBar;isHighlightsButtonVisible$false");
		slParams.overrideConfig = {};

		slParams.overrideConfig.Startup = {};
		slParams.overrideConfig.Part = {};
		slParams.overrideConfig.CommandBar = {};

		slParams.overrideConfig.Startup.autoplay = MediaItem.autoplay?'true':'false';

		if (!!MediaItem.startTime) {
			slParams.overrideConfig.Startup.startPosition = MediaItem.startTime;
		}

		// sottotitoli

		if (typeof(subtitle) != 'undefined' && subtitle != '') {
			slParams.configUri = '/dl/objects/silverlight/uniplayer/Config.smooth.subs.xml';
			slParams.overrideConfig.Part[20] = {};
			slParams.overrideConfig.CommandBar.isSubtitlesButtonVisible = 'true';
			slParams.overrideConfig.Part[20].initiallyVisible = 'true';
			if (/offset=/.test(subtitle)) {
				slParams.overrideConfig.Part[20].offset = subtitle.replace(/,stlPath=(.*),offset=(.*)/, '$2');
				slParams.overrideConfig.Part[20].subtitlesUri = subtitle.replace(/,stlPath=(.*),offset=(.*)/, '$1');
			} else {
				slParams.overrideConfig.Part[20].subtitlesUri = subtitle.replace(/,stlPath=(.*)/, '$1');
			}
		} else {
			slParams.overrideConfig.CommandBar.isSubtitlesButtonVisible = 'false';
		}

		// highlights
		slParams.overrideConfig.Part[10] = {};

		var isHighlightsButtonVisible = true;
		if (typeof(infoUrl) != 'undefined' && infoUrl != '') {
			slParams.overrideConfig.Part[10].uri = infoUrl;
			slParams.overrideConfig.Part[10].initiallyVisible = 'true';
			slParams.overrideConfig.Part[10].refreshInterval = 30;
			slParams.overrideConfig.CommandBar.isHighlightsButtonVisible = 'true';
		} else {
			slParams.overrideConfig.Part[10].initiallyVisible = 'false';
			slParams.overrideConfig.Part[10].refreshInterval = 0;
			slParams.overrideConfig.CommandBar.isHighlightsButtonVisible = 'false';
		}

		// altri pulsanti della CommandBar
		slParams.overrideConfig.CommandBar.isPopupButtonVisible = (MediaItem.popupAvailable?'true':'false');
		slParams.overrideConfig.CommandBar.isExpandButtonVisible = (MediaItem.playerExpandable?'true':'false');
		slParams.overrideConfig.CommandBar.isTimelineVisible = (!MediaItem.isLive?'true':'false');
		slParams.overrideConfig.CommandBar.isTimeAreaVisible = (!MediaItem.isLive?'true':'false');
		slParams.overrideConfig.CommandBar.isReplayButtonVisible = (!MediaItem.isLive?'true':'false');


		slParams.mediaUri = videoURL;
		if (typeof(videoFormat) != 'undefined' &&
				videoFormat != 'smooth' && videoFormat != 'csm' &&
				typeof(videoURL_MP4) != 'undefined') {
			// slParams.mediaUri = videoURL_MP4;
		}

		if (typeof(videoBannerSL) != 'undefined' && videoBannerSL != '') {
			videoBannerSL = videoBannerSL.replace(/&amp;/g, '&');
			if (/.*pathbanner=(.*)$/.test(videoBannerSL)) {
				slParams.advertisingUri = videoBannerSL.replace(/.*pathbanner=(.*)$/, '$1');
			} else {
				slParams.advertisingUri = videoBannerSL;
			}
			bannersLoaded = !!MediaItem.autoplay;
		}

		var initParams = MediaItem.getInitParams(slParams);

		Silverlight.createObjectEx(
			{
				source: "/dl/objects/silverlight/uniplayer/Rai.UniPlayer.xap",
				parentElement: $('#silverlightControlHost')[0],
				id: 'SilverlightControl',
				properties: {
					width: '100%',
					height: '100%',
					inplaceInstallPrompt: false,
					background: 'transparent',
					windowless: windowless,
					framerate: '25',
					enableHtmlAccess: 'true',
					version: '4.0',
					alt: altHtml
				},
				events: {
					onLoad: function() {
						try {
							$('#silverlightControlHost')[0].focus();
						} catch (e) {
						}
					}
				},
				initParams: initParams,
				context: {
				}
			}
		);
	}
	return true;
};

/* *** RAM *** */

function RMPlayer_EMBED_OnVolumeChange(newVolume) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnVolumeChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnVolumeChange(newVolume);
	}
}

function RMPlayer_EMBED_OnMuteChange(newIsMute) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnMuteChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnMuteChange(newIsMute);
	}
}


function RMPlayer_EMBED_OnTitleChange(title) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnTitleChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnTitleChange(title);
	}
}


function RMPlayer_EMBED_OnAuthorChange(author) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnAuthorChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnAuthorChange(author);
	}
}

function RMPlayer_EMBED_OnCopyrightChange(copyright) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnCopyrightChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnCopyrightChange(copyright);
	}
}

function RMPlayer_EMBED_OnErrorMessage(severity,rma_code,user_code,user_string,more_info_url,error) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnErrorMessage == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnErrorMessage(severity,rma_code,user_code,user_string,more_info_url,error);
	}
}

function RMPlayer_EMBED_OnPosLength(pos,len) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnPosLength == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnPosLength(pos,len);
	}
}


function RMPlayer_EMBED_OnPositionChange(pos,len) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnPositionChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnPositionChange(pos,len);
	}
}


function RMPlayer_EMBED_onClipOpened(short_clip_name,url) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnClipOpened == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnClipOpened(short_clip_name,url);
	}
}


function RMPlayer_EMBED_onClipClosed() {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnClipClosed == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnClipClosed();
	}
}

function RMPlayer_EMBED_OnPlayStateChange(oldState, newState) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnPlayStateChange == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnPlayStateChange(oldState, newState);
	}
}

function RMPlayer_EMBED_OnLButtonDown(button_flags, x_pos, ypos) {
	if (typeof document.RMPlayer_EMBED.PAO  == 'object' && typeof document.RMPlayer_EMBED.PAO.raiseOnLButtonDown == 'function') {
		document.RMPlayer_EMBED.PAO.raiseOnLButtonDown(button_flags, x_pos, ypos);
	}
}


/* *** AUDIO *** */
function loadRadio(url, titolo) {
	window.refreshByJS = false;

	var played = false;
	if ($('#lives').length>0) {
		try {
			document.lives.SetSource(url);
			document.lives.DoPlay();
			played = true;
		} catch (e) {
			played = false;
		}
	}
	if (!played) {
		var realZ = '<embed width="150" height="25" name="live" id="lives" TYPE="audio/x-pn-realaudio-plugin" src="'+url+'" CONTROLS="StatusBar" center="true" autostart="true" NOLOGO="true" CONSOLE="one" />';
		$('.realStream').html(realZ);
		//alert('1 '+document.lives);
		//alert('2 '+($('#lives').get(0) == document.lives));
		if (document.lives == null) {
			document.lives = $('#lives').get(0);
			//alert('3 '+document.lives);
		}
	}
	if (titolo.length < 20) {
		$('.Display h2').html(titolo);
	} else {
		$('.Display h2').html('<marquee scrolldelay="1" scrollamount="1">'+titolo+'</marquee>');
	}
	$('.controlliPlay .Play').css({backgroundPosition: '0px 0px'});
	return false;
}

function setRollOverRadio() {
	var li = $(".Channels ul li");
	li.click(function() {
		li.removeClass('selected');
		$(this).addClass('selected');
	});
}
function moveSelection(offset) {
	var lis = $(".Channels ul li");
	var count = lis.length;
	var curr = 0;
	lis.each(function(i){if ($(this).is('.selected')) curr = i;});
	curr = (count+curr+offset)%count;
	var n = $(lis.get(curr));
	$('a', n).click();
	n.click();
}

function changeTitle(title) {
	title = title.replace(/&#39;/g, "'");
	document.title = title;
}

function sliderUpdated(e, ui) {
	if (!ui || ui === '') {
		ui = $('.Volume').slider('ui');
		if (ui['value'] == null) {
			return;
		}
	}

	document.lives.SetVolume(100-ui.value);
	// posiziona lo sfondo dello slider
	var slider = $('.contVolume .ui-slider');
	var handler = $('.contVolume .ui-slider-handle');
	var top = handler.position().top + handler.height()/2;
	slider.css({backgroundPosition: 'left '+top+'px'});
}

var RPStatus = {STOPPED: 0, CONTACTING: 1, BUFFERING: 2, PLAYING: 3, PAUSED: 4, SEEKING: 5};

// function initAudio() {
MediaItem.Audio.createMediaItemSilverlight = function() {
	if (typeof(window.audioUrl) != 'undefined') {
		url = window.audioUrl;
	}
	if (typeof(url) == 'string') {
		window.audioUrl = url; // garantisco che esista audioUrl
	}

	if (typeof(formatoAudio) == 'undefined' || formatoAudio == '') {
		if (/\.ram/.test(audioUrl) || (!/mediapolis\.rai\.it/.test(audioUrl) && !/\./.test(audioUrl.replace(/.*\/dl\//, '')))) {
			formatoAudio = 'RAM';
		} else if (/\.mp3/.test(audioUrl)) {
			formatoAudio = 'MP3';
		}
	}

	if (typeof(formatoAudio) != 'undefined' && (formatoAudio == '' || formatoAudio == 'WMA' || formatoAudio == 'MP3')) {
		if (/mediapolis\.rai\.it/.test(audioUrl) ||
				formatoAudio != 'WMA') {
				return MediaItem.WMASL.createMediaItemSilverlight();
		} else {
				return MediaItem.WMA.createMediaItemSilverlight();
		}
	}

	if (typeof(formatoAudio) != 'undefined' && formatoAudio == 'RAM') {
		window.refreshByJS = false;
		$('.Player').html('<embed console="two" nologo="true" autostart="false" ' +
											'center="true" controls="all" src="' + url +
											'" type="audio/x-pn-realaudio-plugin" id="lives" ' +
											'name="live" height="100%" width="100%" ' +
											'title="RealPlayer" />');
		return false;
	}

	window.refreshByJS = false;

	setRollOverRadio();
	if (url == null || url == '' || url=='null') {
		//loadRadio('http://www.radio.rai.it/live/radio1.ram', 'Radio1');
		var n = $(".Channels ul li:first");
		$('a', n).click();
		n.click();
	} else {
		var l = $(".Channels ul li").filter(function(){
			var s = $('a', $(this)).attr('href');
			if (s == '#')
				s = ' '+$('a', $(this)).attr('onclick');
			return s.indexOf(url)>=0
		});
		if (l.length==0) {
			loadRadio(url, titolo);
		} else {
			$('a', l).click();
			l.click();
		}
	}
	if (titolo.length < 20) {
		$('.Display h2').html(titolo);
	} else {
		$('.Display h2').html('<marquee scrolldelay="1" scrollamount="1">'+titolo+'</marquee>');
	}
	$('.Volume').slider({ steps: 10, range: false, change: sliderUpdated });
	$('.Volume').bind('slide',sliderUpdated);

	// gestione del tasto play/stop
	$('.controlliPlay .Play').click(
		function() {
			var p = document.lives;
			if (p.GetPlayState() == RPStatus.STOPPED) {
				p.DoPlay();
				//$('.controlliPlay .Play').animate({backgroundPosition: '0px -50px'}, 1500);
				$(this).css('backgroundPosition', '0px -50px');
			} else {
				p.DoStop();
				//$('.controlliPlay .Play').animate({backgroundPosition: '0px -150px'}, 1500);
				$(this).css('backgroundPosition', '0px -150px');
			};
			$(this).triggerHandler('hover');
			return false;
		}
	);
	$('.controlliPlay .Play').hover(
		function(){var p = document.lives; if (p.GetPlayState() == RPStatus.STOPPED) {$(this).css('backgroundPosition', '0px -150px');} else {$(this).css('backgroundPosition', '0px -50px');} },
		function(){var p = document.lives; if (p.GetPlayState() == RPStatus.STOPPED) {$(this).css('backgroundPosition', '0px -100px');} else {$(this).css('backgroundPosition', '0px 0px');} }
	);

	// gestione dei pulsanti destra/sinistra
	$('.controlliPlay .Indietro').click(function() { /* moveSelection(-1); */ });
	$('.controlliPlay .Avanti').click(function() { /* moveSelection(1); */ });
};

MediaItem.WMA.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;

	if (titolo.length < 20) {
		$('.Display h2').html(titolo);
	} else {
		$('.Display h2').html('<marquee scrolldelay="1" scrollamount="1">'+titolo+'</marquee>');
	}



	if ($('.realRadio').find('object,embed').length == 0) {
		var html = '<object id="lives" width="231" height="26"\n'+
		'	  classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95"\n'+
		'	  codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"\n'+
		'	  standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">\n'+
		'	  <param name="fileName" value="'+url+'" />\n'+
		'	  <param name="animationatStart" value="true" />\n'+
		'	  <param name="transparentatStart" value="true" />\n'+
		'	  <param name="autoStart" value="true" />\n'+
		'	  <param name="showControls" value="true" />\n'+
		'	  <param name="loop" value="false" />\n'+
		'	  <embed type="application/x-mplayer2"\n'+
		'		pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"\n'+
		'		name="live" displaysize="4" autosize="-1"\n'+
		'		bgcolor="darkblue" showcontrols="true" showtracker="-1"\n'+
		'		showdisplay="0" showstatusbar="-1" videoborder3d="-1" width="231" height="26"\n'+
		'		src="{units/audioUnit/url}" autostart="true" designtimesp="5311" loop="false">\n'+
		'	  </embed>\n'+
		'</object>';
		$('.realRadio').append(html);
	}
	window.refreshByJS = false;

	/*

		<object id='lives' width="231" height="26"
			  classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'
			  codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'
			  standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>
			  <param name='fileName' value="{units/audioUnit/url}" />
			  <param name='animationatStart' value='true' />
			  <param name='transparentatStart' value='true' />
			  <param name='autoStart' value="true" />
			  <param name='showControls' value="true" />
			  <param name='loop' value="false" />
			  <embed type='application/x-mplayer2'
				pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'
				name='live' displaysize='4' autosize='-1'
				bgcolor='darkblue' showcontrols="true" showtracker='-1'
				showdisplay='0' showstatusbar='-1' videoborder3d='-1' width="231" height="26"
				src="{units/audioUnit/url}" autostart="true" designtimesp='5311' loop="false">
			  </embed>
		</object>

	<embed
		class="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6"
		width="250" height="30"
		name="live" id="lives"
		type="audio/x-ms-wma"
		src="{units/audioUnit/url}"
		ShowControls="1"
		center="true"
		autostart="false"
		nologo="true"
		console="one" />
	<style type="text/css">
		div.realRadio div.maskVolume{visibility: hidden;}
		div.realRadio div.contVolume{visibility: hidden;}
		#playerVod div.realRadio div.controlliPlay {display: block;float: left;width: 98px;height: 95px;margin: 0px 0px 0px 0px;padding: 1px 0px 1px 0px;background: url(/dl/RaiTV/images/pulse.gif) no-repeat;}
		#playerVod div.realRadio div.controlliPlay a.Indietro:link, #playerVod div.realRadio div.controlliPlay a.Indietro:visited {display: none;}
		#playerVod div.realRadio div.controlliPlay a.Avanti:link, #playerVod div.realRadio div.controlliPlay a.Avanti:visited{display: none;}
		#playerVod div.realRadio div.controlliPlay a.Play:link, #playerVod div.realRadio div.controlliPlay a.Play:visited{display: none;}
	</style>
	*/
};
MediaItem.WMASL = {}; // Windows Media Audio - SilverLight
MediaItem.WMASL.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;

	var altHtml = '<object type="application/x-oleobject" standby="Loading Microsoft Windows Media Player components..." codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" height="26" width="231" id="lives">'+
		'<param value="'+url+'" name="fileName"/>'+
		'<param value="true" name="animationatStart"/>'+
		'<param value="true" name="transparentatStart"/>'+
		'<param value="true" name="autoStart"/>'+
		'<param value="true" name="showControls"/>'+
		'<param value="false" name="loop"/>'+
		'<embed loop="false" designtimesp="5311" autostart="true" src="'+url+'" height="26" width="231" videoborder3d="-1" showstatusbar="-1" showdisplay="0" showtracker="-1" showcontrols="true" bgcolor="darkblue" autosize="-1" displaysize="4" name="live" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/" type="application/x-mplayer2" />'+
		'</object>';

	if (!/^http:/i.test(url) && /^\//.test(url)) {
		url = 'http://www.rai.tv'+url;
	}

	var initParams = [];

	if (MediaItem.enableDebug === true) {
		if (MediaItem.enableTrace === true) {
			initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.audio.trace.xml");
		} else {
			initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.audio.debug.xml");
		}
	} else {
		initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.audio.xml");
	}
	// initParams.push("overrideConfig=type$Part;id$10;initiallyVisible$false;refreshInterval$0|type$CommandBar;isHighlightsButtonVisible$false");
	var commandBarConfig = [];
	commandBarConfig.push('isSubtitlesButtonVisible$false');
	commandBarConfig.push('isTimelineVisible$true');
	commandBarConfig.push('isPopupButtonVisible$' + (MediaItem.popupAvailable?'true':'false'));
	commandBarConfig.push('isExpandButtonVisible$' + (MediaItem.playerExpandable?'true':'false'));

	if (!MediaItem.autoplay) {
		initParams.push("overrideConfig=type$Startup;autoPlay$false" + '|type$CommandBar;' + commandBarConfig.join(';'));
	} else {
		initParams.push("overrideConfig=type$Startup;autoPlay$true" + '|type$CommandBar;' + commandBarConfig.join(';'));
	}
	initParams.push("mediaUri="+url);
	if (typeof(videoBannerSL) != 'undefined' && videoBannerSL != '') {
		videoBannerSL = videoBannerSL.replace(/&amp;/g, '&');
		if (/.*pathbanner=(.*)$/.test(videoBannerSL)) {
			initParams.push("advertisingUri="+videoBannerSL.replace(/.*pathbanner=(.*)$/, '$1'));
		} else {
			initParams.push("advertisingUri="+videoBannerSL);
		}
		bannersLoaded = !!MediaItem.autoplay;
	}

	initParams = initParams.join(',');

	Silverlight.createObjectEx(
		{
			source: "/dl/objects/silverlight/uniplayer/Rai.UniPlayer.xap",
			parentElement: $('.Player')[0],
			id: 'WmaSL',
			properties: {
				width: '100%',
				height: '100%',
				inplaceInstallPrompt: false,
				background: 'transparent',
				windowless: windowless,
				framerate: '25',
				enableHtmlAccess: 'true',
				version: '4.0',
				alt: altHtml
			},
			events: {
				onLoad: function() {
					try {
						$('#silverlightControlHost')[0].focus();
					} catch (e) {
					}
				}
			},
			initParams: initParams,
			context: {
			}
		}
	);
	window.refreshByJS = false;
};

/* *** FLV *** */
MediaItem.FLV.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;

	var width          = MediaItem.FLV.width || '433';
	var height         = MediaItem.FLV.height || '325';

	var videoCode = AC_FL_RunContent_jquery(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
		'width', width,
		'height', height,
		'id', 'playerFLV',
		'align', 'middle',
		'src', 'http://www.rai.tv/dl/RaiTV/flash/player',
		'quality', 'high',
		'bgcolor', '#0a0a0a',
		'name', 'playerFLV',
		'allowscriptaccess', 'sameDomain',
		'allowfullscreen', 'true',
		'wmode', 'transparent',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'flashvars', flashvars,
		'movie', 'http://www.rai.tv/dl/RaiTV/flash/player'
	);
	if ($('#Player').length > 0) {
		$('#Player').append(videoCode);
	} else {
		$('.Player').append(videoCode);
	}
	window.refreshByJS = false;
};

/* *** RSS *** */
MediaItem.RSS.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;

	var videoCode = AC_FL_RunContent_jquery(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
		'width', '433',
		'height', '325',
		'id', 'playerRSS',
		'align', 'middle',
		'src', 'http://www.rai.tv/dl/RaiTV/flash/podcast',
		'quality', 'high',
		'bgcolor', '#0a0a0a',
		'name', 'playerRSS',
		'allowscriptaccess', 'sameDomain',
		'allowfullscreen', 'true',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'flashvars', 'datapath='+datapath,
		'movie', 'http://www.rai.tv/dl/RaiTV/flash/podcast'
	);
	$('#Player,.Player').append(videoCode);
	window.refreshByJS = false;
};

/* *** Photo (fotogallery) *** */
MediaItem.Photo.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;


	function getParams(s) {
		if (s == null) {
			s = document.location.search;
			if (s == null || s == '') {
				s = document.location.hash;
			}
		}
		if (s.match(/^\?/) || s.match(/^#/)) {
			s = s.substring(1);
		}
		var strParams = s.split('&');
		var params = {};
		var i = 0;
		for (i in strParams) {
			var name = strParams[i];
			if (!!name) {
				var value = true;
				var pos = name.indexOf('=');
				if (pos>0) {
					value = decodeURIComponent(name.substring(pos+1));
					name = name.substring(0, pos);
				}
				params[name] = value;
			}
		}
		return params;
	};
	function getParam(name, string) {
		var params = getParams(string);
		return params[name] || false;
	};

	/*
	old values
	var width = 424;
	var height = 330;
	var thumbsVisible = 'true';
	*/
	var width = '100%';
	var height = '100%';
	var background = '#0a0a0a';
	var thumbsVisible = 'false';

	var initImageIndex = getParam('photoStart');
	try {
		initImageIndex = parseInt(initImageIndex);
	} catch (e) {
		initImageIndex = 1;
	}

	MediaItem.Photo.initImageIndex = initImageIndex;

	if (!!initImageIndex) {
		initImageIndex = ',initImageIndex='+initImageIndex;
	} else {
		initImageIndex = '';
	}

	if (typeof(MediaItem.opts) == 'object') {
		try {
			if (MediaItem.opts.width)
				width = MediaItem.opts.width;
			if (MediaItem.opts.height)
				height = MediaItem.opts.height;
			if (MediaItem.opts.background)
				background = MediaItem.opts.background;
			if (typeof(MediaItem.opts.thumbsVisible) != 'undefined')
				thumbsVisible = MediaItem.opts.thumbsVisible ? 'true':'false';
		} catch(e) {
		}
	}
	var path = '';
	if (typeof(photoXml) != 'undefined') {
		path = photoXml;
	} else if (typeof(uniquename) != 'undefined') {
		path = 'http://www.rai.tv/dl/RaiTV/programmi/media/'+uniquename+'-xml.xml';
	}
	// window.skipNielsen = true;

	MediaItem.Photo.width          = width;
	MediaItem.Photo.height         = height;
	MediaItem.Photo.slideShowTimer = 5; // secondi
	MediaItem.Photo.path           = path;

	if (isIpad || isIphone || isAndroid) {
		if (!path.match(/^https?:/)) {
			if (path.match(/^\//)) {
				path = 'http://www.rai.tv'+path;
			} else {
				path = 'http://www.rai.tv/dl/RaiTV/programmi/media/'+path;
			}
		}
		var xmlLoader = 'http://service.rai.it/xml2json.php?jsonp=?&xmlurl='+escape(path);
		$.getJSON(xmlLoader, MediaItem.Photo.createHtmlPhotoGallery);
	} else {
		Silverlight.createObject(
			// "/dl/portale/silverlight/PhotoGallery/PhotoGallery.xap",
			"/dl/objects/silverlight/raitv/PhotoGallery.xap",
			$('#silverlightControlHost')[0],
			'silverlightControl',
			{
				width: width,
				height: height,
				inplaceInstallPrompt: false,
				background: background,
				windowless: windowless,
				framerate: '25',
				version: '4.0'
			},
			{
				onError: function(){}
			},
			'slideShowTimer='+MediaItem.Photo.slideShowTimer+', galleryXmlPath='+path+', statsFunct=setNielsenLoc, showTitle=true, thumbsVisible='+thumbsVisible+initImageIndex+
			',popupFunct=openPopup'+
			',zoomFunct=zoomWindow',
			{
			}
		);
		try {
			document.getElementById('silverlightControlHost').focus();
		} catch (e) {
		}
	}
};
MediaItem.Photo.createHtmlPhotoGallery = function(data) {
	// manca la gestione del parametro thumbsVisible, ancora :)

	var width          = MediaItem.Photo.width;
	var height         = MediaItem.Photo.height;
	MediaItem.Photo.imageIndex = (MediaItem.Photo.initImageIndex - 1) || 0;
	var slideShowTimer = MediaItem.Photo.slideShowTimer;

	MediaItem.Photo.data = data;
	var units = data['multiple-content'].item.units;


	/*
	<div class="photo">
		<div class="h">
			<h3> </h3>
			<div class="t"> </div>
		</div>
		<div class="m">
			<a class="prev"> </a>
			<a class="next"> </a>
		</div>
		<div class="b">
		</div>
	</div>
	*/
	var html = '<div class="photo"> <div class="h"> <h3> </h3> <div class="t"> </div> </div> <div class="m"> <a class="prev" title="Precedente"> </a> <a class="next" title="Successiva"> </a> <div class="mask"> </div> </div> <div class="b"> </div> </div>'
	var d = $(html);
	d.width(width);
	d.find('>.h').width(width);
	d.find('>.m').width(width);
	d.find('>.m>.mask').width(width);
	d.find('>.b').width(width);
	var desc = '';
	if (units.textUnit && units.textUnit.length) {
		for (var i = 0; i<units.textUnit.length; i++) {
			if (units.textUnit[i]['@attributes'].type == 'Title') {
				tit = units.textUnit[i].text;
			}
			if (units.textUnit[i]['@attributes'].type == 'Testo breve') {
				desc = units.textUnit[i].text;
			}
		}
	}
	d.find('.h h3').html(tit);
	var ul = $('<ul></ul>').appendTo(d.find('.m'));
	for (var i = 0; i<units.imageUnit.length; i++) {
		if (units.imageUnit[i]['@attributes'].type == 'Photogallery RaiTv Image') {
			var li = $('<li><img src="'+units.imageUnit[i].image+'" height="253" /><div></div></li>');
			li.find('div').html(units.imageUnit[i]['@attributes'].name);
			ul.append(li);
		}
	}
	MediaItem.Photo.imagecount = ul.find('li').length;
	ul.find('li').css({width: width+'px', margin: '0px'});
	var newWidth = ul.find('li').width();
	if (!newWidth) {
		newWidth = d.find('.m').width();
	}
	if (!newWidth) {
		newWidth = width;
	}
	width = newWidth;
	ul.css({width: (MediaItem.Photo.imagecount*width)+'px', position: 'absolute', top: '0px', left: -(MediaItem.Photo.imageIndex*width)+'px'});

	function update() {
		// ul.find('li').hide().slice(MediaItem.Photo.imageIndex,  MediaItem.Photo.imageIndex+1).show();
		ul.animate({left: -(MediaItem.Photo.imageIndex*width)+'px'}, 500);
		d.find('.h .t').html((MediaItem.Photo.imageIndex+1) + ' / ' + MediaItem.Photo.imagecount);
		if (!skipNielsen) {
			setNielsenLoc(MediaItem.Photo.imageIndex);
		}
		skipNielsen = false;
	}

	function prev() {
		if (MediaItem.Photo.imageIndex == 0) {
			ul.css({left: -(MediaItem.Photo.imagecount*width)+'px'});
		}
		MediaItem.Photo.imageIndex = (MediaItem.Photo.imageIndex - 1 + MediaItem.Photo.imagecount) % MediaItem.Photo.imagecount;
		update();
	}
	function next() {
		if (MediaItem.Photo.imagecount - 1 == MediaItem.Photo.imageIndex) {
			ul.css({left: width+'px'});
		}
		MediaItem.Photo.imageIndex = (MediaItem.Photo.imageIndex + 1 + MediaItem.Photo.imagecount) % MediaItem.Photo.imagecount;
		update();
	}
	if (typeof(d.find('.m').touchwipe) == 'function') {
		d.find('.m').touchwipe({
			min_move_x: 20,
			wipeLeft: next,
			wipeRight: prev,
			preventDefaultEvents: true
		});
	}

	d.find('a.prev').click(prev);
	d.find('a.next').click(next);

	var skipNielsen = true;
	update();

	$('#silverlightControlHost').empty().append(d);
};

function setNielsenLoc(photoIndex) {


	function replaceMSWord(str) {
		str = str.replace(/…/g,'...');
		str = str.replace(/“/g,'"');
		str = str.replace(/”/g,'"');
		str = str.replace(/’/g,"'");
		return str;
	};

	var tags = '';
	var nomeProgramma = '';
	var logoEditore = '';
	var myPageMedia = '';
	try {myPageMedia = $('#myPageMedia').text() != "null" ? $('#myPageMedia').text() : "";} catch(e){}
	try {nomeProgramma = $("DIV.logoDescr").children("H2").text() != "null" ? replaceMSWord($("DIV.logoDescr").children("H2").text()) : "";} catch(e){}
	nomeProgramma = jQuery.trim(nomeProgramma);

	try {tags = $('#myTematiche').text() != "null" ? replaceMSWord($('#myTematiche').text()) : "";} catch(e){}

	try {
		logoEditore = $(".logoEditore>img").attr("alt");
	} catch(e){
		logoEditore ="";
	}

	if(nomeProgramma == ""){
		tags = tags.substring(0,tags.length-1);
	} else {nomeProgramma = "NomeProgramma:"+nomeProgramma;}
	tags = tags + nomeProgramma;
	tags += "^PageOB:"+myPageMedia;

	var h = location.href+
		"&tags="+tags+
		"&editore="+logoEditore+
		"&foto="+photoIndex+
		"&refresh_ce-awe";

	setNielsen(h);
}


/* *** SmoothStreaming *** */
MediaItem.SmoothStreamingLive = {};
MediaItem.SmoothStreamingLive.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;

	videoURL = videoURL.replace(/&amp;/g, '&');

	var altHtml = false;

	if (isIpad || isIphone || isAndroid) {
		if (typeof(window.videoURL_MP4) != 'undefined') {
			// per iPhone e iPad usiamo il tag html5 video con la versione mp4
			// altHtml = '<video width="640" height="360" controls autobuffer>';
			// altHtml = '<video width="100%" height="100%" controls autobuffer>';

			// <video id="VideoPlayer" src="http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=180354" autoplay="autoplay" controls="controls"> html 5 video not supported </video>
			altHtml = '<video width="100%" height="100%" controls="controls"'+(MediaItem.autoplay?' autobuffer="autobuffer" autoplay="autoplay"':'')+' src="'+window.videoURL_MP4+'">';
			// altHtml += '<source src="'+window.videoURL_MP4+'" type="video/mp4" />';
			altHtml += '<h3>Video non ancora disponibile per dispositivi mobili</h3></video>';
		} else {
			altHtml = '<h3>Video non ancora disponibile per dispositivi mobili</h3>';
		}
		$('#silverlightControlHost').html(altHtml);
		if (isAndroid) {
			$('#silverlightControlHost video').click(function() {
				this.play();
			});
		}
	} else {

		var initParams = [];

		// initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.smooth.xml");
		if (MediaItem.enableDebug === true) {
			if (MediaItem.enableTrace === true) {
				initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.smooth.trace.xml");
			} else {
				initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.smooth.debug.xml");
			}
		} else {
			initParams.push("configUri=/dl/objects/silverlight/uniplayer/Config.smooth.xml");
		}
		var autoplay = '';
		if (!MediaItem.autoplay) {
			autoplay = "|type$Startup;autoPlay$false";
		}
		var commandBarConfig = [];
		commandBarConfig.push('isSubtitlesButtonVisible$true');
		commandBarConfig.push('isPopupButtonVisible$' + (MediaItem.popupAvailable?'true':'false'));
		commandBarConfig.push('isExpandButtonVisible$' + (MediaItem.playerExpandable?'true':'false'));

		if (typeof(infoUrl) != 'undefined' && infoUrl != '') {
			initParams.push("overrideConfig=type$Part;id$10;uri$"+infoUrl+";initiallyVisible$true;refreshInterval$30|type$CommandBar;isHighlightsButtonVisible$true"+autoplay + commandBarConfig.join(';'));
		} else {
			initParams.push("overrideConfig=type$Part;id$10;initiallyVisible$false;refreshInterval$0|type$CommandBar;isHighlightsButtonVisible$false"+autoplay + commandBarConfig.join(';'));
		}
		initParams.push("mediaUri="+videoURL);
		if (typeof(videoBannerSL) != 'undefined' && videoBannerSL != '') {
			videoBannerSL = videoBannerSL.replace(/&amp;/g, '&');
			if (/.*pathbanner=(.*)$/.test(videoBannerSL)) {
				initParams.push("advertisingUri="+videoBannerSL.replace(/.*pathbanner=(.*)$/, '$1'));
			} else {
				initParams.push("advertisingUri="+videoBannerSL);
			}
			bannersLoaded = !!MediaItem.autoplay;
		}

		initParams = initParams.join(',');


		Silverlight.createObjectEx(
			{
				source: "/dl/objects/silverlight/uniplayer/Rai.UniPlayer.xap",
				parentElement: $('#silverlightControlHost')[0],
				id: 'SilverlightControl',
				properties: {
					width: '100%',
					height: '100%',
					inplaceInstallPrompt: false,
					background: 'transparent',
					windowless: windowless,
					framerate: '25',
					enableHtmlAccess: 'true',
					version: '4.0',
					alt: altHtml
				},
				events: {
					onLoad: function() {
						try {
							$('#silverlightControlHost')[0].focus();
						} catch (e) {
						}
					}
				},
				initParams: initParams,
				context: {
				}
			}
		);
	}
};

/* *** SmoothStreaming *** */
MediaItem.SmoothStreaming = {};
MediaItem.SmoothStreaming.createMediaItemSilverlight = MediaItem.SmoothStreamingLive.createMediaItemSilverlight;

$(createMediaItemSilverlight);





// pannello fine video
function replayVod() {
	$(".vodPanel").remove();
	var h = $('#silverlightControlHost');
	try {
		var p = h.find('object,embed');
		var d = h.find('.postVodPanel');
		d.hide().remove();
		p.show();
		$('#SilverlightControl')[0].Content.UniPlayerController.PlayFragment(0,0,0,0,-1,0,0,0);
	} catch(e) {
		h.html('');
		window.mediaItemSilverlightCreated = false;
		window.createMediaItemSilverlight();
	}
	return false;
}

function addFaveBtn() {
	try {
		var uniquename = $.trim($('#uniquename').text());
		var h = $('#silverlightControlHost');
		var d = h.find('.postVodPanel>.myRaiTV');
		if (d.length > 0) {
			var f = d.find('li.Fave');
			if (typeof(window.MyRaiTvUserCode) != 'undefined' && MyRaiTvUserCode != '') {
				// window.clearInterval(loginPollTimer);
				if (f.find('a').length == 0) {
					f.html('<a title="Aggiungi ai preferiti" class="btnFave" href="#"><span class="label">Aggiungi ai preferiti</span></a>');
					f.find('a').click(function() {
						addFavourites(uniquename);
						return false;
					});
				}
			}
		}
	} catch (e) {
		window.clearInterval(loginPollTimer);
		try {console.log(e);}catch(e2){}
	}
};
$(document).bind('myRaiTv.loggedIn', addFaveBtn);
var loginPollTimer = window.setInterval(addFaveBtn, 500);

if (typeof(window.enablePostVodPanel) == 'undefined') {
	window.enablePostVodPanel = true;
}
function playCompleted() {
	try {console.log('playCompleted');}catch(e){}
	try {
		if (window.enablePostVodPanel) {
			var uniquename = $.trim($('#uniquename').text());
			var h = $('#silverlightControlHost');
			var p = h.find('object,embed');
			var d = h.find('.postVodPanel');
			var mySetMedia = $.trim($('#mySetMedia').text());
			var typeMedia = $.trim($('#typeMedia').text());
			if (d.length == 0) {
				d = $('<div class="postVodPanel"></div>');
				d.append('<div class="justSeen">'+
							'<h4><span class="solotesto">Appena visto</span></h4>'+
							'<ul class="m"></ul>'+
						 '</div>');
				d.find('.justSeen ul.m').append('<li class="Rivedi"><a class="rivedi" href="#" onclick="return replayVod()"><span class="label">Rivedi</span></a></li>');
				d.find('.justSeen ul.m').append('<li class="Send"><a href="#" onclick="return sendFriend(\''+uniquename+'\',false); return false;" class="btnSend" title="Invia ad un amico"> <span class="label">Invia ad un amico</span></a></li>');
				d.find('.justSeen ul.m').append('<li class="Share item_Visualizzazioni st_sharethis_custom st_button" displayText="ShareThis"><a class="share" href="#"><span class="label">Condividi</span></a></li>');
				d.find('.justSeen ul.m').append($('#playerVod li:has(ol.Rating)').clone(true).addClass('Rate').append('<span class="label">Vota</span>'));
				d.find('.justSeen ul.m').append('<li class="thanks" style="line-height: 10px; display: none;" id="msgVote">Grazie per aver votato!</li>');

				d.append('<div class="myRaiTV">'+
							'<h4><span class="solotesto">My Rai.tv</span></h4>'+
							'<ul class="m"></ul>'+
						 '</div>');
				d.find('.myRaiTV ul.m').append($('#playerVod li.Commenti').clone(true).removeClass('item_Visualizzazioni').find('a').append('<span class="label">Commenta<span>').end());
				d.find('.myRaiTV ul.m').append('<li class="Playlist"><a href="#" onclick="addPlaylist(\''+uniquename+'\');" class="btnPlaylist" title="Aggiungi alla playlist"><span class="label">Aggiungi alla playlist</span></a></li>');
				d.find('.myRaiTV ul.m').append('<li class="Fave"><span class="label">Aggiungi ai preferiti</span></li>');


				d.append('<div class="moreVideos"></div>');
				d.find('.moreVideos').append('<h4>Altri video</h4>');
				d.find('.moreVideos').append('<div class="videoList"><p style="text-align: center;"><img src="/dl/js/jquery/plugin/loader.gif" alt="Caricamento in corso..." /></p></div>');
				h.append(d);
				var typeMediaDecode = {
					'0': 'V',
					'1': 'A',
					'2': 'P',
					'3': 'F',
					'4': 'V',
					'5': 'V'
				};
				typeMedia = typeMediaDecode[typeMedia];
				if (!typeMedia) {
					typeMedia = 'V';
				}
			}

			if (mySetMedia != '') {
				addFaveBtn();
				d.find('.moreVideos .videoList').load('/dl/RaiTV/programmi/liste/'+mySetMedia+'-'+typeMedia+'-0.html', function(){
					$(this).find('#'+uniquename).remove();
					if (typeof(window.setReflection) == 'function') {
						setReflection('.postVodPanel .moreVideos .reflect');
					}
				});
				stButtons.locateElements(); // dico alla libreria sharethis di inizializzare il nuovo pulsante

				// p.hide();
				d.show();
			}
		}
	} catch (e) {
		try {console.log(e);}catch(e2){}
	}
}

