function css_browser_selector(u){var ua=u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1},g='gecko',w='webkit',s='safari',o='opera',m='mobile',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3.6')?g+' ff3 ff3_6':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('blackberry')?m+' blackberry':is('android')?m+' android':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?m+' j2me':is('iphone')?m+' iphone':is('ipod')?m+' ipod':is('ipad')?m+' ipad':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win'+(is('windows nt 6.0')?' vista':''):is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

var request = false;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
	request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = false;
    }
  }
}
 
if (!request){
  PopUp("Error initializing XMLHttpRequest!");
}

function hidePopUp(valore){
	
	$("#popUpBox").hide("fast");
	$("#popUpBg").animate({opacity:0},500,function(){
		document.getElementById("popUpBox").style.display="none";
		$("#popUpBox").remove();
		document.getElementById("popUpBg").style.display="none";	
		$("#popUpBg").remove();	
		document.onkeydown=function(){};
		
		if(valore==0){
			return false;
		}
		else{
			if(valore==1){
				return true;
			}	
		}	
		});
	}

function PopUp(messaggio,tipo){	
	alert(messaggio);
	return false;	
}

function loginUser(myform,backurl){
	myform=((myform==null)?"loginForm":myform);
	backurl=((backurl==null)?"":backurl);
    var variabili="action=loginUser&email=" + escape(document.forms[myform].login.value) + "&password=" + escape(document.forms[myform].password.value) + "&rnd=" + Math.random();
	$.ajax({
		url:'/includes/ajaxtools.asp',
		type:'POST',
		data:variabili,
		complete:function(data){
			loginBehave(data,backurl);
			}	
		});
}

function getInternetExplorerVersion()
{
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}	

var ActivateShopping=0;
var gapShopper;

function showMoreCities(){
	
	altezza=$(".supermercati tbody").attr("scrollHeight");
	if($(".supermercati tbody").css("height")=="230px"){
		$(".supermercati tbody").animate({height:altezza+'px'},1000);
	}
	else{
		document.getElementById("map_canvas").style.marginTop="0px";
		$(".supermercati tbody").animate({height:'230px'},1000);
	}
}

function switchMarket(idmarket,func){
		 $.ajax({
			 url:"/includes/ajaxtools.asp?action=SwitchMarket&idmarket=" + idmarket + "&rnd=" + Math.random(),
			 complete:function(){
				 		if(func){
							func();
							}
						else{				 
							switch(idmarket){
								case "3":
									document.location.href="/comprasubito";
									break;
								case "1":
								
									if(document.location.href.toLowerCase().indexOf("buonisconto")>0){
										url="/buoniSconto";
										}
									else{
									if(document.location.href.toLowerCase().indexOf("prezzomedio")>0){
										url="/prezzoMedio";
										}
									else{
									if(document.location.href.toLowerCase().indexOf("supermercati")>0){
										url="/supermercati";										
										}
									else{
									if(document.location.href.toLowerCase().indexOf("volantini")>0){
										url="/volantini";										
										}
									else{
									if(document.location.href.toLowerCase().indexOf("marche")>0){
										url="/marche";										
										}
									else{
										url="/categorie/alimentari";
										}}}}}
								
									document.location.href=url;
									break;
								case "2":
								
								
									if(document.location.href.toLowerCase().indexOf("buonisconto")>0){
										url="/buoniSconto";
										}
									else{
									if(document.location.href.toLowerCase().indexOf("prezzomedio")>0){
										url="/prezzoMedio";
										}
									else{
									if(document.location.href.toLowerCase().indexOf("supermercati")>0){
										url="/supermercati";										
										}
									else{	
									if(document.location.href.toLowerCase().indexOf("volantini")>0){
										url="/volantini";										
										}
									else{
									if(document.location.href.toLowerCase().indexOf("marche")>0){
										url="/marche";										
										}
									else{
										url="/categorie/elettrodomestici";
										}}}}}							
								
									document.location.href=url;
									break;
							}
			 		}
			 }
		 });
	}

function formattaNumeri(numero){
	
	numero=numero.toString();
	
	if(numero.indexOf(".")>0){
		decimali=numero.substring(numero.indexOf(".")+1);
		numero=numero.substring(0,numero.indexOf("."));
		decimali=decimali+"0";
		numero=numero+"."+decimali.substring(0,2);
		}
	else{
		numero=numero+".00";
		}
	return(numero);
	}

	function addToCart(idprodotto, idcategoria, newbag){
	    $('.ListaBadge .noList').hide();
	 $.ajax({
		 async:false,
		 url: "/includes/ajaxtools.asp?action=addToCart&idprodotto=" + ((idprodotto != null) ? idprodotto : "") + "&idcategoria=" + ((idcategoria != null) ? idcategoria : "") + "&rnd=" + Math.random() + "&renew=" + ((typeof (newbag) != 'undefined') ? newbag : ""),
		 dataType:"html",
		 complete:function(data){
			 
			 		_gaq.push(['_trackEvent', 'Carts', 'AddProduct', ''+idprodotto+'']);
			 
					if(data.responseText!=""){
						if(data.responseText!="0"){
								if(data.responseText=="renew"){
									$.msg({
										bgPath : '/images/generali/bgDark/',
										autoUnblock : false,
										content:'<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'$.msg("unblock");\'>x</a></div><div style=\'width:300px;font-size:12px;color:#666;\'><div style=\'position:relative;width:100px;float:left;line-height:210px;\'><img src=\'/images/registrati/GroceryBag.png\' height=\'100\' style=\'vertical-align:middle;\'></div><div style=\'position:relative;width:200px;float:left;\'><div style=\'background-color:#fff;padding:5px;position:relative;display:inline-block;\'><h2 class=\'GlossyHead\'><div class=\'orange\'>Nuova lista?</div></h2><br/>Vuoi continuare ad aggiungere prodotti alla Lista della Spesa esistente oppure crearne una nuova?<br/><div style=\'position:relative;width:70px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$.msg("unblock");addToCart(' + ((idprodotto==null)?'null':idprodotto) + ',' + ((idcategoria==null)?'null':idcategoria) + ',1)\' class=\'submitButton\' style=\'width:60px;\'>SI</a><br/>Aggiungi alla lista attuale</a></div><div style=\'position:relative;width:70px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$.msg("unblock");addToCart(' + ((idprodotto==null)?'null':idprodotto) + ',' + ((idcategoria==null)?'null':idcategoria) + ',2)\' class=\'submitButton\' style=\'width:60px;\'>NO</a><br>Crea nuova lista della spesa</div></div></div></div>'
										});
										return false;
									}
								else{
									dati= new String(data.responseText);
									if(dati.indexOf('<script')>=0){;
										script=dati.substring(0,dati.indexOf('</script>')+9);
										dati=dati.substring(dati.indexOf('</script>')+9,1000);
										$('body').append(script);
										}
									dati=dati.split(";")
									prodotto=dati[0];
									foto=dati[1];
									idprodotto=dati[2];
									$('#ResItem' + idprodotto + ' .addTool').html('<a class=\'Actions\' href=\'#sub\'  style=\'margin-left:2px;\' onclick=\'removeFromCartBadge("'+idprodotto+'")\'>-</a><div class=\'Quantities\' style=\'margin-left:5px;\'></div><a class=\'Actions floatright\' href=\'#add\' onclick=\'addToCart("'+idprodotto+'")\'>+</a><!--<a class=\'Actions remove\' href=\'#sub\'  style=\'margin-left:5px;\' onclick=\'removeFromCartBadge("'+idprodotto+'",1)\'>x</a>-->');
									$('#ResItem' + idprodotto + ' .addTool').addClass('addToolOn');
									}
							}
							else{
								SwitchCity();
							}
					}
					else{
						/* STORAGE CARRELLO CHIAMATO A VUOTO PER INIZIALIZZAZIONE, NON ESEGUIRE AZIONI;*/
						idprodotto="0";
						foto="";
						prodotto="";
						} 
						
						if($('.ListaBadge .items #list_' + idprodotto).length>0){
							qt=eval($('.ListaBadge .items #list_' + idprodotto + ' .qt').html())+1;
							$('.ListaBadge .items #list_' + idprodotto + ' .qt').html(qt);
							$('#ResItem' + idprodotto + ' .addTool .Quantities').html(qt);
							$("#list_" + idprodotto).css('backgroundColor','#ffdc1d').delay(500).queue(function() {
									$(this).css('backgroundColor','#fff');											
										aggiornaTotali();
									});
							}
						else{
							$(".ListaBadge .items").append("<div class=\'riga\' style=\'display:none;height:30px;\' id='list_" + idprodotto + "'><div class='prodotto'><a href=\'/prodotti/" + prodotto.replace(" ","_") + "_" + idprodotto + "\' class=\'prodotto\'><img src='" + foto + "' align=\'absmiddle\'/>" + prodotto + "</a></div><div class='qt'>1</div><a class=\"Actions\" href=\"#sub\"  style=\"margin-left:5px;margin-top:7px;\" onclick=\"removeFromCartBadge('"+idprodotto+"',1)\">x</a></div>");
							$('#ResItem' + idprodotto + ' .addTool .Quantities').html('1');
							$("#list_" + idprodotto).css('backgroundColor','#ffdc1d');							
							$("#list_" + idprodotto).slideDown("slow").delay(500).queue(function() {
									$(this).css('backgroundColor','#fff');																
										aggiornaTotali();							
									});
						}
						
		 }});	

}

function aggiornaTotali(){
		$('#shoppingmex').show();
		$('.SaveEditPrint').show();		
		$.ajax({
			url:'/includes/ajaxtools.asp?action=CartTotal&rnd=' + Math.random(),
			complete:function(data){

				if(data.responseText=="" || data.responseText=="0"){
					$('#shoppingmex').hide('fast',function(){
							$('.ListaBadge .noList').show('fast');
						});	
					$('.SaveEditPrint').hide();										
					$('.ListaBadge .totali').remove();
					}
				else{
					
					if($('.ListaBadge .totali').length<=0){
						$('.ListaBadge .totali').remove();
						$('.ListaBadge .items').after('<div class="totali">'+data.responseText+'</div>');
						}
					else{
						$('.ListaBadge .totali').html(data.responseText).find('.note').bind('click',function(){
							idsuper=$(this).parent().find('.logoSuper img')[0].src;
							idsuper=idsuper.substr(idsuper.indexOf('/img')+4,(idsuper.indexOf('.png')-(idsuper.indexOf('/img')+4)));
							DettaglioTotali(idsuper,this);
							});					
						}
						
						if(typeof($('.ListaBadge .totali a')[0])!="undefined"){						
							$('.ListaBadge #shoppingmex .submitButton')[0].href=$('.ListaBadge .totali a')[0].href;
							$($('.ListaBadge #shoppingmex .submitButton')[0]).bind('click',function(){
								_gaq.push(['_trackEvent', 'Registration', 'Source', 'Confronta Tutti']);
								});
							idlist=$('.ListaBadge .totali a')[0].href.substr($('.ListaBadge .totali a')[0].href.indexOf("id=")+3,50);
						}
						$('.ListaBadge .tools .rename').bind('click',function(){
							saveListAS(this,idlist);
							})
						$('.ListaBadge .tools .print').bind('click',function(){
							window.open('/utenti/print.asp?id='+idlist);
							})							
								
					}			
				
				
				if(parseInt($('#doublecheckList').html())!=$('.ListaBadge .riga').length){
						$.ajax({
						url:'/includes/ajaxtools.asp?action=getCompleteCart&rnd='+Math.random(),
						complete:function(data){
							$('.ListaBadge .riga').remove();
							formatCart(data.responseText,1);
							}
						})
					}
					
					
					StoreTempList();
					
				}
			});	
			
	}
	
