//ADV function
function getSite() {
	return "gazzetta";
};

function onChangeProvincia() {
	//Caricare localit� e film
	if($("#provincia").val() == '') {
		$("#idComune").removeOption(/./);
		$("#idComune").addOption("","Scegli");
		$("#idFilm").removeOption(/./);
		$("#idFilm").addOption("","Seleziona il film");
		$("#idCinema").removeOption(/./);
		$("#idCinema").addOption("","Seleziona il cinema");
	}
	$("#idComune").removeOption(/./);
	$("#idComune").addOption("","Scegli");
	$("#idComune").ajaxAddOption("/cinema-tv/json/localita/"+$("#provincia").val()+".json",null,false);
	$("#idFilm").removeOption(/./);
	$("#idFilm").addOption("","Seleziona il film");
	$("#idFilm").ajaxAddOption("/cinema-tv/json/film/province/"+$("#provincia").val()+".json",null,false);
	$("#idCinema").removeOption(/./);
	$("#idCinema").addOption("","Seleziona il cinema");
}

function onChangeComune() {
	//Caricare film e cinema
	if($("#idComune").val() == '') {
		$("#idCinema").removeOption(/./);
		$("#idCinema").addOption("","Seleziona il cinema");
		$("#idFilm").removeOption(/./);
		$("#idFilm").addOption("","Seleziona il film");
		if($("#provincia").val() != '') {
			$("#idFilm").ajaxAddOption("/cinema-tv/json/film/province/"+$("#provincia").val()+".json",null,false);
		}
	}
	$("#idFilm").removeOption(/./);
	$("#idFilm").addOption("","Seleziona il film");
	$("#idFilm").ajaxAddOption("/cinema-tv/json/film/localita/"+$("#idComune").val()+".json",null,false);
	$("#idCinema").removeOption(/./);
	$("#idCinema").addOption("","Seleziona il cinema");
	$("#idCinema").ajaxAddOption("/cinema-tv/json/cinema/"+$("#idComune").val()+".json",null,false);
}

function onChangeEsclusivi(tipo) {
	if(tipo == 'film') {
		$("#genere").selectOptions("", true);
		$("#idCinema").selectOptions("", true);
	} else if(tipo == 'genere') {
		$("#idFilm").selectOptions("", true);
		$("#idCinema").selectOptions("", true);
	} else if(tipo == 'cinema') {
		$("#genere").selectOptions("", true);
		$("#idFilm").selectOptions("", true);
	}
}


function htmlEncode(source) {
	function special(source)
	{
		var result = '';
		for (var i = 0; i < source.length; i++)
		{
			var c = source.charAt(i);
			if (c < ' ' || c > '~')
			{
				c = '&#' + c.charCodeAt() + ';';
			}
			result += c;
		}
		return result;
	}
	var result = source;
	// ampersands (&)
	result = result.replace(/\&/g,'&amp;');
	// less-thans (<)
	result = result.replace(/\</g,'&lt;');
	// greater-thans (>)
	result = result.replace(/\>/g,'&gt;');
	// Replace quotes if it isn't for display,
	// since it's probably going in an html attribute.
	result = result.replace(new RegExp('"','g'), '&quot;');
	// special characters
	result = special(result);

	return result;
}

// Console

if (typeof console == 'undefined') {
	console = new Object;
	console.trace = function() {};
	console.log = function() {};
	console.debug = function() {};
	console.info = function() {};
	console.warn = function() {};
	console.error = function() {};
	console.time = function() {};
	console.timeEnd = function() {};
	console.count = function() {};
} else if (typeof console.time === 'undefined') {
	console.trace = function() {};
	console.time = function() {};
	console.timeEnd = function() {};
	console.count = function() {};
}

// Usata nel rullo temporeale in homePage o nella sezione Ciclismo
function openRadioCorsaTappa(lingua, tappa) {
	//if (tappa == "1" || tappa == "12" || tappa == "21") {
	if ("" + tappa == "1") tappa = "01";
	if ("" + tappa == "2") tappa = "02";
	if ("" + tappa == "3") tappa = "03";
	if ("" + tappa == "4") tappa = "04";
	if ("" + tappa == "5") tappa = "05";
	if ("" + tappa == "6") tappa = "06";
	if ("" + tappa == "7") tappa = "07";
	if ("" + tappa == "8") tappa = "08";
	if ("" + tappa == "9") tappa = "09";
	document.location = "http://www.gazzetta.it/Speciali/Giroditalia/2009/radiocorsa-feed-epson/it/radiocorsa.shtml?t=" + tappa;
	/*} else {
		var hWnd=window.open("http://www.gazzetta.it/temporeale/flash/radiocorsa/temporeale.html?lingua=" + lingua,"Grafica","toolbar=no,width=810,left=1,top=1,height=515,directories=no,location=no,status=no,statusbar=no,resizable=1,menubar=no,scrollbars=no");
		if(!hWnd.opener) hWnd.opener=self;
		if(hWnd.focus!=null) hWnd.focus();
	}*/
}

// Usata nel rullo temporeale in homePage o nella sezione Ciclismo
function openRadioCorsaTesto(tappa) {
	//if (tappa == "1" || tappa == "12" || tappa == "21") {
	if ("" + tappa == "1") tappa = "01";
	if ("" + tappa == "2") tappa = "02";
	if ("" + tappa == "3") tappa = "03";
	if ("" + tappa == "4") tappa = "04";
	if ("" + tappa == "5") tappa = "05";
	if ("" + tappa == "6") tappa = "06";
	if ("" + tappa == "7") tappa = "07";
	if ("" + tappa == "8") tappa = "08";
	if ("" + tappa == "9") tappa = "09";

	document.location = "http://www.gazzetta.it/Speciali/Giroditalia/2010/radiocorsa-feed-epson/it/radiocorsa.shtml?t=" + tappa;
	/*} else {
		var hWnd=window.open("http://www.gazzetta.it/temporeale/flash/radiocorsa/temporeale.html?lingua=" + lingua,"Grafica","toolbar=no,width=810,left=1,top=1,height=515,directories=no,location=no,status=no,statusbar=no,resizable=1,menubar=no,scrollbars=no");
		if(!hWnd.opener) hWnd.opener=self;
		if(hWnd.focus!=null) hWnd.focus();
	}*/
}

// Usata nel rullo temporeale in homePage o nella sezione Ciclismo
function showVideo(_idTappa){
	var hWnd=window.open("http://videochat.gazzetta.it/index_giro.shtml","LiveVideo","toolbar=no,width=997,left=1,top=1,height=700,directories=no,location=no,status=no,statusbar=no,resizable=1,menubar=no,scrollbars=yes");
	if(!hWnd.opener) hWnd.opener=self;
	if(hWnd.focus!=null) hWnd.focus();
}

// Lazy load
function loadExtScript(src, test, callback) {
	var s = document.createElement('script');
	s.src = src;
	document.body.appendChild(s);

	if ($.browser.msie) {
		s.onreadystatechange = function() { if ( this.readyState != "loaded" ) return; callback.call();		}

	} else if ($.browser.safari) {
		var callbackTimer = setInterval(function() {
			var call = false;
			try {
				call = test.call();
			} catch (e) {}

			if (call) {
				clearInterval(callbackTimer);
				callback.call();
			}
		}, 100);

	} else {  // Firefox
		s.onload = callback;
	}
}

// Funzione di notifica all'utente, al posto dell'alert.
function message(s){
	alert(s);
}

// AJAX forms
function ajaxifySingleForm(form, callback) {
	callback = callback || function(){ };
	$(form).validate({
		wrapper: "strong",
		submitHandler: function(form){
			$(form).ajaxSubmit({
			target: $(form).parent(),
			success: function() {
				initAjaxForms();
				callback.call();
				}
			});
		}
	});
}

function initAjaxForms() {
	$("form.ajax").each(function() {
		ajaxifySingleForm(this);
	});
}

