// <xsl:value-of select="' '" />

var MediaItem = {};

MediaItem.type = false;

MediaItem.WMV = {};
MediaItem.RAM = {}; // non usato: servono funzioni globali... :(
MediaItem.Audio = {}; // parzialmente usato: pure qui ci sono parecchie funzioni globali... :(
MediaItem.FLV = {};
MediaItem.RSS = {};
MediaItem.Photo = {};

var mediaItemSilverlightCreated = false;
function createMediaItemSilverlight() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	var rv = true;
	try {
		if (MediaItem[MediaItem.type].createMediaItemSilverlight) {
			rv = MediaItem[MediaItem.type].createMediaItemSilverlight();
		}
	} catch (e) {
		rv = false;
		try {
			console.log(e);
		} catch (e1) {
		}
	}
	return rv;
};
$(createMediaItemSilverlight);

/* *** WMV *** */


//Create our install experience html
// var videoURL = "]]><xsl:value-of select="units/videoUnit[@type='Rai Tv Video']/url"/><![CDATA[";
// var videoTitolo="";
var logoIMG="http://www.rai.tv/dl/RaiTV/silverlight1.0/logo_rai.png";
var liveMode = "0";

MediaItem.WMV.createSilverlight = function() {
	var scene = new Video_Messaggi.Page();
	Silverlight.createObjectEx({
		source: "/dl/RaiTV/silverlight1.0/Page.xaml",
		parentElement: document.getElementById("silverlightControlHost"),
		id: "SilverlightControl",
		properties: {
			width: "384",
			height: "352",
			version: "1.0",
			autoUpgrade: "true"
		},
		events: {
			onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
			onError: function(sender, args) {
				var errorDiv = document.getElementById("errorLocation");
				if (errorDiv != null) {
					var errorText = args.errorType + "- " + args.errorMessage;

					if (args.ErrorType == "ParserError") {
						errorText += "<br>File: " + args.xamlFile;
						errorText += ", line " + args.lineNumber;
						errorText += " character " + args.charPosition;
					} else if (args.ErrorType == "RuntimeError") {
						errorText += "<br>line " + args.lineNumber;
						errorText += " character " + args.charPosition;
					}
					errorDiv.innerHTML = errorText;
				}
			}
		}
	});
};

