/*
 * inizializzo variabili globali
 */
var eb_prefissoHost = '';
var eb_suffissoHost = getSuffissoHost();
var eb_htmlBaseDir = '/be';
var eb_tis_tile = 1;
var eb_tis_randomnumber = Math.floor(Math.random()*10000000000);
	
/* ----------------------------------------------------------
 * DomReady
 * ----------------------------------------------------------
 */
window.addEvent('domready', function() { 
		
    Site.start();
    
    /*
     * tendina scelta provincia
     */
    tendinaProvincia();
    
    /*
     * tendina scelta categoria
     */
    tendinaCategoria();
    
    /* 
     * campo comune sopra i filtri laterali
     * nell'elenco annunci
     */
    filtroComune();
    
    /*
     * Ultimi annunci inseriti sulla homepage
     */
    boxUltimiAnnunci();
    
    /*
     * Azioni sulla risposta annuncio
     */
    rispostaAnnuncio();
        
    /*
     * form
     */
    actionForm();
    
    /*
     * Sulle pagine dei servizi
     */
    serviziBanner();
    
    /*
     * Sulla pagina tvspot
     */
    tvspot();
    
	/*
    if($('sendsegnalazione')){
        $('sendsegnalazione').addEvent('submit', function(e) {
            e.stop();
            this.set('send', {onComplete: function(response) { 
            	$('send_alert').set('html', response);
            }});
            this.send();
        });
    }
    */

});

/* ----------------------------------------------------------
 * Funzioni varie
 * ----------------------------------------------------------
 */

//azioni sui form di risposta annuncio
function rispostaAnnuncio() { 
    if($('rispostaannunciode') || $('rispostaannuncio')) { 
    	
    	//testo
        var myElements = $$('#rispostaannunciode textarea[name=testo], #rispostaannuncio textarea[name=testo]');
        myElements.addEvent('focus', function() { 
        	var frase  = "Vorrei maggiori informazioni riguardo l'annuncio in oggetto"; 
        	var testoInserito = this.get('value');
        	if(testoInserito == frase) { 
        		this.set('value','');
        	}
        }).addEvent('blur', function() {
        	var frase  = "Vorrei maggiori informazioni riguardo l'annuncio in oggetto"; 
        	var testoInserito = this.get('value');
        	if(testoInserito == '') { 
        		this.set('value',frase);
        	}
        }); 
        
    	//posta diretta
        var myElements = $$('#rispostaannunciode, #rispostaannuncio');
        myElements.addEvent('submit', function(e) { 
        	e.stop();
        	var postaDiretta = this.getElement('input[name=posta_diretta]:checked');
            if(!postaDiretta && this.getElement('input[name=posta_diretta]')){
                alert('ATTENZIONE\n\nDevi specificare il tuo consenso o rifiuto (SI/NO) \nai servizi di Postadiretta');

            } else { 
            	this.submit();
            }
        }); 
    }
}

//box ultimi annunci
function boxUltimiAnnunci() { 

    var ultimiAnnunci = $$('.ultimi_annunci .item');
    if(ultimiAnnunci.length>0){
        $$('.ultimi_annunci p').setStyle('display','none');
        ultimiAnnunci.each(function(e) { 
            var aAction = e.getChildren('a');
            aAction.addEvent('click', function(el) { 
                if(this.get('class')=="on") this.set('class','off');
                else this.set('class','on');
                this.getNext().getChildren('p').toggle();

            });
        });
    }
    
}

//tendina selezione provincia
function tendinaProvincia() { 
    
	var tendinaProvinciaContent = false; 
	
    if($$('a.link-cambia-provincia')) { 
    	
    	function provinceAction() {
    		
    		var myDivContainerContent = $('container-tendina').getElement('div.content');
	    	
	    	myDivContainerContent.getElements('a.regione').each(function(el,index){ 
	    		el.addEvent('click',function(e){ 
	    			myDivContainerContent.getElements('li.regione').removeClass('current');
	    			el.getParent('li.regione').toggleClass('current',true);
	    		});
	    	}); 
			
    	}
    	
        $$('a.link-cambia-provincia').each(function(el,index){
        	
        	el.addEvent('click',function(e){ 
        		e.stop();

        		if($('container-tendina')) { 
        			var controllo = $('container-tendina').hasClass('provincia');
        			$('container-tendina').destroy(); 
        			$$('a.link-cambia-provincia').set('html','Cambia Citt&agrave; &raquo;');
        			$$('a.link-cambia-categoria').set('html','Cambia Categoria &raquo;'); 
        			
        			if(controllo) {
        				return; 
        			}
        		}
        		
        		$$('a.link-cambia-provincia').set('html','Chiudi pannello');

        		
				var myDivContainer = new Element("div", {'id':'container-tendina','class':'provincia'});
				var myDivContainerContent = new Element("div", {'class':'content'});				
		        myDivContainerContent.inject(myDivContainer);
				myDivContainer.inject(el.getParent()); 	
				
				
				if(tendinaProvinciaContent) { 
					myDivContainerContent.set('html', tendinaProvinciaContent);
					provinceAction();
					return;
				}
				
				var myRequest = new Request({
				    url: '/be/main.php',
				    method: 'get',
				    onRequest: function(){
						myDivContainerContent.set('html', 'Loading...');
				    },
				    onSuccess: function(responseText){ 
				    	
				    	myDivContainerContent.set('html', responseText); 
				    	provinceAction();
				    	
				    	tendinaProvinciaContent = myDivContainerContent.get('html');

				    },
				    onFailure: function(){
				    	myDivContainerContent.set('html', 'Errore!');
				    }
				});
				var catCorrente = $('cat_corrente').get('value');
				myRequest.send('page=tendina_cambia_provincia&code_cat='+catCorrente);

        	});         	
        	
        }); 
        
    	
        
    }
}

