var prefixDevil = "";
if(location.href.indexOf("/live/dl/") != -1) {
	prefixDevil = "/live";
}

if(typeof(DEBUGRAITV)=='undefined'){
	DEBUGRAITV=false;
};

if(typeof(DEBUGTV)=='undefined'){
	DEBUGTV=false;
};

if(typeof(DEBUG)=='undefined'){
	DEBUG=false;
};

function goThematic(param) {
	location.href = "http://www.rai.tv/dl/RaiTV/cerca_tematiche.html?t="+escape(param);
};

function openPopUp(url,title,width,height) {
	window.open(url,"", "width="+width+", height="+height+", status=no, menubar=no, toolbar=no scrollbar=no");
	return false;
};

function checkEmail(email) {
	if(email == ""){
		return false;
	} else if(!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email)) {
		return false;
	} else {
		return true;
	}
};

function replaceMSWord(str) {
	str = str.replace(/…/g,'...');
	str = str.replace(/“/g,'"');
	str = str.replace(/”/g,'"');
	str = str.replace(/’/g,"'");
	return str;
};

function display_block(id) {
	document.getElementById(id).style.display = "block";
};
function hide_block(id) {
	document.getElementById(id).style.display = "none";
};
function pagination (){
	$("UL.pagine>LI.succ>A").click(function() {
		var setUrl = $("UL.pagine>LI#selected").next().children().attr("id");
		var url = prefixDevil+"/dl/RaiTV/programmi/liste/"+setUrl+".html";
		loadContents(url,"#mediaList");
		setNielsen(url);
		$('html,body').animate( {scrollTop: $( '.visMode' ).offset().top});
		return false;
	});
	$("UL.pagine>LI.prec>A").click(function() {
		var setUrl = $("UL.pagine>LI#selected").prev().children().attr("id");
		var url = prefixDevil+"/dl/RaiTV/programmi/liste/"+setUrl+".html";
		loadContents(url,"#mediaList");
		setNielsen(url);
		$('html,body').animate( {scrollTop: $( '.visMode' ).offset().top});
		return false;
	});
	$("UL.pagine>LI[class!=succ][class!=prec]>A").click(function() {
		var setUrl = $(this).attr("id");
		if(setUrl != null && setUrl != ""){
			var url = prefixDevil+"/dl/RaiTV/programmi/liste/"+setUrl+".html";
			loadContents(url,"#mediaList");
			setNielsen(url);
			$('html,body').animate( {scrollTop: $( '.visMode' ).offset().top});
		}
		return false;
	});
}

var bannersLoaded = false;
var skipSkinReload = false;
var reloadBannersOnNielsen = false;
function setDefaultBanners() {
	if (typeof(stopBannerSL) != 'undefined' && stopBannerSL == "noBanner") {
		return;
	}

	if (typeof(bannerVars) == 'undefined') {
		bannerVars = {};
	}
	if (typeof(bannerVars['300x100']) == 'undefined' || bannerVars['300x100'] == '') {
		bannerVars['300x100'] = 'rai_tv^rai_tv_generica^300x100';
	}
	if (typeof(bannerVars['300x250']) == 'undefined' || bannerVars['300x250'] == '') {
		bannerVars['300x250'] = 'rai_tv^rai_tv_generica^300x250';
	}
	if (typeof(videoBannerSL) == 'undefined' || videoBannerSL == '') {
		videoBannerSL = ',pathbanner=http://ad2.neodatagroup.com/ad/load_ndgruler.jsp?sid=49&amp;loc='+
		                'rai_tv^rai_tv_generica^wmv'+
		                '&amp;bt=n&amp;wt=n&amp;jsvar=';
	}
	if (typeof(videoBannerFLV) == 'undefined' || videoBannerFLV == '') {
		videoBannerFLV = '&amp;pathbanner=http://ad2.neodatagroup.com/ad/load_ndgruler.jsp?sid=49%26loc='+
		                 'rai_tv^rai_tv_generica^wmv'+
		                 '%26bt=n%26wt=n%26jsvar=';
	}
}
// $(setDefaultBanners);
$(function() {
	// permetto l'override di setDefaultBanners
	setDefaultBanners();
});
// la setNielsen viene chiamata anche al caricamento della pagina: la prima volta non deve ricaricare i banner, che' sono gia' stati caricati
reloadBannersOnNielsen = false;
function loadSilverlightAndBanners() {
	//debug('in loadSilverlightAndBanners(), typeof(getAdagioURL) = '+typeof(getAdagioURL));
	if (typeof(createMediaItemSilverlight)!='undefined') {
		createMediaItemSilverlight();
		mediaItemSilverlightCreated = true;
		try {
			$('#silverlightControlHost object')[0].focus();
		} catch(e) {
		}
	}
	if (bannersLoaded == true) {
		return;
	}
	bannersLoaded = true;


	setTimeout(function() {
		if (typeof(bannerVars) != 'undefined'){
			if (typeof(bannerVars['300x100']) != 'undefined') {
				functionsLoadBanner300x100();
			} else if (typeof(bannerVars['300x250']) != 'undefined') {
				functionsLoadBanner300x250();
			} else {
				loadSkinProgramma();
				reloadBannersOnNielsen = true;
			}
		} else {
			loadSkinProgramma();
			reloadBannersOnNielsen = true;
		}
	}, 250);
	// la setNielsen viene chiamata anche al caricamento della pagina: la prima volta non deve ricaricare i banner, che' sono gia' stati caricati
	reloadBannersOnNielsen = false;
}

