﻿if(typeof(DEBUGRAITV)=='undefined'){
	DEBUGRAITV=false;
};
function copyInfoVod() {
	// mantiene i link "Approfondimenti" gia' esistenti
	var keepLinks = true;

	var vInfo = $('#infoVod');
	if (vInfo.length == 0) {
		return false;
	}
	var vId = $('#idMedia', vInfo);
	var vTime = $('#timeMedia', vInfo);
	var vInfoMedia = $('#infoMedia', vInfo);
	var vLinks = $('.linkMedia', vInfo);
	var vDate = $('#dateMedia', vInfo);
	var vTypeMedia = $('#typeMedia', vInfo);

	$('UL.tab>LI:eq('+vTypeMedia.text()+')').addClass("selected");
	//var dest = $('#IDBoxInfo');
	var dest = $('.boxInfo');
	if (dest.length==0) {
		return false;
	}

	// $('h3', dest).append(vId.html());
	$('#titVideoConsigliati').remove();
	$('#listaVideoConsigliati').remove();

	$('h1', dest).append(vId.html());
	$('#paneInfoVideo', dest).append(vInfoMedia.html());
	// var listDati = $('ul:first', dest);
	if (vTime.text() == '00:00:00' || $.trim(vTime.text()) == ''){
		$('.Durata', dest).css({'visibility' : 'hidden'});
	} else {
		$('.Durata', dest).append(vTime.html());
	}
	if (vDate.text() == '00:00:00' || $.trim(vDate.text()) == ''){
		$('.Data', dest).css({'visibility' : 'hidden'});
	} else {
		$('.Data', dest).append(vDate.html());
	}
	// $('.Data', dest).append(vDate.html());

	var listLinks = $('ul.More', dest);
	if (listLinks.length == 0) {
		listLinks = $('<ul class="More"></ul>');
		dest.append(listLinks);
	}
	if (!keepLinks) {
		listLinks.empty();
	}
	vLinks.each(function(){
		var h = $(this).html();
		if (h.length>0) {
			var li = $('<li></li>');
			if (/\/dl\/sanremo\/dada_stream.html/.test(h)) {
				listLinks.css('paddingTop', '5px');
				li.html('<a href="'+h+'">'+$(this).attr('title')+'</a>');
				var t = $(this).attr('target');
				if (!!t) {
					li.find('a').attr('target', t);
				}
				li.attr('class', 'dadaLink');
				li.css({
					display: 'block',
					position: 'absolute', //
					top: '125px', //
					left: '20px', //
					clear: 'both',
					height: '46px',
					width: '410px'
				}).find('a').css({
					display: 'block',
					position: 'relative',
					fontSize: '11px',
					fontWeight: 'bold',
					padding: '15px 70px 11px 20px',
					background: 'transparent url(/dl/sanremo/images/bg_link_raitvdada.jpg) no-repeat scroll left top',
					width: '320px',
					height: '20px'
				});
			} else {
				li.html('<a href="'+h+'">'+$(this).attr('title')+'</a>');
				var t = $(this).attr('target');
				if (!!t) {
					li.find('a').attr('target', t);
				}
			}
			listLinks.append(li);
		}
	});
	return true;
};
function loadProgInfo() {
	var html = $.trim($('#id_ProgContent').html());
	$('#id_ProgContent').remove();
	if (html != '' && !/^\/dl\/RaiTV\/programmi/i.test(html)) {
			$(".contVod").html(html);

			fixProgInfoHtml();

			try {
				var isIpad = (navigator.userAgent.match(/iPad/i));
				var isIphone = (navigator.userAgent.match(/iPhone/i));
				// jScrollPane inutilizzabile con il touch di safari
				if (!isIpad && !isIphone) {
					$('#paneInfoProg').jScrollPane({showArrows:false, scrollbarWidth:16 }); /*descrizioneprog*/
				}
			} catch (e) {}
			// $('#txtInfoProgramma').hide();
			$('#basicInfoProg').hide();
			setReflection(".reflected");
			copyInfoVod();
			applyPngFix();


			$('#basicInfoVod div.holder').append($('#paneInfoVideo'));
			$('#basicInfoVoddiv.holder').find('.jScrollPaneContainer').remove();
			// if ($('#playerVod').is('.liveSmoothPlayer')) {
			// 	$('#paneInfoVideo').attr('style', '').show().css({display: 'block', width: '261px', height: '57px'});
			// } else {
			// 	$('#paneInfoVideo').attr('style', '').show().css({display: 'block', width: '421px', height: '57px'});
			// }
			try {
				var isIpad = (navigator.userAgent.match(/iPad/i));
				var isIphone = (navigator.userAgent.match(/iPhone/i));
				// jScrollPane inutilizzabile con il touch di safari
				if (!isIpad && !isIphone) {
					$('#paneInfoVideo').jScrollPane({showArrows:false, scrollbarWidth:7 }); /*infovideo*/
				}
			} catch (e) {}

			setStatsItem();
			if ($('#pagEdizioni').length > 0) {
				$('#pagEdizioni').appendTo(".Categorie").show();
				var visibles = 4;
				if ( $("#pagEdizioni .linkEdizioni ul li").length > visibles) {
					$.getScript("/dl/js/jquery/plugin/jcarousellite.pack.js", function(){
						$.getScript("/dl/js/jquery/plugin/jquery.easing.js", function(){
							$("#pagEdizioni .linkEdizioni").jCarouselLite({
								 auto: 4000,
								 btnNext: "#pagEdizioni .next",
								 btnPrev: "#pagEdizioni .prev",
								 speed: 1000,
								 visible: visibles,
								 scroll: 1,
								 easing: "easeOutBack"
							});
						});
					});
				} else {
					$("#pagEdizioni .next").css('visibility', 'hidden');
					$("#pagEdizioni .prev").css('visibility', 'hidden');
				}
			}

	} else {
		/* da rimuovere: c'e' l'SSI del block nella page, per ridurre il numero di chiamate ajax */
		AJAX_loadProgInfo();
	}

	$.ajax({
		url: PATH_MYRAITV,
		cache: false,
		success: function(html){
			$(".banner300x100").after(html);
		}
	});

	return false;
};
function fixProgInfoHtml() {

	$('.contVod').each(function() {
		var s = ''+$(this).attr('style');
		if (/background: #303030/i.test(s) ||
			/background: none repeat scroll 0% 0% rgb\(48, 48, 48\)/i.test(s) ||
			/background: none repeat scroll 0% 0% #303030/i.test(s)
		) {
			$(this).attr('style', 'background-color: #303030;');
		}
	});

	var n = $('.contVod #IDBoxInfo');
	n.find('h3').each(function() {
		var h1 = $('<h1></h1>').append($(this).children());
		$(this).before(h1).remove();
	});
	n.attr('id', 'basicInfoVod');
	n.find('>ul:eq(0)').replaceWith('<div class="Durata">Durata: </div><div class="Data">Andato in onda il: </div><div class="visualizz"></div>');

	var m = n.next('div.videoCons').attr('id', 'basicInfoProg');
	m.find('>h3,>h1').remove();
	m.prepend('<h1 id="titInfoProgramma"><span>Info programma</span> <a class="close" href="javascript:hide_block(\'basicInfoProg\'),display_block(\'basicInfoVod\');"/></h1>');

	n = $('.contVod li a.Info');
	n.replaceWith('<a class="Info" href="#" onclick="display_block(\'basicInfoProg\');$(\'#txtInfoProgramma\').show();hide_block(\'basicInfoVod\'); return false;">Info Programma</a>');

	$('.contVod #titVideoConsigliati').hide();
	$('.contVod #listaVideoConsigliati').hide();

	/*renaming 4 xf4 ... da eliminare*/
	if($("#myPageMedia").length > 0 && $("#myPageMedia").text() == 'Page-72ec3233-7130-473a-89e1-a7fb81dce083') {
		$(".Sito").text("Vai al concorso");
		$(".Sito").css("width", "105px");
		$(".Info").attr("style","margin: 9px 5px 0px 65px!important; margin: 9px 5px 0px 28px;");
	}
}
function AJAX_loadProgInfo() {
	/* da rimuovere: c'e' l'SSI del block nella page, per ridurre il numero di chiamate ajax */
	var url = $('.id_ProgContent').text();
	if(url != null && url !="") {
		$.ajax({
		  url: url,
		  cache: false,
		  success: function(html){
			$(".contVod").html(html);

			fixProgInfoHtml();

			try {
				var isIpad = (navigator.userAgent.match(/iPad/i));
				var isIphone = (navigator.userAgent.match(/iPhone/i));
				// jScrollPane inutilizzabile con il touch di safari
				if (!isIpad && !isIphone) {
					$('#paneInfoProg').jScrollPane({showArrows:false, scrollbarWidth:16 }); /*descrizioneprog*/
				}
			} catch (e) {}
			// $('#txtInfoProgramma').hide();
			$('#basicInfoProg').hide();
			$('#basicInfoVod').show();
			setReflection(".reflected");
			copyInfoVod();
			applyPngFix();
			try {
				var isIpad = (navigator.userAgent.match(/iPad/i));
				var isIphone = (navigator.userAgent.match(/iPhone/i));
				// jScrollPane inutilizzabile con il touch di safari
				if (!isIpad && !isIphone) {
					$('#paneInfoVideo').jScrollPane({showArrows:false, scrollbarWidth:7 }); /*infovideo*/
				}
			} catch (e) {}

			setStatsItem();
			if ($('#pagEdizioni').length > 0) {
				$('#pagEdizioni').appendTo(".Categorie").show();
				var visibles = 4;
				if ( $("#pagEdizioni .linkEdizioni ul li").length > visibles) {
					$.getScript("/dl/js/jquery/plugin/jcarousellite.pack.js", function(){
						$.getScript("/dl/js/jquery/plugin/jquery.easing.js", function(){
							$("#pagEdizioni .linkEdizioni").jCarouselLite({
								 auto: true,
								 btnNext: "#pagEdizioni .next",
								 btnPrev: "#pagEdizioni .prev",
								 speed: 1000,
								 visible: visibles,
								 scroll: 1,
								 easing: "easeOutBack"
							});
						});
					});
				} else {
					$("#pagEdizioni .next").css('visibility', 'hidden');
					$("#pagEdizioni .prev").css('visibility', 'hidden');
				}
			}
		}
		});
	}
	return false;
};