function StoreTempList(){
			$.ajax({
				url:'/includes/ajaxtools.asp?rnd=' + Math.random(),
				type:'POST',
				data:'action=storeTempList&list=' + escape($('.ListaBadge').html())
			});		
	}
	
function DettaglioTotali(idcatene,oggetto){
		if($(oggetto).find('.infoSwap').length==0){
			$(oggetto).find('a').fadeTo(100,0.1);
			$(oggetto).append('<div class=\'loadingItem\' style=\'position:absolute;top:0px;left:30px;\'></div>');
			$.ajax({
				url:'/includes/ajaxtools.asp?action=CartTotalDetail&idcatene=' + ((typeof(idcatene)=='undefined')?'':idcatene),
				complete:function(data){
					
						_gaq.push(['_trackEvent', 'Carts', 'ShowTOTDetails', '']);
					
						$(oggetto).simpletip({
							content:'<div class=\'infoSwap\'>'+data.responseText+'</div>',
							hidden:'false',
							position:[-100,25]
							});	
						$(oggetto).find('a').fadeTo(100,1);
						$(oggetto).find('.loadingItem').remove();
						$(oggetto).eq(0).simpletip().show();
						}
				});
		}
	}

function removeFromCartBadge(idprodotto,azione){
		 $.ajax({
		 	url: "/includes/ajaxTools.asp?action=SubProduct&idprodotto=" + idprodotto + "&azione=" + ((typeof(azione)=='undefined')?'':azione) + "&rnd=" + Math.random(),
			async:false,
			complete:function(data){
					
					qt=eval($('.ListaBadge .items #list_' + idprodotto + ' .qt').html());
					if(qt>1 && (typeof(azione)=='undefined')){
						
						qt=qt-1;
						$('.ListaBadge .items #list_' + idprodotto + ' .qt').html(qt);
						$('#ResItem' + idprodotto + ' .addTool .Quantities').html(qt);
						aggiornaTotali();
						}
					else{								
						$("#list_" + idprodotto).slideUp('fast',function() {
									$(this).remove();
								}
							);
						aggiornaTotali();							
						
											
						$('#ResItem' + idprodotto + ' .addTool').html('<a href="#add" onclick="addToCart(\'' + idprodotto + '\')" title="Aggiungi  alla tua lista">aggiungi</a>');
						$('#ResItem' + idprodotto + ' .addTool').removeClass('addToolOn');											
					}
								
				}
			});
	}


/*$().ready(function() {
				$('#coda-slider-1').codaSlider();
				if(document.getElementById("tab3")!=null){
					gapShopper=document.getElementById("tab3").offsetTop;
				}
			});*/

var timerid;
var globalobj;
var globalact;

function slideme(oggetto,azione){
		
		var ver = getInternetExplorerVersion();
		
		if(ver==-1){
			
			if(timerid==null || timerid==''){
				goslide(oggetto, azione);
			}
			else{
				if(oggetto!=globalobj){
					mydiv=document.getElementById(globalobj);	
					mydiv.style.backgroundPosition="0px 0px";
					window.clearTimeout(timerid);
					goslide(oggetto, azione);
				}
			}
		}
		else{
			if(azione==1){
				document.getElementById(oggetto).style.backgroundPosition="44px 0px";
			}
			else{
				document.getElementById(oggetto).style.backgroundPosition="0px 0px";
				}
			}
	}
	
function goslide(oggetto,azione){
		if(azione==1){
			$("#"+oggetto).animate({backgroundPosition: '-45px 0px'},500);
		}
		else{
			$("#"+oggetto).animate({backgroundPosition: '0px 0px'},200)
			}
	
}

function getresultslist(qry,marca,idcitta,idrequest,idcategoria){
		
		if(request.readyState==0){
			
			mydiv=document.createElement("div");
			mydiv.id="loading";
			mydiv.style.position="relative";
			mydiv.style.marginLeft="35%";
			mydiv.innerHTML="<div style=\"padding:12px;\"><img src=\"/images/generali/loading.gif\"> Ricerca in corso</div>";					
			document.getElementById("risultati").appendChild(mydiv);
			
			 var url = "/includes/lista.asp?qry=" + qry + "&marca=" + marca + "&idcitta=" + idcitta + "&rnd=" + Math.random();	 
			 request.open("GET", url, true);
			 request.onreadystatechange = showresultslist;
			 request.send();
		}
		else{
			window.setTimeout("getresultslist('"+qry+"','"+marca+"','"+idcitta+"','"+idrequest + "')",1000);
			}
	}

var utmCampaign;
var FBCoreg;
	
function initFBSession(userid,auth,func){
	
		variabili="action=FBlogin&user=" + userid + "&auth=" + auth + "&utmCampaign=" + ((utmCampaign==null) ? '':utmCampaign) + "&rnd=" + Math.random() + ((FBCoreg==null || FBCoreg=="") ? "": "&coreg=1&coreglink=" + FBCoreg);
		
		$.ajax({
			url:"/includes/ajaxtools.asp",
			data:variabili,
			type:'POST',
			complete:function(data){
				
				if(func){
					func(data);
					}
				else{
					loginBehave(data);
					}
				}			
			}); 
	}
	
function loginBehave(request, url){					
					if(url==null || url==""){
						url=document.location.href.substr(document.location.href.indexOf("/",10),document.location.href.length-(document.location.href.indexOf("/",10)+1));
					}
					
					if(url.indexOf("#")>=0){
						url=url.substr(0,url.indexOf("#"));
						}
					
					if(url.indexOf('/?')==0 || url.indexOf('/#')){
						url="/categorie/home";
					}
					
					if(request.responseText.length<2){						
						switch(request.responseText){
						case "0":
							$('#user-info').parent().fadeTo(200,0.5,function(){
								$('#user-info').parent().fadeTo(200,1);
								$('#user-info').parent().css('backgroundColor','#f0d5b7');
								if($('#user-info .warning').length==0){$('#user-info').append('<div class=\'warning\'>Username o password non validi</div>');}
								});
							break;
						case "3":
							$.msg( 'unblock');
							ShowConfirmEmailToolBox();
							break;
						case "9":
							//FacebookLogin();
							$('#user-info').parent().fadeTo(200,1);
							$('#user-info').parent().css('backgroundColor','#f0d5b7');
							if($('#user-info .warning').length==0){$('#user-info').append('<div class=\'warning\'>Email registrata con Facebook, clicca su Accedi con Facebook</div>');}							
							break;
						default:
							alert("Il processo di login è stato interrotto in modo improvviso, riprova.");
/*							document.location.href="/utenti/registrazione.asp?err=" + request.responseText;*/
							break;
						}
						return false;
						}
					
					if(request.responseText.indexOf('11,')==0){
						risposta=request.responseText.replace('11,','');
						
						$('.registrazioneFormStep2 .welcome img').hide();
						
						var frm=document.forms['BigRegFormS2'];
						frm.iduser.value=risposta;
						frm.reloadafter.value="1";									
						$('.AccediFloat #mainfloat').animate({'margin-left':'-900px'},1000);
						return false;
						}
					
					document.location.href=url;
}	
	
function getcategory(qry,pos,idrequest,guid){
		mydiv=document.createElement("div");
		myform=document.forms['ricerca'];
		mydiv.id="loading";
		mydiv.style.position="relative";
		mydiv.style.marginLeft="35%";
		mydiv.innerHTML="<div style=\"padding:12px;\"><img src=\"/images/generali/loading.gif\"> Caricamento in corso</div>";					
		document.getElementById("risultati").appendChild(mydiv);
		
		 $.ajax({
			 url:"/includes/lista_v2.asp?idcategoria=" + qry + "&rangeKm=" + myform.RangeKm.value + "&pos=" + pos +"&guid=" + myform.guid.value + "&rnd=" + Math.random(),
		 	complete: function(data){
				
						if(data.responseText=="0"){
							SwitchCity();
							}
						else{
				
							if(document.getElementById("loading")!=null){document.getElementById("risultati").removeChild(document.getElementById("loading"));}						
							mydiv=document.createElement("div");
							mydiv.id="resultset";
							mydiv.innerHTML=data.responseText;
							document.getElementById("risultati").appendChild(mydiv);
							
							for(i=0;i<$("#resultset script").length;i++){
								eval($("#resultset script")[i].text);
							}
						}
				}
		 });
	}	


function showhide(oggetto){
	if(document.getElementById(oggetto).style.display=="none" || document.getElementById(oggetto).style.display==""){
		$("#"+oggetto).show("fast",function(){
			document.getElementById(oggetto).style.display="inline-block";
			});
		}
	else{
		$("#"+oggetto).hide("fast",function(){
			document.getElementById(oggetto).style.display="none";	
			});
			
		}
	}

function updateTextFidaty(){
	attivi=0;
	for(i=0;i<document.forms["regForm"].fidaty.length;i++){
			if(document.forms["regForm"].fidaty[i].checked){
				attivi++;
			}
		}
	if(attivi>0){
		document.getElementById("txtRegFidatyHtml").innerHTML="&nbsp; " + attivi + " Card";
		}
	else{
		document.getElementById("txtRegFidatyHtml").innerHTML="&nbsp; - - -";
		}
	}

var altezze = Array(0,0,0,0);
var Ht = "290";
var x = Array(0,0,0,0);
var y = 10;
var z = 10;
var insideTabs= Array("","","","");
var scrolling="";

	
function setcity(idcitta,citta,cap,noaction,backurl){
		
	backurl=((backurl==null)?"":backurl);
	
	if(document.getElementById("mapdescdiv")!=null){$("#mapdescdiv").remove();}
	if(cap!=null && ((cap=="1") && (document.getElementById("SetCap").value=="" || document.getElementById("SetCap").value.length!=5))){
		document.getElementById("SetCap").focus();
		return false;
	}
	
	$.ajax({
		url: "/includes/ajaxTools.asp?action=SetCity&idcitta=" + idcitta + "&nomecitta=" + citta + "&cap=" + ((document.getElementById("SetCap")==null) ? '' : document.getElementById("SetCap").value ) + "&rnd=" + Math.random(),
		complete:function(data){
			alert(data.responseText);
			}
		});
}

var maptimeout;

function gostep2(url){
	if (request.readyState == 4){
			if (request.status == 200)
				{
					if(request.responseText=="-1"){
							PopUp("CAP non trovato");
							document.getElementById("SetCap").value="";
							document.getElementById("SetCap").focus();
							request.abort();
							return false;
						}
					else{
							if(url==null || url==""){
								url=((document.location.href.indexOf("#")<=0) ? document.location.href : document.location.href.substring(0,document.location.href.indexOf("#")));
								url=((document.location.href.indexOf("?")<=0) ? url+"?rnd=" + Math.random() : url+"&rnd=" + Math.random());							
							}
							document.location.href=url;
							request.abort();
							return false;						
						}								
				}
		}
	}