//tendina selezione categoria
function tendinaCategoria() { 
    
	var tendinaCategoriaContent = false;
	
	
    if($$('a.link-cambia-categoria')) { 
    	
    	function categoriesAction() {
    		
    		var myDivContainerContent = $('container-tendina').getElement('div.content');
    		
	    	myDivContainerContent.getElements('li.category_link a').each(function(el,index){ 
	    		el.addEvent('click',function(e){ 
	    			e.stop();
	    			myDivContainerContent.getElements('li.category_link').removeClass('current');
	    			myDivContainerContent.getElements('ul.category_cont').removeClass('current');
	    			
	    			el.getParent().addClass('current'); 
	    			var myId = el.get('id');
	    			myDivContainerContent.getElement('ul#category_cont_'+myId).addClass('current');
					
	    		});
	    	});
			
    	}
    	
    	
        $$('a.link-cambia-categoria').each(function(el,index){
        	
        	el.addEvent('click',function(e){ 
        		e.stop();

        		if($('container-tendina')) { 
        			var controllo = $('container-tendina').hasClass('categoria');
        			$('container-tendina').destroy(); 
        			$$('a.link-cambia-provincia').set('html','Cambia Citt&agrave; &raquo;');
        			$$('a.link-cambia-categoria').set('html','Cambia Categoria &raquo;'); 
        			
        			if(controllo) { 
        				return; 
        			}
        		}
        		
        		el.set('html','Chiudi pannello');

        		
				var myDivContainer = new Element("div", {'id':'container-tendina','class':'categoria'});
				myDivContainer.setStyle('width', '400px');
				myDivContainer.setStyle('top', '27px');
				var myDivContainerContent = new Element("div", {'class':'content'});				
		        myDivContainerContent.inject(myDivContainer);
				myDivContainer.inject(el.getParent()); 
				
				if(tendinaCategoriaContent) { 
					myDivContainerContent.set('html', tendinaCategoriaContent);
					categoriesAction();
					return;
				}
				
				var myRequest = new Request({
					url: '/be/main.php',
				    method: 'get',
				    onRequest: function(){
						myDivContainerContent.set('html', 'Loading...');
				    },
				    onSuccess: function(responseText){
				    	myDivContainerContent.set('html', responseText); 
				    	categoriesAction();
				    	
				    	tendinaCategoriaContent = myDivContainerContent.get('html');
				    },
				    onFailure: function(){
				    	myDivContainerContent.set('html', 'Errore!');
				    }
				});
				
				myRequest.send('page=tendina_cambia_categoria&idcat='+el.get('rel'));

        	});
        });
    }
}

/* 
 * campo comune sopra i filtri laterali
 * nell'elenco annunci
 */
function filtroComune() { 
	
    if($('comune_left')) { 
		new Autocompleter.Request.JSON('comune_left', 'main.php?page=query_comuni', {
			'postVar': 'comune', 
			minLength: 3,
			maxChoices: 10,
			autoSubmit: false,
			cache: true,
			delay: 300, 
			selectMode: 'type-ahead', 
			onRequest: function() { 
				//fa nulla
			},
			onComplete: function() {
				//fa nulla
			}
		}); 
		
		function controlloComuneInserito(myComune, myUrl) { 
			new Request.JSON({
					url: 'main.php?page=query_comuni', 
					onSuccess: function(responseJSON){ 
						if(responseJSON[0] != undefined) { 
							myComune = myComune.clean();
							myComune = myComune.tidy();
							myComune = myComune.replace(/ /g,'-');
							
							myUrl = myUrl.replace('#COMUNE#',myComune.toString());
							myUrl = myUrl.toURI();
							myUrl.go();
						} else { 
							alert(myComune+" non esiste!");
						}
					} 
				}).send('comune=' + myComune);
		}
		
        $('btn_comune_left').addEvent('click',function(e){ 

            var myUrl = $('hidden_comune_left').get('value');
            var myComune = $('comune_left').get('value'); 
            
            if(myComune) { 
            	Cookie.write('viewfumettocomune', '1', {domain: '.bakeca.it',duration:0});
            	controlloComuneInserito(myComune, myUrl);            	
            } else { 
            	alert("Inserire il comune!");
            }
        });

         $('comune_left').addEvent('keydown',function(e){
            if (e.key == 'enter'){
                var myUrl = $('hidden_comune_left').get('value');
                var myComune = $('comune_left').get('value');

                if(myComune) {
                	Cookie.write('viewfumettocomune', '1', {domain: '.bakeca.it',duration:0});
                	controlloComuneInserito(myComune, myUrl); 
                } else {
                    alert("Selezionare un comune!");
                }
            }
        });
        
		$('comune_left').addEvent('focus',function(e) {
			if (Cookie.read('viewfumettocomune') != '1'){
				$('comune-fumetto').show();
			}
		});
		
		$('comune_left').addEvent('blur',function(e){
			$('comune-fumetto').hide();
		});
    }
}