function link_expand() {
	$("a[rel*=expand]")
		.each(function() {
			var destinazioneLink = $(this).attr("href");
			var target_var = $(this).attr("target");
			var cliccato=0;
			$(this).unbind("click").click(function() {
                                        cliccato=1;
				})
				.parents(":eq(0)")
				.unbind("click")
				.click( function() {
					if(cliccato==0){
						if(target_var=="_blank") window.open(destinazioneLink,'sponsor');
						else window.location = destinazioneLink;
					}
					cliccato=0;
				})
				.hover(function () {
					$(this).css({ cursor: "pointer" });
				}, function () {
					$(this).css({ cursor: "default" });
			});
	});
}

/* SITE CENSUS DA SWF */
function count_ajax_m_flash(nome_flash){
		var o = {
			rsPath: "/"+nome_flash
		}
		$('.box_white embed').ajaxMetrics(o);
}

var count_cycle = 0;
/* NEWS CARICATE VIA xml */
function getNews(){
	var lnk=$("#newsticker").attr('name');
	if(lnk){
		$.ajax({
			type:"GET",
			url:"/ultimora/notizie/"+lnk,
			dataType:"xml",
			success:function(xml){
				var testo="";
				$("notizia",xml).each(function(){
					var id_text=$(this).attr('id');
                    var cat=$(this).attr('sezione');
                    if (cat == "smallhome") cat = "home";
					var titolo_text=$(this).find('titolo').text();
					var data_text=$(this).find('data').text();
					var section_text=$(this).find('categoria').text();
					var ora_text=$(this).find('ora').text();
					var titolo=titolo_text.substring(0,titolo_text.indexOf(':',0))+': ';
					var text=titolo_text.substring(titolo_text.indexOf(':',0)+1,titolo_text.length-1);
					testo+='<li>';
					testo+='<strong><span class="highlight-time">'+ora_text+'</span> &nbsp;'+titolo+'</strong>';
                    testo+='<a href="http://www.gazzetta.it/ultimora/agrnews.jsp?id='+id_text+'&cat='+cat+'&sezione='+section_text+'">'+text+'</a>';
					testo+='</li>';
				});
			 $('#newsticker').html(testo);
			 startCycle();
			}
		});
	  var newsTimeout=setTimeout(getNews,30000);
	}
}
/* NEWS CARICATE VIA JSON */
var lnk_rullo_notizie="";
function getNews_Json(){
	$("#newsticker").empty();
	var testo = [];
	var replace_par = new Array("{", "}");
	var url_json = "";
	if( conta_passaggio > 0) {
	clearInterval(intval);
	}

	$('#newsticker').hide();
	if(lnk_rullo_notizie){
	    $.ajax({
	        url: "http://json.gazzettaobjects.it/notizie-ultima-ora/"+lnk_rullo_notizie.replace(".xml",".json"),
	        type: "GET",
	        dataType: "script",
	        success: function(data){
	          if($(xml_wrap.notizie.notizia).length > 0){
	            $.each(xml_wrap.notizie.notizia, function(i, item){
	                var id_text=item.id;
	                var cat=item.sezione;
	                var url=item.url;
	                cat = "home";
	                var titolo_text=item.titolo;
	                var data_text=item.data;
	                var titolo="";
	                var ora_text=item.ora;
                  if($("body#home.sub-default.type-home").length > 0) titolo=item.categoria + " - ";
	                testo.push('<li><strong><span class="highlight-time">', ora_text, '</span> &nbsp;', titolo, '</strong><a href="http://www.gazzetta.it', url, '">', titolo_text, '</a></li>');
	            }); // fine $.each
	            testoString = testo.join("");
	            $('#newsticker').html(testoString);
	            startRullo();
	            }
	            else {
                lnk_rullo_notizie = "smallnotiziegazzettahome.xml";
                getNews_Json();              
              }
	        }
    	});
	}
}




/*










function getNews_Json(){
	$("#newsticker").empty();
	var lnk=$("#newsticker").attr('name');
	var testo="";
	var replace_par = new Array("{", "}");
	var url_json = "";
	if( conta_passaggio > 0)	clearInterval(intval);
	$('#newsticker').hide();
	if(lnk){
		url_json = "/notizie-ultima-ora/"+lnk.replace(".xml",".json"),

		$.getScript("http://www.gazzetta.it"+url_json, function(){
				  $.each(xml_wrap.notizie.notizia, function(i,item){
					var id_text=item.id;
                    var cat=item.sezione;
					var url=item.url;
                    cat = "home";
					var titolo_text=item.titolo;
					var data_text=item.data;
					var section_text=item.categoria;
					var ora_text=item.ora;
					var titolo=titolo_text.substring(0,titolo_text.indexOf(':',0))+': ';
					var text=titolo_text.substring(titolo_text.indexOf(':',0)+1,titolo_text.length-1);

					testo+='<li>';
					testo+='<strong><span class="highlight-time">'+ora_text+'</span>'+titolo+'</strong>';
                    testo+='<a href="http://www.gazzetta.it'+url+'">'+text+'</a>';
					testo+='</li>';
				  });
				 $('#newsticker').html(testo);

				 startRullo();
		});
	   var newsTimeout=setTimeout(getNews_Json,60000);
	}
}




*/

















	var pause_news = 0;
	var pos_ul = 0;
	var numero_li = 0;
	var altezza_ul_news = 0;
	var conta_passaggio = 0;

	function spostaUl(){
		$("#newsticker").css("top",pos_ul+"px");
		if( pos_ul == 23)	$('#newsticker').show();
		if(pause_news == 0) {
			if(numero_li > altezza_ul_news) {
				pos_ul = 23;
				numero_li = -23;
			}
			else {
				pos_ul = pos_ul-1;
				numero_li++;
			}
		}
	}
function startRullo(){
	 pause_news = 0;
	 pos_ul = 23;
	 numero_li = 0;
	 altezza_ul_news = $("#newsticker").height()+pos_ul;
	if( conta_passaggio > 0)	clearInterval(intval);
	conta_passaggio++;
	intval = setInterval(spostaUl, 150);

	$("#newsticker li").bind('mouseover', function() {
		pause_news = 1;
	})
	.bind('mouseout', function() {
		pause_news = 0;
	});
	}

function startCycle(){
	$('#slideshow').cycle('stop');
	$('#newsticker-switch .next-arrow, #newsticker-switch .prev-arrow').unbind();
	$('#newsticker').cycle({
		fx:     'scrollUp',
		speed:  'fast',
		timeout: 5000,
		next:   '#newsticker-switch .next-arrow',
		prev:   '#newsticker-switch .prev-arrow'
	});
}

var click_cor = 0;
var num_max_foto = 1;
var counter_foto = 1;
function aggiorna_foto(){
	aggiorna_num_foto();
	var new_src_foto = $("#carousel li[jcarouselindex="+counter_foto+"] img").attr("name");
	var new_alt_foto = $("#carousel li[jcarouselindex="+counter_foto+"] img").attr("alt");
	$("#fotogallery-popup .photo-content img.foto-big").attr("src",new_src_foto).attr("alt",new_alt_foto);
	$(".photo-content span").html(new_alt_foto);
}
function aggiorna_num_foto(){
	$("#fotogallery-popup .pager span").html("<strong>"+counter_foto+"</strong> / "+num_max_foto);
	$("#carousel li").removeClass("selected");
	$("#carousel li[jcarouselindex="+counter_foto+"]").addClass("selected");
}

function verificaSelezione(idSondaggio) {
    var totale = document.getElementById("totaleIdx_" + idSondaggio).value;
    var f = document.forms["formVota" + idSondaggio];

    var messageTitle = "ATTENZIONE!!\n";
    var errorMessage = "";

    for (i = 1; i <= totale; i++) {
        var tip = document.getElementById("tipologia_" + idSondaggio +"_" + i).value;
        var min = document.getElementById("min_" + idSondaggio +"_" + i).value;
        var max = document.getElementById("max_" + idSondaggio +"_" + i).value;

        var counter = 0;
        var chkboxes = $(".opt_" + idSondaggio + "_" + i);
        for (j = 0; j < chkboxes.length; j++) {
            if (chkboxes[j].checked) {
                counter++;
            }
        }

        if (counter < min || counter > max) {
            if (tip == "1")
                errorMessage += "Non � stata selezionata nessuna risposta (domanda n. " + i + ")"+ "\n";
            if (tip == "2")
                errorMessage += "Selezionare min " + min + " risposte e max " + max + " risposte nella domanda " + i + "\n";

        }
    }

    if (errorMessage != "") {
        alert(messageTitle + errorMessage);
        return false;
    }
    return true;
}