function checkRegForm(myform,func){
	
	_gaq.push(['_trackEvent', 'Registration', 'Step1', 'registering']);
	
	var frm=document.forms[((myform==null)?"regForm":myform)];
	if(frm.email.value=="" || frm.email.value.indexOf("@")<=0 || frm.email.value.indexOf(".")<=0 || frm.email.value.length<5){
			frm.email.style.backgroundColor="#ffdada";
			frm.email.focus();			
			PopUp("Inserisci un indirizzo email corretto");
			return false;
		}
	if(frm.nome.value==""){
			frm.nome.style.backgroundColor="#ffdada";
			frm.nome.focus();						
			PopUp("Inserisci nome");
			return false;
		}	
	/*if(frm.cap.value=="" || frm.cap.value.length<5){
			frm.cap.style.backgroundColor="#ffdada";
			frm.cap.focus();						
			PopUp("Verifica inserimento CAP");
			return false;
		}				*/
	if(frm.sesso.value==""){
			frm.sesso.focus();						
			PopUp("Seleziona Uomo o Donna");
			return false;
		}	
	if(frm.password.value.length<6){
			frm.password.style.backgroundColor="#ffdada";
			frm.password.focus();					
			PopUp("La password deve essere di almeno 6 caratteri");
			return false;
		}	
	if(typeof(frm.password2)!="undefined" && frm.password2.value!=frm.password.value){
			frm.password2.style.backgroundColor="#ffdada";
			frm.password2.focus();					
			PopUp("Le password non corrispondono");
			return false;
		}
	if(frm.privacy.checked!=true){
			frm.privacy.focus();					
			PopUp("E' necessario accettare i termini di contratto");
			return false;
		}								
	if(frm.dtn_d.value=="" || frm.dtn_m.value=="" || frm.dtn_y.value=="" || isDate(frm.dtn_m.value+"/"+frm.dtn_d.value+"/"+frm.dtn_y.value)==false){
			frm.dtn_d.focus();						
			PopUp("Inserisci data di nascita");
			return false;
		}
	
	variabili="method=coreg&"+$(frm).serialize()+"&rnd=" + Math.random();
	
	$.ajax({
		type:'POST',
		url:'/includes/SaveUser.asp',
		data:variabili,
		complete:function(resp){
			
			risposta=resp.responseText.replace("11,","");
			risposta=risposta.replace("1,","");
						
			switch(risposta){
				case "FOUNDEMAIL":
					PopUp("Account già registrato");
					frm.email.style.backgroundColor="#ffdada";
					frm.email.focus();
					return false;						
					break;
				case "1FOUNDEMAIL":
					PopUp("Account già registrato");
					frm.email.style.backgroundColor="#ffdada";
					frm.email.focus();
					return false;						
					break;
				case "1MODIFYMAIL":
					break;
				case "MODIFYMAIL":
					break;
				case "MODIFY":
					break;
				case "1MODIFY":
					break;
				case "FOUNDNICK":
					PopUp("Account già registrato");
					frm.email.style.backgroundColor="#ffdada";
					frm.email.focus();							
					return false;
					break;
				case "1FOUNDNICK":
					PopUp("Account già registrato");
					frm.email.style.backgroundColor="#ffdada";
					frm.email.focus();							
					return false;
					break;
				default:
				
					if(func){
						func();
						}
					else{
				
						if(typeof(document.forms['BigRegFormS2'])=="undefined"){
							LoginForm(function(){
								
									var frm=document.forms['BigRegFormS2'];
									frm.iduser.value=risposta;	
									frm.reloadafter.value="1";
									$('.AccediFloat #mainfloat').animate({'margin-left':'-900px'},1000);
									
								});
							}
						else{
						
							var frm=document.forms['BigRegFormS2'];
							frm.iduser.value=risposta;									
							$('.AccediFloat #mainfloat').animate({'margin-left':'-900px'},1000);					
							ShowConfirmEmailToolBox();
							}
						_gaq.push(['_trackEvent', 'Registration', 'Step1', 'confirmed']);
					}
					break;					
				}
			}
		});
	return false;
	}

function checkRegFormS2(myform){
	
	var frm=document.forms[((myform==null)?"BigRegFormS2":myform)];
	
	variabili="action=AssignUserDetails&animali="+frm.animali.value;
	variabili+="&professione="+frm.professione.value;
	variabili+="&figli="+frm.figli.value;
	variabili+="&iduser="+frm.iduser.value;
	
     $('#'+myform+' input:checked').each(function() {
       variabili+="&"+$(this)[0].name+'='+$(this).val();
     });
	
	variabili+="&rnd=" + Math.random();
	
	$.ajax({
		type:'POST',
		url:'/includes/ajaxTools.asp',
		data:variabili,
		complete:function(resp){
			_gaq.push(['_trackEvent', 'Registration', 'Step2', 'filled']);
			skipRegFrm2(myform,1);
			}
		});
		return false;
	}
	
function skipRegFrm2(myform,saved){
	
	var frm=document.forms[((myform==null)?"BigRegFormS2":myform)];
	
	if(typeof(saved)=='undefined'){
		_gaq.push(['_trackEvent', 'Registration', 'Step2', 'skipped']);
	}
	
	if(frm.reloadafter.value==""){
		$.msg( 'unblock');
		}
	else{
		document.location.href="/categorie/home";
		}
	}

function ShowConfirmEmailToolBox(){
	if($('.ConfirmEmailToolBox').length>0){
		$('.ConfirmEmailToolBox').fadeTo(500,0.2,function(){
			$('.ConfirmEmailToolBox').fadeTo(500,1);
			});
		}
	else{
		$('.main').first().before('<div class=\'ConfirmEmailToolBox\'>Per accedere a Risparmiosuper devi confermare il tuo indirizzo email.</div>');
		$('.ConfirmEmailToolBox').animate({'height':'40'},500);
		}
	}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        /*Check that current character is number.*/
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    /* All characters are numbers.*/
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    /* Search through string's characters one by one.*/
    /* If character is not in bag, append to returnString.*/
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	/* February has 29 days in any year evenly divisible by four,*/
    /*/ EXCEPT for centurial years which are not also divisible by 400.*/
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		PopUp("Formato data non valido")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		PopUp("Scegli mese")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		PopUp("Scegli giorno")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		PopUp("Scegli un anno valido")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		PopUp("Data non valida")
		return false
	}
return true
}


var publiclista;


function formatCart(myHTML,cosa){
	
	data=myHTML.replace('formatCart:\'','').split('\n');
	
	if(data.length==1){
		$(".ListaBadge .noList").show();
		$('.SaveEditPrint').hide();										
		$('.ListaBadge .totali').remove();
		StoreTempList();
		return true;
		}
	
	for(i=0;i<data.length-1;i++){
	
		dati=data[i].split(";");
		prodotto=dati[0];
		foto=dati[1];
		idprodotto=dati[2];
		num=dati[3];		

		$(".ListaBadge .items").append("<div class=\'riga\' style=\'height:30px;\' id='list_" + idprodotto + "'><div class='prodotto'><img src='" + foto + "' align=\'absmiddle\'/>" + prodotto + "</div><div class='qt'>" + num + "</div><a class=\"Actions\" href=\"#sub\"  style=\"margin-left:5px;margin-top:7px;\" onclick=\"removeFromCartBadge('"+idprodotto+"',1)\">x</a></div>");
	}
	
	$(".ListaBadge .noList").hide();	
		if(typeof(cosa)=="undefined"){
			aggiornaTotali();
		}
	}

function SwapIt(){
	myswaps=$(".swap");
	swapping="";
	
	$('.tableDiv tr>td:nth-child(1)').addClass('orange');
	
	$('.tableDiv tr:eq(0)').find('td:eq(0)').addClass('orangeHead');
	if($('.tableDiv tr:eq(0)').find('td:eq(0) img')[0]!=null){
		$('.tableDiv tr:eq(0)').find('td:eq(0) img')[0].src="/images/utenti/lista/v2/TopSuperOn.png";
	}
	
	for(i=0;i<myswaps.length;i++){
		$(myswaps[i]).load("/lista/lista.asp?view=swap&position="+myswaps[i].id,UpdateListTotals);
	}
	
	mydivs=$('.tableDiv tr>td:nth-child(1)').find('.swap');
	for(i=0;i<mydivs.length;i++){
		$(mydivs[i]).load("/lista/lista.asp?view=swap&extended=1&position="+mydivs[i].id);
	}
	
	totale=$('.tableDiv tr>td:nth-child(1)').find('.totale');
	$(totale).removeClass('totale');
	$(totale).addClass('totaleOn');		
}
	
function UpdateListTotals(){
	mycols=$('.tableDiv td');
	colonne=mycols.length/$('.tableDiv tr').length;
	
	for(i=1;i<colonne+1;i++){	
		mycols=$('.tableDiv tr>td:nth-child(' + i + ')');
		somma=0;
		stringa="";
		for(k=0;k<mycols.length-1;k++){
			prezzo=mycols[k].innerHTML.substr(0,mycols[k].innerHTML.indexOf("€"));
			prezzo=prezzo.replace(/>/g," ");
			prezzo=prezzo.split(" ");
			mioprezzo=prezzo[prezzo.length-1];
			if(isNaN(parseFloat(mioprezzo.replace(",",".")))==false){				
				somma+=parseFloat(mioprezzo.replace(",","."));
				stringa=stringa+"+"+mioprezzo.replace(",",".");
			}
		}
		if($('.tableDiv tr>td:nth-child(' + i + ')').find('.totale span')[0]==null){
			$('.tableDiv tr>td:nth-child(' + i + ')').find('.totaleOn span').html(formattaNumeri(somma)+'&euro;');
		}
		else{
			$('.tableDiv tr>td:nth-child(' + i + ')').find('.totale span').html(formattaNumeri(somma)+'&euro;');			
			}
	}	
}
	
function HighLighSuper(colonna,superMarket){
	colonna=colonna+1;
	$('.tableDiv tr:eq(0)').find('td').removeClass('orangeHead');
	myimgs=$('.tableDiv tr:eq(0)').find('td img');
	excolonna=0;
	for(i=0;i<myimgs.length;i=i+2){
		if(myimgs[i].src.indexOf("TopSuper.png")<0){
			myimgs[i].src="/images/utenti/lista/v2/TopSuper.png";
			excolonna=i/2;
			break;
			}
		}	
	$('.tableDiv').animate({opacity:0.2},500,function(){
		$('.tableDiv tr>td').removeClass('orange');
		$('.tableDiv tr>td:nth-child(' + colonna + ')').addClass('orange');	
		$('.tableDiv tbody').animate({scrollLeft:((colonna*125)-115-(10-(colonna*5)))+'px'},500);	
		$('.tableDiv').animate({opacity:1},500);			
		});
	
	mydivs=$('.tableDiv tr>td:nth-child(' + (excolonna+1) + ')').find('.swap');
	for(i=0;i<mydivs.length;i++){
		$(mydivs[i]).load("/lista/lista.asp?view=swap&position="+mydivs[i].id);
	}		
	mydivs=$('.tableDiv tr>td:nth-child(' + colonna + ')').find('.swap');
	for(i=0;i<mydivs.length;i++){
		$(mydivs[i]).load("/lista/lista.asp?view=swap&extended=1&position="+mydivs[i].id);
	}	
	
	$('.tableDiv tr:eq(0)').find('td:eq(' + (colonna-1) + ')').addClass('orangeHead');	
	$('.tableDiv tr:eq(0)').find('td:eq(' + (colonna-1) + ') img')[0].src="/images/utenti/lista/v2/TopSuperOn.png";				

	totale=$('.tableDiv tr>td:nth-child(' + (excolonna+1) + ')').find('.totaleOn');
	$(totale).removeClass('totaleOn');
	$(totale).addClass('totale');	
	
	totale=$('.tableDiv tr>td:nth-child(' + colonna + ')').find('.totale');
	$(totale).removeClass('totale');
	$(totale).addClass('totaleOn');	
	}