// var htmlNoComments = '<div class="txtNoComments"><span>Ancora nessun commento disponibile.<br />Vuoi essere il primo?</span><div class="btnMyRT"><a href="#" onclick="Commenti.show(); return false;" class="Accedi">Accedi</a><a href="http://www.rai.tv/dl/RaiTV/MyRaiTV/iscrizione.html" class="Registra">Registrati</a> </div></div>';
var htmlNoComments = '<div class="txtNoComments"><span>Ancora nessun commento disponibile.<br />Vuoi essere il primo?</span></div>';
var htmlCommentsDisabled = '<div class="txtNoComments"><div class="Top"></div><span style="width: 100%;margin: 10px 0px 0px 0px;">Non è possibile commentare questo elemento.</span></div>';

if (typeof(commentsDisabled) == 'undefined') {
	var commentsDisabled = false;
}
if (typeof(increaseStatsDisabled) == 'undefined') {
	var increaseStatsDisabled = false;
}

function setStatsItem() {
	var uniquename = "";
	var title = "";
	var tags = "";
	var pathImgStat ="";
	var nomeProgramma ="";
	var logoEditore ="";
	var duration = "";
	var durationPost = "";
	var description = "";
	var editore = "";
	var dateMedia = "";
	var myPageMedia = "";
	try {uniquename = $('#uniquename').text() != "null" ? $('#uniquename').text() : "";} catch(e){}
	try {title = $('#idMedia').text() != "null" || $('#idMedia').length != 0 ? replaceMSWord($('#idMedia').text()) : "";} catch(e){}
	try {nomeProgramma = $("DIV.logoDescr").children("H2").text() != "null" ? replaceMSWord($("DIV.logoDescr").children("H2").text()) : "";} catch(e){}
	try {tags = $('#myTematiche').text() != "null" ? $.trim(replaceMSWord($('#myTematiche').text())) : "";} catch(e){}
	try {pathImgStat = $('#pathImgStat').text() != "null" ? $.trim($('#pathImgStat').text()) : "";} catch(e){}
	try {description = $('#infoMedia').text() != "null" ? $.trim($('#infoMedia').text()) : "";} catch(e){}
	try {dateMedia = $('#dateMedia').text() != "null" ? $.trim($('#dateMedia').text()) : "";} catch(e){}
	try {myPageMedia = $('#myPageMedia').text() != "null" ? $.trim($('#myPageMedia').text()) : "";} catch(e){}
	myPageMedia = (''+myPageMedia).substring(0, 41); // non si sa perche', ma a volte ha preso troppo testo (span chiuso male).. :/
	nomeProgramma = jQuery.trim(nomeProgramma);

	var videoUrl, videoUrl_H264, videoUrl_M3U8, isPodcast, hasClosedCaption;
	videoUrl = $('meta[name=videourl]').attr('content') || false;
	videoUrl_H264 = $('meta[name=videourl_h264]').attr('content') || false;
	videoUrl_M3U8 = $('meta[name=videourl_m3u8]').attr('content') || false;
	isPodcast = $('meta[name=podcast]').attr('content') || false;
	hasClosedCaption = $('meta[name=closedcaption]').attr('content') || false;
	// console.log(videoUrl_H264, videoUrl_M3U8, isPodcast, hasClosedCaption);


	//staticUrl = "/StatisticheProxy/proxy.jsp?action=#action#&domain=RaiTv&days=7&state=1&records=12&order=&tags=NomeProgramma%3A"+escape(nomeProgramma)+"&xsl=rai_tv-statistiche-v2";
	staticUrl = "/StatisticheProxy/proxy.jsp?action=#action#&domain=RaiTv&days=7&state=1&records=12&order=&tags=PageOB%3A"+myPageMedia+"&xsl=rai_tv-statistiche-v2";


	if($("meta[name='programmaTV']").attr("content") == 'Sanremo 2010' ||
	   $('#myPageMedia').text() == 'Page-2747da15-aa6c-43d5-8562-1ae50595ff8d' // sanremo 2011
	   ) {
		$('div.Categorie ul.tab li:has(a.piuTutto)').remove();
	} else {
		$('div.Categorie ul.tab li:has(a.piuTutto)').show();
	}
	//Aspettando ok per rilascio adesso ContentSet di Arturo e Kiwi
	/*if($('#mySetMedia').text() == 'ContentSet-6a610f2a-0289-44a0-9599-eae74d0cca53') {
		$(".vodOpzioni").clone(true).insertAfter(".boxInfo>H3");
	}*/
	// $(".vodOpzioni").clone(true).insertAfter(".boxInfo>H3");
	var opzioniVideo = $('div.opzioniVideo');
	if (opzioniVideo.length == 0) {
		opzioniVideo = $('<div class="opzioniVideo"></div>');
	}
	opzioniVideo.appendTo('#playerVod .boxVod');

	/*
	testo sotto il player
	*/
	if($("meta[name='programmaTV']").attr("content") == 'Sanremo 2010' && $('#uniquename').text() !=  'ContentItem-6b34ebff-b2ba-401f-b44a-2d0f79257d63') {
	/*
		var alertSanremo = $('<div class="alertSanremo">Entro il 12 gennaio <b>Sanremo Academy</b>, la commissione presieduta dal direttore artistico Gianmarco Mazzi, <b>a suo insindacabile giudizio</b>, sceglier&agrave; le <b>sei</b> canzoni-artisti che, unitamente alle due provenienti da SanremoLab, andranno a formare il cast dei giovani in gara nella sezione Sanremo Nuova Generazione.<br /><br />Da <b>luned&igrave; 18 gennaio 2010</b> le 8 canzoni degli artisti Sanremo Nuova Generazione e i relativi video saranno pubblicati sul sito</div>');
		alertSanremo.prependTo('.opzioniVideo');
	*/
		var titolo = $('.Display h2').html();
		if (titolo != null) {
		titolo = titolo.replace("-", "<br />");
		$('.Display h2').html(titolo).attr("style","height:48px;margin-top:-24px;font-size: 14px;");
		}
	}


	var vodOpzioni = $(".vodOpzioni");
	if (!vodOpzioni.is('ul')) {
		vodOpzioni = $('<ul class="vodOpzioni"></ul>').append(vodOpzioni.remove().children());
		opzioniVideo.append(vodOpzioni);
	}
	vodOpzioni.find('li.Feed').remove();



	// copiato da functions.pack.js
	$(".btnFacebook").click(function() {
		var urlRaiTv = encodeURIComponent("http://www.rai.tv/dl/RaiTV/programmi/media/"+$("#uniquename").text()+".html");
		openPopUp('http://www.facebook.com/sharer.php?u='+urlRaiTv+'%3F'+rnd,'RaiTv',440,620);
		return false;
	});




	if(nomeProgramma == ""){
		tags = tags.substring(0,tags.length-1);
	} else {nomeProgramma = "NomeProgramma:"+nomeProgramma;}
	tags = tags + nomeProgramma;
	tags += "^PageOB:"+myPageMedia;

	// isPodcast, hasClosedCaption
	if (!!isPodcast) {
		tags += '^PODCAST';
	}
	if (!!hasClosedCaption) {
		tags += '^SOTTOTITOLATO';
	}


	if ($("#timeMedia").text() != '00:00:00' && $("#timeMedia").text() != ''){
		duration = "&duration="+escape($("#timeMedia").text());
		durationPost = $.trim($("#timeMedia").text());
	}

	try {
		logoEditore = $(".logoEditore>img").attr("alt") || '';
		editore = "^Editore:"+logoEditore;
	} catch(e){
		logoEditore ="";
	}

	setNielsen(location.href+"&tags="+tags.replace(/Category:([^:]*:)?Category[a-z0-9-]*[\^]/g, '').replace(/TAG:([^:]*:)?Category[a-z0-9-]*[\^]/g, '')+"&editore="+logoEditore);


	var vTypeMedia = $.trim($('#typeMedia').text());
	try {
		vTypeMedia = parseInt(vTypeMedia);
	} catch (e) {
		vTypeMedia = 5;
	}
	var sTypeMedia = '';
	switch (vTypeMedia) {
		case 0:
			sTypeMedia = 'Video';
			break;
		case 1:
			sTypeMedia = 'Audio';
			break;
		case 2:
			sTypeMedia = 'Podcast';
			break;
		case 3:
			sTypeMedia = 'Foto';
			break;
		case 4:
			sTypeMedia = 'UGC';
			break;
		case 5:
		default:
			sTypeMedia = 'altro';
	}


	var videoURL_MP4 = "";
	try {
		videoURL_MP4 = window.videoURL_MP4 || '';
	} catch (e) {
		videoURL_MP4 = "";
	}
	if (!videoURL_MP4) {
		if (!!videoUrl_M3U8) {
			videoURL_MP4 = videoUrl_M3U8;
		} else if (!!videoUrl_H264) {
			videoURL_MP4 = videoUrl_H264;
		}
	}

	if(uniquename != null && uniquename != "") {
		if (!increaseStatsDisabled) {
			var itemData = {
				action: "increaseVisits",
				domain: "RaiTv",
				localId: uniquename,
				tags: tags+editore,
				title: title,
				imagePath: pathImgStat,
				duration: durationPost,
				description: replaceMSWord(description.substr(0,1500)),
				publDate: dateMedia,
				url: videoURL_MP4,
				type: sTypeMedia
			};
			// videoUrl, videoUrl_H264, videoUrl_M3U8,
			if (!!videoUrl) {
				itemData.urlWeb = videoUrl;
			}
			// l'h264 viene inviato come "url" (legacy)
			// if (!!videoUrl_H264) {
			// 	itemData.videoUrl_H264 = videoUrl_H264;
			// }
			if (!!videoUrl_M3U8) {
				itemData.urlM3u8 = videoUrl_M3U8;
			}

			$.ajax({
			   type: "POST",
			   contentType: "application/x-www-form-urlencoded; charset=utf-8",
			   url: "http://"+document.domain+"/StatisticheProxy/proxyPost.jsp",
			   data: itemData
			 });
		}
		var urlContent = "/StatisticheProxy/proxy.jsp?action=getContent&domain=RaiTv&localId="+uniquename+"&xsl=rai_tv-statistiche-content&beginningIndexForComments=1&endIndexForComments=10";
		if (DEBUGRAITV) {alert(urlContent);}
		$.ajax({
		  url: urlContent,
		  type: 'GET',
		  cache: false,
		  error: function() {
			debug('Errore in getContent...');
		  },
		  success: function(html){
				if (html != '' && html.indexOf('<title>')<0) {
					var temp = $('<ul></ul>');
					html = html.replace('<scr'+'ipt src="/dl/RaiTV/js/rating.js" type="text/javascript"></scr'+'ipt>', '');
					temp.html(html);
					var vis = temp.find('li.item_Visualizzazioni');
					var rat = temp.find('ol.Rating');
					var com = temp.find('li.item_comments');

					var cont = $('div.opzioniVideo');
					var vodOpt = cont.find('ul.vodOpzioni');

					var dMsgVote = cont.find('#msgVote');

					if (vis.length>0) {
						var dVis = cont.find('div.Visite');
						if (dVis.length == 0) {
							dVis = $('<div class="Visite"></div>');
							// dRate.after(dVis);
							// dMsgVote.after(dVis);
							$('#playerVod .boxVod .Data').after(dVis);
						}
						vis = vis.text().substring('Visualizzazioni: '.length);
						dVis.html('<span>Visualizzazioni:</span> '+vis);
					}


					if (commentsDisabled) {
						if (vodOpzioni.find('li.Commenti').length==0) {
							vodOpzioni.append('<li class="Commenti"> </li>');
						}
					} else {
						if (vodOpzioni.find('li.Commenti').length==0) {
							vodOpzioni.append('<li class="Commenti"><a class="btnComm" href="#"/></li>');
						}
						var btnComm = vodOpzioni.find('li.Commenti a.btnComm');
						btnComm.click(Commenti.toggle);
					}


					if (rat.length>0) {
						var ratLi = rat.parent();
						dMsgVote = ratLi.next();
						dMsgVote.css({width: '64px', lineHeight: '10px'})
						vodOpzioni.append(ratLi);
						vodOpzioni.append(dMsgVote);
						ratLi.prev().addClass('item_Visualizzazioni');



						// var dRate = cont.find('div.Rate');
						// if (dRate.length == 0) {
						// 	dRate = $('<div class="Rate"></div>');
						// 	if (vodOpt.length == 0) {
						// 		cont.prepend(dRate);
						// 	} else {
						// 		vodOpt.after(dRate);
						// 	}
						// }
						// dRate.append(rat).prev().addClass('item_Visualizzazioni');
						// if (dMsgVote.length == 0) {
						// 	dMsgVote = $('<div class="Rate" style="display: none; padding: 0px 0px 0px 7px; line-height: 10px; font-size: 10px;"></div>');
						// 	dMsgVote.append(temp.find('#msgVote').html());
						// 	dRate.after(dMsgVote);
						// }
						$.getScript('/dl/RaiTV/js/rating.js');
					}

					if($("meta[name='programmaTV']").attr("content") == 'Sanremo 2010' ||
					   $('#myPageMedia').text() == 'Page-2747da15-aa6c-43d5-8562-1ae50595ff8d' // sanremo 2011
					   ) {
						$(".Rate").html('');
						if (rat.length>0) {
							var ratLi = rat.parent();
							dMsgVote = ratLi.next();
							ratLi.html('');
							dMsgVote.remove();
						}
					}


					var boxCommenti = $('div#playerVod div.boxCommenti').show();
					if (boxCommenti.length == 0) {
						// boxCommenti = $('<div class="boxCommenti"><div class="Top"><img class="l" src="/dl/test/claudio/RaiTV/images/ico_myraitv.png" /><a href="#" class="commenta">Leggi e commenta</a> <div class="commenti"></div></div></div>');
						boxCommenti = $('<div class="boxCommenti"><div class="Top"><a href="#" class="commenta">Leggi e commenta</a> <div class="btnMyRT"><a href="#" onclick="Commenti.show(); return false;" class="Accedi">Accedi</a><a href="http://www.rai.tv/dl/RaiTV/MyRaiTV/iscrizione.html" class="Registra">Registrati</a> </div> <div class="commenti"></div></div></div>');
						// $('.boxVod').append(boxCommenti);
						$('div#playerVod').append(boxCommenti);
					}

					boxCommenti.find('.btnMyRT').hide();
					if (commentsDisabled) {
						boxCommenti.html(htmlCommentsDisabled);
					} else {
						boxCommenti.find('.Top a.commenta').click(Commenti.toggle);

						if (com.length > 0) {
							var singleComment = boxCommenti.find('.txtCommentsSmall');
							if (singleComment.length == 0) {
								singleComment = $('<div class="txtCommentsSmall"></div>');
								boxCommenti.append(singleComment);
							}
							singleComment.empty().append(com.find('ul.elencoCommenti>li:eq(0)').children().clone(true));
							var cDate = singleComment.find('b.commentDate');
							cDate.text(' ' + Commenti.formatDate(cDate.text()) );
							var numCommenti = com.find('.totalNumberOfComments').text();
							boxCommenti.find('.Top .commenti').html('Commenti ('+numCommenti+')');
							if (numCommenti == '0') {
								boxCommenti.find('.Top a.commenta').text('Commenta');
							}
							Commenti.setCurrPage(0);
							Commenti.setCommentsCount(numCommenti);
							Commenti.setComments(com.find('ul.elencoCommenti>li'));
							Commenti.initPagination();
						} else {
							boxCommenti.find('.Top .commenti').html('Commenti (0)');
							if (boxCommenti.find('.txtNoComments').length == 0) {
								boxCommenti.append(htmlNoComments);
							} else {
								boxCommenti.find('.txtNoComments').show();
							}
							boxCommenti.find('.Top a.commenta').text('Commenta');

							// $(document).bind('myRaiTv.loggedIn', function(){
							// 	// controlla se l'utonto e' loggato...
							// 	if (MyRaiTvUserCode == '') {
							// 		boxCommenti.find('.btnMyRT').show();
							// 	} else {
							// 		boxCommenti.find('.btnMyRT').hide();
							// 	}
							// });
							// // controlla se l'utonto e' loggato...
							// if (MyRaiTvUserCode == '') {
							// 	boxCommenti.find('.btnMyRT').show();
							// } else {
							// 	boxCommenti.find('.btnMyRT').hide();
							// }
							$(document).bind('myRaiTv.loggedIn', function(){
								// controlla se l'utonto e' loggato...
								if (MyRaiTvUserCode == '') {
									boxCommenti.find('.btnMyRT').show();
									boxCommenti.find('.Top a.commenta').hide();
								} else {
									boxCommenti.find('.btnMyRT').hide();
									boxCommenti.find('.Top a.commenta').show();
								}
							});
							// controlla se l'utonto e' loggato...
							if (MyRaiTvUserCode == '') {
								boxCommenti.find('.btnMyRT').show();
								boxCommenti.find('.Top a.commenta').hide();
							} else {
								boxCommenti.find('.btnMyRT').hide();
								boxCommenti.find('.Top a.commenta').show();
							}
						}
					}
				} else {
					if (html == '') {
						debug('Errore in getContent... (empty html)');
					} else {
						debug('Errore in getContent... (title present)');
					}
					$(".item_Pubblicato").after('<!-- errore -->');
				}
			}
		});

		// var urlConsigliati = "/StatisticheProxy/proxy.jsp?action=mostVisited&domain=RaiTv&days=7&state=1&records=6&order=&tags="+escape(nomeProgramma)+"&xsl=rai_tv-statistiche-consigliati";
        //
		// $.ajax({
		//   url: urlConsigliati,
		//   type: 'GET',
		//   cache: false,
		//   success: function(html){
		// 	if (html.indexOf('<title>')<0) {
		// 		$(".listaVideoSmall").html(html);
		// 		$('#pane').jScrollPane({showArrows:false, scrollbarWidth:16 });
		// 		setReflection(".reflected");
		// 		applyPngFix();
		// 	} else {
		// 		$(".listaVideoSmall").html('<!-- errore -->');
		// 	}
		//   }
		// });
	}
};
function downloadPodcast(path,name,est) {
	if(typeof est == 'undefined') {est = "";}
	if(name == null && name =="") {name = "RaiTvPodcast";}

	var p = new RegExp('[;àèìòù&"/\\\\]','g');
	name = name.replace(p,'_');

	if(path != null && path !="") {
		window.open("http://www.rai.tv/services/download.jsp?path="+escape(path)+"&name="+escape(replaceMSWord(name))+"&est="+est,"podcast");
	}
	return false;
};