/* GIRO 2009 */

function mostra_classifica(str){
	target = document.getElementById("box-ordine");
	target2 = document.getElementById("box-classifica");

	if (str == "1"){
		target.style.display = "block";
		target2.style.display = "none";
	}

	if (str == "2"){
		target.style.display = "none";
		target2.style.display = "block";
	}
}

function mostra_tappa(str){
	target = document.getElementById("tappa1-7");
	target2 = document.getElementById("tappa8-14");
	target3 = document.getElementById("tappa15-21");

	if (str == "1"){
		target.style.display = "block";
		target2.style.display = "none";
		target3.style.display = "none";
	}

	if (str == "2"){
		target.style.display = "none";
		target2.style.display = "block";
		target3.style.display = "none";
	}

	if (str == "3"){
		target.style.display = "none";
		target2.style.display = "none";
		target3.style.display = "block";
	}
}
	function resizeImgFotogallery(){
		$(".bodycontent .list-foto a.selected img").each(function(){
			$(this).css({height:$(this).height()-8+"px",width:$(this).width()-8+"px"});
		});
	}

/*FUNCTION LE LA RICERCA*/
function cercaNelSitoBottom() {
	var argomento = (self.document.forms['cerca2'].q.value);
	var actionForm = (self.document.forms['siteSearch1'].action);
	document.siteSearch1.ricerca_par.value=argomento;
	document.siteSearch1.action= actionForm + "?q=" + argomento;
	document.siteSearch1.submit();
}
// cerca in testata
function cercaNelSito() {
	var argomento = (self.document.forms['cerca'].q.value);
	var actionForm = (self.document.forms['siteSearch1'].action);
 	document.siteSearch1.ricerca_par.value=argomento;
	document.siteSearch1.action= actionForm + "?q=" + argomento;
	document.siteSearch1.submit();
}