function getPrezzoStorico(idprodotto,idprovincia,idcategoria,categoria){
		
		if(request.readyState==0){
			
			 var url = "/includes/insights/prezzi.asp?qry=&tipo=101&desc=&idcatena=&idcategoria=" + idcategoria + "&idprovincia=" + ((idprovincia!=null)? idprovincia : "") + "&idprodotto=" + ((idprodotto!=null)? idprodotto : "") + "&categoria=" + escape(((categoria!=null)? categoria : "")) + "&datamin=&datamax=&comparativa=&group=&rnd=" + Math.random();	 
			 request.open("GET", url, true);
			 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
			 request.onreadystatechange = function(){
				 	if (request.readyState == 4){
						if (request.status == 200)
							{
							
							$("#graphPrezzo").html(request.responseText);
					
							request.abort();
							}
					}
				 };
			 request.send(null);
		}
		else{
			window.setTimeout("getPrezzoStorico('"+ idprodotto + "','"+((idprovincia!=null)? idprovincia : "") + "','"+((idcategoria!=null)? idcategoria : "") + "','"+((categoria!=null)? escape(categoria) : "") + "')",1000);
			}
	}



function getPrezzoMedio(idcategoria,idprovincia,oggetto){		
		 	$(oggetto).parent().parent().parent().find('.graph').parent().parent().remove();
			
			$(oggetto).parent().parent().after('<tr><td colspan=\'2\'><div style=\'height:20px;overflow:hidden;color:#666;font-size:12px;text-align:Center;\' class=\'graph\'>Caricamento dati</div></td></tr>');			
			
			$.ajax({
				 url:"/includes/insights/prezzi.asp?qry=&tipo=100&desc=&idcatena=&idcategoria=" + idcategoria + "&idprovincia=" + ((idprovincia!=null)? idprovincia : "") + "&datamin=&datamax=&comparativa=&group=&rnd=" + Math.random(),
				 complete:function(data){
					 
  					 	 _gaq.push(['_trackEvent', 'PrezziMedi', 'Graph', ''+idcategoria+'']);	
							
						 $(oggetto).parent().parent().parent().find('.graph').html(data.responseText);
						 $(oggetto).parent().parent().parent().find('.graph').animate({'height':'250px'},500);
					 }
				 });			
	}


function switchBoxProdotti(oggetto){
	if(document.getElementById("suggestPrezzo").style.display!="none"){
			$("#suggestPrezzo").fadeTo('fast',0);
			$("#labsuggestPrezzo").removeClass("BtnActive");
			$("#labsuggestPrezzo").addClass("BtnOff");			
			document.getElementById("suggestPrezzo").style.display="none";
		}
	if(document.getElementById("graphPrezzo").style.display!="none"){
			$("#graphPrezzo").fadeTo('fast',0);
			document.getElementById("graphPrezzo").style.display="none";
			$("#labgraphPrezzo").removeClass("BtnActive");	
			$("#labgraphPrezzo").addClass("BtnOff");						
		}
	if(document.getElementById("scontiPrezzo").style.display!="none"){
			$("#scontiPrezzo").fadeTo('fast',0);
			document.getElementById("scontiPrezzo").style.display="none";
			$("#labscontiPrezzo").removeClass("BtnActive");
			$("#labscontiPrezzo").addClass("BtnOff");							
		}	
				
	$("#lab" + oggetto).removeClass("BtnOff");	
	$("#lab" + oggetto).addClass("BtnActive");
	$("#"+oggetto).show();
	$("#"+oggetto).fadeTo('fast',1);
	}


function removeFromCart(idprodotto,azione){
		var opzioni="";
		 if(azione!=null){
		 	opzioni="&azione=" + azione;
		 }
		 var url = "/includes/ajaxTools.asp?action=SubProduct&idprodotto=" + idprodotto + "&idlista=" + publiclista + opzioni+"&rnd=" + Math.random();	 
		 request.open("GET", url, true);
		 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
		 request.onreadystatechange = function(){
				if (request.readyState == 4){
					if (request.status == 200)
						{
						request.abort();
						loadlist(publiclista);
						addToCart('','','','-1');
						}
				}
			 };
		 request.send(null);
	}
	
function EmptyUserList(){
	
	if(confirm("Sei sicuro di voler eliminare questa lista?")==true){
	
		 var url = "/includes/ajaxTools.asp?action=EmptyList&idlista=" + publiclista + "&rnd=" + Math.random();	 
		 request.open("GET", url, true);
		 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
		 request.onreadystatechange = function(){
				if (request.readyState == 4){
					if (request.status == 200)
						{
						request.abort();
						loadlist(publiclista);
						}
				}
			 };
		 request.send(null);
		}
	}

function bindSuggest(valore,campo,htmlBox){
	campo=eval(campo);
	campo.value=valore;
	$(htmlBox).hide('fast');
	
	}

function searchSuggest(azione,sorgente,htmlBox){
	
	 campo=eval(sorgente);
	 
	 var url = "/includes/ajaxTools.asp?action=" + azione + "&filt=" + campo.value + "&rnd=" + Math.random();	 
	 request.open("GET", url, true);
	 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
	 request.onreadystatechange = function(){
			if (request.readyState == 4){
				if (request.status == 200)
					{
					righe=request.responseText.split("|");
					strHTML="";
					for(i=0;i<righe.length;i++){
						if(righe[i]!=""){
							strHTML+="<a href=\"#set\" onclick=\"bindSuggest('" + righe[i].replace("'","\'") + "','" + sorgente + "','" + htmlBox + "');\">" + righe[i].replace("'","\'") + "</a><br/>";
							}
						}
					
					$(htmlBox + " .lista").html(strHTML);	
					altezza=$(htmlBox + " .lista").css('height');
					$(htmlBox).animate({height:altezza},'slow');					
					request.abort();
					}
			}
		 };
	 request.send(null);
	}	

function saveListName(lista){
		
		
		
		 var url = "/includes/ajaxTools.asp?action=SaveList&idlista=" + lista + "&name=" + document.getElementById("NewListName" + lista).value + "&rnd=" + Math.random();	
		 request.open("GET", url, true);
		 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
		 request.onreadystatechange = function(){
				if (request.readyState == 4){
					if (request.status == 200)
						{
						$("#link" + lista).parent().replaceWith("<a href=\"#switchList\" onclick=\"loadlist('" + lista + "');\" ondblclick=\"changeListName(this,'" + lista + "')\">"+request.responseText+"</a>");
						request.abort();
						document.location.href="/utenti?cartid=" + lista;
						}
				}
			 };
		 request.send(null);
	}

function PrintUserList(conferma){
	if(conferma==null){
		PopUp("<div style=\"font-size:12px;margin-top:-5px;\"><b>Scegli la stampa</b><br/><br/><input type=\"radio\" value=\"1\" id=\"PrintOpzione\" name=\"PrintOpzione\" checked=\"checked\"/> Migliori offerte supermercati<br/><input type=\"radio\" value=\"2\" id=\"PrintOpzione\" name=\"PrintOpzione\"/> Mia lista prodotti<br/><br/>Mostra <select id=\"PrintNumero\"><option value=\"1\">1</option><option value=\"2\">2</option></select> supermercati a confronto<div style=\"text-align:right\"><a href=\"#print\" onclick=\"PrintUserList(1);\"><img src=\"/images/utenti/lista/btnPrint.gif\"/></a></div></div>",3);
	}
	else{
		
		if(document.getElementById("PrintOpzione").checked==true){
			opzione=1;
		}
		else{
			opzione=2;
			}
		
		window.open("/utenti/stampa.asp?stampa=" + opzione + "&numero=" +document.getElementById("PrintNumero").value + "&idlista=" + publiclista + "&rnd=" + Math.random(),"printList","width:500,height:450,statusbar:no");
		hidePopUp();
		}
}

function changeListName(oggetto,lista){
	if(lista==null || lista==""){
			lista=publiclista;
		}
	if(oggetto!=null){
		origHTML=oggetto.outerHTML.replace(/\n/g,"");
		oggetto.outerHTML=("<span style=\"color:#999;font-size:12px;\">Nuovo nome:</span><br/><input type=\"text\" value=\"" + oggetto.innerHTML.replace(/\n/g,"" ) + "\" id=\"NewListName" + lista + "\" style=\"width:120px;\" onfocus=\"if(this.value=='Lista senza nome'){this.value='';}\"><br/><a href=\"#save\" id=\"link" + lista + "\">salva</a>");
	}
	else{
		PopUp("Salva la tua lista della spesa!<br/><br/><b>Inserisci nome:</b><br/><input type=\"text\" value=\"\" id=\"NewListName" + lista + "\" style=\"width:120px;\">&nbsp; <a href=\"#save\" id=\"link" + lista + "\"><img src=\"/images/utenti/lista/btnSave.gif\"/></a>",3);
		}
	document.getElementById("link" + lista).onclick=function(){
		saveListName(lista);
		};
	}
	
function getFacebookFriends(accesstoken,inizio,func){

	$("#friendList").fadeTo('fast',0.5);
	
	 var url = "/includes/ajaxTools.asp?action=GetFacebookFriends&accesstoken=" + accesstoken + "&sent=" + FBsentFriends +"&start=" + inizio + "&rnd=" + Math.random();	
	 request.open("GET", url, true);
	 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
	 request.onreadystatechange = function(){
			if (request.readyState == 4){
				if (request.status == 200)
					{
						if(func){
							func(request);
							}
						else{
							$("#friendList").fadeTo('fast',1);
							document.getElementById("friendList").innerHTML=document.getElementById("friendList").innerHTML+request.responseText;
							}
					}
			}
		 };
	 request.send(null);
	}
	
var FBinviteFriends=",";
var FBsentFriends=",";
function inviteFB(FBid){
		
	if(FBinviteFriends.indexOf(","+FBid+",")>-1){
		FBinviteFriends=FBinviteFriends.replace(","+FBid+",",",");
		$("#FBF" + FBid +" img").css("border","5px solid #f0f0f0");		
	}
	else{
		FBinviteFriends=FBinviteFriends+FBid+",";
		$("#FBF" + FBid +" img").css("border","5px solid #6fdc02");
		}
}

var pubFBtoken;

function sendFacebookInvites(accesstoken){
	
	if(FBinviteFriends.length>1){
	
		pubFBtoken=accesstoken;
		
		$("#friendList").fadeTo('fast',0.5);
		$("#friendList").animate({height:40},500,function(){
				
				$("#friendList").html("<h1>Invio inviti in corso...</h1>");
				$("#friendList").fadeTo('fast',1);
				
				 var url = "/includes/ajaxTools.asp?action=sendFBinvites&accesstoken=" + accesstoken + "&ids=" + FBinviteFriends + "&rnd=" + Math.random();	
				 request.open("GET", url, true);
				 request.setRequestHeader("Content-Type", "text/html; charset=windows-1252");
				 request.onreadystatechange = function(){
						if (request.readyState == 4){
							if (request.status == 200)
								{
									$("#friendList").html("<div><h1>Inviti inviati, Grazie!</h1><h2>Se vuoi puoi invitare altri amici</h2></div>");
									document.getElementById("friendList").style.height="";
									FBsentFriends=FBsentFriends+FBinviteFriends;
									FBinviteFriends="";
									getFacebookFriends(pubFBtoken,0);
								}
						}
					 };
				 request.send(null);
				
				});
		}
		else{
			PopUp("Scegli quali amici invitare cliccando sulla foto corrispondente.");
			}
	}
	