MediaItem.WMV.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;
	
	if (typeof(codificaVideo) != 'undefined' && codificaVideo == "MP4V3") {
		var playerHtml = '<object id="mediaPlayer" classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6"\n'+
			'	width="384" height="352"\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'+
			'	<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'+
			'	<embed type="application/x-mplayer2" pluginspage = "http://www.microsoft.com/windows/mediaPlayer/"\n'+
			'		src="'+videoURL+'"\n'+
			'		animationatStart="true"\n'+
			'		transparentatStart="true"\n'+
			'		autoStart="true"\n'+
			'		controls="imagewindow"\n'+
			'		ShowControls="true"\n'+
			'		ShowStatusBar="true"\n'+
			'		ShowDisplay="true"\n'+
			'		name="MediaPlayer"\n'+
			'		bgcolor="#B4BBCA"\n'+
			'		width="384"\n'+
			'		height="352" />\n'+
			'</object>';
		$('#silverlightControlHost').html(playerHtml);
	} else {

		var installExperienceHTML = '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">';
		// installExperienceHTML += '<param name="source" value="/dl/portale/silverlight/Vod/Lettore_Rai_VOD.xap"/>';
		installExperienceHTML += '<param name="source" value="/dl/objects/silverlight/raitv/Lettore_Rai_VOD.xap"/>';
		installExperienceHTML += '<param name="onerror" value="onSilverlightError" />';
		installExperienceHTML += '<param name="background" value="#0a0a0a" />';
		installExperienceHTML += '<param name="windowless" value="false" />';
		installExperienceHTML += '<param name="minRuntimeVersion" value="2.0.31005.0" />';
		installExperienceHTML += '<param name="autoUpgrade" value="true" />';
		installExperienceHTML += '<param name="initparams" value="videoPath='+ videoURL;
		if (!isUgc) {
			installExperienceHTML += videoBannerSL;
		}
		installExperienceHTML += ',aspect='+videoFormat;
		installExperienceHTML += subtitle;
		installExperienceHTML += ',auto=true" />';
		installExperienceHTML +='<center style="color:black;" ><a>Se vuoi visualizzare il video installa Microsoft Silverlight</a></center><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">';
		installExperienceHTML += '<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Installa Microsoft Silverlight" style="border-style: none"/>';
		installExperienceHTML +='</a></center>';
		installExperienceHTML +='</object>';

		var installExperienceHTMLLX = '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">';
		// installExperienceHTMLLX += '<param name="source" value="/dl/portale/silverlight/Vod/Lettore_Rai_VOD.xap"/>';
		installExperienceHTMLLX += '<param name="source" value="/dl/objects/silverlight/raitv/Lettore_Rai_VOD.xap"/>';
		installExperienceHTMLLX += '<param name="onerror" value="onSilverlightError" />';
		installExperienceHTMLLX += '<param name="background" value="#0a0a0a" />';
		installExperienceHTMLLX += '<param name="windowless" value="false" />';
		installExperienceHTMLLX += '<param name="minRuntimeVersion" value="2.0.31005.0" />';
		installExperienceHTMLLX += '<param name="autoUpgrade" value="true" />';
		installExperienceHTMLLX += '<param name="initparams" value="videoPath='+ videoURL;
		if (!isUgc) {
			installExperienceHTMLLX += videoBannerSL;
		}
		installExperienceHTMLLX += ',aspect='+videoFormat;
		installExperienceHTMLLX += subtitle;
		installExperienceHTMLLX += ',auto=true" />';
		installExperienceHTMLLX +='<center style="color:black;" ><a>Per visualizzare il contenuto video installa Moonlight <a href="http://www.go-mono.com/moonlight/">da questo sito</a> e poi torna sulla pagina.</a></center>';
		installExperienceHTMLLX +='</object>';
		
		Silverlight.InstallAndCreateSilverlight(
			'2.0',
			document.getElementById('silverlightControlHost'),
			installExperienceHTML,
			installExperienceHTMLLX,
			'InstallPromptDiv',
			MediaItem.WMV.createSilverlight
		);
		
		
		try {
			document.getElementById('silverlightControlHost').focus();
		} catch (e) {
		}
	}
};

/* *** 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) {
	if ($('#lives').length>0) {
		document.lives.SetSource(url);
		document.lives.DoPlay();
	} else {
		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() {
	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); */ });
}


/* *** FLV *** */
MediaItem.FLV.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', 'playerFLV',
		'align', 'middle',
		'src', 'http://www.rai.tv/dl/RaiTV/flash/player',
		'quality', 'high',
		'bgcolor', '#0a0a0a',
		'name', 'playerFLV',
		'allowscriptaccess', 'sameDomain',
		'allowfullscreen', 'true',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'flashvars', flashvars,
		'movie', 'http://www.rai.tv/dl/RaiTV/flash/player'
	);
	$('#Player').append(videoCode);
};

/* *** 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').append(videoCode);
};

/* *** Photo (fotogallery) *** */
MediaItem.Photo.createMediaItemSilverlight = function() {
	if (mediaItemSilverlightCreated == true) {
		return false;
	}
	mediaItemSilverlightCreated = true;
	var width = 424;
	var height = 330;
	var background = '#0a0a0a';
	var thumbsVisible = 'true';
	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;
	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: 'true',
			framerate: '25',
			version: '3.0'
		},
		{
			onError: function(){}
		},
		'slideShowTimer=5, galleryXmlPath='+path+', statsFunct=setNielsenLoc, thumbsVisible='+thumbsVisible,
		{
		}
	);
	try {
		document.getElementById('silverlightControlHost').focus();
	} catch (e) {
	}
};

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;

	setNielsen(h);
}