/*
 * Utilizzata negli elenchi annunci per 
 * la stellina dei preferiti
 */
function outStellina(idpub,dettaglio) { 
	
	if(typeof(statusPref)=="undefined" || !statusPref) return(false);

	var elemento = 'st'+idpub;
	var strDett = '';
	
	if(dettaglio=='1'){ 
		strDett = '&amp;dett=ok';
	}

	var urlImmagine = urlAjax + '&amp;idp=' + idpub + strDett;

	var title = 'Aggiungi ai preferiti';
	var label = 'Aggiungi ai preferiti';
	var classe = '';
	
	if(dettaglio=='1'){ 
		label = 'Aggiungi';
	}
	
    if(test){
        if(test.indexOf(idpub)>=0) {
        	title = 'Rimuovi dai preferiti';
            label = 'Rimuovi dai preferiti';
            classe = 'class="selected"'; 
            
        	if(dettaglio=='1'){ 
        		label = 'Rimuovi';
        	}
        }
    }
    
  	if(document) { 
  		document.write(' <a '+classe+' title="'+title+'" onClick=\"getAjax(\''+elemento+'\',\''+urlImmagine+'\');\"><span>'+label+'</span></a>');
  	}
}

var Site = {
	start : function() {
	
		if (Browser.Engine.trident) { 
			Site.fixExplorer();
		}
		
		if($('city_search') || $('main_search')) {
			Site.initMainSearch();  
		}
		
		Site.initLeftSearch();
		
		Site.pageCheck(); 
		
		//in caso sia stato spedito il form
	    if($('apri_reply')) {
	        Site.adreply.showForm();
	    }
	    
	},

	fixExplorer : function() {
		$$('table').set('cellspacing', 0);
	},
	
	pageCheck: function() { 
		var pageID = $$('body')[0].get('id');
		Site.initAdReply();
		
	},
	
	initListPage:function() {
		var fbox = new FiltersList('filterbox');
		var detail = new CollapsableDetails();
	},
	
	initMainSearch : function() {
		Site.mainSearch = new MainSearch();
	},
	
	initLeftSearch : function() {
		Site.leftSearch = new LeftSearch();
	},
	
	initAdReply : function() {
		Site.adreply = new AdReply();
	}
};

/*
 * Uilizzato nel dettaglio annuncio per
 * aprire e chiudere il form sulla spalla laterale
 */
var AdReply = new Class ({
	initialize: function() {
		this.container = $('ad_reply')
		if(this.container) {
			this.replyActions = this.container.getElements('a.reply_action_link');
			if(this.replyForm = this.container.getElement('div.reply_form')) {
				this.formReveal = new Fx.Reveal(this.replyForm, {
					transition: Fx.Transitions.Sine.easeOut,
					duration: 'long', 
					mode: 'vertical', 
					onStart: this.showFormStart,  
					onComplete: this.showFormComplete
				});

				for ( i = 0; i < this.replyActions.length; i++) {
					this.replyActions[i].addEvent('click',function(event){
						event.preventDefault();
						Site.adreply.showForm();	
					});
				}
			}
		}
	},
	
	showFormStart: function() { 
		
		$('ad_reply').getElements('.reply_action').addClass('openform');

	}, 
	showFormComplete: function() { 

		var myHeight = $('ad_reply').getElement('div.reply_form').getStyle('height').toInt(); 

		if(myHeight == 0) { 
			$('ad_reply').getElements('.reply_action').removeClass('openform');
		}

	}, 
	showForm: function(i) { 
		
		this.formReveal.toggle(); 
		
	}
});

/*
 * Ricarca principale nel top della pagina
 */
var MainSearch = new Class ({
	initialize: function(){
		this.whatInput = $('search_string');
		this.whatHint = $('search_hint');
		this.searchBtn = $('search_submit');
		
		$('site_search_form').reset();
		this.activateSearchHint();
		this.activateSubmit();
		
	},

	activateSearchHint: function() {

        if (this.whatInput.value == '') {
            this.whatHint.removeClass('hidden');
        }
        
		// Al click sull'hint, lo nasconde ed assegna il focus all'input
		this.whatHint.addEvent('click',function(){
			Site.mainSearch.whatHint.addClass('hidden');
			Site.mainSearch.whatInput.focus();
		})
		
		// Al focus sull'input, nasconde l'hint
		this.whatInput.addEvent('focus',function(){
			Site.mainSearch.whatHint.addClass('hidden');
		})
		
		// Al blur dell'input, nel caso non sia stato immesso testo visualizza l'hint
		this.whatInput.addEvent('blur',function(){
			if (Site.mainSearch.whatInput.value == '') {
				Site.mainSearch.whatHint.removeClass('hidden');
			}
		})
	},
	
	activateSubmit: function() {
		
		// Submit del form di ricerca
		this.searchBtn.addEvent('click',function(event){
			event.preventDefault();
            window.document.location = getSearchUrl();
			//$('site_search_form').submit();
		});

        if($('site_search_form')){
            $('site_search_form').addEvent('submit', function(el) {
                el.preventDefault();
                window.document.location = getSearchUrl();
            });
        }
	}
});