function loadAllSuperProducts(idsuper){
	
	if($("#MostraTutto").length==0){
		
		$('.mysearchfilt').show('fast');
		
		$('html,body').animate({scrollTop: $(".BestOffer").offset().top},'slow');
		
		var mydiv=document.createElement("div");
		mydiv.id="MostraTutto";
		mydiv.style.display="none";
		$('.BestOffer').append(mydiv);	
		$("#MostraTutto").load("/includes/ajaxTools.asp?action=loadAllSuperProducts&idsuper=" + idsuper,function(responseText, textStatus, XMLHttpRequest){
			$("#MostraTutto").show('slow');
			});
		}
	else{
		if($("#MostraTutto")[0].style.display=="none"){
			$("#MostraTutto").show('slow');
			$('.mysearchfilt').show('fast');
			}
		else{
			$(".BestOffer .item").show();
			$("#MostraTutto").hide('fast');
			$('.mysearchfilt').hide('fast');
			}
		}
	}
	
function ForgotPass(step,variabile){
	
	myForms=$('#BigloginForm');
	myform=myForms[0];
	
	switch(((step==null)?1:step)){
		case 1:
			$('#passWiz').show('fast');
			if(myform.login.value!=""){
				myform.wizemail.value=myform.login.value;
				myform.wizemail.select();
				}
		break;
		case 2:
			if(variabile==1){
					
					email=myform.wizemail.value;
					
					$('#passWiz').hide('fast');
					$('#passWiz').html("<font style=\"color:red\">Attenzione, ricontrolla il codice inserito</font><br>Inserisci qui sotto il codice di controllo appena ricevuto via email e la nuova password scelta.<br><input type=\"text\" name=\"code\" value=\"Codice\" onclick=\"this.select()\"/><br><input type=\"text\" name=\"newpass\" value=\"Nuova password\" onclick=\"this.select()\"/><input type=\"hidden\" name=\"wizemail\" value=\"" + email + "\" /><br/><a href=\"#savenew\" onclick=\"ForgotPass(3)\">Salva nuova password</a>");
					$('#passWiz').show('fast');
				
				}
			else{
				$('#passWiz').hide('fast');
				$('#passWiz').html("Ti stiamo inviando una mail con le istruzioni per resettare la tua password...");
				$('#passWiz').show('fast',function(){
				
				$.ajax({
				url: "/includes/ajaxtools.asp?action=resetpass&email=" + myform.wizemail.value,
			  	success: function(dati){
					
					email=myform.wizemail.value;
					
					$('#passWiz').hide('fast');
					$('#passWiz').html("Inserisci qui sotto il codice di controllo appena ricevuto via email e la nuova password scelta.<br><input type=\"text\" name=\"code\" value=\"Codice\" onclick=\"this.select()\"/><br><input type=\"text\" name=\"newpass\" value=\"Nuova password\" onclick=\"this.select()\"/><input type=\"hidden\" name=\"wizemail\" value=\"" + email + "\" /><br/><a href=\"#savenew\" onclick=\"ForgotPass(3)\">Salva nuova password</a>");
					$('#passWiz').show('fast');
					}
				});
				
				});	
			}
		break;	
		case 3:	
			$.ajax({
				url: "/includes/ajaxtools.asp?action=savenewpass&email=" + myform.wizemail.value + "&code=" + myform.code.value + "&newpass=" + myform.newpass.value,
			  	success: function(dati){
						if(dati=="1"){
								myform.login.value=myform.wizemail.value;
								myform.password.value=myform.newpass.value;
								$('#passWiz').hide('fast');
								$('#passWiz').html("Password salvata! Ora attendi mentre effettuiamo il login...");
								$('#passWiz').show('fast');
								window.setTimeout("loginUser('BigloginForm','/index.asp')",2000);
						}
						else{
							ForgotPass(2,1);
							}
					}
				});
			break;
			
		}
	}
	
	
function initializeGeoCoding(){
	
	if(navigator.userAgent.toLowerCase().indexOf('msie')>0){		
		customMsgBox="msie.png";		
		}
	else{if(navigator.userAgent.toLowerCase().indexOf('chrome')>0){			
		customMsgBox="chrome.png";					
		}
	else{if(navigator.userAgent.toLowerCase().indexOf('safari')>0){			
		customMsgBox="safari.png";			
		}
	else{if(navigator.userAgent.toLowerCase().indexOf('firefox')>0){			
		customMsgBox="firefox.png";						
		}
	else{if(navigator.userAgent.toLowerCase().indexOf('maxthon')>0){			
		customMsgBox="maxthon.png";					
		}
	else{		
		customMsgBox="std.png";
		}}}}}
		
	
    $('#AddressFinder').html('<div style=\'text-align:center;width:680px;\'><img src=\'/images/generali/HouseGps.png\' vspace=\'10\'/></div></div><div class=\'loadingItem\' style=\'width:200px;margin-left:auto;margin-right:auto;\'>Geolocalizzazione in corso...</div><div style=\'text-align:center;\'>Se questa schermata appare per pi&ugrave; di 10 secondi <a href=\'#disable geo\' onclick=\'$("#jquery-msg-overlay").remove();SwitchCity("1");\'>CLICCA QUI</a></div><div class=\'GeoWarning\' style="height:130px;"><img src=\'/images/generali/geo_browser_'+customMsgBox+'?\' align="right"/>Il tuo <b>Browser</b> potrebbe<br> chiederti l\'autorizzazione<br>a condividere la posizione.<br><br><b>Consenti di Condividerla!</b></div>');	
	
	
	navigator.geolocation.watchPosition(function(position){
	
	var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'latLng': latlng}, function(results, status) {
	
	  if (status == google.maps.GeocoderStatus.OK) {
		  
    $('#AddressFinder').html('<div style=\'text-align:center;width:680px;\'><img src=\'/images/generali/HouseGps.png\' vspace=\'10\'/></div></div><div class=\'loadingItem\' style=\'width:200px;margin-left:auto;margin-right:auto;\'>Caricamento impostazioni locali</div>');		  
		  indirizzo=results[1].formatted_address;
		  if(indirizzo.indexOf('Italia')>0 || indirizzo.indexOf('Italy')>0){			  
			  $.ajax({
				url:'/includes/ajaxTools.asp?action=SetCity&pos=' + results[0].geometry.location + '&address=' + escape(indirizzo) +"&rnd=" + Math.random(),
				error:function(dati){
					GeoLocate='off';
					SwitchCity();
					 _gaq.push(['_trackEvent', 'Geo', 'Geolocalizzazione', 'UNRECOGNIZED']);
					},
				success: function(data){
					
					  _gaq.push(['_trackEvent', 'Geo', 'Geolocalizzazione', 'OK']);
					
					if(data==""){
						url=((document.location.href.indexOf("#")<=0) ? document.location.href : document.location.href.substring(0,document.location.href.indexOf("#")));
						url=((document.location.href.indexOf("?")<=0) ? url+"?rnd=" + Math.random() : url+"&rnd=" + Math.random());							
						document.location.href=url;
						}
					}
				});
		  }
		  else{
  			  _gaq.push(['_trackEvent', 'Geo', 'Geolocalizzazione', 'NOT_ITALY']);
			  alert('Siamo spiacenti ma Risparmiosuper attualmente è disponibile solo in Italia, Inserisci l\'indirizzo manualmente.');
			  $.msg('unblock');
			  SwitchCity();
			  }
		  
	  }
	});		
	});
  }	

function loadGeoScript() {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.google.com/maps/api/js?sensor=false&language=it&callback=initializeGeoCoding&key=AIzaSyCFFjg0h1FGNEsO6PMNEyM61PZIggDhL6A";
	document.body.appendChild(script);
  }	

var globalAddressVariableLookup;
var GeoLocate="on";

function geocodedaddress(){	
	geocoder = new google.maps.Geocoder();	
	geocoder.geocode( { 'address': globalAddressVariableLookup+' Italia'}, function(results, status) {		
	  if (status == google.maps.GeocoderStatus.OK) { 
	  		indirizzo=results[0].formatted_address;
			
	  		
			
			  var cap="";
			  var stato="";
			  var provincia="";
			  var citta="";
			
			  for(i=0;i<results[0].address_components.length;i++){
				  switch(results[0].address_components[i].types[0]){
					  case "locality": citta=results[0].address_components[i].long_name;
					  break;								  
					  case "administrative_area_level_2": provincia=results[0].address_components[i].short_name;
					  break;							  
					  case "country": stato=results[0].address_components[i].short_name;
					  break;
					  case "postal_code": cap=results[0].address_components[i].long_name;
					  break;							  
					  }
				  }		
				  	
				  if(stato=='IT'){
					  
					   _gaq.push(['_trackEvent', 'Geo', 'Geolocalizzazione', 'MANUAL']);
					  
					  $('#AddressFinder').html('<div style=\'text-align:center;width:680px;\'><img src=\'/images/generali/MapGps.png\' vspace=\'10\'/></div></div><div class=\'loadingItem\' style=\'width:200px;margin-left:auto;margin-right:auto;\'>Caricamento impostazioni locali</div>');
					  $.ajax({
						url:'/includes/ajaxTools.asp?action=SetCity&pos=' + results[0].geometry.location + '&cap=' + escape(cap) + '&provincia=' + escape(provincia) + '&citta=' + escape(citta) + '&rnd=' + Math.random(),
						success: function(data){
							
							if(data==""){
								url=((document.location.href.indexOf("#")<=0) ? document.location.href : document.location.href.substring(0,document.location.href.indexOf("#")));
								url=((document.location.href.indexOf("?")<=0) ? url+"?rnd=" + Math.random() : url+"&rnd=" + Math.random());							
								document.location.href=url;
								}
							}
						});
				  }
				  else{
		  				  _gaq.push(['_trackEvent', 'Geo', 'Geolocalizzazione', 'MANUAL_NOT_ITALY']);
						alert("Attualmente risparmiosuper è disponibile solo in Italia, Inserisci l'indirizzo completo o il nome di una località Italiana.");		  
					  }
			}
		else{
			  _gaq.push(['_trackEvent', 'Geo', 'Geolocalizzazione', 'MANUAL_NOT_RECOGNIZED']);
			alert('Spiacenti, Indirizzo non trovato.');
			}
		});
  }	

function addresslookup(campo){
	
	_gaq.push(['_trackEvent', 'Geo', 'Indirizzi', campo]);
	
	globalAddressVariableLookup=$('#'+campo)[0].value;
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.google.com/maps/api/js?sensor=false&language=it&callback=geocodedaddress&key=AIzaSyCFFjg0h1FGNEsO6PMNEyM61PZIggDhL6A";
	document.body.appendChild(script);
	}
	
var google;	

function LoginForm(func,reg_code,accesstype){
			
	$.ajax({	
				url:'/includes/loginform.asp?reg_code=' + ((typeof(reg_code)=='undefined') ? '':reg_code)+'&accesstype='+((typeof(accesstype)=='undefined') ? '':accesstype),
				dataType:'html',
				complete:function(data){			
				_gaq.push(['_trackEvent', 'Registration', 'Step1', 'show']);
					
				$.msg({
					bgPath : '/images/generali/bgDark/',
					autoUnblock : false,
					content:'<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'$.msg("unblock");\'>x</a></div>'+data.responseText
					});
					
					
					if(func) func(self._name, self.type);	
					}
				});

	}	
	