function loadSkinProgramma() {
	// reloadBannersOnNielsen = true;
	// console.log(bannerskin);
	if (skipSkinReload == true) {
		return;
	}
	skipSkinReload = true;
	if (typeof(getAdagioURL) == 'function' && typeof(bannerskin) != 'undefined' && bannerskin != '') {
		var url = getAdagioURL(
			bannerskin,
			'',
			// '$(bannercode).appendTo(".contVod");',
			// '$(".contVod").append(bannercode);',
			'$(".contVod").wrapInner(bannercode);',
			';',
			'',
			'');
		//console.log('loadSkinProgramma => '+url);
		bannercode = '';
		$.getScript(url);
	} else {
	//console.log('mmm....');
	}
}

function functionsLoadBanner300x100() {
	reloadBannersOnNielsen = true;
	if (typeof(getAdagioURL) != 'undefined' && typeof(bannerVars['300x100']) != 'undefined') {
		var v = bannerVars['300x100'];
		var fmt = '';
		var loc = '';
		var kw = '';
		if (typeof(v) == 'object') {
			if (v.adagioLocation) {
				loc = v.adagioLocation;
			}
			if (v.adagioFormat) {
				fmt = v.adagioFormat;
			}
			if (v.adagioKw) {
				kw = v.adagioKw;
			}
		} else if (typeof(v) == 'string') {
			loc = v;
		} else {
			loc = ''+v;
		}
		var url = getAdagioURL(
			loc,
			fmt,
			"$('.banner300x100').html(bannercode);functionsLoadBanner300x250();",
			"$('.banner300x100').html('');functionsLoadBanner300x250();",
			kw,
			'');
		//debug('functionsLoadBanner300x100 => '+url);
		bannercode = '';
		$.getScript(url);
	} else {
		functionsLoadBanner300x250();
	}
}
function functionsLoadBanner300x250() {
	reloadBannersOnNielsen = true;
	if (typeof(getAdagioURL) != 'undefined' && typeof(bannerVars['300x250']) != 'undefined') {
		var v = bannerVars['300x250'];
		var fmt = '';
		var loc = '';
		var kw = '';
		if (typeof(v) == 'object') {
			if (v.adagioLocation) {
				loc = v.adagioLocation;
			}
			if (v.adagioFormat) {
				fmt = v.adagioFormat;
			}
			if (v.adagioKw) {
				kw = v.adagioKw;
			}
		} else if (typeof(v) == 'string') {
			loc = v;
		} else {
			loc = ''+v;
		}
		var url = getAdagioURL(
			loc,
			fmt,
			"$('.banner300x250').html(bannercode);loadSkinProgramma();",
			"$('.banner300x250').html('');loadSkinProgramma();",
			kw,
			'');
		//debug('functionsLoadBanner300x250 => '+url);
		bannercode = '';
		$.getScript(url);
	} else {
		loadSkinProgramma();
	}
}