/*
 * Filtri di ricerca sulla spalla sx in elenco annunci
 */
var LeftSearch = new Class ({ 
	
	initialize: function(){ 
	
		this.blocchiFiltro = $$('div.annuncio-filtri div.filtro');
		this.animaBloccoFiltro();
		
	},

	animaBloccoFiltro: function() {
			
		this.blocchiFiltro.each(function(el,index){
		    
			if(!el.hasClass('selezionati')) { 
				var aTitoloElement = el.getElement('p.filtro-titolo span');
						
				if(aTitoloElement) { 
					
					var myATag = new Element('a', {
						html: aTitoloElement.get('html'), 
						title: 'Clicca per comprimere/espandere questa categoria di filtri'
					});
	
					$(myATag).replaces(aTitoloElement);
					
					
					myATag.addEvent('click', function(e) { 	            
			            
			            var ulElement = el.getElement('ul');
			            		            
			            slide = new Fx.Reveal(ulElement, {
			                transition: Fx.Transitions.Sine.easeOut,
			                duration: 'short',
			                mode: 'vertical'
			            });
			            
			            slide.toggle();
	
			            if(slide.hidden) myATag.addClass('open');
			            else myATag.removeClass('open');
	
						
					});
				}
				

				var liMaggioriOpzioni = el.getElement('li.maggioriop');
				
				if(liMaggioriOpzioni) { 
					
					liMaggioriOpzioni.setStyle('cursor','pointer');
					
					liMaggioriOpzioni.addEvent('click', function(e) { 	            
			            						
			            var liNascosti = el.getElements('li.maggioriop-hidden');
						liNascosti.each(function(myLiEl,myLiIndex){
							myLiEl.removeClass('maggioriop-hidden');
						});
						
			            liMaggioriOpzioni.setStyle('display','none');
						
					});
				}

				
			}
		});
	}
});

/*
 * Tab sulla risposta annuncio
 */
function changePanel(tab,panel){
    $(tab).getParent().getChildren().set('class','tab');
    $(tab).set('class','tab active');
    panels=$$('.panels').getChildren('.panel');
    $each(panels,function(value,key){
        $each(value,function(elem,key){
            $(elem).set('class','panel');
        });
    });
    $(panel).set('class','panel active');
}

/*
 * Viene utilizzata per il link della 
 * categoria "servizi per adulti" sulla home delle categorie
 */
function gospa(element, pageTracker) { 

	element.set('target', '_blank');
	element.set('href', 'http://www.escort-magazine.com/it/?utm_source=bakeka.it&utm_medium=cpc&utm_campaign=bakeka_homepage');
	pageTracker._trackEvent('homepage','clickcategoria','escortmagazine');
	return true;
} 

/*
 * Ritorna l'url di ricerca in base ai 
 * filtri selezionati
 */
function getSearchUrl() {

    var filtri = new Array();

    var sep = "/";

	var baseUrl = 'http://'+eb_prefissoHost;
	
    if ($('vhost') && $('vhost').value != '') { 
    	baseUrl += $('vhost').value;
    } else {
		alert("Scegli una citta'");
		return false;
	}
    
    baseUrl += eb_suffissoHost;
    if ($('search_category')) baseUrl += $('search_category').value;

    baseUrl += '-0';

    var qs = '';           
   // if ($('search_string') && $('search_string')!='') qs += escape($('search_string').value);
   // P.A.
   // rimosso escape NOTA- se ? necessario correggere questa riga, valutare soluzioni insieme a Piumaz e Sviluppone 
    if ($('search_string') && $('search_string')!='') qs += $('search_string').value;
    
    // recupero tutti i parametri dal form
    if($('id_search_left')){
        var searchFields = $$('#id_search_left ul li input[type=radio]:checked');
        
        searchFields.each(function(el,index){ 
        	
           if(el.get('value') && el.get('name')!='inserzionisti'){
                if(el.get('value')!='' && el.get('name')!=''){
                    if(el.get('name')=='codiceQuartiere') { 
                    	filtri.push('quartiere-'+el.get('value'));
                    } else { 
                    	filtri.push(el.get('name')+'-'+el.get('value'));
                    }
                }
           }
        });
        
       //inserzionista
 	   inserzionist=$$('input[name=inserzionisti]:checked');
	   if($defined(inserzionist[0]) && inserzionist[0].get('value')!='entrambi' && inserzionist[0].get('value')!='') { 
		   filtri.push('inserzionista-'+inserzionist[0].get('value'));
	   }
   }

   
   if ($('comune_left') && $('comune_left').value!='') { 
	   filtri.push('comune-'+$('comune_left').value);
   }
   
   if(filtri.length>0){
       qs+='/search';
       filtri.sort();
       filtri.each(function(el,index){
    	   qs+=sep+el;
        });
   }

   return (baseUrl + (qs.length >0 ? '?'+qs : ''));
}