var Commenti = function() {
	var commentsPerPage = 10;

	var boxTuttiCommenti = false;
	var divCategorie = $('div.Main div.Categorie');
	var uniquename = false;
	try {uniquename = $('#uniquename').text() != "null" ? $('#uniquename').text() : false;} catch(e){};
	if (!uniquename || commentsDisabled) {
		function stubFunction() {
			return false;
		};
		return {
			valid: stubFunction,
			// init: init,
			loadPage: stubFunction,
			setCommentsCount: stubFunction,
			setCurrPage: stubFunction,
			setComments: stubFunction,
			initPagination: stubFunction,
			toggle: stubFunction,
			show: stubFunction,
			hide: stubFunction,
			formatDate: stubFunction
		};
	}

	function init() {
		boxTuttiCommenti = $('div.Main div.boxTuttiCommenti');
		$(document).bind('myRaiTv.loggedIn', function(){
			if (MyRaiTvUserCode == '') {
				boxTuttiCommenti.find('.textAreaComm').hide();
				boxTuttiCommenti.find('.boxLogIn').show();
			} else {
				boxTuttiCommenti.find('.textAreaComm').show();
				boxTuttiCommenti.find('.boxLogIn').hide();
			}
		});
		if (boxTuttiCommenti.length == 0) {
			boxTuttiCommenti = $(
				'<div class="boxTuttiCommenti" style="display: none;">'+
					'<div class="tab"><strong>Tutti i commenti</strong>'+
						'<a title="Chiudi" class="Close" href="#"><span class="solotesto">Chiudi</span></a>'+
					'</div>'+
					'<div class="Top"></div>'+
					'<div class="Mid">'+
						'<div style="display: none;" class="boxLogIn">'+
							'<h4>Effettua il login e commenta</h4>'+
							'<ul>'+
								'<li class="user">'+
									'<input type="text" value="Utente" name="username"/>'+
								'</li>'+
								'<li class="pass">'+
									'<input type="password" value="Pass" name="password"/>'+
									'<input type="image" src="/dl/portale/image/trasparent.png" class="submit" value="Entra" />'+
								'</li>'+
							'</ul>'+
						'</div>'+
						'<div class="textAreaComm">'+
							'<div class="sfondoArea">'+
								'<textarea>Inserisci qui il tuo commento...</textarea>'+
								'<div style="display: none;" class="ok">Commento inserito correttamente.<br/>I commenti sono moderati: il tuo messaggio non sarà visibile fino a quando non sarà approvato dalla redazione.</div>'+
								'<div style="display: none;" class="ko">Si è verificato un errore durante l\'inserimento del commento.<br/>Riprovare più tardi.</div>'+
							'</div>'+
							'<div class="btns">'+
							'<a class="pubblica" href="#">Pubblica il commento</a> | <a class="elimina" href="#">Elimina</a>'+
							'</div>'+
						'</div>'+
						'<ul class="elencoCommenti">'+
						'</ul>'+
						'<div class="pagination">'+
						'</div>'+
					'</div>'+
					'<div class="Bot"></div>'+
				'</div>'
			);
			if ($('div.Main div#myraitvHeader').length>0) {
				$('div.Main div#myraitvHeader').after(boxTuttiCommenti);
			} else {
				$('div.Main').prepend(boxTuttiCommenti);
			}
			// bind close
			boxTuttiCommenti.find('div.tab a.Close').click(hide);
			// bind login
			myRaiTvLogin();
			// bind post comment
			boxTuttiCommenti.find('.textAreaComm a.pubblica').click(postComment);
			boxTuttiCommenti.find('.textAreaComm a.elimina').click(resetComment);
			boxTuttiCommenti.find('.textAreaComm textarea').bind('focus', inputFocus);
			boxTuttiCommenti.find('.textAreaComm textarea').bind('blur', inputBlur);

			boxTuttiCommenti.find('.boxLogIn input[name="username"]').bind('focus', inputFocus);
			boxTuttiCommenti.find('.boxLogIn input[name="password"]').bind('focus', inputFocus);
			boxTuttiCommenti.find('.boxLogIn input[name="username"]').bind('blur', inputBlur);
			boxTuttiCommenti.find('.boxLogIn input[name="password"]').bind('blur', inputBlur);
		}
		// controlla se l'utonto e' loggato...
		if (typeof(MyRaiTvUserCode) == 'undefined' || MyRaiTvUserCode == '') {
			boxTuttiCommenti.find('.textAreaComm').hide();
			boxTuttiCommenti.find('.boxLogIn').show();
		} else {
			boxTuttiCommenti.find('.textAreaComm').show();
			boxTuttiCommenti.find('.boxLogIn').hide();
		}

		// loadPage(0);
	};

	function inputFocus() {
		if (this.value == this.defaultValue) {
			this.value = '';
		}
	};

	function inputBlur() {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	};

	function myRaiTvLogin() {
		var n = boxTuttiCommenti.find('.boxLogIn');

		var uname = n.find('input[name="username"]');
		var pw = n.find('input[name="password"]');

		uname.bind('focus', inputFocus).bind('focus', inputFocus);
		pw.bind('blur', inputBlur).bind('blur', inputBlur);

		function postLogin() {
			if(uname[0].value != uname[0].defaultValue && pw[0].value != pw[0].defaultValue) {
				$.post(PATH_LOGIN, {username: uname[0].value, password: pw[0].value },
				function(data) {
					var result = data.split("-");
					var esito = 0;
					if(result.length > 1) {
						utils.cookie.set("MyRaiTvUser",data,"",'/',HOST,'');
						esito = 1;
						login(esito);
					}  else if (result[0] == "nonvalido"){
						esito = 2;
						login(esito);
					} else {
						esito = 3;
						login(esito);
					}
					if (MyRaiTvUserCode == '') {
						boxTuttiCommenti.find('.textAreaComm').hide();
						boxTuttiCommenti.find('.boxLogIn').show();
					} else {
						boxTuttiCommenti.find('.textAreaComm').show();
						boxTuttiCommenti.find('.boxLogIn').hide();
					}
					$(document).trigger('myRaiTv.loggedIn');
				});
			} else {
				var optionShadowbox = {
								title : "Login",
								content:'<div id="msg">'+messages["loginERROR"]+'</div>',
								player : "html",
								height :100,
								width: 300,
								options :{ animate:false}
								};
				messageShadowbox(optionShadowbox);
			}
			return false;
		}

		n.find('input.submit').click(postLogin);
		n.wrapInner('<form action="#" method="post"></form>');
		n.find('form').bind('submit', postLogin);
	};

	function show() {
		boxTuttiCommenti.show();
		divCategorie.hide();
		setNielsen(document.location + '?showComments');
		$('html,body').animate({scrollTop: $('div.Main').position().top}, 500);
		return false;
	};
	function hide() {
		boxTuttiCommenti.hide();
		divCategorie.show();
		setNielsen(document.location + '?hideComments');
		return false;
	};
	function toggle() {
		if (boxTuttiCommenti.is(':visible')) {
			hide();
		} else {
			show();
		}
		return false;
	};

	var totComments = 0;
	var currPage = 0;
	function initPagination() {
		var totPages = Math.ceil(totComments / commentsPerPage);
		var panel = boxTuttiCommenti.find('div.pagination');
		panel.empty();
		if (totPages > 1) {
			var prev = $('<a class="prev" href="#"></a>');
			panel.append(prev);
			if (currPage <= 0) {
				prev.addClass('current');
				prev.click(function(){
					return false;
				});
			} else {
				prev.click(function(){
					loadPage(currPage - 1);
					return false;
				});
			}

			var fromPage = currPage - 7;
			if (fromPage < 0) {
				fromPage = 0;
			}
			var toPage = fromPage + 15;
			if (toPage > totPages) {
				toPage = totPages;
			}
			for (var i = fromPage; i < toPage; i++) {
				if (i == currPage) {
					panel.append('<span class="current">'+(i+1)+'</span>');
				} else {
					var curr = $('<a href="#">'+(i+1)+'</a>');
					curr.click((function() {
						var p = i;
						return function(){
							loadPage(p);
							return false;
						}
					})());
					panel.append(curr);
				}
			}

			var next = $('<a class="next" href="#"></a>');
			panel.append(next);
			if (currPage >= totPages-1) {
				next.addClass('current');
				next.click(function(){
					return false;
				});
			} else {
				next.click(function(){
					loadPage(currPage + 1);
					return false;
				});
			}
		}
	};
	function setCommentsCount(tot) {
		totComments = tot;
	};
	function setComments(items) {
		boxTuttiCommenti.find('ul.elencoCommenti').empty();
		if (items != null && items.length > 0) {
			boxTuttiCommenti.find('ul.elencoCommenti').append(items);
			boxTuttiCommenti.find('ul.elencoCommenti li b.commentDate').each(function() {
				var dateString = $(this).text();
				dateString = formatDate(dateString);
				$(this).text(' - '+dateString);
			});
		}
	};
	var dateThresholds = {
		days: 3*24*60*60*1000, // oltre 3 giorni: stampo la data completa
		day: 24*60*60*1000, // oltre 1 giorno: n giorni fa
		hours: 60*60*1000, // oggi: n ore fa
		minutes: 60*1000, // minuti: n minuti fa
		seconds: 1000 // secondi: n secondi fa
	};
	var dateFormatValues = {
		day: 24*60*60*1000, // 1 giorno
		hour: 60*60*1000, // 1 ora
		minute: 60*1000, // 1 minuto
		second: 1000 // 1 secondo
	};
	function formatDate(dateString) {
		// 09/10/2009 13:27:07
		var res = dateString.replace(/(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d:\d\d:\d\d)/, '$3/$2/$1 $4');
		var d = new Date(res);
		var now = new Date();
		var delta = now - d;

		if (delta < 0) {
			// non dovrebbe succedere... ma imbroglio :P
			res = '1 secondo fa';
		} else if (delta < dateThresholds.minutes) {
			delta = Math.floor(delta / dateFormatValues.second);
			res = delta + ' second'+(delta==1?'o':'i')+' fa';
		} else if (delta < dateThresholds.hours) {
			delta = Math.floor(delta / dateFormatValues.minute);
			res = delta + ' minut'+(delta==1?'o':'i')+' fa';
		} else if (delta < dateThresholds.day) {
			delta = Math.floor(delta / dateFormatValues.hour);
			res = delta + ' or'+(delta==1?'a':'e')+' fa';
		} else if (delta < dateThresholds.days) {
			delta = Math.floor(delta / dateFormatValues.day);
			if (delta == 1) {
				res = 'ieri'
			} else {
				res = delta + ' giorni fa';
			}
		} else {
			res = dateString.replace(/(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d:\d\d):\d\d/, '$1/$2/$3 $4');
		}

		return res;
	};

	function setCurrPage(page) {
		currPage = page;
	};
	function loadPage(page) {

		var urlContent = "/StatisticheProxy/proxy.jsp?action=getContent&domain=RaiTv&localId="+
			uniquename+
			"&xsl=rai_tv-statistiche-content";
		if (typeof(page) == 'undefined') {
			page = currPage;
		}
		setCurrPage(page);

		urlContent += '&beginningIndexForComments='+(currPage*commentsPerPage + 1)+
			'&endIndexForComments='+((currPage+1)*commentsPerPage);

		debug('Loading comments page '+(currPage+1)+' from url:\n'+urlContent);

		setNielsen(urlContent);

		$.ajax({
		  url: urlContent,
		  type: 'GET',
		  cache: false,
		  error: function() {
			debug('Error getting comments...');
		  },
		  success: function(html){
			html = html.replace('<script src="/dl/RaiTV/js/rating.js" type="text/javascript"></script>', '');
			if (html.indexOf('<title>')<0) {
				var res = $('<ul></ul>').append(html);
				if (res.find('li.item_comments').length > 0) {
					setCommentsCount(res.find('span.totalNumberOfComments').text());
					setComments(res.find('ul.elencoCommenti').children());
				} else {
					setCommentsCount(0);
					setComments('');
				}
				initPagination();
			} else {
				debug('Error getting comments (there\'s a title)...');
				// $(".elencoCommenti").html('<!-- errore -->');
			}
		  }
		});
	};

	function postComment() {
		var n = boxTuttiCommenti.find('.textAreaComm .sfondoArea textarea');

		if (n.is('.posting')) {
			debug('Post in progress....');
			return false;
		}

		debug('Posting comment...');

		var urlContent = "/MyRaiTv/addComment.do"; // FAILING ;)
		var postData = {
			username: MyRaiTvNickname,
			confirmKey: MyRaiTvUserCode,
			domain: "RaiTv",
			localId: uniquename,
			textBody: n[0].value
		};

		debug(postData);

		n.addClass('posting');

		function showConfirmMessage(m, callback) {
			n.fadeOut(500, function() {
				m.fadeIn(1000, function () {
					setTimeout(function() {
						m.fadeOut(1000, function () {
							n.fadeIn(500);
							n.removeClass('posting');
							if (typeof(callback) == 'function') {
								callback();
							}
						});
					}, 5000);
				});
			});
		}

		$.ajax({
			type: "POST",
			url: urlContent,
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			data: postData,
			dataType: "text",
			success: function(result){
				debug(result);
				var res = result.split('-');
				try {
					if(/^ok$/i.test(res[0])) {
						var m = boxTuttiCommenti.find('.textAreaComm .sfondoArea div.ok');
						if (totComments == 0 || (totComments == '' && boxTuttiCommenti.find('ul.elencoCommenti li').length == 0)) {
							showConfirmMessage(m, hide);
						} else {
							showConfirmMessage(m, function() {
								boxTuttiCommenti.find('.textAreaComm').slideUp(500);
								boxTuttiCommenti.find('ul.elencoCommenti').css({borderTopWidth: '0px'});
							});
						}
					} else {
						var m = boxTuttiCommenti.find('.textAreaComm .sfondoArea div.ko');
						showConfirmMessage(m);
					}
				} catch(e) {
					var m = boxTuttiCommenti.find('.textAreaComm .sfondoArea div.ko');
					showConfirmMessage(m);
				}
			},
			error : function(result){
				n.removeClass('posting');
				var m = boxTuttiCommenti.find('.textAreaComm .sfondoArea div.ko');
				showConfirmMessage(m);
			}
		});

		return false;
	};
	function resetComment() {
		var n = boxTuttiCommenti.find('.textAreaComm .sfondoArea textarea')[0];
		n.value = n.defaultValue;
		return false;
	};

	init();

	// restituisco un oggetto con solo le funzioni che voglio esporre all'esterno: variabili e altre funzioni restano private.
	return {
		// init: init, // questo non serve: viene chiamato solo internamente
		loadPage: loadPage, // utile per debug
		setCommentsCount: setCommentsCount, // usato al caricamento della pagina in setStatsItem
		setCurrPage: setCurrPage,           // usato al caricamento della pagina in setStatsItem
		setComments: setComments,           // usato al caricamento della pagina in setStatsItem
		initPagination: initPagination,     // usato al caricamento della pagina in setStatsItem
		toggle: toggle,                     // legato al pulsante "Leggi e commenta" e al pulsante in vodOpzioni
		show: show,                         // legato al pulsante "Accedi" (visibile quando mancano commenti)
		hide: hide,                         // esposto solo per coerenza con "show"
		formatDate: formatDate              // usato al caricamento della pagina in setStatsItem
	}
};