var GlobalTimer;

function autoBgScroll(oggetto){
	scrollBg(oggetto,0);
	}

function scrollBg(oggetto,direzione){
	window.clearTimeout(GlobalTimer);
	
	px=parseInt($(oggetto + ' .scroll li').css('width').replace("px",""));
	massimo=($(oggetto + ' .scroll li').length-1)*px;	
	
	if((Math.abs(parseInt($(oggetto + ' .scroll').css('marginLeft').replace("px","")))>=massimo && direzione==0 ) || (parseInt($(oggetto + ' .scroll').css('marginLeft').replace("px",""))==0 && direzione==1)){
		direzione=((direzione==0)?1:0);
		px=massimo;
		}
	$(oggetto + ' .scroll').animate({
		marginLeft:"+="+((direzione==0)?"-":"+")+"" + px + "px"
		},500,function(){
			GlobalTimer=window.setTimeout('autoBgScroll(\'' + oggetto + '\')',6500);
			});
	}
	
/*function searchFilters(){
	myform=document.forms["ricerca"];
	getcategory('1',50,0);
	}*/
	
function SwitchCity(disableGeo){
	
		_gaq.push(['_trackEvent', 'Geo', 'SwitchCity', ''+GeoLocate+'']);
	
		if(GeoLocate=="on"){
			if (navigator.geolocation == undefined || ($.browser.msie) || disableGeo!=undefined) {
				$.msg({
					bgPath : '/images/generali/bgDark/',
					autoUnblock : false,
					content : '<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'_gaq.push(["_trackEvent", "Geo", "Geolocalizzazione", "MANUAL_CLOSED"]);$.msg("unblock");\'>x</a></div><div id=\'AddressFinder\' style\'width:850px;position:relative;\'><div style=\'width:400px;position:relative;float:left;padding-top:90px;\'><h2 style="text-align:left;font-size:40px;color:#f09834;">Dove Sei?</h2><br/><input type="text" id="PopUpAddress" value="Inserisci il tuo indirizzo, CAP, citta" style="padding-left:4px;color:#b4b4b4;border:1px solid #CCC;width:270px;height:28px;line-height:28px;margin-right:5px;font-size:16px;" onclick="this.value=\'\';"/><a class="submitButton" href="#setcity" onclick="addresslookup(\'PopUpAddress\')" style="height:34px;font-size:24px;line-height:34px;">INVIA</a><br><div style="margin-top:10px;color:#ed9939;font-size:18px;font-weight:normal;">per trovare il supermercato pi&ugrave;<br>economico nella tua zona.</div></div><div style=\'width:423px;height:354px;position:relative;float:left;\'><img src=\'/images/generali/PopSuper.jpg\' style=\'margin-bottom:10px;\'/></div></div>',
					afterBlock:function(){
						$('#PopUpAddress').bind('keydown',function(event) {
							if(event.keyCode==13){
								addresslookup('PopUpAddress');
								};
						  });
						}
					});
			}
			else{				  
				$.msg({
					bgPath : '/images/generali/bgDark/',
					autoUnblock : false,
					content : '<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'_gaq.push(["_trackEvent", "Geo", "Geolocalizzazione", "MANUAL_CLOSED"]);$.msg("unblock");\'>x</a></div><div id=\'AddressFinder\' style\'width:850px;position:relative;\'><div style=\'width:400px;position:relative;float:left;padding-top:40px;\'><h2 style="text-align:left;font-size:40px;color:#f09834;">Dove Sei?</h2><br/><input type="text" id="PopUpAddress" value="Inserisci il tuo indirizzo, CAP, citta" style="padding-left:4px;color:#b4b4b4;border:1px solid #CCC;width:270px;height:28px;line-height:28px;margin-right:5px;font-size:16px;" onclick="this.value=\'\';"/><a class="submitButton" href="#setcity" onclick="addresslookup(\'PopUpAddress\')" style="height:34px;font-size:24px;line-height:34px;">INVIA</a><br><div style="margin-top:10px;color:#ed9939;font-size:18px;font-weight:normal;">per trovare il supermercato pi&ugrave;<br>economico nella tua zona.</div><div style="margin-top:10px;padding-top:10px;border-top:2px solid #fff;"><span style="color:#ef9839;font-size:26px;">Localizzati</span><br><a href="#setcity" onclick="loadGeoScript();" style="font-size:18px;color:#808080;font-weight:normal;text-decoration:none;"><img src=\'/images/generali/HouseGps.png\' style=\'margin-right:50px;\' align="right"/>oppure consentici di rilevare<br>automaticamente la tua posizione</a></div></div><div style=\'width:423px;height:354px;position:relative;float:left;\'><img src=\'/images/generali/PopSuper.jpg\' style=\'margin-bottom:10px;\'/></div></div>',
					afterBlock:function(){
						$('#PopUpAddress').bind('keydown',function(event) {
							if(event.keyCode==13){
								addresslookup('PopUpAddress');
								};
						  });
						}
					});
			}
		}	
	}

function DropDown(oggetto,menu,subfilt,aggiorna,defaultvalue){
	if($('#'+oggetto + ' .submenu').length>0){
		$('#'+oggetto + ' .submenu').hide('fast',function(){
			$('#'+oggetto + ' .submenu').remove();
			if(typeof(aggiorna)!='undefined' && aggiorna!=null){
				DropDown(oggetto,menu,subfilt);
				}
			else{
				setSearchFilter();
				}
			});
		}
	else{
		if(typeof(aggiorna)=='undefined' || aggiorna==null){
			$('#'+oggetto).append('<div class=\'loading\'>Caricamento...</div>');
			$.ajax({
				url:'/includes/ajaxtools.asp?action=showFilters&filter=' + menu + '&subfilt=' + ((typeof(subfilt)=='undefined')?'':subfilt) + '&default=' + ((typeof(defaultvalue)=='undefined')?'':defaultvalue),
				complete:function(data){
					$('#'+oggetto + ' .loading').remove();
					$('#'+oggetto).append('<div class=\'submenu\'>'+data.responseText+'</div>');
					$('#'+oggetto + ' .submenu').show('fast');
					if(menu=='super'){
						getSuperNumber();
						}					
					if(typeof(defaultvalue)!='undefined'){
						setSearchFilter();
						}
					}
				});
			}
		}
	}
	
	
function getSuperNumber(forza){
	$('.UserBadge .city #puntivendita').fadeTo(100,0.5);
	$.ajax({
		url:'/includes/ajaxtools.asp?action=updatePuntiVendita&rnd=' + Math.random() + '&f=' + ((typeof(forza)=='undefined') ? '':forza),
		complete:function(data){
			if(data.responseText=="" || data.responseText=="0"){
				$('.UserBadge .city #puntivendita').html("... ");
				}
			else{
				$('.UserBadge .city #puntivendita').html(data.responseText);
				}
			$('.UserBadge .city #puntivendita').fadeTo(100,1);									
			}
		});	
	}	
	
function setSearchFilter(field,method){	
	$('#risultati').fadeTo(100,0.1);
	$.ajax({
		url:'/includes/lista_v2.asp',
		type:'POST',
		data:$('form[name=ricerca]').serialize(),
		complete:function(data){		
			$('#risultati').html(data.responseText);
			$('#risultati').fadeTo(250,1);
			if(field=='distanza'){
				getSuperNumber(1);	
				}				
			}
		});
	}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function resetslider(slider,valore){
	if($("#"+slider).slider("option", valore)==0){
		$('#prezzoda').val($("#"+slider).slider("option", valore));
		$("#"+slider).slider( "values",0,$("#"+slider).slider("option", valore));
		}
	else{
		$('#prezzoa').val($("#"+slider).slider("option", valore));
		$("#"+slider).slider( "values",1,$("#"+slider).slider("option", valore));
		}
	}	
	
function removecheck(checkbox,valore,allbut){
	if(typeof(allbut)=='undefined'){
		$('input:checked[value="' + valore + '"]').attr('checked', false);
	}
	else{
		
		$('input:checked[value!="' + valore + '"]').attr('checked', false);
		}
	setSearchFilter();
	}
	
function removetext(campo,testo){
	$('input[name="' + campo + '"]')[0].value=$('input[name="' + campo + '"]')[0].value.replace(testo,"").trim();
	setSearchFilter();
	}	
	
function SurfCategory(idcategoria,categoria,idpadre){
	if($('#CategoryFilt .submenu').length==0){
		DropDown('CategoryFilt','categorie',idcategoria+'&p='+idpadre,null,idcategoria);
	}
	else{
		$('#CategoryFilt .submenu').remove();
		DropDown('CategoryFilt','categorie',idcategoria+'&p='+idpadre,null,idcategoria);
		}
	window.history.pushState(null, null, '/categorie/' + categoria.replace(/ /g,'_') + '_'+idcategoria);
	}
	
function loadUserBadge(){
	$.ajax({
		url:'/includes/ajaxtools.asp?action=loaduserbadge',
		complete:function(data){
			$('.UserBadge .badge').fadeTo(200,0.5,function(){
					$('.UserBadge .badge').html(data.responseText);
					$('.UserBadge .badge').fadeTo(200,1);
				});
			}
		});
	}
	
function setRangeKM(){
	$.ajax({
		url:'/includes/ajaxtools.asp?action=setRangeKM&distanza=' + $('#RangeKm').val(),
		complete:function(){
			getSuperNumber(1);
			if(document.location.href.indexOf('?')>0){
				document.location.href+='&rnd=' + Math.random();
				}
			else{
				document.location.href+='?rnd=' + Math.random();
				}
			}
		});
	}
	
function SearchQuery(valore){
	if($('#FiltriRicerca').length>0){
		myform=$('#FiltriRicerca')[0];
		myform.qry.value=valore;
		setSearchFilter();
		}
	else{
		document.location.href="/categorie/home?qry=" + escape(valore);
		}
	}
	
function toggleSwitchLines(oggetto){
		if($(oggetto).parent().css('height')=='25px'){
			k=-1;
			for(i=0;i<$('.SwitchLine').length;i++){
				if($($('.SwitchLine')[i]).css('height')!='25px'){
					k=i;	
					$($('.SwitchLine')[i]).find('div').hide();	
					}
				}
			if(k>-1){
				$($('.SwitchLine')[k]).animate({
					'height':'25px'
					},500,function(){
						$('html,body').animate({scrollTop: $(oggetto).offset().top},'slow');
						});
				}
			$(oggetto).parent().animate({
				'height':(parseInt($(oggetto).parent().find('div').first().css('height').replace('px',''))+40)+'px'
				},1000,function(){
						$(oggetto).parent().find('div').show();	
						});	
		}
		else{
			$(oggetto).parent().animate({
				'height':'25px'
				},1000);
			}
	}
	
function FilterBrands(valore){	
	if(valore.value.length>1 || valore.value.length==0){
		$.ajax({
			url:'/includes/ajaxtools.asp?action=FilterBrandsPage&filt=' + valore.value,
			complete:function(resp){
				$($('.mainloghi div')[1]).html(resp.responseText);
				}
			});
		}
	}

function downWkAds(idwk){
	_gaq.push(['_trackEvent', 'WkAds', 'Download', ''+idwk+'']);
	}