/*
 * Ritorna il suffisso host
 */
function getSuffissoHost()
{
	var a = window.location.hostname.split('.');
	var res = '';
	for(i=1; i< a.length; i++) res += ("." + a[i]);
	return res+'/';
}

/*
 * Carica la mappa di google
 */
var mapLoaded = false;
function mostraMappa(valore) {
    if (!mapLoaded) {
        var url = "http://";
        if ($('vhost')) url += $('vhost').value;
        else url += 'milano';
        url += eb_suffissoHost+'be/public/inc/iframe.php';
        //console.log(url);
        var params = 'a='+valore;

		$('geocoord').show();
    	getAjax('geocoord',url+'?'+params);
        mapLoaded = true;
    }
    else { 
    	$('geocoord').toggle();
    }
    
    document.location.href = "#mappa";
    
}

/*
 * Chiamata ajax
 */
function getAjax(elemento,url,vis){
	if(!vis)vis='block';
	var req = new Request.HTML({
		url:url, 
		
		onRequest: function() { 
			//meglio di non altrimenti non funzionano le funzioni del toplist
			//$(elemento).set('text', 'Loading...');
		},
    
		onSuccess: function(html) {
			$(elemento).set('text', '');
			$(elemento).adopt(html);
			$(elemento).setStyle("display", vis);
		},
		
		onFailure: function() {
			$(elemento).set('text', 'The request failed.');
		}
	});
	req.send();
}

/*
 * Controllo CodiceFiscale
 */
function ControllaCF(cf) {
    var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return false;
    cf = cf.toUpperCase();
    if( cf.length != 16 )
        return false;
    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for( i = 0; i < 16; i++ ){
        if( validi.indexOf( cf.charAt(i) ) == -1 )
            return false;
    }
    set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
    s = 0;
    for( i = 1; i <= 13; i += 2 )
        s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    for( i = 0; i <= 14; i += 2 )
        s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
        return false;
    return true;
}

/*
 * Controllo PIVA
 */
function ControllaPIVA(pi) {
    if( pi == '' )  return false;
    if( pi.length != 11 )
        return false;
    validi = "0123456789";
    for( i = 0; i < 11; i++ ){
        if( validi.indexOf( pi.charAt(i) ) == -1 )
            return false;
    }
    s = 0;
    for( i = 0; i <= 9; i += 2 )
        s += pi.charCodeAt(i) - '0'.charCodeAt(0);
    for( i = 1; i <= 9; i += 2 ){
        c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
        if( c > 9 )  c = c - 9;
        s += c;
    }
    if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
        return false;
    return true;
}

/*
 * Utilizzata sui link dei banner
 */
function vai(destination,ext) {
	if (ext==1) {
    	w=window.open(destination,'_wingas','width=800,height=640,scrollbars=yes,resizable=yes,menubar=yes,location=yes,toolbar=yes');
        if (window.focus) {w.focus();}
    }
	else window.document.location = destination;

}

/*
 * Utilizzata sul pulsante "elimina annuncio" 
 * e chissà dove...
 */
function confirmAndGo(destination) {
	if (confirm("L'operazione di cancellazione e' irreversibile. \n\nVuoi continuare?")) {
		window.document.location = destination;
		return true;
	}
	
	return false;
}

/*
 * Azioni da applicare sugli elementi form
 */
function actionForm() { 
	
	$$('form input.countertext').addEvent('keyup', function(e) { 
			
	    var maxlength = this.get('maxlength');
	    
	    this.set('value', this.get('value').slice(0,maxlength)); 
	    
	    var myLength = this.get('value').length;
	    
	    var caratteriRimanenti = maxlength-1;    
        $('kwedit').value=1;	    
        
	    if(this.getParent().getElement('p.counter') == null) { 
	    	var elementCounter = new Element('p', {'class':'counter'});
	    	elementCounter.inject(this, 'after'); 
	    } else { 
	    	caratteriRimanenti = maxlength - myLength;
	    }
	    
	    this.getParent().getElement('p.counter').set('html', caratteriRimanenti + ' caratteri rimanenti');

	});	
	
} 

/*
 * Sulle pagine dei servizi
 */
function serviziBanner() { 
	
	//nascondo i blocchi
	var blocchi = $$('div.servizi-content-block div.block');
	
	//menu
	var lastIdOpen = false;
	if(blocchi.length>1) { 
		blocchi.each(function(el,i){ 
			el.setStyle('display','none'); 

			if(el.hasClass('vetrina') && i == 0) { 
				el.setStyle('display','block');
				lastIdOpen = el.getProperty('id');
			}
		});
		
		$$('div.servizi-links a').addEvent('click', function(e) { 
			
			e.stop(); 
			
			$$('div.servizi-links a').each(function(el,i){ 
				el.removeClass('current'); 
			});
			
			this.addClass('current'); 
			
			var myUrl = this.getProperty('href');					
			var myId = myUrl.split('#');
			myId = myId[1];
			
			if(lastIdOpen) { 
				$(lastIdOpen).hide();
			}
			
			$$('div.servizi-info').hide();
			$(myId).show();
			lastIdOpen = myId;
						
	
		});
	}
}

