/**#@+
* @author   Flavio Pala
* Amando scripts ( jQuery version )
*/
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; } 

	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?") ) {
        
        request = $.post(
            "/scripts/cancella_commento.php", 
            { 'id_commento' : id_commento },
            function( resp ) {                  
                if( resp == "Commento cancellato" ) {  $("#commento_"+id_commento).css("display","none"); } else { alert(resp); }
            }
        );
	
	   	if( request == null ) { alert('Si è verificato un errore durante la cancellazione'); return; }

	} 
	
	return false;
}

function modifica( id_commento ) {
	
	vecchio_commento = jQuery.trim( $("#commento_"+id_commento+" > p").html() );
	
	mod = '<form action="/scripts/modifica_commento.php" method="post"><input type="hidden" name="id_commento" value="'+id_commento+'" /><textarea rows="5" cols="72" name="commento">'+vecchio_commento+'</textarea><br /><input type="submit" value="Invia" /></form>';
	
	$("#commento_"+id_commento+" > p").html(mod);

}

function vota( voto, id_votazione, extraid ) {

	if( auth === 0 ) { iscriviti(); return; }
    
    if( extraid == undefined ) {

        postdata = { 'id_votazione' : id_votazione, 'voto' : voto };

        id = "numero_voti";

    } else {

        postdata = { "id_votazione" : id_votazione, "voto" : voto, "extraid" : extraid };

        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 ); }
                        
    }
    
    request = $.post(
            "/scripts/vota.php", 
            postdata,
            function( resp ) {                  
                if( resp == "Voto Riuscito" ) { $("#"+id).html( parseInt($("#"+id).html(),10) + 1 ); } else { alert(resp); }
            }
    );
	    
   	if( request == null ) { alert('Si è verificato un errore durante la votazione'); return; }

}

function condividi_email() {
	location.href = "mailto:?subject=Amando.it%20-%20"+escape(document.title)+"&body="+escape(location.href);
}

function mostraTesto( id ) {
     request = $.get( "/scripts/recuperaTesto.php", {"id":id}, function( resp ){ if( resp!="" ){ $("#t_"+id).html(resp); } } );
     return false;    
}

function google_ad_request_done( google_ads ) {

	if( google_ads.length < 1 ) {
	    return;
	}
	
	var i;
	//http://pagead2.googlesyndication.com/pagead/abglogo/abg-it-100c-000000.png
	var s = '<a href="'+google_info.feedback_url+'" class="'+google_ad_style_ads_by_google+'" target="_blank">Annunci Google</a><br />';
	
	if( google_ads[0].type == "flash" ) {
		
	   	s += '<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_ads[0].url+'" target="_blank" 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 if( google_ads[0].type == "html" ) {
        
        s += google_ads[0].snippet;
        
    } 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;        
        }
        
        /*if( google_ad_style_width=='728' && google_ad_style_height=='90' ) {

            style_li = 'height:100%; width:220px;';
            google_ad_style_width = 660;
            
       	} else*/ if( !google_ad_style_vertical ) { 
		         
            style_li = '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>60 && google_ads.length>1 ) { height_temp = 60; }
            style_li = 'width:100%; height:'+height_temp+'px;';
			         
        }
    
        s += '<ul>';
        
        for( i=0; i<google_ads.length; ++i ) {
                        
            s += '<li style="'+style_li+'">' + 
	            	'<div class="google_ads_ad">' +
						'<span class="'+google_ad_style_title+add_style_title+google_ad_style_color+'">' +
							'<a href="'+google_ads[i].url+'" title="Visita '+google_ads[i].visible_url+'" target="_blank">' + 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+google_ad_style_color+'">' +
							'<a href="'+google_ads[i].url+'" title="Visita '+google_ads[i].visible_url+'" target="_blank">' + 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

function pwdFocus() { $('#fakepassword').hide(); $('#password').show(); $('#password').focus(); }

function pwdBlur() {  if( $('#password').attr('value') == '' ) { $('#password').hide(); $('#fakepassword').show(); }  }
					      
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;
    }
}

function select_status() {
    div = $("#status");
    if( div.css("display") == "none" ) { div.css("display",'inline'); } else { div.css("display",'none'); }
} 

function change_status( usr ) {
   
    privacyValue = parseInt( $("#selprivacy").val(), 10 );
    
    request = $.get( 
                    "/gremlin/privacy.php", 
                    { "id" :  usr, "status" : privacyValue },
                    function( resp ) {
                        alert("Tipo di privacy cambiata, potrebbe essere necessario qualche secondo perché le modifiche abbiano effetto");
                        if( resp == 'SUCCESS' ) {
                            if( privacyValue == 0 ) { imgurl = '/gremlin/resources/visible.gif'; } else { imgurl = '/gremlin/resources/invisible.gif'; }
                            $("#privacy").attr('src', imgurl);
                            $("#status").css("display","none");
                        }
                    }
                    );
   
}

var navBar = {

	init: function( id ) {

		var $parent = $('#'+id);

		// Ciclo tutti i link nella navbar di primo livello
		$('#'+id+'_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.'+id+'_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;}

function log_error_js(errore, no_prefix) {
    
    if( no_prefix != true ) { errore = "ERRORE JS 1: " + errore; }
    
    request = $.post( "/tools/ajax.php", { "type" : "error", "errstr" : errore } );
    
    if( request == null ) { return; }
 
}

window.onerror = function(err, filename, line) {
            
            //errore sconosciuto
            if( typeof err === 'object' ) {
                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;
            }

            // in genere questi sono errori di caricamento
            if( line<=20 || line>=1500 ) {
                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 logghiamo gli errori di analytics
            if( err.indexOf("_gat")!=-1 ||
                err.indexOf("Error loading script") != -1 ||
                err.indexOf("pageTracker") != -1) {
                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 ) {
                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 == "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; }

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