function loadContents(url,elHTML) {
	if (DEBUGRAITV) {alert("ERRORE");}
	$.ajax({
	  url: url,
	  cache: false,
	  success: function(html){
		if (html.indexOf('<title>')<0) {
			$(elHTML).html(html);
			setView();
			$("#mediaList").fadeIn("slow", function () {
				setReflection(".reflect");
				pagination();
				applyPngFix();
				login();
			});
		} else {
			$.ajax({
			  url: PATH_NO_CONTENT,
			  cache: false,
			  success: function(html){
				$(elHTML).html(html);
				setView();
				$("#mediaList").fadeIn("slow", function () {
					setReflection(".reflect");
				});
			  }
			});
		}
		loadSilverlightAndBanners();
	  },
	  error: function(html){
		if (DEBUGRAITV) {alert("ERRORE");}
		$.ajax({
		  url: PATH_NO_CONTENT,
		  cache: false,
		  success: function(html){
			$(elHTML).html(html);
			setView();
			$("#mediaList").fadeIn("slow", function () {
				setReflection(".reflect");
			});
		  }
		});
		loadSilverlightAndBanners();
	  }
	});
	return false;
};
function loadUgc() {
	var url = $('.id_UGC').text();
	if(url != null && url !="") {
		$.ajax({
		  url: url,
		  cache: false,
		  success: function(html){
			$("#id_BOXUGC").html(html);
		  }
		});
	}
	return false;
};
function setView() {
	var view = 'list';
	if($("UL.vis>LI.selected").children().attr("class").toString() == "visGrid") {
		var view = 'grid';
		if($("#mediaList").children("div[class*='Strett']").length!=0) {
			$("#mediaList").children().attr("class","listaVideo iconeStrette");
		} else {
			$("#mediaList").children().attr("class","listaVideo");
		}
	} else {
		if($("#mediaList").children("div[class*='Strett']").length!=0) {
			$("#mediaList").children().attr("class","listaVideoLista listaStretta");
		} else {
			$("#mediaList").children().attr("class","listaVideoLista");
		}
	}
	// setNielsen(document.url + '#setView='+view);
};
function setReflection(selector) {
	var rimages = $(selector).get();
	for (i=0;i<rimages.length;i++) {
		var rheight = null;
		var ropacity = null;

		var classes = rimages[i].className.split(' ');
		for (j=0;j<classes.length;j++) {
			if (classes[j].indexOf("rheight") == 0) {
				var rheight = classes[j].substring(7)/100;
			} else if (classes[j].indexOf("ropacity") == 0) {
				var ropacity = classes[j].substring(8)/100;
			}
		}

		Reflection.add(rimages[i], { height: rheight, opacity : ropacity});
	}
};
var skipNielsen = false;
var firstNielsen = true;
function setNielsen(url) {
	if (skipNielsen == true) {
		skipNielsen = false;
		return true;
	}
	if (url == undefined){url = location.href};
	url = unescape(url);

	//if (url.match("^/dl")){url = "http://www.rai.tv"+url};
	if (url.match("^/dl") || url.match("/StatisticheProxy")){url = "http://"+document.domain+url};
	url = url.replace(/[ ']/g, '');
	if (!firstNielsen) {
		if (!/refresh_ce-awe/.test(url)) {
			url += '&refresh_ce-awe';
		}
	}
	firstNielsen = false;
	url = encodeURIComponent(url);
	// richiesta di nielsen...
	url = url.replace(/%2F/g,'/');
	var rnd = new Date();
	rnd = rnd.getTime();
	$("#nielsen img").attr("src","//secure-it.imrworldwide.com/cgi-bin/m?ci=rainet-it&cg=0&si="+url+'&rnd='+rnd);

	if (reloadBannersOnNielsen == true) {
		try {
			functionsLoadBanner300x100();
		} catch(e) {
			try {
				console.log('exception catched', e);
			} catch(f) {
			}
		}
	}
};
function loadTabCategory(index,elSet) {
	switch(index) {
		case 0:
			__TAB = "V";
			break;
		case 1:
			__TAB = "A";
			break;
		case 2:
			__TAB = "P";
			break;
		case 3:
			__TAB = "F";
			break;
		case 4:
			__TAB = "U";
			break;
		case 5:
			__TAB = "W";
			break;
	}
	$("UL.elencoTematiche>LI").attr("id","");
	$("UL.elencoTematiche LI").hide();

	$("UL.elencoTematiche LI[class*='"+__TAB+"']").show();
	$("UL.elencoTematiche LI[class*='"+__TAB+"']").parents().show();
	/*$("UL.elencoTematiche>LI[class*='"+__TAB+"']").show();*/

	var first = $("UL.elencoTematiche>LI:visible:eq(0)");
	var urlSet = "";

	if(elSet==""){
		//OnClick della Pagina con il ContentSet settato
		if(__TAB == "W") {
			first.attr("id","selected");
			//alert(staticUrl.replace(/#action#/,first.children().attr("id")));
			urlSet = staticUrl.replace(/#action#/,first.children().attr("id"));
			setNielsen(urlSet);
		} else {
			$("UL.sottoTematica").hide();
			if(first.children("UL[class='sottoTematica']").length!=0) {
				if(DEBUGRAITV){alert("1");}
				first.children().show();
				first.attr("id","selectedDown");
				first.children("UL").children("LI[class*='"+__TAB+"']").show();
				if($("UL.elencoTematiche>LI:visible:eq(0)[class*='"+__TAB+"']").length!=0) {
					if(DEBUGRAITV){alert("2");}
					urlSet = first.children().attr("id");
				} else {
					if(DEBUGRAITV){alert("3");}
					first.children("UL").children("LI:visible:eq(0)").attr("id","selected");
					first.attr("id","unselectedDown");
					urlSet = first.children("UL").children("LI:visible:eq(0)").children().attr("id");
				}
			} else {
				if(DEBUGRAITV){alert("4");}
				first.attr("id","selected");
				urlSet = first.children().attr("id");
			}
			setNielsen(prefixDevil+"/dl/RaiTV/programmi/liste/"+urlSet+"-"+__TAB+"-0.html");
		}
	} else {
		//OnLoad della Pagina con il ContentSet settato
		if($("#"+elSet).next(".sottoTematica").length!=0) {
			if(DEBUGRAITV){alert("5");}
			//Categoria con figli
			$("#"+elSet).parent().attr("id","selectedDown");
			$("#"+elSet).next().children("LI[class*='"+__TAB+"']").show();
		} else {
			if(DEBUGRAITV){alert("6");}
			//Categoria senza figli
			$("UL.sottoTematica").not($("#"+elSet).parents(".sottoTematica").get()).hide();
			$("#"+elSet).parent().siblings("LI[class*='"+__TAB+"']").show();
			$("#"+elSet).parent().attr("id","selected");
			$("#"+elSet).parents(".sottoTematica").parent().attr("id","unselectedDown");
		}

		urlSet = elSet;
	}
	if(__TAB == "W") {
		loadContents(urlSet,"#mediaList");
	} else if (urlSet != undefined){
		var page = $(document).getUrlParam("p")==null || $(document).getUrlParam("p")== "" ? "0" : $(document).getUrlParam("p");
		if (page == '0') {
			var strParamName = 'p';
			if (!!document.location.hash && document.location.hash.indexOf(strParamName) > -1 ) {
				var qString = document.location.hash.substr(1,document.location.hash.length).split("&");
				if (qString==null) {
					page = '0';
				} else {
					for (var i=0;i<qString.length; i++) {
						if (escape(unescape(qString[i].split("=")[0])) == strParamName){
							page = qString[i].split("=")[1];
						}
					}
				}
			}
		}
		if (page == null || page == '' || page == 'null') {
			page = '0';
		}
		loadContents(prefixDevil+"/dl/RaiTV/programmi/liste/"+urlSet+"-"+__TAB+"-"+page+".html","#mediaList");
		//loadContents(prefixDevil+"/dl/RaiTV/programmi/liste/"+urlSet+"-"+__TAB+"-0.html","#mediaList");
	} else {
		loadContents(PATH_NO_CONTENT,"#mediaList");
	}
};

function applyPngFix ()
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])

	if ((version >= 5.5) && (version < 7) && (document.body.filters))
	{
	   for(var i=0; i<document.images.length; i++)
	   {
		  var img = document.images[i]
		  var imgName = img.src.toUpperCase()
		  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		  {
			 var imgID = (img.id) ? "id='" + img.id + "' " : ""
			 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			 var imgStyle = "display:inline-block;" + img.style.cssText
			 if (img.align == "left") imgStyle = "float:left;" + imgStyle
			 if (img.align == "right") imgStyle = "float:right;" + imgStyle
			 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			 var strNewHTML = "<span " + imgID + imgClass + imgTitle
			 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
			 img.outerHTML = strNewHTML
			 i = i-1
		  }
	   }
	}
};