/*
 * Sulla pagina tvspot
 */
function tvspot() { 
	
	
	//nascondo il form
	if($$('div.tvspot-form-container form label.error').length == 0) { 
		$$('div.tvspot-form-container form').hide();
	}

	$$('div.tvspot-form-container a.link-scrivici, div.tvspot-form-container a.link-espandi').addEvent('click', function(e) { 
		e.stop(); 
		$$('div.tvspot-form-container form').toggle();	
		
		if(this.hasClass('link-espandi')) { 
			if(this.get('text')=="Espandi") { 
				this.set('text', 'Chiudi');
			} else { 
				this.set('text', 'Espandi');
			}
		}
		
	});
}

/*
 *  Funzioni di Alert 
 */
function alert_apri_invito(categoria,pos,mode)
{                              
    if(pos=="")
    {
     pos='top';
    }
    else
    {                       
     pos='bottom';
    }             
    if(mode=="AUTH")
    { 
       if(pos=="top")
       {                                                                                      
        pageTracker._trackEvent(categoria, "alertiscrizione", "topalert");
                          
       }
       else
       {                     
        pageTracker._trackEvent(categoria, "alertiscrizione", "bottomalert");
       }
    $('frm_alert_invite_top').submit();
    }
    else
    {
    $('alertsearch-list-top').toggleClass('open');
    }
}                                        

function alert_configura(pos,categoria)
{                       
   if(pos=="")
    {
    pos='top';
    }
   else
    {
    pos='bottom';
    }                                         
    if($('alert_email_top')!=null)
    {           
        if(isEmail($('alert_email_top').value))
        {
           if(pos=='top')
           {                                                                   
            pageTracker._trackEvent(categoria, "alertiscrizione", "topalert");
           }       
         $('frm_alert_invite_top').submit();
        }
        else
        {
        if(isEmail($('alert_email_bottom').value))
            {
                                   
             pageTracker._trackEvent(categoria, "alertiscrizione", "bottomalert");
             $('frm_alert_invite_bottom').submit();
            }
            else
            {
             alert('Inserisci una Email valida!!');
            } 
        }
    }
    else
    {             
        if(isEmail($('alert_email_bottom').value))
        {
           if(pos=='bottom')
           {
            pageTracker._trackEvent(categoria, "alertiscrizione", "bottomalert");
           }
         $('frm_alert_invite_bottom').submit();
        }
        else
        {
        alert('Inserisci una Email valida!!');
        }                                         
    }                         
}                 


function alert_attiva(statoalert,autenticato)
{         
                                          
    if($('kwedit').value==-1)
    {
     $('kwedit').value=0;
    }                             
    var req = new Request({
      method: 'get',
      url:'http://'+bakecaObj.baseurl+'be/main.php?page=ajax_alert&',  
      data: { 'challenge' : $('challenge').value,'kchallenge':$('challenge').value },
      onRequest: function() {  },
      onComplete: function(response) {
      $('err_msg2').set('style','display:none');
       if(response!="1")
        {              
        $('captcha').innerHTML=response;
        $('err_msg2').set('style','display:inline'); 
        $('challenge').set('style','border:2px solid #E26500');
        }
        else                       
        { 
        $('challenge').set('style','');
        alert_attiva_true(statoalert,autenticato);
        }
       }
    }).send();     
    return ;                                
}
               
function alert_attiva_true(statoalert,autenticato)
{                                 
    if($('kwedit').value==-1)
    {
     $('kwedit').value=0;
    }                             

   var err=0;       
   if($('sel_catadre')!=null)
   {
   v_catpadre=$('sel_catpadre').value;          
   $('dv_link_padre').removeClass('error');
   if(v_catpadre=="-1")
     {                             
     err=1                                      
     $('dv_link_padre').set('class','error');
     }
   }                                
                     
   if($('sel_luogo')!=null)
   {
   v_luogo=$('sel_luogo').value;
   $('dv_sel_luogo').removeClass('error');
     if(v_luogo=="-1")
     {    
     err=1    
     $('dv_sel_luogo').set('class','error');
     }
   }
                               
   if($('sel_catpadre')!=null)
   {
   v_catpadre=$('sel_catpadre').value;
   $('dv_link_padre').removeClass('error');
     if(v_catpadre=="-1")
     {    
     err=1    
     $('dv_link_padre').set('class','error');
     }
   }
   if($('sel_cat')!=null)
   {
   v_cat=$('sel_cat').value;     
   $('dv_link_categoria').removeClass('error');
     if(v_cat=="-1")
     {      
     err=1    
     $('dv_link_categoria').set('class','error');
     }
   }
     if(err==1)
     {
     $('err_msg').set('style','display:inline'); 
     }
     else
     {
     $('err_msg').set('style','display:none'); 
       if($('sel_cat')==null)
       {
        alert('Attendi il caricamento della pagina!!');
        return;
       }
       if(autenticato==1)
       {
        pageTracker._trackEvent($('sel_cat').value, "alertattivazione", "miabakeca")
       }
       else
       {
        pageTracker._trackEvent($('sel_cat').value, "alertconfigurazione", "nonregistrato");
       }
          
         if($('cb_privacy')==null)
         {
          $('frmalert').submit();
         return;
         }
         if($('cb_privacy').checked)
         {                         
          $('frmalert').submit();
         }
         else
         {     
          alert('Devi autorizzare il trattamento dei dati personali');
         }
     }
}
                   