function LoadWkAds(idwk,catena){
	$('.volantini .volantino').css('backgroundColor','#fff');
	$('.volantini .volantino .GuardaButton').html('GUARDA');		

	$('#wkad' + idwk).css('backgroundColor','#f0f0f0');
	$('#wkad' + idwk + ' .GuardaButton').html('Carico...');

	$.ajax({
		url:'/includes/ajaxTools.asp?action=loadAllWkAdsProducts&idWkAds=' + idwk,
		complete:function(resp){
			
			_gaq.push(['_trackEvent', 'WkAds', 'Open', ''+idwk+'']);
			
			$('.volantini .BestOffer')[0].style.display="inline-block";
			$('html,body').animate({scrollTop: $('.volantini .BestOffer').offset().top},'slow');			
			$('#wkad' + idwk + ' .GuardaButton').html('Chiudi');
			$('#wkad' + idwk + ' .GuardaButton')[0].onclick=function(){
				CloseWkAds(idwk,catena);
					};
						
			$('.volantini .BestOffer').html('<h2 class="GlossyHead"><div class="grey">Dettaglio Volantino ' + catena + '<div style="position:relative;float:right;"><a href="#closeme" onclick="CloseWkAds('+idwk+',\''+catena+'\');">Nascondi dettaglio</a></div></div></h2><div class=\'mysearchfilt\'>Cerca i prodotti nel volantino: <input type="text" onkeyup="FilterBoxesByName(this,\'.BestOffer .item\')" value="Digita qui il prodotto" style="color:#666;" onfocus="if(this.value==\'Digita qui il prodotto\'){this.value=\'\';}"/></div>'+resp.responseText);				
				
			}
		});
	}

function FilterBoxesByName(filtro,oggetto){
	$(oggetto).each(function(){
		if($(this).find('.titolo').html().toLowerCase().indexOf(filtro.value.toLowerCase())>=0){
			$(this).show();
			}
		else{
			$(this).hide();			
			}
		});
	}
	
function CloseWkAds(idwk,catena){
		$('.volantini .volantino').css('backgroundColor','#fff');
		$('.volantini .volantino .GuardaButton').html('GUARDA');
		$('#wkad' + idwk + ' .GuardaButton')[0].onclick=function(){
			LoadWkAds(idwk,catena);
				};			
	
		$('html,body').animate({scrollTop: '0px'},'slow');
		$('.volantini .BestOffer').hide('fast');
	}
	
function SuggestAPrice(ancora){
	$.ajax({
		url:'/includes/ajaxtools.asp?action=SuggestAPriceBox',
		complete:function(dati){
			$(ancora).after('<div class=\'SuggestAPriceBox\'>'+dati.responseText+'</div>');
			}
		});
	}

var iLikeitScope;
var iLikeitID;

function ILikeit(scopo,id){
		if(typeof(scopo)!='undefined'){
			$.ajax({
			url:'/includes/ajaxtools.asp?action=ILikeit&scopo=' + scopo + '&id=' + id
			});
		}
	}
	
function priceAlert(id){
	
	_gaq.push(['_trackEvent', 'PriceAlert', 'show', ''+id+'']);
	
	oggetto=$('.social').find('a')[0];
	if($(oggetto).qtip().length==1){
		$(oggetto).qtip({
			   content:'<b style="text-shadow:1px 1px 1px #666;font-size:24px;color:#fff;margin-bottom:5px;">Allerta prezzo</b><br><br><b style="font-size:14px;">A quanto acquisteresti questo prodotto?</b><br/><br>Ti avviseremo immediatamente, via email, quando questo prodotto sar&agrave; in offerta intorno a te al prezzo indicato.<br><br><input type=\'text\' value=\'Prezzo in &euro; es. 10,5\' style=\'color:#666;\' onfocus=\'this.value="";\' id=\'pricealertText\'/> &euro; &nbsp; &nbsp; <a href=\'#idem\' onclick=\'setPriceAlert(' + id + ')\' class=\'submitButton\'>avvisami</a>',
			   show: {event: false},			
			   hide: {event: 'unfocus'},
			   position: {at: 'bottom center'},
			   style:{classes: 'ui-tooltip-shadow ui-tooltip-rounded ui-tooltip-dark'}
			   });	
		   }
		   $(oggetto).qtip('show');
	}
	
function setPriceAlert(id){
	
	_gaq.push(['_trackEvent', 'PriceAlert', 'set', ''+id+'']);
	
	$.ajax({
		url:'/includes/ajaxtools.asp?action=storePriceAlert&idprodotto=' + id + '&prezzo=' + $('#pricealertText').val(),
		complete:function(data){
			if(data.responseText==""){
				oggetto=$('.social').find('a')[0];
				$(oggetto).qtip('hide');
				$(oggetto).html('Prezzo salvato');		
				$(oggetto).animate({backgroundColor: '#bde988'});
				$(oggetto).qtip('destroy');
				}
			else{
				$(oggetto).qtip('destroy');
				LoginForm();
				}
			}
		});
	}

	function AbandonList(conferma, idprodotto){

	    if (typeof (conferma) == 'undefined') {
	        _gaq.push(['_trackEvent', 'Carts', 'Azioni', 'Crea nuova']);

	        $.ajax({
	            url: '/includes/ajaxtools.asp?action=AbandonList',
	            complete: function ()
	            {
	                document.location.href = "/categorie/home?n=1";
	            }
	        });
	    } else if (conferma == "createNewList") {
	        _gaq.push(['_trackEvent', 'Carts', 'Azioni', 'Crea nuova']);

	        $.ajax({
	            url: '/includes/ajaxtools.asp?action=AbandonList',
                cache: false,
	            complete: function (){
	                //$(".ListaBadge").find(".items").hide();
	                $(".orange.listName").text('La mia lista');
	                addToCart(idprodotto);
	            }
	        });

	    } else {
	        if ($('.loginBar a').html() == "Esci") {
	            $.msg({
	                bgPath: '/images/generali/bgDark/',
	                autoUnblock: false,
	                content: '<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'$.msg("unblock");\'>x</a></div><div style=\'width:300px;font-size:12px;color:#666;\'><div style=\'position:relative;width:100px;float:left;line-height:210px;\'><img src=\'/images/registrati/GroceryBag.png\' height=\'100\' style=\'vertical-align:middle;\'></div><div style=\'position:relative;width:200px;float:left;\'><div style=\'background-color:#fff;padding:5px;position:relative;display:inline-block;\'><h2 class=\'GlossyHead\'><div class=\'orange\'>Nuova lista?</div></h2><br/>Hai scelto di creare una nuova lista della spesa. La lista che stai lasciando verrà salvata in automatico e la troverai ne "le mie liste".<br/><div style=\'position:relative;width:70px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$.msg("unblock");AbandonList()\' class=\'submitButton\' style=\'width:60px;\'>SI</a><br/>Crea una nuova lista della spesa</a></div><div style=\'position:relative;width:70px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$.msg("unblock");\' class=\'submitButton\' style=\'width:60px;\'>NO</a><br>Continua a riempire questa lista</div></div></div></div>'
	            });
	        }
	        else {
	            $.msg({
	                bgPath: '/images/generali/bgDark/',
	                autoUnblock: false,
	                content: '<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'$.msg("unblock");\'>x</a></div><div style=\'width:300px;font-size:12px;color:#666;\'><div style=\'position:relative;width:100px;float:left;line-height:210px;\'><img src=\'/images/registrati/GroceryBag.png\' height=\'100\' style=\'vertical-align:middle;\'></div><div style=\'position:relative;width:200px;float:left;\'><div style=\'background-color:#fff;padding:5px;position:relative;display:inline-block;\'><h2 class=\'GlossyHead\'><div class=\'orange\'>Salva le tue liste!</div></h2><br/>Per salvare le tue liste, essere informato sulle ultime offerte, accedi a Risparmiosuper! E\' gratis.<br/><div style=\'position:relative;width:170px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$("#jquery-msg-overlay").remove();LoginForm()\' class=\'submitButton\' style=\'width:60px;\'>Accedi</a></div></div></div></div>'
	            });
	        }
	    }
	}
	
	
	
function saveListAS(ancora,lista,name){
	if(typeof(name)=='undefined'){
		if($(ancora).qtip().length==1){
			$(ancora).qtip({
				   content:'<b style="text-shadow:1px 1px 1px #666;font-size:24px;color:#fff;margin-bottom:5px;">Scegli nome</b><br><br><span style="font-size:12px;">Dai un nome alle tue liste, ti aiuter&agrave; a ritrovarle facilmente.</span><br><br><input type=\'text\' value=\'es. spesa domenicale\' style=\'color:#666;\' onfocus=\'this.value="";\' id=\'saveListASText\'/> &nbsp; &nbsp; <a href=\'#idem\' class=\'submitButton\'>Salva</a>',
				   show: {event: false},			
				   hide: {event: 'unfocus'},
				   position: {at: 'bottom center'},
				   style:{classes: 'ui-tooltip-shadow ui-tooltip-rounded ui-tooltip-dark'}
				   });	
				   
				  
			   }
			   $(ancora).qtip('show');
			   $('.qtip').find('.submitButton').bind('click',function(){
				   saveListAS(ancora,lista,$("#saveListASText").val());		   
			   });
		}
	else{
		
		_gaq.push(['_trackEvent', 'Carts', 'Azioni', 'Salva con nome']);		
		
		data="action=saveListAS";
		data+="&idLista="+lista;
		data+="&name="+name;
		url="/includes/utenti/ajaxToolsUserArea.asp";	
			
		$.ajax({	url:url,
			 		data:data,
					success:function(data){					
						$(".qtip").remove();							
							if($('.titoloLista').length>0){								
								$(ancora).parent().parent().parent().find('.titoloLista a').fadeTo(200,0.1,function(){
									$(ancora).parent().parent().parent().find('.titoloLista a').html(name);
									$(ancora).parent().parent().parent().find('.titoloLista a').fadeTo(500,1);
									});
								}
							if($('.ListaBadge').length>0){
								$(ancora).parent().parent().parent().find('.ListaBadge .GlossyHead div').fadeTo(200,0.1,function(){
									$(ancora).parent().parent().parent().find('.ListaBadge  .GlossyHead div').html(name);
									$(ancora).parent().parent().parent().find('.ListaBadge  .GlossyHead div').fadeTo(500,1, function(){
											StoreTempList();	
									});									
							  });
								}																					
						}
			});	
			
				
		}
	}
	