function sendFriend(idItem,choice) {
	var optionShadowbox = {};
	$(".notice").attr("class","notice").html("");
	if(idItem != "" && choice == true) {
		var emailObject = "Un tuo amico ti segnala Rai.tv";
		var title = $("#"+idItem + ">.Desc>.Lancio>H2").text();
		if(title == "" || title == null) {
			title = $("#idMedia").text();
		}
		if(title == "" || title == null) {
			title = "http://www.rai.tv/dl/RaiTV/programmi/media/"+idItem+".html";
		}

		var programName = $("DIV.logoDescr").children("H2").text();
		if(programName == "" || title == programName) {
			programName = $("#"+idItem + ">.Desc>.Lancio>H5").text();
		}

		var emailBody = "Un tuo amico ti segnala:<br><a href=\"http://www.rai.tv/dl/RaiTV/programmi/media/"+idItem+".html\">"+title+"</a> - "+programName+"<br>su Rai.tv<br><br>Messaggio: "+$("#emailCommento").val()+"<br><br><hr>Entra anche tu nel mondo <a href=\"http://www.rai.tv/dl/RaiTV/MyRaiTV/iscrizione.html\">MyRaitv</a> ed inizia a creare la tua homepage personalizzata.<br><br>Buona navigazione<br><a href=\"http://www.rai.tv\">Raitv</a>";
		var valori = {emailFrom : $("#emailFrom").val(), emailTo:$("#emailTo").val(),emailBody: emailBody, emailObject :emailObject};

		if(checkEmail($("#emailFrom").val()) && checkEmail($("#emailTo").val())) {
			$.ajax({
			   url: "http://www.rai.tv/services/sendEmail.jsp",
			   type: "POST",
			   dataType: "text",
			   data: valori,
			   success: function(result){
					if(jQuery.trim(result) == "ok") {
						optionShadowbox = {
											title : "Invia ad un amico",
											content:'<div id="msg">'+messages["emailSendOK"]+' <a title="Chiudi" class="Close" onclick="Shadowbox.close(); return false;" href="#" style="display: block; width: 15px; height: 15px; position: absolute; top: 2px; right: 2px; background: transparent url(/dl/RaiTV/images/btn_close_comm.gif) no-repeat scroll 0 0"><span class="solotesto">Chiudi</span></a></div>',
											player : "html",
											height :100,
											width: 300,
											options :{ animate:false}
										};
						Shadowbox.init({
							skipSetup: true // skip the automatic setup
						});
						Shadowbox.open(optionShadowbox);
					} else {
							optionShadowbox = {
											title : "Invia ad un amico",
											content:'<div id="msg">'+messages["emailSendKO"]+' <a title="Chiudi" class="Close" onclick="Shadowbox.close(); return false;" href="#" style="display: block; width: 15px; height: 15px; position: absolute; top: 2px; right: 2px; background: transparent url(/dl/RaiTV/images/btn_close_comm.gif) no-repeat scroll 0 0"><span class="solotesto">Chiudi</span></a></div>',
											player : "html",
											height :100,
											width: 300,
											options :{ animate:false}
										};
						Shadowbox.init({
							skipSetup: true // skip the automatic setup
						});
						Shadowbox.open(optionShadowbox);
					}
			   },
			   error : function(result){
					optionShadowbox = {
										title : "Invia ad un amico",
										content:'<div id="msg">'+messages["emailSendKO"]+'</div>',
										player : "html",
										height :100,
										width: 300,
										options :{ animate:false}
									};
					Shadowbox.init({
						skipSetup: true // skip the automatic setup
					});
					Shadowbox.open(optionShadowbox);
				}
			});
		} else {
			if(!checkEmail($("#emailFrom").val())) {
				$("#emailFrom").parent().next().attr("class","notice Error").html(messages["emailNotValid"]);
			}
			if(!checkEmail($("#emailTo").val())) {
				$("#emailTo").parent().next().attr("class","notice Error").html(messages["emailNotValid"]);
			}
		}
	} else {
		var html = "<h2 class=\"inviaAmico\"><span class=\"solotesto\">Invia ad un amico</span></h2><div class=\"sendFriend\"><ul><li><div class=\"label\">Email amico:</div><div class=\"input\"><input name=\"emailTo\" type=\"text\" class=\"testo\" id=\"emailTo\"/></div><div class=\"notice\"></div></li><li><div class=\"label\">Tua email:</div><div class=\"input\"><input name=\"emailFrom\" type=\"text\" class=\"testo\" id=\"emailFrom\"/></div><div class=\"notice\"></div></li><li><div class=\"label\">Messaggio:</div><div class=\"textarea\"><textarea id=\"emailCommento\"></textarea></div></li></ul><div class=\"inviaAmicoConfirm\"><span></span><ul class=\"confirm\"><li><a href=\"#\" onclick='javascript:Shadowbox.close();'>Annulla</a></li><li><a href=\"#\" onclick=\"javascript:sendFriend('"+idItem+"',true);\">Invia</a></li></ul></div></div>";
		optionShadowbox = {
							title : "Invia ad un amico",
							content:'<div id="msg">'+html+'</div>',
							player : "html",
							height :320,
							width: 600,
							options :{ animate:false,enableKeys:false}
						};
		Shadowbox.init({
			skipSetup: true // skip the automatic setup
		});
		Shadowbox.open(optionShadowbox);
	}
};