var alert_id_luogo_sel=-1;        
var alert_code_cat_padre_sel=-1;
var alert_code_cat_sel=-1;
function alert_caricacategoriepadre(sel_luogo,id_prodotto)
{                                                
                                                               
  url='http://'+bakecaObj.baseurl+'be/main.php';   
  selLuogo=$(sel_luogo);   
  elem=$('dv_link_padre');  
  alert_id_luogo_sel=selLuogo.value;    
  if($('sel_catpadre')!=null)
  {    
  alert_code_cat_padre_sel=$('sel_catpadre').value;         
  }    
   if(selLuogo.value!="-1")
   {                                                
    var req = new Request({
      method: 'get',
      url: url,  
      data: {'current_catpadre':alert_code_cat_padre_sel,'page':'ajax_alert','load':'categoriepadre','id_luogo':selLuogo.value,'id_prodotto':id_prodotto },
      onRequest: function() {  },
      onComplete: function(response) {
      elem.innerHTML=response;       
       if($('sel_catpadre')!=null)
         {    
           if($('sel_catpadre').value!="-1")
            {
             alert_caricacategorie('sel_catpadre',selLuogo.value,id_prodotto);
            }
         }   
         
       }
    }).send();  
   }   
}

                                  
function alert_caricacategorie(selpadre,id_luogo,id_prodotto)
{                                           
 if($('sel_cat')!=null)
  {
  alert_code_cat_sel=$('sel_cat').value;                 
  }
  elem=$('dv_link_categoria');
    var req = new Request({           
      method: 'get',
      url:'http://'+bakecaObj.baseurl+'be/main.php?page=ajax_alert&load=categorie&id_luogo='+id_luogo,  
      data: {'current_cat':alert_code_cat_sel, 'code_link_padre' : $('sel_catpadre').value,'id_luogo':id_luogo },
      onRequest: function() {  },
      onComplete: function(response) {
       elem.innerHTML=response; 
       alert_caricafaccette('sel_cat',id_luogo);    
       }
    }).send();     
}


            
function alert_track_event(codcategoria,azione,altro)
{       
 esi= pageTracker._trackEvent(codcategoria,azione,altro);
  return true;
}
                  
                  
function alert_caricafaccette(selcat,id_luogo)
{                  
  elem=$('dv_faccette');
  if($('sel_cat')!=null)
    {    
    var req = new Request({
      method: 'get',
      url:'http://'+bakecaObj.baseurl+'be/main.php?page=ajax_alert&load=faccette&id_luogo='+id_luogo,  
      data: { 'code_link' : $('sel_cat').value,'id_luogo':id_luogo },
      onRequest: function() {  },
      onComplete: function(response) {
       elem.innerHTML=response; 
       }
    }).send();     
    }
}
            
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function isEmail(string) {
	if (string.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) != -1)
		return 1;
	else
		return 0;
}
            
/*-- leadg */
            