$(function() {
	// se e' una function vuol dire che non e' ancora stato istanziato l'oggetto
	// non dovrebbe venire istanziato da nessuno prima, ma non si sa mai...
	if (typeof(Commenti) == 'function') {
		Commenti = new Commenti();
	}

	$.ajax({
		url: '/dl/RaiTV/box_social.html',
		type: 'GET',
		cache: false,
		error: function() {
			debug('Error getting social...');
		},
		success: function(html){
		//html = html.replace('<script src="/dl/RaiTV/js/rating.js" type="text/javascript"></script>', '');
			$('.spallaDx').prepend(html);
			if($("#myPageMedia").length > 0 && $("#myPageMedia").text() == 'Page-72ec3233-7130-473a-89e1-a7fb81dce083') {
				$(".spallaDx").prepend('<a href="http://www.concorsoxfactor.rai.it/" target="_blank" title="Vai al concorso" style="display:block;margin: 0px 0px 20px 0px;"><img src="/dl/RaiTV/images/xf4_concorso.jpg" width="300" height="100"/></a>');
			}
		}
	});
	//var fbLikeHtml = '<div class="fbLike"><iframe src="http://www.facebook.com/plugins/like.php?href='+escape(document.location)+'&layout=button_count&show_faces=false&width=300&action=like&colorscheme=dark&height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:35px;" allowTransparency="true"><iframe></div>';
	//var fbLikeHtml = '<div class="fbLike"><fb:like href="'+escape(document.location)+'" show_faces="false" colorscheme="dark" action="like" layout="button_count" width="300" ></fb:like></div>';
	// var fbLikeHtml = '<div class="fbLike"><fb:like layout="button_count" show_faces="true" width="450" font="trebuchet ms"></fb:like></div>';
    //
	// $('.boxVod').append(fbLikeHtml);
	//document.write(fbLikeHtml);
	// FB.init();
	// FB.XFBML.parse();

	var loc = ''+window.location;
	if (/\/dl\/RaiTV\/programmi\/media\/ContentItem/.test(loc) ) {
		var shareHtml =
			'<div class="socialNetworks">'+
			'<div class="fb">'+
			'<iframe src="http://www.facebook.com/plugins/like.php?href='+encodeURIComponent(loc)+'&layout=standard&show_faces=false&width=295&action=like&colorscheme=dark&height=35&locale=it_IT" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:295px; height:35px;" allowTransparency="true"></iframe>'+
			'</div>'+
			'<div class="share">'+
			'<span displayText="Tweet" class="st_twitter_custom st_button"> </span><span displayText="Facebook" class="st_facebook_custom st_button"> </span><span displayText="Yahoo! Buzz" class="st_ybuzz_custom st_button"> </span><span displayText="Google Buzz" class="st_gbuzz_custom st_button"> </span><span displayText="Email" class="st_email_custom st_button"> </span><span displayText="ShareThis" class="st_sharethis_custom st_button">ShareThis</span>'+
			'</div>'+
			'</div>';
		$('#playerVod').append(shareHtml);
		$('#playerVod .boxCommenti').css('height', '30px');

		if(typeof(stButtons)!='undefined'){
			stButtons.locateElements(); // sharethis
		};
	}
});