function OrdersBox(idprodotto,sezione,azione){
	$('.orderbox').each(function(){				
				if($(this).val()){  return false;	}							
			});
			
	$('input[name="cancel_return"]').val(window.location.href)

			
	if(typeof(azione)=="undefined"){
		
		if(sezione=="regalo"){
			icone="presentIcon.png";
			testo="A chi vuoi regalarlo?";
			tipo='1';
			
			_gaq.push(['_trackEvent', 'Ordini', 'Tipo', 'regalo']);			
			}
		else{
			icone="truckIcon.png";
			testo="Dove consegnamo?";
			tipo='0';	
			
			_gaq.push(['_trackEvent', 'Ordini', 'Tipo', 'personale']);		
			}
		
		$.msg({
			bgPath : '/images/generali/bgDark/',
			autoUnblock : false,
			content : '<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'$.msg("unblock");\'>x</a></div><div id=\'OrderBox\'><h2 class="GlossyHead"><div class="orange">' + testo + '</div></h2><div class=\'OrderBoxIcon\'><input type=\'hidden\'  class="orderbox" name=\'idprodotto\' value=\'' + idprodotto + '\'><input type=\'hidden\'  class="orderbox" name=\'tipo\' value=\'' + tipo + '\'><img src=\'/images/prodotti/' + icone + '\' style=\'vertical-align:middle;\'/></div><div class=\'OrderBoxAddress\'><br><label>Nome e cognome</label><input type="text" name="nome" class="orderbox"/><br><label>Indirizzo</label><input type="text" name="indirizzo" class="orderbox"/><br><label>CAP</label><input type="text" name="cap" class="orderbox"/><br><label>Citta</label><input type="text" name="citta" class="orderbox"/><br><label>Provincia</label><input type="text" name="provincia" class="orderbox"/><br><label>Contatto telefonico</label><input type="text" name="ctel" class="orderbox"/><br><label>Contatto email</label><input type="text" name="cmail" class="orderbox"/><br><label>Tuo Codice Fiscale</label><input type="text" name="cf" class="orderbox"/><br><br><center><a href="#send" onclick="OrdersBox(\'' + idprodotto + '\',\'' + sezione + '\',1)" class="submitButton">Salva dati di spedizione</a></center></div>'
			});
			return false;
		}
	else{
		variabili="";
		$('#OrderBox .orderbox').each(function(){
				if($(this).val()==""){
					alert("Tutti i campi sono obbligatori");
					variabili="";
					
					_gaq.push(['_trackEvent', 'Ordini', 'Errori', 'Mancano campi']);	
					return false;
					}
				variabili+=$(this)[0].name + "=" + escape($(this).val()) + "&";
								
			});
		
		if(variabili!=""){
			
			$('#OrderBox .submitButton').css('backgroundColor','#e0e0e0');
			$('#OrderBox .submitButton').html('Salvataggio ordine in corso...');
			$('#OrderBox .submitButton')[0].onclick=function(){};
			variabili += "amount=" +  ($('input[name="amount"]').first().val()).replace(".",",");
			variabili += "&discount_amount=" +  ($('input[name="discount_amount"]').first().val()).replace(".",",");
			
			_gaq.push(['_trackEvent', 'Ordini', 'Completa', 'Ricezione dati']);
			
			$.ajax({
				url:'/includes/ajaxtools.asp?action=placeOrder',
				data:variabili,
				success:function(resp){
					
					_gaq.push(['_trackEvent', 'Ordini', 'Completa', 'Dati ricevuti']);
					
					$('input[name="custom"]').val(resp);
					$('#shopCompra')[0].submit();
					}
				});
			}
		}
	}
	
function DeletePref(){
	$.ajax({
		url:'/includes/ajaxtools.asp?action=DeletePref&'+ $(".rowRightBadge. input:checked").serialize(),
		complete:function(){
			$(".rowRightBadge. input:checked").each(function(){
				$(this).closest('.rowRightBadge').hide('fast');
				});
			}
		});
	}	
	
function LoadSampleProducts(guid){
	$('.sampleProducts').each(function(){
		var oggetto=$(this);
		
		if(oggetto.html()!=""){		
		dati=oggetto.html().split(":");
		numero=((dati[1]!=null)?parseInt(dati[1]):3);
		
		$.ajax({
			url:'/includes/lista_v2.asp?guid=' + guid + '&pos=(45.4708669,9.167563299999983)&RangeKm=25&qry=' + dati[0] + '&maxres=' + numero,
			success:function(resp){
				oggetto.html('<div class="risultati" id="risultati" style="width:' + numero*147 + 'px !important;overflow:hidden;">'+resp+'</div>');
				}
			});
		}
		});
	}
	
	
function enlargePic(immagine){
	$('.BigPicGallery').remove();
	$(immagine).before('<div class="BigPicGallery"><div><a href="#closeme" onclick="$(\'.BigPicGallery\').remove();">x</a></div><a href="#closeme" onclick="$(\'.BigPicGallery\').remove();"><img src="' + immagine.src.replace('60_60_','200_200_') + '" style="max-height:200px;"/></a></div>')
	}
	
var HomeCaruselPages=Array();
var HomeCaruselTimer;
	
function startHomeCarusel(carosello,pagina,direzione){
	window.clearTimeout(HomeCaruselTimer);
	if(typeof(pagina)=="undefined"){
		HomeCaruselPages.length=0;
		HomeCaruselPages.push($('.caroselloHomeCategorie .contenitore').html());
		for(myI=0;myI<carosello.length;myI++){
			switch(carosello[myI].prezzi.length){
				case 3:
					HomeCaruselPages.push("<div style='background-image:url(" + carosello[myI].foto + ");background-repeat:no-repeat;background-position:right center;cursor:pointer;'><div class='contenuti' onclick='_gaq.push([\"_trackEvent\", \"Prodotti\", \"Vetrina\", \""+carosello[myI].id+"\"]);window.location.href=\"" + carosello[myI].link_prodotto + "\"'><h2>" + carosello[myI].prodotto + "</h2><h3>" + carosello[myI].marca + "</h3><table><tr><td class='main' style=\'padding-bottom:5px;\'><img src='/images/super/loghi/" + carosello[myI].prezzi[0].idcatena + ".png'/><br>" + carosello[myI].prezzi[0].promozione + "&euro;</td><td style=\'padding-bottom:5px;\'><img src='/images/super/loghi/" + carosello[myI].prezzi[1].idcatena + ".png'/><br>" + carosello[myI].prezzi[1].promozione + "&euro;</td><td style=\'padding-bottom:5px;\'><img src='/images/super/loghi/" + carosello[myI].prezzi[2].idcatena + ".png'/><br>" + carosello[myI].prezzi[2].promozione + "&euro;</td></tr></table></div><div class=\'addTool mainHomeCart\'><a href=\'#add\' onclick=\'_gaq.push([\"_trackEvent\", \"Carts\", \"Vetrina\", \""+carosello[myI].id+"\"]);addToCart(\"" + carosello[myI].id + "\")\' title=\'Aggiungi alla tua lista\'>aggiungi</a></div></div>");
					break;
				case 2:
					HomeCaruselPages.push("<div style='background-image:url(" + carosello[myI].foto + ");background-repeat:no-repeat;background-position:right center;cursor:pointer;'><div class='contenuti' onclick='_gaq.push([\"_trackEvent\", \"Prodotti\", \"Vetrina\", \""+carosello[myI].id+"\"]);window.location.href=\"" + carosello[myI].link_prodotto + "\"'><h2>" + carosello[myI].prodotto + "</h2><h3>" + carosello[myI].marca + "</h3><table><tr><td class='main' style=\'padding-bottom:5px;\'><img src='/images/super/loghi/" + carosello[myI].prezzi[0].idcatena + ".png'/><br>" + carosello[myI].prezzi[0].promozione + "&euro;</td><td style=\'padding-bottom:5px;\'><img src='/images/super/loghi/" + carosello[myI].prezzi[1].idcatena + ".png'/><br>" + carosello[myI].prezzi[1].promozione + "&euro;</td></tr></table></div><div class=\'addTool mainHomeCart\'><a href=\'#add\' onclick=\'_gaq.push([\"_trackEvent\", \"Carts\", \"Vetrina\", \""+carosello[myI].id+"\"]);addToCart(\"" + carosello[myI].id + "\")\' title=\'Aggiungi alla tua lista\'>aggiungi</a></div></div>");				
			}
			}
		pagina=1;
		
		paginazione="";
		paginazione+="<a href='#pre' style='border-right:1px dotted #999;' class='pre'><</a>";
		for(myI=0;myI<HomeCaruselPages.length;myI++){
			paginazione+="<a href='#goto' onclick='startHomeCarusel(\"\"," + myI + ",\"\")' style='border-right:1px dotted #999;'>" + (myI+1) + "</a>";			
			}
		paginazione+="<a href='#next' class='next'>></a>";
		
		$('.caroselloHomeCategorie .contenitore').after("<div class=\"paginazione\">" + paginazione + "</div>");		
	}
	else{
		if(typeof(pagina)!="undefined" && direzione!=""){
			pagina=eval(pagina+direzione+"1");
			
			if(pagina<0){
				pagina=HomeCaruselPages.length-1;
				}
			if(pagina>=HomeCaruselPages.length){
				pagina=0;
				}			
			}
		}
	
	$('.caroselloHomeCategorie .paginazione a').css('background-color','transparent');
	$($('.caroselloHomeCategorie .paginazione a')[pagina+1]).css('background-color','#e4e4b9');
	
	$('.caroselloHomeCategorie .paginazione .pre')[0].onclick=function(){startHomeCarusel('',pagina,'-')};
	$('.caroselloHomeCategorie .paginazione .next')[0].onclick=function(){startHomeCarusel('',pagina,'+')};	
	
	$('.caroselloHomeCategorie .contenitore').fadeTo(500,0.2,function(){
		$('.caroselloHomeCategorie .contenitore').html(HomeCaruselPages[pagina]);
		$('.caroselloHomeCategorie .contenitore').fadeTo(500,1,function(){		
			HomeCaruselTimer=window.setTimeout("startHomeCarusel(''," + pagina + ",'+')",6000);
			});
		});
}


function resetTypeCartList_(val){
    var lurl = '';
    if (val != '') {lurl = '/includes/ajaxtools.asp?action=resetTypeCartList&val=' + val; } else {lurl = '/includes/ajaxtools.asp?action=resetTypeCartList&act=returnval'; }
    $.ajax({ url: lurl,
        type: 'GET',
        cache: false,
        complete: function (resp)
        {
            //return resp.responseText;
            valTypeCartList = resp.responseText;
        }
    });
}


function checkTypeCartList(currentMarket, idprodotto){
    $.ajax({ url: '/includes/ajaxtools.asp?action=resetTypeCartList&act=returnval',
        type: 'GET',
        cache: false,
        complete: function (resp)
        {
            var valTypeCartList = resp.responseText;
            if (valTypeCartList != currentMarket && valTypeCartList != '-1') {
                $.msg({
                    bgPath: '/images/generali/bgDark/',
                    autoUnblock: false,
                    content: '<div class=\'CloseMsgBox\'><a href=\'#chiudi\' onclick=\'$.msg("unblock");\'>x</a></div><div style=\'width:300px;font-size:12px;color:#666;\'><div style=\'position:relative;width:100px;float:left;line-height:210px;\'><img src=\'/images/registrati/GroceryBag.png\' height=\'100\' style=\'vertical-align:middle;\'></div><div style=\'position:relative;width:200px;float:left;\'><div style=\'background-color:#fff;padding:5px;position:relative;display:inline-block;\'>La tua lista contiene prodotti di un altro tipo.<br/><span style=\'font-size:14px;\'>Vuoi creare una lista nuova?</span><br/><br/><div style=\'position:relative;width:70px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$.msg("unblock");AbandonList("createNewList","' + idprodotto + '")\' class=\'submitButton\' style=\'width:60px;\'>SI</a><br/>Crea una nuova lista della spesa</a></div><div style=\'position:relative;width:70px;padding:10px;float:left;text-align:center;\'><a href=\'#aggiungi\' onclick=\'$.msg("unblock");resetTypeCartList("-1");addToCart("' + idprodotto + '")\' class=\'submitButton\' style=\'width:60px;\'>NO</a><br>Continua a riempire questa lista</div></div></div></div>'
                });
                return false;
            } else { addToCart(idprodotto); return true; }
        }
    });
}


function resetTypeCartList(val){$.ajax({url: '/includes/ajaxtools.asp?action=resetTypeCartList&val=' + val});}