/* stub */
function rewriteHREF() {
	return true;
}
var staticUrl = "";
//staticUrl = '/StatisticheProxy/proxy.jsp?action=#action#&domain=RaiTv&days=7&state=1&records=6&order=&xsl=rai_tv-statistiche-consigliati&tags=NomeProgramma%3A';
staticUrl = '/StatisticheProxy/proxy.jsp?action=#action#&domain=RaiTv&days=7&state=1&records=6&order=&xsl=rai_tv-statistiche-consigliati&tags=PageOB%3A';
$(function()
{

	/*try {
		if (window.top.location.host != "www.rai.tv"){
			window.top.location.href=location.href.replace(/www.rai.it/,'www.rai.tv');
		}
	} catch(e){window.top.location.href=location.href.replace(/www.rai.it/,'www.rai.tv');}*/


	$('.box_TopHeader li.TM_Raiit').removeClass('li_Selected');
	$('.box_TopHeader li.TM_RaiTV').addClass('li_Selected');
	var loadSet = "";var indexTab = 0;
	try {
		pageVisited = $("UL.tab").attr("id").toString();
	} catch(e){}

	$("#mediaList").fadeIn("slow");
	if(navigator.platform.toLowerCase().match("linux") == "linux" && pageVisited == "home") {
		$("#silverlightControlHost").hide();
		$("#linuxWall").show();
	} else {
		$("#silverlightControlHost").show();
		$("#linuxWall").hide();
	}

	$("UL.vis>LI").click(function() {
		if(!$(this).is('.selected')) {
			var view = 'list';
			$("UL.vis>LI").removeClass("selected");
			$(this).addClass("selected");

			if($("#mediaList>.listaVideoLista, #mediaList>.listaVideo").is('.listaVideoLista')) {
				view = 'grid';
				if($("#mediaList>.listaVideoLista, #mediaList>.listaVideo").is(".listaStretta"))
				{
					$("#mediaList>.listaVideoLista").attr("class", "listaVideo iconeStrette");
				} else {
					$("#mediaList>.listaVideoLista").attr("class", "listaVideo");
				}

			} else {
				if($("#mediaList>.listaVideoLista, #mediaList>.listaVideo").is(".iconeStrette")){
					$("#mediaList>.listaVideo").attr("class", "listaVideoLista listaStretta");
				} else {
					$("#mediaList>.listaVideo").attr("class", "listaVideoLista");
				}
			}
			// reloadBannersOnNielsen = false;
			setNielsen(document.location.pathname + '#setView='+view);
		}
		return false;
	});

	if(pageVisited == "page") {
		$.ajaxSetup({async:false});
		$("UL.elencoTematiche LI").hide();
		loadSet = $("#mySetMedia").text();
		indexTab = parseInt($("#typeMedia").text());
		loadTabCategory(indexTab,loadSet);
		// skipNielsen = true;
		// $("UL.vis>LI:eq(1)").click(); // questo click() provoca la prima chiamata nielsen

		$.ajaxSetup({async:true});
	}

	$("UL.tab>LI").click(function() {
		$("UL.tab>LI").removeClass("selected");
		$(this).addClass("selected");
		if($('UL.vis').length != 0) {
				if(pageVisited == "page") {
				index = $("UL.tab>LI").index(this);
				loadSet="";
				loadTabCategory(index,loadSet);
			} else {
				var url = $(this).children().next().attr("rel");
				if(DEBUGRAITV){alert(url);}
				loadContents(url,"#listeMedia");
				index = $("UL.tab>LI").index(this);
				if(index > 1) {
					$("UL.vis>LI:eq(0)").click();
				} else {
					$("UL.vis>LI:eq(1)").click();
				}
				setNielsen(url);
			}
		}
		return false;
	});

	// questo codice (btnFacebook) e' stato copiato anche in /dl/RaiTV/js/2009.10/function_programma.pack.js: li' veniva riscritta la barra e non funzionava piu' nulla... :/
	$(".btnFacebook").click(function() {
		var urlRaiTv = encodeURIComponent("http://www.rai.tv/dl/RaiTV/programmi/media/"+$("#uniquename").text()+".html");
		openPopUp('http://www.facebook.com/share.php?u='+urlRaiTv,'RaiTv',540,650);
		return false;
	});

	$("A#customise").click(function() {
			var optionShadowbox = {
							title : "Scopri come personalizzare Rai.tv",
							content:'http://www.rai.tv/dl/RaiTV/MyRaiTV/personalizzaRaiTv.html',
							player : "iframe",
							height :400,
							width: 800,
							options :{ animate:false}
						};
			Shadowbox.init({
			skipSetup: true // skip the automatic setup
			});
			Shadowbox.open(optionShadowbox);
		return false;
	});


	// cerchiamo di aggiustare i player realaudio...
	if (document.lives == null && document.live != null) {
		document.lives = document.live;
	}
});
var pageVisited = "";
var PATH_NO_CONTENT = prefixDevil+"/dl/RaiTV/no_content.html";
var PATH_MYRAITV = prefixDevil+"/dl/RaiTV/MyRaiTV/myraitv.html";
var __TAB = "";