//JS DI LA TUA
function loadContent(url) {
			$('#login-dlt, #submit-commento').unbind();
		    $('#box-green .content-user').load(
				url,
				{},
				function(){
				go_example();
					var s = document.URL;
					if (document.URL.toString().indexOf("#") > -1)
						s = document.URL.toString().substring(0, document.URL.toString().indexOf("#"))

					$('#login-dlt #destinationField').attr("value", s + "?#afterlogin");

					$("#dltSubmit").click(function () {
						//$("#login-header #destURL").attr("value", $("#login-dlt #destinationField").val());
						//$("#login-header #user").attr("value", $("#login-dlt input[name=edit[name]]").val());
						//$("#login-header #pass").attr("value", $("#login-dlt input[name=edit[pass]]").val());
						$("#login-dlt").submit();
						return false;
					});

					/*$('#login-dlt').submit(function() {
						//var options = {target: '#content-user'};
						$('#login-dlt').ajaxSubmit();
							return false;
					});*/

							$('#submit-commento').validate();
							$('#submit-commento').submit(function() {
								/*var options = {
									target: '#box-green .content-user',
									beforeSubmit:  validate,
									success: successCallBack,
									processData: false
								};*/
								//$(this).ajaxSubmit(options);
								if (validate()) {
/*
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&agrave;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&egrave;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&egrave;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&igrave;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&ograve;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&ugrave;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&ccedil;"));
$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", $('#submit-commento input[name=milUgc.ugcTitolo]').attr("value").toString().replace(/�/gi, "&degree;"));

$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&agrave;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&egrave;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&egrave;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&igrave;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&ograve;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&ugrave;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&ccedil;"));
$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", $('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value").toString().replace(/�/gi, "&degree;"));
*/
								 	$("#box-green .content-user").load("/dilatuagaz/invioRecensione.do", {
																			"milUgc.ugcTitolo" : htmlEncode($('#submit-commento input[name=milUgc.ugcTitolo]').attr("value")),
																			"milUgc.ugcTesto" : htmlEncode($('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value")),
																			"username" : $('#submit-commento input[name=username]').attr("value"),
																			"nickname" : $('#submit-commento input[name=nickname]').attr("value"),
																			"nomeEventoEntita" : $('#submit-commento input[name=nomeEventoEntita]').attr("value"),
																			"returnUrl" : $('#submit-commento input[name=returnUrl]').attr("value"),
																			"pubblicate" : $('#submit-commento input[name=pubblicate]').attr("value"),
																			"oggetto" : $('#submit-commento input[name=oggetto]').attr("value"),
																			"tipologia" : $('#submit-commento input[name=tipologia]').attr("value"),
																			"formId" : $('#submit-commento input[name=formId]').attr("value"),
																			"preview" : $('#submit-commento input[name=preview]').attr("value") }, successCallBack);
								}
								return false;
							});
					$(".delete").click(function() {
						// reset dei campi...
						$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", "");
						$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", "");
						return false;
 					});
				});
		}


		function validate(formData, jqForm, options) {
			var ret = true;
			if ($('#submit-commento input[name=milUgc.ugcTitolo]').attr("value") == "Scrivi titolo") {
				$('#submit-commento input[name=milUgc.ugcTitolo]').attr("value", "");
				ret = false;
				$('#submit-commento').validate();
			}
			if ($('#submit-commento input[name=milUgc.ugcTesto]').attr("value") == "Scrivi il testo del commento") {
				$('#submit-commento textarea[name=milUgc.ugcTesto]').attr("value", "");
				ret = false;
				$('#submit-commento').validate();
			}
			$('#submit-commento .error').each(function (i) {
				if ($(this).css("display") != "none") {
					ret = false;
				}
			});
		    return ret;
		}

		// post-submit callback
		function successCallBack()  {
  			$('#altro-commento').click(function() {
				 loadContent($(this).attr('href'));
				 return false;
			});
		}

function apriInviaPagina() {
	var miourl=window.location.href;
	var miourl_s=miourl.split("&");
	var loc="";
	for (i in miourl_s)
	loc+=miourl_s[i]+"!*";
	loc=loc.substr(0,loc.length-2)
	tit = document.title
	prop = "menubar=no,status=no,titlebar=no,toolbar=no,width=450,height=450,scrollbars=yes"
	window.open("http://www.gazzetta.it/cf/tellafriend/formGol.cfm?rr="+loc+"&tit="+tit, "InviaPagina", prop);
}

/*FUNCTION VECCHIA GAZZETTA*/
function apri_popup_methode(url_articolo) {
var pathToRemove = "/Gazzetta dello Sport";
var lenPathToRemove = pathToRemove.length;
if (url_articolo.indexOf(pathToRemove) > -1) url_articolo = url_articolo.substring(lenPathToRemove);
if (url_articolo.indexOf(".xml") > -1)  url_articolo = url_articolo.substring(0, url_articolo.indexOf(".xml")) + ".shtml";
var hWnd = window.open(url_articolo,"","toolbar=yes,width=450,height=600,resizable=1,menubar=no,scrollbars=yes");
if (!hWnd.opener) hWnd.opener = self;
if (hWnd.focus != null) hWnd.focus();
}

function galleriaN(str,str2) {
var larghezza = screen.Width;
if (larghezza >= 1024) {
window.open('/gallery/' + str + '/vuoto.shtml?' + str2 + '','gallery','width=745,height=660,status=no');
} else {
window.open('/gallery/' + str + '/vuoto.shtml?' + str2 + '','gallery','width=760,height=550,status=no');
}
}

function galleriaD(str,str2) {
	var larghezza = screen.Width;
	if (larghezza >= 1024) {
		window.open('/gallery/' + str + '/vuotoD.shtml?' + str2 + '','gallery','width=745,height=660,status=no');
	} else {
		window.open('/gallery/' + str + '/vuotoD.shtml?' + str2 + '','gallery','width=760,height=550,status=no');
	}
}

function openlink(xlink){
	window.open("/openxlink.shtml?" + xlink, "xpage");
}

function popUpGallery(url,type,strWidth,strHeight){
	var tools="";
	tools="resizable=0,toolbar=no,location=no,scrollbars=no,width="+strWidth+",height="+strHeight+",left=0,top=0";
	nuova_finestra=window.open(url,'fotogallery',tools);
	nuova_finestra.focus();
}

function popUpGeneric(url,type,strWidth,strHeight){

	var tools="";
	tools="resizable,toolbar=no,location=no,scrollbars=no,width="+strWidth+",height="+strHeight+",left=0,top=0";

	nuova_finestra = window.open(url, "gazzetta_it", tools);
	nuova_finestra.focus();

}

function apri_popup_methode_mailto(e) {
	var hWnd = window.open(e,"","toolbar=no,width=400,height=420,resizable=0,menubar=no,scrollbars=yes");
	if (!hWnd.opener) hWnd.opener = self;
	if (hWnd.focus != null) hWnd.focus();
}
	function go_example(){
		$('.in-text input, .in-text textarea, #keywords-photo, .example').example(function() {
			return $(this).attr('title');
		});
	}
//pr6 senza scrollbars
function DZ1(nomefile,larghezza,altezza) {
	parametri="menubar=no,location=no,toolbar=no,status=no,scrollbars=no,resizable=no,width="
	parametri=parametri+larghezza+",height="+altezza
	newWin=open('','',parametri)
	newWin.location.href=nomefile
}

function pr6(nomefile,larghezza,altezza) {
	parametri="menubar=no,location=no,toolbar=no,status=no,scrollbars=yes,resizable=no,width="
	parametri=parametri+larghezza+",height="+altezza
	newWin=open('','',parametri)
	newWin.location.href=nomefile
}

function pr6_EN(nomefile,larghezza,altezza) {
var pathToRemove = "/English";
var lenPathToRemove = pathToRemove.length;
if (nomefile.indexOf(pathToRemove) > -1) nomefile = nomefile.substring(lenPathToRemove);
if (nomefile.indexOf(".xml") > -1)  nomefile = nomefile.substring(0, nomefile.indexOf(".xml")) + ".shtml";
	parametri="menubar=no,location=no,toolbar=no,status=no,scrollbars=no,resizable=no,width="
	parametri=parametri+larghezza+",height="+altezza
	newWin=open('','',parametri)
	newWin.location.href=nomefile
}

function pr4(nomefile,larghezza,altezza) {
var pathToRemove = "/Gazzetta dello Sport";
var lenPathToRemove = pathToRemove.length;
if (nomefile.indexOf(pathToRemove) > -1) nomefile = nomefile.substring(lenPathToRemove);
if (nomefile.indexOf(".xml") > -1)  nomefile = nomefile.substring(0, nomefile.indexOf(".xml")) + ".shtml";
	parametri="menubar=no,location=no,toolbar=yes,status=yes,scrollbars=yes,resizable=yes,width="
	parametri=parametri+larghezza+",height="+altezza
	newWin=open('','',parametri)
	newWin.location.href=nomefile
}

function pr7(nomefile,larghezza,altezza) {
var pathToRemove = "/Gazzetta dello Sport";
var lenPathToRemove = pathToRemove.length;
if (nomefile.indexOf(pathToRemove) > -1) nomefile = nomefile.substring(lenPathToRemove);
if (nomefile.indexOf(".xml") > -1)  nomefile = nomefile.substring(0, nomefile.indexOf(".xml")) + ".shtml";
	parametri="menubar=no,location=no,toolbar=no,status=no,scrollbars=no,resizable=no,width="
	parametri=parametri+larghezza+",height="+altezza
	newWin=open('','',parametri)
	newWin.location.href=nomefile
}

function apri_popup_methode_mailto(url_pagina_mail) {
var hWnd = window.open(url_pagina_mail,"","toolbar=no,width=400,height=420,resizable=0,menubar=no,scrollbars=yes");
if (!hWnd.opener) hWnd.opener = self;
if (hWnd.focus != null) hWnd.focus();
}

/*GET COOKIE GAZZASPACE*/
  function getCookie(name) {
    var prefix = name + "=";
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1) return null;
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
    var cookie_string = unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
    return cookie_string;
  }
/***********************************************************************
**************              DOCUMENT.READY                **************
***********************************************************************/

$(document).ready(function() {
	// DA TOGLIERE APPENA RISOLTO DAI METHODISTI : TOGLIE I COMMENTI NELLA PARTE ENGLISH
if((document.URL).indexOf("english.gazzetta.it/More_sports/")>-1) {
$("span.commenti").each(function(){
$(this).parents("a:eq(0)").remove();
});
}

	// Ridefinisco il document.write in modo che non dia fastidio dopo il document.ready()
	document.write = function(text) {
	    $("body").append(text)
	}
	document.writeln = function(text) {
	    $("body").append(text)
	}

	cookie = $.cookie("rcsLogin");
	if (cookie != null) {
		//var posizioneFinale = nomeUtente.indexOf("|");
		//nomeUtente = nomeUtente.substring(0, posizioneFinale);
		var cookieVal = cookie.split("|");

		document.communityUser = new Object();
		communityUser = {
			userName        : cookieVal[0],
			userNumber		: cookieVal[2]
		};
		if ($("body#sportweek").length > 0) {
			$("#header form.input-green").html('Bentornato <a href="http://gazzaspace.gazzetta.it/"> ' + communityUser.userName + '</a><a class="logout" href="http://gazzaspace.gazzetta.it/user/logout">Logout</a>');
		}
		else {
			$("#header form.input-green").html('<a class="logout" href="http://gazzaspace.gazzetta.it/user/logout">Logout</a>Bentornato <a href="http://gazzaspace.gazzetta.it/"> ' + communityUser.userName + '</a>');
		}


	} else {
		if ($("body#sportweek").length > 0) {
			$("#header form.input-green").html('<input type="hidden" id="destURL" class="destination" name="edit[destination]" value="'+document.URL+'?login=ok" /><input type="text" id="user" class="formfield" title="Username" taborder="1" name="edit[name]" value="" /><input type="password" id="pass" class="shortfield" title="Password" taborder="2" name="edit[pass]" value="" /><a href="#" class="button-bold bt-green submit_form">Login</a>');
			$("#header form.input-green").after('<a href="" class="ricorda-pw">Ricorda la password | </a><a href="" class="registrati">REGISTRATI</a>');
		} else 	{
		$("#header form.input-green").html('<input type="hidden" id="destURL" class="destination" name="edit[destination]" value="'+document.URL+'?login=ok" /><input type="text" id="user" class="formfield" title="GazzaSpace Username" taborder="1" name="edit[name]" value="" /><input type="password" id="pass" class="shortfield" title="Password" taborder="2" name="edit[pass]" value="" /><a href="#" class="button-bold bt-green submit_form">Login</a>');
		}
	}

  	$("#pagina-personale").click(function(){
		window.location = "http://gazzaspace.gazzetta.it/";
	});
	$("#speciali select").change(function(){
		var value_selected = $(this).val();
		window.location = value_selected;
	});

	$("#articolo #commenta-up, #articolo .last-comment").click(function(){
      $.scrollTo("#box-green");
  });
	$(".list-link a:last-child").css("border","none");


  // *******************  S E T T I N G S  GAZZASPACE  ********************
  var t = 120; // time interval in seconds for presence update
  var myCookieName = 'gazzaspace_presence_update'; // cookie name
  var url = 'http://gazzaspace.gazzetta.it/ajax.php?type=presence&op=update';
  // **********************************************************

  var now = new Date().getTime();
  var last_updated = getCookie(myCookieName);
  if (now - last_updated > t * 1000) {
    var rcsCookie = getCookie('rcsLogin');
    if (rcsCookie) {
      var parts = rcsCookie.split("|");
      document.cookie = myCookieName + "=" + now;
      $.getJSON(url + "&uid=" + parts[1] + "&jsoncallback=?", function(data) {});
    }
  }


	/*INVIA ARTICOLO*/
	$("#service-toolbar li a.message-icon").click(function(){
		var popfile = "2";
		var miourl=window.location.href;
		if ($('body').attr('id') == 'english' || miourl.search('http://english.gazzetta.it') > -1) {
			 popfile = 'en';
		}
		var miourl_s=miourl.split("&");
		var loc="";
		for (i in miourl_s)
		loc+=miourl_s[i]+"!*";
		loc=loc.substr(0,loc.length-2)
		var tit = document.title.replace(/[^\u0000-\u007F]/g, " ");
		prop = "menubar=no,status=no,resizable=no,titlebar=no,toolbar=no,width=630,height=610,scrollbars=yes"
			window.open("http://www.gazzetta.it/cf/tellafriend/formGol_"+popfile+".cfm?rr="+loc+"&tit="+tit, "InviaPagina", prop);
		return false;
	});

	$(".ticketing-block .body-annuncio a.message-icon").click(function(){
		var miourl=$(this).attr("href");
		var miourl_s=miourl.split("&");
		var loc="";
		for (i in miourl_s)
		loc+=miourl_s[i]+"!*";
		loc=loc.substr(0,loc.length-2)
		tit = document.title
		prop = "menubar=no,status=no,titlebar=no,toolbar=no,width=630,height=610,scrollbars=yes"
		window.open("http://www.gazzetta.it/cf/tellafriend/formGol_2.cfm?rr="+loc+"&tit="+tit, "InviaPagina", prop);
		return false;
	});

	// Carica notizie da file XML
	lnk_rullo_notizie=$("#newsticker").attr('name');
	getNews_Json();
	setInterval ( getNews_Json, 60000 );	
	/*
	if((document.URL).indexOf("debug=json")>-1) {
   getNews_Json();
  }
  else {
	 getNews();
  }
  */
	//MODIFICHE PER IE6
    if ($.browser.msie && parseFloat($.browser.version)<=6) {
		$("h3.line-top:first").removeClass();
	}

	$("#most-items .tab").click(function(){
		$("#most-items ul").css("display", "none").removeClass("hidden");
		$("#most-items ul#"+$(this).attr("rel")).css("display", "block");
		$("#most-items a").removeClass("current");
		$(this).addClass("current");
		return false;
	});


	$("#related-items li:lt(4)").css("display","block");
	var open_rel_it = 0;
	$("#related-items .show-article a").click(function(){
		if(open_rel_it == 0) {
			$("#related-items li").css("display","block");
			open_rel_it = 1;
			}
		else {
			$("#related-items li:gt(3)").css("display","none");
			open_rel_it = 0;
			}
		return false;
	});


	$("#box-blu .box-b-head a").click(function() {
		$("#box-blu .last-video,#box-blu .last_article").css("display","none");
		$("#box-blu ."+$(this).attr("rel")).css("display","block");
		$("#box-blu .box-b-head a").removeClass("selected");
		$(this).addClass("selected");
		return false;
	});


	$('.in-text input, .in-text textarea, #keywords-photo').example(function() {
	 	return $(this).attr('title');
	});


	$("#survey div").each(function(){
		var perc_text = $(this).find("span.percentage").html();
		perc_text = perc_text.replace(/[% ]/gi, "");
		var perc_number = Math.round(perc_text*245/100);
		$(this).find("span.result").css("width",perc_number);
	});

	/*FOTOGALLERY*/
	resizeImgFotogallery();
	var h3_content = "";
	$(".bodycontent .list-foto img").hover(function(){
		h3_content = $(".bodycontent h3").html();
		$(".bodycontent h3").html($(this).attr("alt"));
		},function(){
		$(".bodycontent h3").html(h3_content);
	}).click(function(){
		h3_content = $(this).attr("alt");
		$(".bodycontent .list-foto a.selected img").css({height:"102px",width:"148px"});
		$(".bodycontent .list-foto a").removeClass("selected");
		$(this).parent("a:eq(0)").addClass("selected");
		resizeImgFotogallery();
		});
	/*FINE FOTOGALLERY*/


	if($('#carousel').size()>0){

		$(".show-cor").click(function(){
			if(click_cor==0){
				$('.photo-content ul').css("display","block");
				$(".show-cor").addClass("text-blu");
				click_cor=1;
			}
			else {
				$('.photo-content ul').css("display","none");
				$(".show-cor").removeClass("text-blu");
				click_cor=0;
			}
		});
		var_start = 1;
    if((document.URL).indexOf("?position=")>-1) {
      url_splittato = (document.URL).split("=");
      var_start = (url_splittato[1]);
    }

		$('#carousel').jcarousel({
		  buttonNextHTML:'<span id="next-pg" title="successiva">successiva</span>',
		  buttonPrevHTML:'<span id="prev-pg" title="precedente">precedente</span>',
		  start: var_start
		});

		num_max_foto = $('#carousel li:last').attr("jcarouselindex");
		counter_foto = 1;
		aggiorna_num_foto();

		$('#carousel img').click(function(){
			counter_foto = $(this).parents("li:eq(0)").attr("jcarouselindex")/1;
			aggiorna_foto();
		});

		$('#carousel').css("visibility","visible");

		$(".pager .previous").click(function(){
			if(counter_foto>1) {
				counter_foto--;
				aggiorna_foto();
			}
			return false;
		});

		$(".pager .next, .photo-content .foto-big").click(function(){
			if(counter_foto<num_max_foto) {
				counter_foto++;
				aggiorna_foto();
			}
			return false;
		});


		var bg_body = "";
		if($(".bg-body").length>0) bg_body = $(".bg-body").attr("value");
		//if($(".photo-content ul").height()>310) $(".photo-content ul").css("height","310px");
		if($(".photo-content ul").height()>310) {
			if ($.browser.msie && parseFloat($.browser.version)<=6) $(".photo-content ul").css("height","300px");
			else $(".photo-content ul").css("height","298px");
			}
		if(bg_body.length>0){
			$("#popup").css({background:"transparent url("+bg_body+") no-repeat scroll top left", padding:"100px 75px 0 75px"});
		   window.resizeBy(150, 100);
		   self.focus();
		}
		var bg_leader = "";
		var bg_leader_url = "";
		if($(".leaderboard").length>0) {
			bg_leader = $(".leaderboard").attr("value");
			bg_leader_url = $(".leaderboard").attr("name");
		}
		if(bg_leader.length>0){
			var div_leaderbord = "<div id='div-leaderboard'> <img src='"+bg_leader+"' alt='' /> </div>";
			$("#fotogallery-popup").before(div_leaderbord);
		}
		var hover_pop =0;
		$("body").click(function(){
			if(hover_pop==0 && bg_leader_url.length>0) window.location = bg_leader_url;
		});

		$("#fotogallery-popup").hover(
			  function () {
				hover_pop =1;
			  },
			  function () {
			   hover_pop =0;
			  }
		);

    if((document.URL).indexOf("?position=")>-1) {
      url_splittato = (document.URL).split("=");
      num_click = (url_splittato[1])-1;
      for(var conta_f=0;conta_f<num_click;conta_f++){
        $(".pager .next").click();
      }
      if($("#carousel li").length == num_click+1) $("#next-pg").click();
    }

	}


	$('.tooltip').tooltip({showBody: "|"});

/*  Tab  */
//	$('#risultati-classifica ul:not(.bottom-menu-risandclass) li a').click(function(){
$('#risultati-classifica ul:first li a').click(function(){
    	$('#risultati-classifica ul li').removeClass('active');
	    $(this).parent().addClass('active');
		$('#risultati-classifica div').addClass('hidden');
		$('#'+$(this).attr("rel")).removeClass('hidden');
		return false;
	});

	$('#meteobox a.meteo-change').css('display', 'block').click(function(){
    	$('#meteolayer').removeClass('hidden');
		return false;
	});

	/*Box gazzaspace*/
	$('div.column .gazzaspace-container div.gazzaspace:eq(1),div#body-half-right .gazzaspace-container div.gazzaspace:eq(1)').each(function(){
    $(this).find("a.blue-pointer:eq(1)").css("display","none");
    $(this).find("a.blue-pointer:gt(4)").css("display","none");
  });
  $('#body-half-right .gazzaspace .half-left:eq(0), #body-half-right .gazzaspace .half-right').addClass('clearfix');


	/*BITS: liste risultati - classifiche*/
	$("#risultati-classifica #seriea , #risultati-classifica #serieb").addClass("risclass");
	$("#risultati-classifica .risclass").each(function(){
		  var list_a = $(this).find("ul.standings li").length;
		  var resto = list_a%2;
		  var col_1 = Math.round(list_a/2);
		  var col_2 = (list_a - col_1);

		  if (resto == 0)
		  	col_2 = col_2-1;

		  var list1 = $(this).find("ul.standings li:lt("+col_1+")");
		  var list2 = $(this).find("ul.standings li:gt("+(col_2)+")");
		  list1.wrapAll("<li><ul class='standings-a-sx'>");
		  list2.wrapAll("<li><ul class='standings-a-dx'>");
	  if ($("#risultati-classifica .risclass span.point:first").text() != 0) {

		  var idDiv_risclass =  $(this).attr("id");
		  var classRetrocessione = "retrocessione";
		  var classCleague = "c-league";
		  var classPrel = "prel";
		  var classUefa = "uefa";
		  var classPromossa = "promossa";
		  var classPlayoff = "playoff";
		  var classPlayout = "playout";
		  var list_dx = $(this).find("ul.standings-a-dx li").length;
		  var sx_class = "ul.standings-a-sx li span.team";
		  var dx_class = "ul.standings-a-dx li span.team";

		  if ( idDiv_risclass == "seriea" || idDiv_risclass == "liga" )
		  {
			$(this).find(sx_class + ":lt(3)").addClass(classCleague);
			$(this).find(sx_class + ":eq(3)").addClass(classPrel);
			$(this).find(sx_class + ":lt(7):not(."+classCleague+", ."+classPrel+")").addClass(classUefa);
      $(this).find(dx_class).map(function(i) {
	   			return i > (list_dx-4) ? this : null;
				}).addClass(classRetrocessione);

		  }
		  else if (idDiv_risclass == "premier")
		  {
			$(this).find(sx_class + ":lt(3)").addClass(classCleague);
			$(this).find(sx_class + ":eq(3)").addClass(classPrel);
			$(this).find(sx_class + ":lt(5):not(."+classCleague+", ."+classPrel+")").addClass(classUefa);
			 $(this).find(dx_class).map(function(i) {
	   			return i > (list_dx-4) ? this : null;
				}).addClass(classRetrocessione);

		  }
		 else if (idDiv_risclass == "bundesliga")
		  {
			$(this).find(sx_class + ":lt(2)").addClass(classCleague);
			$(this).find(sx_class + ":eq(2)").addClass(classPrel);
			$(this).find(sx_class + ":lt(6):not(."+classCleague+", ."+classPrel+")").addClass(classUefa);
			 $(this).find(dx_class).map(function(i) {
	   			return i > (list_dx-4) ? this : null;
				}).addClass(classRetrocessione);

		  }
		  else if (idDiv_risclass == "ligue1")
		  {
			$(this).find(sx_class + ":lt(2)").addClass(classCleague);
			$(this).find(sx_class + ":eq(2)").addClass(classPrel);
			$(this).find(sx_class + ":lt(4):not(."+classCleague+", ."+classPrel+")").addClass(classUefa);
			 $(this).find(dx_class).map(function(i) {
	   			return i > (list_dx-4) ? this : null;
				}).addClass(classRetrocessione);

		  }
		   else if (idDiv_risclass == "serieb")
		  {
			$(this).find(sx_class + ":lt(2)").addClass(classPromossa);
			$(this).find(sx_class + ":lt(6):not(."+classPromossa+")").addClass(classPlayoff);
			$(this).find(dx_class + ":eq("+ (list_dx-4) +")").addClass(classPlayout);
			$(this).find(dx_class + ":eq("+ (list_dx-5) +")").addClass(classPlayout);
			$(this).find(dx_class).map(function(i) {
	   			return i > (list_dx-4) ? this : null;
				}).addClass(classRetrocessione);

		}
		else if (idDiv_risclass == "sm_1divA" || idDiv_risclass == "sm_1divB" || idDiv_risclass == "sm_2divA" || idDiv_risclass == "sm_2divB" || idDiv_risclass == "sm_2divC")
		{
			$(this).find(sx_class + ":eq(0)").addClass(classPromossa);
			$(this).find(sx_class + ":lt(5):not(."+classPromossa+")").addClass(classPlayoff);
			/*$(this).find(dx_class + ":eq("+ (list_dx-1) +")").addClass(classRetrocessione);
			$(this).find(dx_class + ":eq("+ (list_dx-2) +")").addClass(classPlayout);
			$(this).find(dx_class + ":eq("+ (list_dx-3) +")").addClass(classPlayout);
			$(this).find(dx_class + ":eq("+ (list_dx-4) +")").addClass(classPlayout);
			$(this).find(dx_class + ":eq("+ (list_dx-5) +")").addClass(classPlayout);*/
			$(this).find(dx_class).map(function(i) {
	   			return i > (list_dx-6) ? this : null;
				}).addClass(classPlayout);
			$(this).find(dx_class + ":eq("+ (list_dx-1) +")").removeClass(classPlayout).addClass(classRetrocessione);
		}
		else if (idDiv_risclass == "serie-am" || idDiv_risclass == "serie-a2m" || idDiv_risclass == "serie-af")
		{
			$(this).find(sx_class + ":lt(8)").addClass(classPlayoff);
				if (list_a/2 < 8) {
	    			var restino = (8 - list_a/2);
            		$(this).find(dx_class + ":lt("+restino+")").addClass(classPlayoff);
				}
			$(this).find(dx_class + ":eq("+ (list_dx-1) +")").addClass(classRetrocessione);
			$(this).find(dx_class + ":eq("+ (list_dx-2) +")").addClass(classRetrocessione);
		}
	}

	 });


//PAGINAZIONE VECCHIA TRASFORMATA IN NUOVA
	var num_li_tot = $(".sub-fotogallery .bodycontent .page li").length;
	var count_li_page = 0;
	var class_last_li = $(".sub-fotogallery .bodycontent .page li:last").attr("class");
	var num_last_li =2;

	$(".sub-fotogallery .bodycontent .page li").each(function(){
		if(class_last_li.indexOf("prev_next") == -1) num_last_li = 1;
		if(count_li_page==0 && $(this).attr("class")=="prev_next") {$(this).addClass("prev");}
		else if(count_li_page==0 && $(this).attr("class")!="prev_next") {$(this).after("<li class='separator'> - </li>");}

		if(count_li_page==num_li_tot-1 && $(this).attr("class")=="prev_next") $(this).addClass("next");

		if(count_li_page>0 && num_li_tot>count_li_page+num_last_li ) $(this).after("<li class='separator'> - </li>");
		count_li_page++;
	});



	/*MODIFICA ID FOOTER DI GAZZASPACE FINCHE' NON VERRANNO A PRENDERSI IL FOOTER CON L'ID CORRETTO*/
	if(((document.URL).indexOf("http://gazzaspace.gazzetta.it/")>-1) && $("#footer.clear")) $("#footer.clear").attr("id","footer-gazza");

  /*aggiungo il padding su IE7: il margin-bottom dell'elemento interno non viene calcolato*/
  if ($.browser.msie && parseFloat($.browser.version)==7) {
  $(".bodycontent .layered-opener").parent('div:eq(0)').css("padding-bottom","20px");
  }

  //SONDAGGIO IN COLONNE
  $("ul[class*=split-column]").each(function(){
		var column_split = (((($(this).attr("class")).split(" "))[1]).split("_"))[1];
		var width_li = 620/column_split;
		var altezza_li_spl = 0;
		var conta_li_spl = 1;
		var ul_selected_spl = $(this);
		$(this).find("li").each(function(){
			$(this).css("width", width_li).css("text-align", "center");
			$(this).find("input").after("<br />").before("<br />");
			if($(this).height()>altezza_li_spl) altezza_li_spl = $(this).height();
			if(conta_li_spl%3 == 0) {
				$(ul_selected_spl).find("li:eq("+(conta_li_spl-1)+")").css("height",altezza_li_spl);
				$(ul_selected_spl).find("li:eq("+(conta_li_spl-2)+")").css("height",altezza_li_spl);
				$(ul_selected_spl).find("li:eq("+(conta_li_spl-3)+")").css("height",altezza_li_spl);
				altezza_li_spl = 0;
			}
			conta_li_spl ++;

		});
	});

  //METEO MAPPE SQUADRE
  squadra_m = new Array("atalanta", "bari", "bologna", "cagliari", "catania", "chievo", "fiorentina", "genoa", "inter", "juventus", "lazio", "livorno", "milan", "napoli", "palermo", "parma", "roma",  "sampdoria", "siena", "udinese");
  squadra_citta = new Array("bergamo", "bari","bologna","cagliari","catania", "verona", "firenze", "genova","milano", "torino","roma", "livorno","milano", "napoli","palermo", "parma","roma", "genova","siena", "udine");
  squadra_pos = new Array("0", "javascript:findLoc('Bari Strada Torrebella')","javascript:findLoc('Bologna Via Andrea Costa 174')","1","2", "javascript:findLoc('Verona Piazzale Olimpia')", "4", "5","6", "7","8", "9","10", "11","12", "13","15", "16","17", "19");
  if($("#meteo-mappe").length>0) {
	  var squadra = (($("#meteo-mappe").attr("class")).split(" "))[0];
	  var pos_array = 0;
	  $("#meteo-mappe .title").html("QUI "+squadra);
	  for(i=0; i<squadra_m.length;i++) {
		    if((squadra_m[i]).indexOf(squadra)>-1) {
				pos_array = i;
				i = squadra_m.length;
			}
		  }
	   var nome_c = squadra_citta[pos_array];
	   loadMeteoXml(xmlFileUrl_Meteo,nome_c,changeHtmlSquadra);
	   $("#meteo-mappe #link_mappe").attr("href", $("#meteo-mappe #link_mappe").attr("href")+"?stadio="+(pos_array));
	}

		//controlla quante giornate ci sono per stringere i margini serie b
	var giornate_len = $("body#calcio ul.giornate li").length;
	if (giornate_len > 38) {
		$("body#calcio ul.giornate li").css("margin-left","-1px");
		$("body#calcio ul.giornate li a").css("width","auto");
		//$("#calcio ul.giornate-db").css("font-size","11px");
		}
	//per l'hockey
	var giornateHockey_len = jQuery("body.sub-hokey ul.giornate li").length;
	if (giornateHockey_len > 42) {
		jQuery("body.sub-hokey ul.giornate li").css("margin-left","0px");
		jQuery("body.sub-hokey ul.giornate li a").css({
                    'width':'auto',
                    'font-size':'11px',
                    'font-weight':'normal'
                     });
		}

		$("#home-2col .boxoffice a").each(function(){
		$(this).attr("href", "http://cinema-tv.corriere.it"+$(this).attr("href"))
	});

    $("#ricercacinema .innerform").css("float", "left");
	$("#trova_cinema").click(function(){
		$(this).removeClass("rosa_gazzetta").addClass("rosa_gazzetta");
		$("#trova_film").removeClass("rosa_gazzetta");
		$("#ricercafilm").css("display","none");
		$("#ricercacinema").css("display","block");
	});
	$("#trova_film").click(function(){
		$(this).removeClass("rosa_gazzetta").addClass("rosa_gazzetta");
		$("#trova_cinema").removeClass("rosa_gazzetta");
		$("#ricercacinema").css("display","none");
		$("#ricercafilm").css("display","block");
	});

	if($("body#sportweek") && (document.URL).indexOf("/domanda_")>-1){
		sPath = window.location.pathname;
		$(".page a[href="+sPath +"]").addClass("select");
	}

		/*tagliare la stringa*/
	var fnReplace = function() {
    testoCella = $(this).text();

    if (testoCella.substring((testoCella.length) - 1) == " ") testoCella = testoCella.substring(0, (testoCella.length) - 1);
    new_testoCella = "";
    s_split = testoCella.split(" ");
    new_testoTd = "";

    for (var i = 0; i < s_split.length; i++) {
        if (s_split[i] != "" && s_split[i] != " ") {
            if (i != 0) new_testoCella = new_testoCella + " ";
            new_testoCella = new_testoCella + (s_split[i]).charAt(0).toUpperCase() + (s_split[i]).substring(1);
        }
    }
    $(this).attr("title", new_testoCella);

    new_testoTd = new_testoTd + (s_split[0]).charAt(0).toUpperCase() + (s_split[0]).substring(1);
    if (s_split.length > 1) {
        if ((s_split[1]).length > 3) {
            if (s_split[0].length < 4) {
                new_testoTd = new_testoTd + " " + (s_split[1]).charAt(0).toUpperCase() + (s_split[1]).substring(1);
            }
            else
            new_testoTd = new_testoTd + " " + (s_split[1]).charAt(0).toUpperCase() + ".";
        }
        else
        new_testoTd = new_testoTd + " " + (s_split[1]).charAt(0).toUpperCase() + (s_split[1]).substring(1);
    }

    /*controlla se c'� un link e lo mantiene*/
    if ($(this).find("a").length > 0) {
        $(this).find("a").html(new_testoTd);
    }
    else {
        $(this).html(new_testoTd);
    }


};


$("body.sub-estero-bundesliga .bodycontent .data-container td:not(.risultato, .stadio, .arbitro),body.sub-estero-liga .bodycontent .data-container td:not(.risultato)").each(fnReplace);

// backup 25/09/09 19.10 per richiesta tosi x inibizione script su sezione pallavolo
//$("body.sub-estero-bundesliga .bodycontent .data-container td:not(.risultato, .stadio, .arbitro),body.sub-estero-liga .bodycontent .data-container td:not(.risultato),body.sub-pallavolo .bodycontent .data-container td:not(.risultato)").each(fnReplace);

/*,#basket .bodycontent .data-container td:not(.risultato) tolto come richiesto da spadafora il 9-9-9
body.sub-rugby .bodycontent .data-container td:not(.risultato) tolto come richiesto da tosi il 10-9-9*/
$("body.sub-seried .bodycontent .data-container td:not(.risultato, .stadio, .arbitro,.orario,.centrab)").each(fnReplace);

$("#premier span.left-team, #premier span.right-team, #liga span.left-team, #liga span.right-team,#bundesliga span.left-team, #bundesliga span.right-team, #ligue1 span.left-team, #ligue1 span.right-team,#premier .standings span.team,#liga .standings span.team,#bundesliga .standings span.team,#ligue1 .standings span.team").each(fnReplace);

$("body#basket #risultati-classifica #nba span.left-team, body#basket #risultati-classifica #nba span.right-team").each(fnReplace);
if($("body.sub-formazioni").length>0) {
var altezza_ul_1 = 0;
var altezza_ul_2 = 0;
var conta_posi = 1;
    $("body.sub-formazioni div.formazione").find("ul.text:first").each(function(){
            if($(this).height() >  altezza_ul_1) altezza_ul_1 = $(this).height();
            if(conta_posi % 2 == 0){
                $("body.sub-formazioni div.formazione:eq("+(conta_posi-2)+")").find("ul.text:first").css("height",+altezza_ul_1+"px");
                $("body.sub-formazioni div.formazione:eq("+(conta_posi-1)+")").find("ul.text:first").css("height",+altezza_ul_1+"px");
                altezza_ul_1 = 0;
            }
            conta_posi++;
    });

    conta_posi = 1;

    $("body.sub-formazioni div.formazione").find("ul.text:last").each(function(){
            if($(this).height() >  altezza_ul_2) altezza_ul_2 = $(this).height();
            if(conta_posi % 2 == 0){
                $("body.sub-formazioni div.formazione:eq("+(conta_posi-2)+")").find("ul.text:last").css("height",+altezza_ul_2+"px");
                $("body.sub-formazioni div.formazione:eq("+(conta_posi-1)+")").find("ul.text:last").css("height",+altezza_ul_2+"px");
                altezza_ul_2 = 0;
            }
            conta_posi++;
    });

  var altezza_col = 0;
  var conta_posi_col = 1;
      $("body.sub-formazioni div.formazione").find("ul:not(.text)").each(function(){
              if($(this).height() >  altezza_col) altezza_col = $(this).height();
              if(conta_posi_col % 4 == 0){
                  $("body.sub-formazioni div.formazione:eq("+((conta_posi_col/2)-2)+")").find("ul:not(.text)").css("height",+altezza_col+"px");
                  $("body.sub-formazioni div.formazione:eq("+((conta_posi_col/2)-1)+")").find("ul:not(.text)").css("height",+altezza_col+"px");
                  altezza_col = 0;
              }
              conta_posi_col++;
      });

}

$(".column .line-top .sub-title-right").html("IN ARCHIVIO");

$("#calcio.sub-default #rightcol #serieb .legenda dd:eq(0)").text("Promozione");
$("#calcio.sub-default #rightcol #serieb .legenda dd:eq(1)").text("Playoff");
$("#calcio.sub-default #rightcol #serieb .legenda dd:eq(2)").text("Playout");

$("#calcio.sub-default #rightcol #serieb .legenda dt:eq(0)").attr("class","highlight-type-8");
$("#calcio.sub-default #rightcol #serieb .legenda dt:eq(1)").attr("class","highlight-type-7");

});
// CHIUSURA document.ready


$(window).load( function() {

	link_expand();

	initAjaxForms();

	// Ridefinisco il document.write in modo che non dia fastidio dopo il window.load()
	document.write = function(text) {
	    $("body").append(text)
	}
	document.writeln = function(text) {
	    $("body").append(text)
	}

	// Controllo oas - se un box contiene solo un elemento viene nascosto
	$(".check-oas, .banner750x90").each( function() {
		if(($(this).html()).indexOf("empty.gif")>-1 || $(this).children().length<=1) {
			if($(this).attr("class")=="banner750x90") {
				$("#header .infospace").css("display","none");
				$("#header a.menu-linx").css("top","237px");
				$("#header a.menu-town").css("top","161px");
				$("#header a.menu-mobile").css("top","26px");
				$("#header a.menu-forum").css("top","306px");
			}
			$(this).css("display","none");
		}
	});
  $("#header").css("display","block");
	// Background sondaggio
	var bg_sondaggio = "";
	if ($(".bg_poll").length > 0) {
		bg_sondaggio = $(".bg_poll").attr("value");
		$(".poll").css("background", "transparent url(" + bg_sondaggio + ") no-repeat scroll left top");
	}

	// Background pulsante sondaggio
	var bg_button_sondaggio = "";
	if ($(".bg_button_poll").length > 0) {
		bg_button_sondaggio = $(".bg_button_poll").attr("value");
		$(".bt-poll").css("background", "transparent url(" + bg_button_sondaggio + ") no-repeat scroll left top");
		$(".bt-poll").css("border", "0");
		$(".bt-poll").css("width", "43px");
		$(".bt-poll").css("padding", "4px 3px");
	}

	// color pulsante sondaggio
	var color_button_sondaggio = "";
	if ($(".color_button_poll").length > 0) {
		color_button_sondaggio = $(".color_button_poll").attr("value");
		$(".bt-poll").css("color",  color_button_sondaggio );
	}

	// box blog home random

	if ($("#box-blog").length > 0) {
		var rndBlogLeft = parseInt(Math.random()*$("#box-blog .list-content li").length);
		var selectedBlogLeft = $('#box-blog .list-content li:eq('+rndBlogLeft+')');
		$(selectedBlogLeft).prepend('<img src="'+ $(selectedBlogLeft).find("span").html() +'" class="left"/>');
		$(selectedBlogLeft).addClass('clearfix');
		$(selectedBlogLeft).insertBefore($('#box-blog .list-content li:eq(0)'));

		var rndBlogRight = parseInt(Math.random()*$("#box-blog .list-content-last li").length);
		var selectedBlogRight = $('#box-blog .list-content-last li:eq('+rndBlogRight+')');
		$(selectedBlogRight).prepend('<img src="'+ $(selectedBlogRight).find("span").html() +'" class="left"/>');
		$(selectedBlogRight).addClass('clearfix');
		$(selectedBlogRight).insertBefore($('#box-blog .list-content-last li:eq(0)'));
	}


	// Link mailto per gli articoli
/*	$("#articolo a").map(function() { return (/javascript:apri_popup_methode_mailto/gi).test(this.href)==true ? this : null  }).each(function() {
			this.href = this.href.replace("javascript:apri_popup_methode_mailto('", "").replace("')", "");
		})
		.attr("rel", "popup console 400 420");*/

	// Di' la tua
	$('#commenta-up').click(function() {
		$('#commenta').click();
	});

    $('#commenta').click(function() {
		loadContent($(this).attr('href'));
		return false;
    });

	if (cookie != null && document.URL.indexOf("#afterlogin") > -1) {
		// ATTENZIONE!! Operazione potenzialmente PERICOLOSISSIMA!!
		// il caricamento automatico se l'utente risulta loggato genera
		// sicuramente CARICO al server del DI'LA TUA.
		$('#commenta').click();
	}

	$("a.submit_form").click( function() {
		$(this).parent("form:eq(0)").submit();
		return false;
	});

 	/*sposta in basso o in alto l'elenco di date delle coppe nella pagina societ� delle squadre*/
 	$("ul.coppa strong").each(function(){
		if ($(this).html() < 11) {
   		$(this).parents("li").find("div").css({'margin-top' : '15px' ,'margin-bottom' : '15px'});
		};
	})

	if((document.URL).indexOf("mappe/mappe.shtml?stadio=")>-1) {
		pos_squadra_map = squadra_pos[((document.URL).split("="))[1]];
		if(pos_squadra_map.indexOf("javascript") > -1) eval(pos_squadra_map);
		else eval($("#mappe_stadi_it a:eq("+pos_squadra_map+")").attr("href"));
	}

	// sportweek domande e risposte
	$(".domande-risposte a.leggi").click(function(){
		$(this).hide();
		$(this).next().show();
		$(this).parent("li").find("a.chiudi").show();
		$(this).parent("li").addClass("selected");
		return false;
	});

	$(".domande-risposte a.chiudi").click(function(){
		$(this).hide();
		$(this).prev().hide();
		$(this).parent("li").find("a.leggi").show();
		$(this).parent("li").removeClass("selected");
		return false;
	});

	$(".pulsante-invia a").click(function(){
		prop = "menubar=no,status=no,titlebar=no,toolbar=no,width=630,height=610,scrollbars=yes"
		window.open("http://www.gazzetta.it/cf/domande_risposte/form.cfm", "domanderisposte", prop);
		return false;
	});

	//testatine risultati e classifiche
	if ($('#squadra-top').css("background-image") == "none") {
		$('#squadra-top h2').css("display", "block");
	}

	if($(".ticketing-block").length>0){
		var altezzaTick = 0;
		 $(".ticketing-block .body-annuncio").each(function(){
			  if($(this).height() > altezzaTick) altezzaTick = $(this).height();
		 });
		 if(altezzaTick!=0) $(".ticketing-block .body-annuncio").css("height",altezzaTick+"px");
	}

	if($("#gazzaticket ul.ticketing-list").length>1){
		$("#gazzaticket ul.ticketing-list").css("width","300px");
	  	$("#gazzaticket ul.ticketing-list").css("float","left");
	  	$("#gazzaticket ul.ticketing-list:first").css("margin-right","20px");

	  	var altezzaPTick = 0;
		$("#gazzaticket ul.ticketing-list p").each(function(){
			if($(this).height()>altezzaPTick) altezzaPTick = $(this).height();
		})
	  	$("#gazzaticket ul.ticketing-list p").css("height",altezzaPTick+"px");
	}

  	$("#gazzagame .paginazione").css("display","block");
// Hack per modificare l'output dell'applicazione Quote
	$("a.fixed-content-link[href=http://www.gazzetta.it/quote/]")
		.next()
		.each( function() {
			$(this)
				.html("<a href=\"" + $(this).attr("href") + "\" class=\"blue-pointer\">Leggi l'ultimo articolo</a>")
		})

	$("a.fixed-content-link[href=http://www.gazzetta.it/quote/]")
	.addClass("blue-pointer")

	/*per colorare le caselle*/
	$(".big_quote tbody").each(function(){
		$(this).find("tr").each(function(){
			var class_table = "odd";
			$(this).find("td").each(function(i){
				if(i!=0){
					$(this).addClass(class_table)
					if(i%3 == 0) {
						if(class_table.indexOf("odd") > -1){
							class_table="even";
						}
						else class_table="odd"
					}
				}
			})
		})
	})
	$("td.odd, td.even").find("a").css({display: "block",width:"32px"});

	//$("#box-sponsor").addClass("clear").css("float","none");
});
