// funzione per assegnare l'oggetto XMLHttpRequest
// compatibile con i browsers più recenti e diffusi
function mkXMLHttpRequest() {
 
    // lista delle variabili locali
    var
        // variabile di ritorno, nulla di default
        XHR = null,
        // informazioni sul nome del browser
        browserUtente = navigator.userAgent.toUpperCase();
 
    // browser standard con supporto nativo
    // non importa il tipo di browser
    if( typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object" ) {
        XHR = new XMLHttpRequest();
    }
 
    // browser Internet Explorer
    // è necessario filtrare la versione 4
    else if( window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0 ) {
 
        // la versione 6 di IE ha un nome differente
        // per il tipo di oggetto ActiveX
        if( browserUtente.indexOf("MSIE 5") < 0 ) {
            XHR = new ActiveXObject("Msxml2.XMLHTTP");
        // le versioni 5 e 5.5 invece sfruttano lo stesso nome
        } else {
            XHR = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
 
    return XHR;
}


/* 
 *  mostra un alert ai non loggati/registrati
 */
function iscriviti() {
	alert("Per poter accedere a tutti i contenuti devi fare il login (in alto a destra).\nSe non sei ancora registrato ricorda che la registrazione è GRATUITA!");
	setTimeout("top.location = 'http://www.amando.it/login/registrazione.htm';",100);
	return;
}

function segnala(id) {

	if( auth===0 ) {
    
		iscriviti();
		return;
        
	} else {

		redir = '';
		if( top.location.href.indexOf('#')!==-1 ) {
			redir = top.location.href.substring(0,top.location.href.indexOf('#'));
		} else {
			redir = top.location.href;
		}
			
		window.open('/scripts/segnala.php?url='+redir+'&id='+id,'','width=500,height=300,menubar=no,status=no,resizable=no,scrollbars=yes,toolbar=no,location=no');
	
    }
	
}

function cancella(id_commento) {
	
	if( confirm("Sei sicuro di voler cancellare il commento?") ) { 
	
		var request = mkXMLHttpRequest();
	
	   	if( request==null ) {
			alert('Si è verificato un errore durante la cancellazione');
	       	return;
	   	}
	
	   	request.open("POST", "/scripts/cancella_commento.php", true);
	   	request.setRequestHeader("content-type","application/x-www-form-urlencoded");
		
		//per evitare bug mozilla
	  	if( typeof request.setRequestHeader=='function' ) {
	   		request.setRequestHeader("Connection", "Close");
		}
		
		request.onreadystatechange = function() {
	                if( request.readyState==4 ) {
	                    if( request.status==200 ) {
	
	                        var resp = request.responseText;
																		
	                        if( resp=="Commento cancellato" ) {
								document.getElementById('commento_'+id_commento).style.display = 'none';
							} else {
								alert(resp);
							}
	 
	                    } else {                    
	                        alert("Si è verificato un errore temporaneo nella cancellazione, riprovare tra qualche minuto");
	                    }
	                }
	            };
	
		postdata = 'id_commento='+id_commento;
			 
   		request.send(postdata);

	} 
	
	return false;
}

function vota(voto,id_votazione,extraid) {

	if( auth===0 ) {
		iscriviti();
		return;
	}
	
	var request = mkXMLHttpRequest();

   	if( request==null ) {
		alert('Si è verificato un errore durante la votazione');
       	return;
   	}

   	request.open("POST", "/scripts/vota.php", true);
   	request.setRequestHeader("content-type","application/x-www-form-urlencoded");
	
	//per evitare bug mozilla
  	if( typeof request.setRequestHeader=='function' ) {
   		request.setRequestHeader("Connection", "Close");
	}
	
	request.onreadystatechange = function() {
                if( request.readyState==4 ) {
                    if( request.status==200 ) {

                        var resp = request.responseText;
												
                        if( resp=="Voto Riuscito" ) {

							id = "";

							if( extraid==undefined ) {
								
								id = "numero_voti";

							} else {

								if( voto==1 ) {
									id = "voti_positivi_";
								} else {
									id = "voti_negativi_";
								}
								
								if( String(id_votazione).indexOf("3")==0 ) {
									id += parseInt(String(id_votazione).substring(1),10);
								}								
							}
							
							num_voti_orig = parseInt(document.getElementById(id).innerHTML,10)+1;
							document.getElementById(id).innerHTML = num_voti_orig;
							
						} else {

							alert(resp);
														
						}
 
                    } else {                    
                        alert("Si è verificato un errore temporaneo nella votazione, riprovare tra qualche minuto");
                    }
                }
            };
	
	postdata = "id_votazione="+id_votazione+"&voto="+voto;
			
	if( extraid!=undefined ) {
		postdata += "&extraid="+extraid;
	}

   	request.send(postdata);
    
}

// ------varie vecchio amando.it------------------------------------------------------------------------------------------

function addToBookmark() {
     var bookmarkurl="http://www.amando.it/";
     var bookmarktitle="Amando.it: Una vita di Emozioni...";

     if( window.external && navigator.appName=="Microsoft Internet Explorer" ) {
	   return window.external.AddFavorite(bookmarkurl,bookmarktitle);
	 } /* else if( window.sidebar && sidebar.addPanel ) {
	   return window.sidebar.addPanel(bookmarktitle,bookmarkurl,'');
	 }*/ else {
        alert("Funzione non implementata con questo browser; se utilizzi Netscape, Mozilla Firefox o Opera, usa Ctrl+D");
     }
}

//Mostra anteprima del messaggio del muretto
function mostraAnteprima() {
    finestra = open("/scripts/muretto.php?testo=" + document.myform.testoAnnuncio.value+"&nome="+document.myform.nome.value,"popAnteprima","scrollbars=yes, width=350, height=350");
}

function addText( input, insText ) { 
    input.focus(); 
    if( input.createTextRange ) { 
        document.selection.createRange().text += insText; 
    } else if( input.setSelectionRange ) { 
        var len = input.selectionEnd; 
        input.value = input.value.substr( 0, len ) + insText + input.value.substr( len ); 
        input.setSelectionRange(len+insText.length,len+insText.length); 
    } else { 
        input.value += insText; 
    } 
} 

//Visualizza faccine nel muretto
function mostraFaccina(f, testo) {
    addText(f.testoAnnuncio, testo+' ');
    return false;
}

function mostraMessaggiCercatiMuretto() {
    
    if (!document.myform.nome.value) {
        alert('Attenzione, specificare il nick da cercare');
        return false;        
    }
    
    finestra = open("/scripts/cercaMessaggi.php?select=" + document.myform.select.options[document.myform.select.selectedIndex].value +"&nome="+document.myform.nome.value,"popAnteprima","scrollbars=yes, width=490, height=600");
    if( finestra ) { finestra.focus(); }
}

function inviaTesti(idTesto) {
    document.location = "/scripts/composeMail.php?id="+idTesto;
}

function mostra_categorie(object) {
    var gruppi = [];
    gruppi[1] = "Auguri";
    gruppi[2] = "Biglietti";
    gruppi[3] = "Frasi ";
    gruppi[4] = "Lettere";
    gruppi[5] = "Poesie";
    gruppi[6] = "Racconti";
    gruppi[7] = "Sms";
    gruppi[8] = "Amore";

    var categoria_nome1 = [];
    var categoria_nome2 = [];
    var categoria_nome3 = [];
    var categoria_nome4 = [];
    var categoria_nome5 = [];
    var categoria_nome6 = [];
    var categoria_nome7 = [];
    var categoria_nome8 = [];

    var categoria_id1 = [];
    var categoria_id2 = [];
    var categoria_id3 = [];
    var categoria_id4 = [];
    var categoria_id5 = [];
    var categoria_id6 = [];
    var categoria_id7 = [];
    var categoria_id8 = [];

    categoria_nome1[0] = "Auguri Comunione";
    categoria_nome1[1] = "Auguri di Compleanno";
    categoria_nome1[2] = "Auguri di Natale";
    categoria_nome1[3] = "Auguri di Pasqua";
    categoria_nome1[4] = "Auguri di San Valentino";
    categoria_nome1[5] = "Auguri Festa del Papà";
    categoria_nome1[6] = "Auguri Festa della Donna";
    categoria_nome1[7] = "Auguri Festa della Mamma";

    categoria_id1[0] = "54";
    categoria_id1[1] = "34";
    categoria_id1[2] = "23";
    categoria_id1[3] = "21";
    categoria_id1[4] = "15";
    categoria_id1[5] = "17";
    categoria_id1[6] = "31";
    categoria_id1[7] = "20";

    categoria_nome2[0] = "Biglietti Anniversario";
    categoria_nome2[1] = "Biglietti Battesimo";
    categoria_nome2[2] = "Biglietti Compleanno";
    categoria_nome2[3] = "Biglietti Comunione";
    categoria_nome2[4] = "Biglietti Cresima";
    categoria_nome2[5] = "Biglietti Laurea";
    categoria_nome2[6] = "Biglietti Matrimonio";
    categoria_nome2[7] = "Biglietti Natale";
    categoria_nome2[8] = "Biglietti Onomastico";
    categoria_nome2[9] = "Biglietti San Valentino";

    categoria_id2[0] = "63";
    categoria_id2[1] = "64";
    categoria_id2[2] = "57";
    categoria_id2[3] = "60";
    categoria_id2[4] = "58";
    categoria_id2[5] = "62";
    categoria_id2[6] = "59";
    categoria_id2[7] = "66";
    categoria_id2[8] = "61";
    categoria_id2[9] = "65";

    categoria_nome3[0] = "Aforismi e Citazioni";
    categoria_nome3[1] = "Frasi BuonaNotte";
    categoria_nome3[2] = "Frasi Cresima";
    categoria_nome3[3] = "Frasi d'Amore";
    categoria_nome3[4] = "Frasi dei Baci";
    categoria_nome3[5] = "Frasi del BuonGiorno";
    categoria_nome3[6] = "Frasi di Amicizia";
    categoria_nome3[7] = "Frasi di Compleanno";
    categoria_nome3[8] = "Frasi di Natale";
    categoria_nome3[9] = "Frasi di Pasqua";
    categoria_nome3[10] = "Frasi di Scuse";
    categoria_nome3[11] = "Frasi Festa del Papà";
    categoria_nome3[12] = "Frasi Festa della Donna";
    categoria_nome3[13] = "Frasi Festa della Mamma";
    categoria_nome3[14] = "Frasi Laurea e Diploma";
    categoria_nome3[15] = "Frasi Nascite";
    categoria_nome3[16] = "Frasi per la Befana";
    categoria_nome3[17] = "Frasi per Matrimonio";
    categoria_nome3[18] = "Frasi per Onomastico";
    categoria_nome3[19] = "Frasi per San Valentino";

    categoria_id3[0] = "11";
    categoria_id3[1] = "7";
    categoria_id3[2] = "55";
    categoria_id3[3] = "1";
    categoria_id3[4] = "2";
    categoria_id3[5] = "30";
    categoria_id3[6] = "3";
    categoria_id3[7] = "4";
    categoria_id3[8] = "25";
    categoria_id3[9] = "22";
    categoria_id3[10] = "28";
    categoria_id3[11] = "14";
    categoria_id3[14] = "32";
    categoria_id3[15] = "19";
    categoria_id3[16] = "27";
    categoria_id3[17] = "6";
    categoria_id3[18] = "24";
    categoria_id3[19] = "5";
    categoria_id3[20] = "35";
    categoria_id3[21] = "16";

    categoria_nome4[0] = "Lettere d'Amore";
    categoria_id4[0] = "9";

    categoria_nome5[0] = "Poesie d'Amore";
    categoria_nome5[1] = "Poesie di Natale";
    categoria_nome5[2] = "Poesie Festa del Papà";
    categoria_nome5[3] = "Poesie Festa della Mamma"; 

    categoria_id5[0] = "8";
    categoria_id5[1] = "26";
    categoria_id5[2] = "29";
    categoria_id5[3] = "18";

    categoria_nome6[0] = "Racconti";
    categoria_nome6[1] = "Racconti d'Amore";
    categoria_nome6[2] = "Racconti di Natale";
    categoria_nome6[3] = "Racconti di Viaggio";

    categoria_id6[0] = "43";
    categoria_id6[1] = "42";
    categoria_id6[2] = "41";
    categoria_id6[3] = "67";

    categoria_nome7[0] = "Sms d'Amore";
    categoria_nome7[1] = "Sms di Amicizia";
    categoria_nome7[2] = "Sms di Pasqua";
    categoria_nome7[3] = "Sms Festa del Papà";
    categoria_nome7[4] = "Sms Sexy";

    categoria_id7[0] = "10";
    categoria_id7[1] = "33";
    categoria_id7[2] = "53";
    categoria_id7[3] = "52";
    categoria_id7[4] = "12";

    categoria_nome8[0] = "Due di Picche";
    categoria_id8[0] = "56";

    var index_gruppo = object.options[object.selectedIndex].value;
    var obj_lista_categorie = document.getElementById('lista_categorie');

    if (index_gruppo == 0) {
        while(obj_lista_categorie.options.length > 1) {
            obj_lista_categorie.options[1] = null;
        }
    } else {
        var lunghezza = obj_lista_categorie.options.length;
        var numero_categorie = eval("categoria_nome"+index_gruppo+".length");

        for( var i=0; i<numero_categorie; i++ ) {
            obj_lista_categorie.options[i+1] = new Option(eval("categoria_nome"+index_gruppo+"["+i+"]"),eval("categoria_id"+index_gruppo+"["+i+"]"));
        }
        
        for( i=numero_categorie; i<lunghezza; i++ ) {
            obj_lista_categorie.options[numero_categorie+1] = null;
        }
    }
    
}

//-------------------------------funzioni per le ad------------------------------------------------------------------

function move_div_from_to(div_from, div_to) {
		var new_parent = document.getElementById(div_to);
        var figlio = document.getElementById(div_from);
		try {
			document.body.removeChild(figlio);
		} catch( DOMException ) { 
			setTimeout( 'document.body.removeChild(figlio)', 50 );
		}
        new_parent.appendChild(figlio); 	  
}

function is_tipo_pagina(tipo) {
 
    page = new String(document.location);//document.location;//

    if( tipo=='homepage' ) {
      return ( page=="http://www.amando.it/" || page=="http://www.amando.loc/" || page=="http://foto.amando.loc/" || page=="http://foto.amando.it/" );
    } else if( tipo=='cartoline' ) {
       return (page.indexOf('cartoline') != -1);
    } else if( tipo=='giochi' ) {
       return (page.indexOf('giochi') != -1);
    } else if( tipo=='cartoline' ) {
       return (page.indexOf('cartoline') != -1);
    } else if( tipo=='canzoni' ) {
       return (page.indexOf('canzoni') != -1);
    }  else if( tipo=='ricette' ) {
       return (page.indexOf('ricette') != -1);
    } else if( tipo=='testi' ) {
       return ((page.indexOf('frasi') != -1) || (page.indexOf('sms') != -1) || (page.indexOf('poesie') != -1)
        || (page.indexOf('lettere') != -1) || (page.indexOf('racconti') != -1) || (page.indexOf('racconti') != -1)
        || (page.indexOf('biglietti') != -1) || (page.indexOf('aforismi') != -1) || (page.indexOf('citazioni') != -1));
    }
}


function is_homepage() {
 return is_tipo_pagina('homepage');
}

function banner_up_728x90() {
 
    if( !window.rdm ){
       rdm = new String( Math.random() );
       rdm = rdm.substring(2,11);
    }
 
    var tag_tgadv = '';
  
	if( is_tipo_pagina('homepage') ) {
		tag_tgadv = 'amando_it_hp_728x90';
	} else if( is_tipo_pagina('cartoline') ) {
		tag_tgadv = 'amando_it_cartoline_728x90';
	}else if( is_tipo_pagina('giochi') ) {
		tag_tgadv = 'amando_it_giochi_728x90';
	} else if( is_tipo_pagina('canzoni') ) {
		tag_tgadv = 'amando_it_canzoni_728x90';
	} else if( is_tipo_pagina('testi') ) {
		tag_tgadv = 'amando_it_testi_728x90';
	} else if( is_tipo_pagina('ricette') ) {
		tag_tgadv = 'amando_it_ricette_728x90';
	} else {
		tag_tgadv = 'amando_it_gr_728x90';
	}

  document.write('<scr' + 'ipt src="http://ad.it.doubleclick.net/adj/amando.it/'+tag_tgadv+';dcopt=ist;tile=1;sz=728x90;ord='+rdm+'" type="text/javascript"></scr' + 'ipt>');
}
 
function banner_up_300x250() {
 
    if( !window.rdm ){
        rdm = new String (Math.random());
        rdm = rdm.substring(2,11);
    }

    var tag_tgadv = '';

    if( is_tipo_pagina('homepage') ) {
        tag_tgadv = 'amando_it_hp_300x250';
    } else if( is_tipo_pagina('cartoline') ) {
        tag_tgadv = 'amando_it_cartoline_300x250';
    } else if( is_tipo_pagina('giochi') ) {
        tag_tgadv = 'amando_it_giochi_300x250';
    } else if( is_tipo_pagina('canzoni') ) {
        tag_tgadv = 'amando_it_canzoni_300x250';
    } else if( is_tipo_pagina('testi') ) {
        tag_tgadv = 'amando_it_testi_300x250';
    } else if( is_tipo_pagina('ricette') ) {
        tag_tgadv = 'amando_it_ricette_300x250';
    } else {
        tag_tgadv = 'amando_it_gr_300x250';
    }
    
    document.write('<scr' + 'ipt src="http://ad.it.doubleclick.net/adj/amando.it/'+tag_tgadv+';tile=2;sz=300x250,300x600;ord='+rdm+'" type="text/javascript"></scr' + 'ipt>');
}
 
function banner_up_160x600() {
 
    if( !window.rdm ){
        rdm = new String( Math.random() );
        rdm = rdm.substring(2,11);
    }

    var tag_tgadv = '';

    if( is_tipo_pagina('homepage') ) {
        tag_tgadv = 'amando_it_hp_aaax600';
    } else if( is_tipo_pagina('cartoline') ) {
        tag_tgadv = 'amando_it_cartoline_aaax600';
    } else if( is_tipo_pagina('giochi') ) {
        tag_tgadv = 'amando_it_giochi_aaax600';
    } else if( is_tipo_pagina('canzoni') ) {
        tag_tgadv = 'amando_it_canzoni_aaax600';
    } else if( is_tipo_pagina('testi') ) {
        tag_tgadv = 'amando_it_testi_aaax600';
    } else if( is_tipo_pagina('ricette') ) {
        tag_tgadv = 'amando_it_ricette_aaax600';
    } else {
        tag_tgadv = 'amando_it_gr_aaax600';
    }

    document.write('<scr' + 'ipt src="http://ad.it.doubleclick.net/adj/amando.it/'+tag_tgadv+';tile=3;sz=120x600,160x600;ord='+rdm+'" type="text/javascript"></scr' + 'ipt>');    
}
 
function banner_dynamic() {

    if( !window.rdm ){
        rdm = new String( Math.random() );
        rdm = rdm.substring(2,11);
    }

    var tag_tgadv = '';

    if( is_tipo_pagina('homepage') ) {
        tag_tgadv = 'amando_it_hp_dinamic';
    } else if( is_tipo_pagina('cartoline') ) {
        tag_tgadv = 'amando_it_cartoline_dinamic';
    } else if( is_tipo_pagina('giochi') ) {
        tag_tgadv = 'amando_it_giochi_dinamic';
    } else if( is_tipo_pagina('canzoni') ) {
        tag_tgadv = 'amando_it_canzoni_dinamic';
    } else if( is_tipo_pagina('testi') ) {
        tag_tgadv = 'amando_it_testi_dinamic';
    } else if( is_tipo_pagina('ricette') ) {
        tag_tgadv = 'amando_it_ricette_dinamic';
    } else {
        tag_tgadv = 'amando_it_gr_dinamic';
    }

    document.write('<scr' + 'ipt src="http://ad.it.doubleclick.net/adj/amando.it/'+tag_tgadv+';tile=4;sz=1x1;ord='+rdm+'" type="text/javascript"></scr' + 'ipt>');    
}  

function banner_right_300x100() {
 
    if( !window.rdm ){
        rdm = new String( Math.random() );
        rdm = rdm.substring(2,11);
    }
 
    var tag_tgadv = '';
 
    if( is_tipo_pagina('homepage') ) {
        tag_tgadv = 'amando_it_hp_300x100';
    } else if( is_tipo_pagina('cartoline') ) {
        tag_tgadv = 'amando_it_cartoline_300x100';
    } else if( is_tipo_pagina('giochi') ) {
        tag_tgadv = 'amando_it_giochi_300x100';
    } else if( is_tipo_pagina('canzoni') ) {
        tag_tgadv = 'amando_it_canzoni_300x100';
    } else if( is_tipo_pagina('testi') ) {
        tag_tgadv = 'amando_it_testi_300x100';
    } else if( is_tipo_pagina('ricette') ) {
        tag_tgadv = 'amando_it_ricette_300x100';
    } else {
        tag_tgadv = 'amando_it_gr_300x100';
    }
 
    document.write('<scr' + 'ipt src="http://ad.it.doubleclick.net/adj/amando.it/'+tag_tgadv+';tile=5;ord='+rdm+'" type="text/javascript"></scr' + 'ipt>');       
}  

function google_ad_request_done( google_ads ) {

	var s = '';
	var i;
	
	if( google_ads.length == 0 ) { //provare con < 1
	    return;
	}
	
	if( google_ads[0].type==="flash" ) {
		
	   s += '<a href=\"' + google_info.feedback_url + '\" class="'+google_ad_style_ads_by_google+'">Annunci Google</a><br />' + 
	       '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
	    ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + 
	    google_ad.image_width + '" height="' + google_ad.image_height + '"> <param name="movie" value="' + 
	    google_ad.image_url + '">' + '<param name="quality" value="high">' + 
	    '<param name="AllowScriptAccess" value="never">' + 
	    '<embed src="' + google_ad.image_url + '" width="' + google_ad.image_width + '" height="' + google_ad.image_height + 
	    '" type="application/x-shockwave-flash"' + ' AllowScriptAccess="never" ' + 
	    ' pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>';
	
	} else if( google_ads[0].type==="image" ) {

	   s += '<a href=\"' + google_info.feedback_url + '\" class="'+google_ad_style_ads_by_google+'">Annunci Google</a><br /><a href="' + 
	    google_ads[0].url + '" target="_top" title="Visita ' + 
	    google_ads[0].visible_url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'Visita ' +
	    google_ads[0].visible_url + '\';return true"><img border="0" src="' + 
	    google_ads[0].image_url + '"width="' + google_ads[0].image_width + '"height="' + google_ads[0].image_height + '" alt="" /></a>';


    } else {
    
        var add_style_title = '';
        var add_style_other = '';
        if( google_ads.length==1 && !google_ad_style_vertical ) {
            add_style_title = ' ' + google_ad_style_big_title;
            add_style_other = ' ' + google_ad_style_big_other;        
        }
        // http://pagead2.googlesyndication.com/pagead/abglogo/abg-it-100c-000000.png
    
       s += '<a href=\"'+google_info.feedback_url+'\" class="'+google_ad_style_ads_by_google+'">Annunci Google</a>'; 
    
        
        if( !google_ad_style_vertical ) { 
		         
            style_li = 'overflow:hidden; height:100%; width:'+Math.floor(google_ad_style_width/google_ads.length)+'px;';
        
		} else {

            var height_temp = Math.floor(google_ad_style_height/google_ads.length);
            if( height_temp>65 && google_ads.length>1 ) {
                height_temp = 65;
            }
            style_li = 'overflow:hidden; width:100%; height:'+height_temp+'px;';
			         
        }
    
        s += '<ul>';
        
        for( i=0; i<google_ads.length; ++i ) {
                        
            s += '<li style="'+style_li+'" class="'+google_ad_style_result+'">' + 
            '<div class="google_ads_ad"><span class="'+google_ad_style_title+add_style_title+'" style="white-space:nowrap; overflow:hidden;">'
			+ '<a href="'+google_ads[i].url+'" title="Visita '+google_ads[i].visible_url+'">'+google_ads[i].line1+'</a></span>'+
            '<br /><span class="'+google_ad_style_text+add_style_other+'">'+google_ads[i].line2+' '+google_ads[i].line3+'</span>'+
            '<br /><span class="'+google_ad_style_url+add_style_other+'" style="white-space:nowrap; overflow:hidden;">'+
			'<a href="'+google_ads[i].url+'" title="Visita '+google_ads[i].visible_url+'">'+google_ads[i].visible_url+'</a></span></div></li>';
            
        }
        
        s += '</ul>';        
    }
    
    s = '<div class="'+google_ad_style_container+'" style="width:'+google_ad_style_width+'px; height:'+google_ad_style_height+'px;">'+s+'</div>';

    document.write(s);
    return;
} // fine google_ad_request_done

   
//----------------------------------------------------------------------------------------------------------------
    
var xPos;
var yPos;

function show_baloon( msg, e ) {

	if( !e ) { var e = window.event; }
	
	var targ;
	if( e.target ) { targ = e.target; }
	else if( e.srcElement ) { targ = e.srcElement; }
	if (targ.nodeType == 3) { // defeat Safari bug
		targ = targ.parentNode;
	}
		
    if( 'undefined' != typeof e.pageX ) {
		xPos = e.pageX + document.body.scrollLeft;
		yPos = e.pageY + document.body.scrollTop;
	} else {
		xPos = e.clientX;
		yPos = e.clientY + document.documentElement.scrollTop;
	}
		
	var baloon = document.getElementById("baloon");
	document.getElementById("container").appendChild(baloon);
   	baloon.innerHTML = "<p>"+msg+"</p>";
   	baloon.style.top = parseInt(yPos,10)+2 + "px";
   	baloon.style.left = parseInt(xPos,10)+2 + "px";
   	baloon.style.visibility = "visible";
}

function hide_baloon() {
   var baloon = document.getElementById("baloon");
   baloon.style.visibility = "hidden";
}
						      
/**
* @author   Flavio Pala
* @desc     evita login errate
*/
function login_data_ok() {
    var password = document.getElementById('password');
    var username = document.getElementById('nick');
    if( password==undefined || username==undefined || password.value.length==0 || username.value.length==0 ) {
        alert('Attenzione!! Inserisci tutti i campi richiesti!!');
        return false;
    } else if( (username.value.length<3) || (username.value.length>24) ) {
        alert('Attenzione!! Il nickname deve essere minimo di 3 caratteri e max di 24 caratteri');    
        return false;
    } else if( password.value.length<5 ) {
        alert('Attenzione!! La password deve essere almeno di 5 caratteri!');    
        return false;
    } else if( username.value.indexOf('@')!=-1 ) {
        alert('Attenzione!! Non puoi usare un indirizzo e-mail come nick!');    
        return false;
    } else {
        return true;
    }
}

/**#@+
* @author   Flavio Pala
* @desc     cambio dello stato privacy
*/
function select_status() {
    var div = document.getElementById("status");
    if( div!=undefined ) {
        if( div.style.display=='none' ) { 
            div.style.display = 'inline';
        } else {
            div.style.display = 'none';
		}
    }
} 

function change_status( usr ) {
    var request = new mkXMLHttpRequest();
    var privacyValue = parseInt(document.getElementById("selprivacy").value,10);
    request.open("GET", "/gremlin/privacy.php?id="+usr+"&status="+privacyValue, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.onreadystatechange = function() {
                if( request.readyState==4 ) {
                    if( request.status==200 ) {
                        alert("Tipo di privacy cambiata, potrebbe essere necessario qualche secondo perché le modifiche abbiano effetto");
                        var resp = request.responseText;
                        if( resp=='SUCCESS' ) {
                            if( privacyValue==0 ) {
                                imgurl = '/gremlin/resources/visible.gif';
                            } else {
                                imgurl = '/gremlin/resources/invisible.gif';
                            }
                            document.getElementById('privacy').setAttribute('src', imgurl);
							document.getElementById("status").style.display = "none";
                        }   
                    } else {                    
                        alert("Si è verificato un errore temporaneo nel cambio del tipo di privacy, riprovare tra qualche minuto\n(status: "+request.status+")");
                    }
                }
            };  
    request.send(null);
}
/**#@-*/

//nuove

var navBar = {

	init: function() {

		var $parent = $('#navbar');

		// Ciclo tutti i link nella navbar di primo livello
		$('#navbar_liv1 a').each(function(){

			// Se non ha id, lo salto
			if($(this).attr('id') == '') {
				return 1;
			}

			// Recupero le navbar di secondo livello associata
			var $navbarLiv2 = $parent.find('div.navbar_liv2.'+$(this).attr('id'));

			// Se non lo trovo, continuo col prossimo link
			if($navbarLiv2.length == 0) {
				return 1;
			}

			// Aggiungo tutti gli eventi alla navbar di primo e secondo livello
			$(this).mouseover(function(){
				$navbarLiv2.css({display: 'block'});
			});

			$(this).mouseout(function(){
				$navbarLiv2.css({display: 'none'});
			});

			$navbarLiv2.mouseover(function(){
				$(this).css({display: 'block'});
			});

			$navbarLiv2.mouseout(function(){
				$(this).css({display: 'none'});
			});

		});

	}
	
};

var slideShow =  {

	pause: 4000,
	fade: 750,
	_timeOut: null,

	init : function(params) {

		if(params != undefined){
			if(params.pause != undefined) {
				slideShow.pause = params.pause;
			}
			if(params.fade != undefined) {
				slideShow.fade = params.fade;
			}
		}

		
		$('#slideshow_abstract li').each(function(){
			$(this).click(function(){
				window.location.href = $(this).find('a').attr('href');
			});
		}).mouseenter(function(){

			// Se non ha id esco
			var id = $(this).attr('id');
			if(id == '') {
				return;
			}

			slideShow._pause();

			var $newNews = $('#'+id+'_highlight');
			var $actNews = $newNews.siblings();
			
			$newNews.fadeIn(0);
			$actNews.fadeIn(0);

			$actNews.removeClass('act');
			$newNews.addClass('act');

			$(this).siblings().removeClass('act');
			$(this).addClass('act');

		}).mouseleave(function(){
			slideShow._play();
		});


		$('#slideshow_highlight li').each(function(){
			$(this).click(function(){
				window.location.href = $(this).find('a').attr('href');
			});
		}).mouseenter(function(){
			$(this).addClass('hover');
			slideShow._pause();
		}).mouseleave(function(){
			$(this).removeClass('hover');
			slideShow._play();
		});

		$('#slideshow_abstract li:first').addClass('act');
		$('#slideshow_highlight li:first').addClass('act');

		slideShow._play();
		
	},

	_fadeToNews: function(id, play){

		var $newNews = $('#'+id);
		var $newAbstract = $('#'+id.replace(/_highlight$/, ''));
		var $actNews = $('#slideshow_highlight .act');

		$newAbstract.siblings().removeClass('act');
		$newAbstract.addClass('act');
		
		// Se sono lo stesso oggetto, esco
		if($newNews.attr('id') == $actNews.attr('id')) {
			return;
		}

		$actNews.css('z-index', 1);
		$newNews.css('z-index', 0);
		$newNews.addClass('act');
		$newNews.fadeIn(0);

		$actNews.fadeOut(slideShow.fade, function(){
			$(this).removeClass('act');
			if(play) {
				slideShow._play();
			}
		});

	},
	
	_play: function(){

		var $nextNews = $('#slideshow_highlight .act').nextAll();
		if($nextNews.length == 0) {
			$nextNews = $('#slideshow_highlight .act').siblings();
		}

		slideShow._pause();
		slideShow._timeOut = setTimeout('slideShow._fadeToNews(\''+$nextNews.attr('id')+'\', true)', slideShow.pause);

	},

	_pause: function(){
		clearTimeout(slideShow._timeOut);
		slideShow._timeOut = null;
	}

};

var articleVote = {

	value: null,
	
	init: function(){
		$('#valutazione-articolo a').each(function(index){
			if($(this).hasClass('on')) {
				articleVote.value = index;
			}
			$(this).attr('id', 'star_'+index);
			// $(this).attr('href', 'javascript:void(0);');
			
			$(this).mouseenter(function(){
				var $current = $(this);
				$('#valutazione-articolo a').each(function(){
					if(/_([0-9]+)$/.exec($(this).attr('id'))[1] <= /_([0-9]+)$/.exec($current.attr('id'))[1]) {
						$(this).addClass('on');
					} else {
						$(this).removeClass('on');
					}
				});
			});

			$(this).click(function(){
				articleVote.value = /_([0-9]+)$/.exec($(this).attr('id'))[1];
			});

			$(this).focus(function(){
				$(this).blur();
			});

		});

		$('#valutazione-articolo span').mouseleave(function(){
			$('#valutazione-articolo a').each(function(){
				if(/_([0-9]+)$/.exec($(this).attr('id'))[1] <= articleVote.value) {
					$(this).addClass('on');
				} else {
					$(this).removeClass('on');
				}
			});
		});

	}

};

function fbs_click() { u=location.href; t=document.title; window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}

//-------------------------------funzioni per il logging degli errori------------------------------------------------------------------
 
function log_error_js(errore, no_prefix) {
           var request = mkXMLHttpRequest();

           if(request == null) {
               return;
           }

           if(no_prefix != true) {
               errore = "ERRORE JS 1: "+errore;
           }

           request.open("post", "/tools/ajax.php", true);
           request.setRequestHeader("content-type","application/x-www-form-urlencoded");
           request.setRequestHeader("connection", "close");
           request.send("type=error&errstr="+encodeURIComponent(errore));
}

window.onerror = function(err, filename, line) {
            
            //errore sconosciuto
            if( typeof err === 'object' ) {
                //log_error_js(" ERRORE JS: "+err.message+" tipo: "+err.type, true);
                return;
            }

            // in genere questi sono errori di caricamento
            if( line<=20 || line>=1500 ) {
                 /*if( 
                  || err == "Errore di sintassi"    || 
                  ||           || 
                  || err == "Ungültiges Zeichen"    || err == "Erreur de syntaxe"
                  || err == "Erro de sintaxe"       || err == "Error de sintaxis"
                  || err == "illegal character"     ||  ) {*/
                    return;
                 //}
            }

            // unknown source; probably in google analytics code
            if( err.indexOf("'}'")!=-1 || err.indexOf('"}"')!=-1 || 
				err.indexOf("')'")!=-1 || err.indexOf('")"')!=-1 ||
				err.indexOf('„)“')!=-1 ) {
                return;
            }
                
            if( err == "http://www.google-analytics.com/ga.js" ) {
                return;
            }
                        
            //non loggo gli errori dovuti al tinymce
            if( filename.indexOf("/cartoline/compose.php")!=-1 ) {
                return;
            }
            
            if( filename.indexOf("/login/perso_password.htm?pswRst=")!=-1 || 
                filename.indexOf(".mht")!=-1 || filename.indexOf("file://")!=-1 || 
                filename.indexOf("mhtml")!=-1 ||
                filename.indexOf("res://")!=-1  ) {
                return;
            }
            
            if( err=='Argomento non valido.' && line==85 ){
                return;
            }
			                    
            if( err.indexOf("':'")!=-1 || err.indexOf('"undefined"')!=-1 || err.indexOf("'undefined'")!=-1 ||
                err.indexOf("개체가")!=-1 || err.indexOf('对象不支持此属性或方法')!=-1 || err.indexOf('オブジェクトでサポートされていないプロパティまたはメソッドです。')!=-1 || err.indexOf('物件不支援此屬性或方法')!=-1 ||
				err.indexOf("800a03e8")!=-1 || err.indexOf("80020101")!=-1 || err.indexOf("'cursor'")!=-1 ||

				err.indexOf("badzu_desc.item(0)")!=-1 || err == "Syntaxfehler" || err=='Out of memory' ||
                err.indexOf("Memoria esaurita")!=-1 || err.indexOf("ClassFactory")!=-1 || err.indexOf("???")!=-1 ||
                err.indexOf("s9b")!=-1 || err.indexOf("DLL")!=-1 || err.indexOf("dartCreativeDisplayManagers")!=-1 ||
                err.indexOf("currentStyle")!=-1 || err.indexOf("this.callbackParameters")!=-1 || err.indexOf("Win32")!=-1 ||
                err=='Accesso a posizione di memoria non valido.' || err=='Classe non registrata.' ||
                err=='Impossibile trovare il modulo specificato.' || err=='Klasse is niet geregistreerd' ||
                err=='$ is not defined' || err=='A várt elem azonosító' || err=='Belirleyici gerekli' ||
				err=="Carattere non valido"  || err=="Invalid character" || err=="Caractère incorrect" ||
				err=="Carácter no válido" || err=='Expected identifier' || err=='Se esperaba un identificador' ||
                err=='Αναμενόμενο αναγνωριστικό' || err=='Предполагается наличие идентификатора' ||
				err=='Previsto identificatore' || err=='The specified module could not be found.' ||
				err=='‏‏ההרשאה נדחתה' || err=='Toegang geweigerd' || err=='Identificador esperado' ||
				err=='Accesso negato.' ||
				
                err=='Object required' || err=='Necessario oggetto' || err=='Errore non specificato.' ||
                err=='Errore non specificato' || err=='Previsto oggetto' || err=='Object expected' ||
                err=='Unbekannter Fehler' || err=='Objet attendu' || err=='Previsto identificatore' ||
                err=='Objekt erforderlich' || err=='Object vereist' || err.indexOf("postamble")!=-1 ||
                err=='Unspecified error.' || err=='Wymagany jest obiekt' || err=='Permission denied' ||
                err=='Permissão negada' || err=='Permiso denegado' || err=='Prevista funzione' ||
                err=='Argomento non valido.' || err=='Klasse nicht registriert' || err=='Objeto esperado' ||
                err=='Accesso negato.' || err=='Se requiere un objeto' || err=="Se esperaba un objeto" ||
				err=='Objekt erwartet' || err=='İzin verilmedi' || err=='Očakáva sa objekt' ||
                err=='Costante String senza terminazione' || err == "Errore di sintassi" || err == "Syntax error" ||
                err=='Constante chaîne non terminée' || err=='Unterminated string constant' ||
                err=='Interfaccia non registrata.' || err=='Razred ni registriran' || err=='Bezeichner erwartet' ||
                err=="Autorizzazione negata" || err=="Разрешение отклонено" || err=='Permission refusée' ||
				err=='Error no especificado.' || err=='Предполагается наличие объекта' ||
                
                err=="Proprietà o metodo non supportati dall'oggetto" ||
                err=="Object doesn't support this property or method" ||
                err=='Das Objekt unterstützt diese Eigenschaft oder Methode nicht.' ||
                err=='O objeto não dá suporte para a propriedade ou método' ||
                err=='O objecto não suporta esta propriedade ou método' ||
                err=='El objeto no acepta esta propiedad o método' ||
                err=='Cet objet ne gère pas cette propriété ou cette méthode' ||
                err=='Объект не поддерживает это свойство или метод' ||
                err=='Deze eigenschap of methode wordt niet ondersteund door dit object' ||
                err=='Obiekt nie obsługuje tej właściwości lub metody.' ||
                err=='Az objektum nem támogatja ezt a tulajdonságot vagy metódust.' ||
                err=='Predmet ne podpira te lastnosti ali metode' ||
                err=='Το αντικείμενο δεν υποστηρίζει αυτή την ιδιότητα ή μέθοδο' ||
                err=='Nesne bu özellik veya yöntemi desteklemiyor' ||
                err=='Objektet stöder inte egenskapen eller metoden.' ||
                err=='Objekt tuto vlastnost nebo metodu nepodporuje.' ||
                err=='Objektet støtter ikke angitt egenskap eller metode' ||
                err=='Objekt nepodporuje túto vlastnosť alebo metódu' ||
                err=='Objekti ei tue tätä ominaisuutta tai menetelmää' ||
                err=='Objektet understøtter ikke denne egenskab eller metode' ||
                err=='‏‏האובייקט אינו תומך במאפיין או בפעולת שירות אלה' ||
                err=='هذه الخاصية أو هذا الأسلوب غير معتمدين من قبل الكائ' ||
				err=='Esta propriedade ou método não é suportado pelo objeto' ) {
                return;
            }
            
            //errori dovuti a google adsense in pagine con markup xhtml
            //attenzione: disabilitarlo in caso di forti modifiche
            //potrebbe evitare il logging su altri errori
            if( (err.indexOf("';'") || err.indexOf('";"')) && line==24 ) { return; }
            
                
            // non logghiamo gli errori di analytics
            if( err.indexOf("_gat")!=-1 ||
                err.indexOf("Error loading script") != -1 ||
                err.indexOf("pageTracker") != -1) {
                return;
            }
            
            //non logghiamo gli errori dovuti a script esterni
            if( filename.indexOf("http://www.amando.it")==-1 ||
                filename.indexOf("http://foto.amando.it")==-1
                ) {
                return;
            }

            log_error_js("["+filename+" @ linea: "+line+"] - ERRORE JS: "+err, true);
       };