if (typeof(DEBUGTV) == 'undefined') {
	DEBUGTV = false;
	if (document.location.search != null && document.location.search.length>1) {
		// eseguo tutto in una closure: evito di creare variabili globali non necessarie
		(function(){
			var s = document.location.search;
			if (s.match(/^\?/)) {
				s = s.substring(1);
			}
			var strParams = s.split('&');
			var params = {};
			var i = 0;
			for (i in strParams) {
				var name = strParams[i];
				var value = true;
				var pos = name.indexOf('=');
				if (pos>0) {
					value = name.substring(pos+1);
					name = name.substring(0, pos);
				}
				params[name] = value;
			}
			if (params.debug === true || params.debug == 'true' || params.debug == 'debug') {
				DEBUGTV = true;
			}
		})();
	}
}
if (typeof(debug) == 'undefined') {
	function debug(s) {
		if (DEBUGTV) {alert(s);}
	}
}
if (typeof(console) == 'undefined') {
	console = {};
}
if (typeof(console.log) == 'undefined') {
	console.log = function(msg) {
		if (DEBUG) {
			alert(msg);
		}
	};
}
debug = function(msg) {
	try {
		console.log(msg);
	} catch (e) {
		if (DEBUG) {
			alert(msg);
		}
	}
	return true;
}