function leadgrichiesta_convalida()
{ 
 var esi=1;
     
     
    $('err_title').set('style','display:none'); 
          
          /*       
    if(!checkFieldCompleted('nome'))
        {
        esi=0;
        }                            
    if(!checkFieldCompleted('cognome'))
        {
        esi=0;
        }                              
    if(!checkFieldCompleted('telefono'))
        {
        esi=0;
        }         
    if(!checkFieldEmail('email'))
        {
        esi=0;
        }
        */
                  
    if(!checkFieldNumeric('prezzomin'))
        {
        esi=0;
        }
    if(!checkFieldNumeric('prezzomax'))
        {
        esi=0;
        }           
    if(!checkFieldCompleted('prezzomin'))
        {
        esi=0;
        }         
                                         
    if(!checkFieldCompleted('prezzomax')) 
        {
        esi=0;
        }         
        
                               
    if(!checkFieldCompleted('sel_regione')) 
        {
        esi=0;
        }         
                                          
    if(!checkFieldCompleted('sel_provincia')) 
        {
        esi=0;
        }         
    if(!checkFieldCompleted('sel_comune')) 
        {
        esi=0;
        } 
                
    if(!checkFieldCompleted('privacy')) 
        {
        esi=0;
        }         
        
 
        
        
        
    if(esi==0)
    {                
    $('err_title').set('style','display:inline'); 
    }
    
    if(esi==1)
    {                                     
    n1=parseFloat(($('prezzomin').value));
    n2=parseFloat(($('prezzomax').value));
    if(n1>n2)
     {
     alert('Correggere i prezzi, i max è inferiore al min');
     hilightError("prezzomin");
     hilightError("prezzomax");
     return false;
     }
     
    }              
                             
    var req = new Request({
      method: 'get',
      async:false,
      url:'http://'+bakecaObj.baseurl+'be/main.php?page=captcha_leadgrichiesta&',  
      data: { 'challenge' : $('challenge').value,'kchallenge':$('challenge').value },
      onRequest: function() {  },
      onComplete: function(response) {               
      $('err_msg2').set('style','display:none');
       if(response!="1")
        {          
        esi=0;
        $('captcha').innerHTML=response;
        $('err_msg2').set('style','display:inline'); 
        $('challenge').set('style','border:2px solid #E26500');
        }
        else                       
        { 
        $('challenge').set('style','');
        
        //leadg_registra();
        }
       }
    }).send();    
                  
    if(esi==1)   
    {
        return true;
    }
    else
    {             
        return false;
    }                                
}
function leadgrichiesta_invia()
{    
  if(leadgrichiesta_convalida())
    {
    alert('valido');
          $('frmleadg').submit();
    }
    else
    {                         
    }
}

                                      
function checkFieldCompleted(fieldname)
{                                     
   if($(fieldname)!=null)
   {                      
   var tagname=$(fieldname).get("tag");
           
                   
   try
   {
   $('err_msg_'+fieldname).set('style','display:none');
   valore=$(fieldname).value;
   $('dv_'+fieldname).removeClass('error');
   }
   catch(e)
   {
   alert('spazio per messaggio di errore indefinito:'+'err_msg_'+fieldname);
   }
   
     if(tagname=='select')
     {
       if(valore.trim()==""||valore.trim()=="-1")
         {                   
         $('dv_'+fieldname).set('class','error');               
         $('err_msg_'+fieldname).set('style','display:inline'); 

         return false;
         }
         else
         {
         return true;
         }
     }
     else
     {                      
         var tp=$(fieldname).get("type");
         if(tp=="checkbox")
         {  
            var chkd;                                  
            chkd=$(fieldname).get("checked");
           // alert(valore);
             if(!chkd)
             {                 
             $('dv_'+fieldname).set('class','error');               
             $('err_msg_'+fieldname).set('style','display:inline'); 
             return false;
             }
             else
             {
             return true;
             }   
         } 
         else
         {     
             if(valore.trim()=="")
             {                 
             $('dv_'+fieldname).set('class','error');               
             $('err_msg_'+fieldname).set('style','display:inline'); 
             return false;
             }
             else
             {
             return true;
             }
         }
     }   
   }
   
   return false
                     
}           
function hilightError(fieldname)
{                                                          
     $('dv_'+fieldname).set('class','error');              
}          

function checkFieldEmail(fieldname)
{                     
   if($(fieldname)!=null)
   {
   $('err_msg_'+fieldname).set('style','display:none');
   valore=$(fieldname).value;
   $('dv_'+fieldname).removeClass('error');
     if(!isEmail(valore.trim()))
     {                                                     
     $('dv_'+fieldname).set('class','error');                  
     $('err_msg_'+fieldname).set('style','display:inline'); 

     return false;
     }
     else
     {
     return true;
     }
   }                  
   return false       
}



function checkFieldNumeric(fieldname)
{                     
   if($(fieldname)!=null)
   {                     
   $('err_msg_'+fieldname).set('style','display:none');
   valore=$(fieldname).value;
   $('dv_'+fieldname).removeClass('error');
     if(!isNumber(valore.trim()))
     {                 
     $('dv_'+fieldname).set('class','error');               
     $('err_msg_'+fieldname).set('style','display:inline'); 

     return false;
     }
     else
     {
     return true;
     }
   }                  
   return false       
}
                 

function displaySelectProvince()
{                
  app="leadgrichiesta";
  elem=$('dv_sel_provincia');
  if($('sel_regione')!=null)
    {                          
    var req = new Request({
      method: 'get',
      url:'http://'+bakecaObj.baseurl+'be/main.php?page=ajaxluogo_'+app+'&load=provincia',  
      data: { 'codicelinkregione' : $('sel_regione').value },
      onRequest: function() {  },
      onComplete: function(response) { 
       elem.innerHTML=response; 
       }
    }).send();     
    }            
}


function displaySelectComuni()
{                              
  app="leadgrichiesta";
  elem=$('dv_sel_comune');            
  if($('sel_provincia')!=null)
    {                          
    var req = new Request({
      method: 'get',
      url:'http://'+bakecaObj.baseurl+'be/main.php?page=ajaxluogo_'+app+'&load=comune',  
      data: { 'codiceprovincia' : $('sel_provincia').value },
      onRequest: function() {  },
      onComplete: function(response) {     
       elem.innerHTML=response; 
       }
    }).send();     
    }            
}


function leadgrichiesta_registra()
{ 
}





            
            
