
function floorInteri(el){ if (!el.value.test(/^[-+]?[0-9]+$/)) { el.errors.push("Inserire un numero intero (positivo o negativo)");   return false; } else {return true;}}
function floorInteriP(el){ if (!el.value.test(/^[+]?[0-9]+$/)) { el.errors.push("Interire un numero intero positivo o zero");   return false; } else {return true;}}
function floorInteriPP(el){ if (!el.value.test(/^[1-9]{1}[0-9]*$/)) { el.errors.push("Inserire un numero intero maggiore di zero");   return false; } else {return true;}}
function floorFloat(el){ if (!el.value.test(/^[-+]?[0-9]*\.?[0-9]+$/)) { el.errors.push("Inserire un numero (positivo o negativo) (usare il carattere punto per i decimali)");   return false; } else {return true;}}
function floorFloatP(el){ if (!el.value.test(/^[+]?[0-9]*\.?[0-9]+$/)) { el.errors.push("Inserire un numero positivo o zero (usare il carattere punto per i decimali)");   return false; } else {return true;}}
function floorFloatPP(el){ if (!el.value.test(/^[+]?(([1-9]{1}[0-9]*\.?[0-9]+)|([0]{1}\.{1}[0-9]+)|([1-9]{1,}))$/)) { el.errors.push("Inserire un numero maggiore di zero (usare il carattere punto per i decimali)");   return false; } else {return true;}}
function floorBool(el){ if (!el.value.test(/^[01]{0,1}$/)) { el.errors.push("Specificare sì o no");   return false; } else {return true;}}
function floorStringhe(el){ if (!el.value.test(/^[a-z0-9èéòàùì.,;:-_\s]+$/)) { el.errors.push("Inserire un testo composto da lettere, numeri, spazi e/o caratteri di punteggiatura");   return false; } else {return true;}}
function floorConferma(el){ if (!el.value.test(/^[1]{1}$/)) { el.errors.push("E' necessario spuntare la casella di conferma");   return false; } else {return true;}}
function floorCategoria(el){ if (!el.value.test(/^[2-9]{1}[0-9]*$/)) { el.errors.push("E' necessario selezionare una categoria");   return false; } else {return true;}}

function number_format(a, b, c, d) {
	if(a) {
		a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b); e = a + '';f = e.split('.');
	 	if (!f[0]) {f[0] = '0'; }
	 	if (!f[1]) {f[1] = '';}
	 	if (f[1].length < b) {g = f[1]; for (i=f[1].length + 1; i <= b; i++) { g += '0'; } f[1] = g;}
	 	if(d != '' && f[0].length > 3) {h = f[0]; f[0] = '';for(j = 3; j < h.length; j+=3) { i = h.slice(h.length - j, h.length - j + 3); f[0] = d + i +  f[0] + '';}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];}
		c = (b <= 0) ? '' : c;
		return f[0] + c + f[1];
	}
	else return '0.00';
}

function prezzo_immagine(div,totale) {
	var html="";var cifra;
	for(var i=0;i<totale.length;i++) {
		if(totale[i]==".") cifra="dp";
		else cifra=totale[i]+"p";
		html=html+"<img src='http://www.ciaogo.com/sito/img/numeri/"+cifra+"p.png' title='' alt='' />";
	}
	$(div).set('html',html);	
}	

function redirect(url) { 
	location.href = url;
} 
function preferiti(){
	if (window.sidebar) window.sidebar.addPanel(document.title, location.href,'');
	else if( window.external )   window.external.AddFavorite( location.href, document.title);
	return false;
}

function breadcrumb_elimina(id_bread) {
	var p=$(id_bread).getAllNext("span.breadcrumb_link");
	if(p)p.each(function(el) {el.destroy()});

}
function breadcrumb_aggiungi(nome,tipo,id_cat,id_geo) {
	
	if(!$('breadcrumb_'+id_geo)){
		$('breadcrumb_right').set('html',$('breadcrumb_right').get('html')+"<span id='breadcrumb_"+id_geo+"' class='breadcrumb_link'><input type='hidden'  value='"+tipo+"_"+id_cat+"_"+id_geo+"'/><img src='http://www.ciaogo.com/sito/img/f1.gif' title='' alt='' /><a href='#' title=''>"+nome+"</a>&nbsp;&nbsp;&nbsp;</span>");
		$$('.breadcrumb_link').each(function(el) {
			el.addEvent('click',function(evento) {
				evento.preventDefault();
				breadcrumb_elimina(el.get('id'));
				var links=el.getElement('input').get('value').split('_');
				crea_ammap(links[0],links[1],links[2]);
			});
		});
	}

}

var aperti=new Array();
function div_prenota_chiudi(id) {
	if(!aperti[id])$(id).setStyle('display','none');	
}
var periodo_apri=false;
var scrolla_to=false;
function vacanze_parser() {
	var per_sel=false;
	var mese_sel=false;
	//selettori periodi vacanze
	var cliccato=false; 
			
	$$('.vacanza_menu_mese').addEvent('mouseover',function() {
		this.getElement('.vacanza_prenota_mese').setStyle('background-position','center left');
		this.getElement('.vacanza_prenota_date').setStyle('display','block');
	});
	$$('.vacanza_menu_mese').addEvent('mouseout',function() {
		if(!cliccato) {
			if(mese_sel!=this.getElement('.vacanza_prenota_mese'))this.getElement('.vacanza_prenota_mese').setStyle('background-position','top left');
			else this.getElement('.vacanza_prenota_mese').setStyle('background-position','bottom left');
			this.getElement('.vacanza_prenota_date').setStyle('display','none');
		}
		cliccato=false;
	});
	
	$$('.vacanza_partenza').addEvent('click',function (evento) {
		cliccato=true; //segnala che è stato cliccato
		this.getParent().setStyle('display','none'); //nasconta il bloccheto del mese
		if(mese_sel)mese_sel.setStyle('background-position','top left'); //.. ne cambia lo sfondo
		mese_sel=this.getParent().getParent().getElement('.vacanza_prenota_mese');
		mese_sel.setStyle('background-position','bottom left');   //aggiorna l'ultimo aperto
		//interroga via ajax e riceve il modulo del periodo
		
		var ids=this.get('id').split('/');
		id=ids[0]+'_dettaglio';
		var id_per=ids[1]; //recupera id del periodo
		$(id).set('html',"<img src='http://www.ciaogo.com/sito/img/loading.gif' title='' alt='' />");
		var req = new Request.HTML({url:'http://www.ciaogo.com/ajax/periodo/'+this.get('id')+'.html', 
			onSuccess: function(tree,el,html) {
				$(id).set('html',html); //fa apparire il listino
				var formula=$(id).getElement('.formula').get('value');
				//se è un albergo
				if(formula=="alb") {
					var vecchio_trat=false;
					//recupera iscrizione, assicurazione e passeggeri minimi e massimi consentiti
					var iscrizione=$('iscrizione_'+id_per).get('value');
					//var assicurazione=$('assicurazione_'+id_per).get('value');
					var per_max=$('per_max_'+id_per).get('value');
					var per_min=$('per_min_'+id_per).get('value');
					var dispo_alb=$('dispo_alb_'+id_per).get('value').split('_');
					$(id).getElements('.periodo_listino').addEvent('change',function(evento) {
						var persone=0;
						var trattamento=$('trattamento_'+id_per).get('value');
						//fa apperire il blocco dei prezzi del trattamento scelto
						if(vecchio_trat) $(vecchio_trat).setStyle('display','none'); //nasconde il vecchio
						$(trattamento+'_'+id_per).setStyle('display','block');
						vecchio_trat=$(trattamento+'_'+id_per);
						//ora deve calcolare i totali
						var lista=$(id).getElements('.periodo_listino');
						var definitivo=0; //sommatore del prezzo definitivo
						var adulti=0; //deve ricordarsi il numero di adulti
						var errore=false; //se inizializzato viene stampato a video
						//var persone_ar;
						lista.each(function(persona,i) {
							//se non è il trattamentoi
							if(i>0) {
								var chi=persona.getProperty('name');
								var num=persona.get('value');
								//se siamo in adulti si ricorda quanti sono
								if(i==1)adulti=num*1;
								//effettua i controlli sui minimi e massimi dei viaggiatori
								persone=persone+num*1;				
								var prezzo=$(trattamento+'_'+chi+'_'+id_per).get('value');
								var totale=num*prezzo;
								definitivo=definitivo+totale*1;
								$('totale_'+chi+'_'+id_per).set('value',number_format(totale,2,".",""));
							}
						});				
						if(persone>per_max || persone<per_min) {errore="Attenzione, indicare un numero di partecipanti compreso tra "+per_min+" e "+per_max+".";}
						//alert(dispo_alb[persone]);
						if(dispo_alb[persone]=="0") errore="Non ci sono posti disponibili per questa combinazione!";
						if(!errore) {
							$('prenota-'+id_per+'-button').setStyle('display','inline');
							definitivo=(definitivo*1)+(iscrizione*1*persone);
							prezzo_immagine('definitivo_'+id_per,number_format(definitivo,2,".",""));
							$('prenota-'+id_per+'-pp').set('value',definitivo);
							$('prenota-'+id_per+'-c').set('value',dispo_alb[persone]+"_"+persone+"_0_0_0_0");
							$('prenota-'+id_per+'-p').set('value',id_per);
						}
						else {
							$('prenota-'+id_per+'-button').setStyle('display','none');
							$('definitivo_'+id_per).set("html","<span class='testo_rosso testo10'>Esaurito</span>");
							//mostra a video l'errore
							alert(errore);
							//ripristina i partecipanti
							lista.each(function(persona,i) {
								//se non è il trattamentoi
								if(i==0);
								else if(i==1)persona.set('value',2);
								else persona.set('value','0');								 
							});
							//lista[0].fireEvent('change');							
						}
						
					});
					$(id).getElement('.periodo_listino').fireEvent('change');
				}
				if(formula=="ap") {
					var vecchio_trat=false;
					//recupera iscrizione, assicurazione e passeggeri minimi e massimi consentiti
					var iscrizione=$('iscrizione_'+id_per).get('value');
					$(id).getElements('.sistemazione').addEvent('click',function(evento) {
						if(this.checked) {
							var prendi_id=this.get('id').split("_");
							var persone=$('persone_'+prendi_id[1]+'_'+prendi_id[2]).get('value');
							if (persone>3) persone=3;
							var prezzo_ap=$('prezzo_'+prendi_id[1]+'_'+prendi_id[2]).get('value');
							definitivo=(prezzo_ap*1)+(iscrizione*1*persone);
							prezzo_immagine('definitivo_'+id_per,number_format(definitivo,2,".",""));
							//setta i dati nel form
							$('prenota-'+id_per+'-pp').set('value',definitivo);
							$('prenota-'+id_per+'-c').set('value',$('dispo_'+prendi_id[1]+'_'+prendi_id[2]).get('value')+'_'+persone+'_0_0_0_0');
							$('prenota-'+id_per+'-p').set('value',id_per);
						}
					});
					$(id).getElement('.sistemazione').checked=true;
					$(id).getElement('.sistemazione').fireEvent('click');
				}
			},
			onFailure: function(error) {
			}
		}).post();		
	});
	if(periodo_apri) {if($(periodo_apri)) $(periodo_apri).fireEvent('click');periodo_apri=false;}
	if(scrolla_to) {if($(scrolla_to)){var scrolla = new Fx.Scroll($(document.body)).toElement(scrolla_to);scrolla_to=false;}}
	
 
}

function crea_ammap(tipo,id_cat,id_geo) {		
	var so = new SWFObject("http://www.ciaogo.com/sito/swf/ammap.swf", "mappa", "691", "454", "8", "#FFFFFF");
	so.addVariable("path", "http://www.ciaogo.com/sito/swf/");
	so.addVariable("data_file", escape("http://www.ciaogo.com/ammap/data/"+tipo+"/"+id_cat+"/"+id_geo+".html"));
	so.addVariable("settings_file", escape("http://www.ciaogo.com/sito/swf/ammap_settings.xml?l=it&stile=offerte"));		
	so.addVariable("preloader_color", "#999999");
	so.addParam("wmode", "transparent");  
	so.write("mappa");
	if($('mappa_sin') && $('mappa_sin_loading')) {
		$('mappa_sin').set('html',"<br/><br/><br/><br/><br/><br/><img src='http://www.ciaogo.com/sito/img/loading.gif' title='' alt='' />");
		var req = new Request.HTML({url:'http://www.ciaogo.com/ajax/vetrina_sin_ammap/'+tipo+'/'+id_cat+'/'+id_geo+'.html', 
			onSuccess: function(tree,el,html) {
				$('mappa_sin').set('html',html);
				
				$$('.vetrina_sin_consiglio_blocco').addEvent('mouseover',function() {
					this.setStyle('background','#f1f1f1');
				});
				$$('.vetrina_sin_consiglio_blocco').addEvent('mouseout',function() {
					this.setStyle('background','#fff');
				});
			},
			onFailure: function(error) {
			}
		}).post();
	}		
}



var map=null;
var geocoder=null;
var bounds=null;
var so=null;
var points=new Array();
var i_point=0;
var icons = new Array();
var viaggio_aperto=false;
var viaggio_calendario=false;
var id_ric=false;
var highlightCircle=false;
var base_lat=0;
var base_lon=0;



function crea_icona(nome)  {
	var icon = new GIcon();
	icon.image = "http://www.ciaogo.com/sito/img/gmap/icona_"+nome+".png";icon.shadow = "http://www.ciaogo.com/sito/img/gmap/ombra_"+nome+".png";
	icon.iconSize = new GSize(32, 32);icon.shadowSize = new GSize(56, 32);	icon.iconAnchor = new GPoint(16, 32);	icon.infoWindowAnchor = new GPoint(16, 0);
	icons[nome]=icon;
}

function crea_gmap() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("mappa"));
	geocoder = new GClientGeocoder();
    map.setCenter(new GLatLng(41.77131167976406, 12.54638671875), 5);           
	map.addControl(new GLargeMapControl()); 						
	map.setMapType(G_HYBRID_MAP);         
	map.addControl(new GMapTypeControl());

	map.addControl(new GScaleControl());
	map.disableScrollWheelZoom(); 					
	bounds = new GLatLngBounds();
	
	
	crea_icona("hotel1");
	crea_icona("hotel2");
	crea_icona("hotel3");
	crea_icona("hotel4");
	crea_icona("hotel5");
	crea_icona("centro");
	crea_icona("aeroporto");
	crea_icona("vacanza");
	crea_icona("spiaggia");
	crea_icona("pi");
	
	$('mappa_hover').setStyles({'display':'block'}); 


  }
}
function gmap_centra(map) {
	if(points.length>1) {
		var zoomLevel = map.getBoundsZoomLevel(bounds);
		map.setZoom(zoomLevel);
		var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
		var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
		map.setCenter(new GLatLng(clat, clng));
		var adjust = Math.abs(bounds.getNorthEast().lng() - bounds.getSouthWest().lng()) > 180;
		if(adjust) clng += 180;
		var newBounds = map.getBounds();
		for(i=0;i<points.length;i++) {
		   if(!(newBounds.contains(points[i]))) {
		      clng -= 180;
		      map.setCenter(new GLatLng(clat, clng));
		      break;
		   }
		}
	}
	else {
		var punto=points[0];
		if(punto) {
			map.setCenter(new GLatLng(punto.lat(), punto.lng()));
			map.setZoom(12);
		}
		 
	}
}

function gmap_highlight(i){
	if(points[i]) {
		var markerPoint = points[i]; 	
		var polyPoints = Array(); 	
		if (highlightCircle) {
		map.removeOverlay(highlightCircle);
		}	
		var mapNormalProj = G_NORMAL_MAP.getProjection();
		var mapZoom = map.getZoom();
		var clickedPixel = mapNormalProj.fromLatLngToPixel(markerPoint, mapZoom);	
		var polySmallRadius = 20;	
		var polyNumSides = 20;
		var polySideLength = 18;
		
		for (var a = 0; a<(polyNumSides+1); a++) {
		var aRad = polySideLength*a*(Math.PI/180);
		var polyRadius = polySmallRadius; 
		var pixelX = clickedPixel.x + polyRadius * Math.cos(aRad);
		var pixelY = clickedPixel.y + polyRadius * Math.sin(aRad);
		var polyPixel = new GPoint(pixelX,pixelY);
		var polyPoint = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
		polyPoints.push(polyPoint);
		} 
		highlightCircle = new GPolygon(polyPoints,"#000000",2,0.0,"#00214d",.5);
		map.addOverlay(highlightCircle);
	}
}




function gmap_marker(point,id,viaggio) {
	
	var icona=viaggio.getElement('#icona_'+id).get('value');
	var marker=new GMarker(point,icons['hotel1']);  
	//new GMarker(point,icons[icon]);				
	var html=$('viaggio_tip_'+id).get('html');
	GEvent.addListener(marker,"mouseover",function(){ Tip(html); });
	GEvent.addListener(marker,"mouseout",function(){ UnTip(); });
	GEvent.addListener(marker,"click",function(){viaggio_op('dettaglio',id,true); }); 	
	return marker;
}
var viaggi={}; 
function viaggi_carica(tipo,id_geo,id_ricerca,pag,query) {
	$('elenco_viaggi').set("html","<br/><br/><img src='http://www.ciaogo.com/sito/img/loading.gif' title='' alt='' />");
	id_ric=id_ricerca;
	$('mappa_hover').setStyles({'display':'block'}); 
	var req = new Request.HTML({url:'http://www.ciaogo.com/ajax/viaggi/'+tipo+'/'+id_geo+'/'+id_ricerca+'/'+pag+'.html'+query, 
		onSuccess: function(tree,el,html) {
			$('elenco_viaggi').set('html',html);$$('.viaggi_menu_pag').each(function(link) {
				link.addEvent('click',function(evento) {
					evento.preventDefault();
					viaggi_carica(tipo,id_geo,id_ricerca,this.get('html'),query);
				});
			});
			$$('.tip_prenota').each(function (item, index) {
				var content = item.get('title').split('::');  
				item.store('tip:title', content[0]);  
				item.store('tip:text', content[1]);  
			}); 
			var prenotaz = new Tips('.tip_prenota'); 			
			viaggi_parser();
			vacanze_parser();

		},
		onFailure: function(error) {
		}
	}).post();
	
}
function viaggio_menu(azione,id) {
	//nasconde la vecchia linguetta del menu
	if($('viaggio_'+id).getElement('.v_link_sel')) {
		var ccc=$('viaggio_'+id).getElement('.v_link_sel');
		ccc.removeClass('v_link_sel');
		ccc.addClass('v_link');
	}
	//e la mostra sul nuovo link
	var ccc=$('viaggio_'+id).getElement('.v_'+azione).getParent();
	ccc.removeClass('v_link');
	ccc.addClass('v_link_sel');
}
function viaggio_op(azione,id,scroll) {
	if($('viaggio_dettaglio_'+id)) {
		//se c'era gia un viaggio aperto lo chiude
		if(viaggio_aperto){
			//$('viaggio_'+viaggio_aperto).setStyles({'height':'100px','border':'1px solid #cdcdcd'});
			$('viaggio_'+viaggio_aperto).getElement('.viaggio_dettaglio').setStyle('display','none');
			if($('viaggio_prenota_'+viaggio_aperto) && $('viaggio_prenota_'+viaggio_aperto).getStyle('display')=='none') {
				$('viaggio_prenota_'+viaggio_aperto).setStyle('display','inline');
				viaggio_menu('prenota',viaggio_aperto);
			}
		}
		//alert($('viaggio_prenota_'+id).getStyle('display'));
		if(azione!='prenota' && $('viaggio_prenota_'+id) && ($('viaggio_prenota_'+id).getStyle('display')=='block' || $('viaggio_prenota_'+id).getStyle('display')=='inline')) $('viaggio_prenota_'+id).setStyle('display','none');
		viaggio_aperto=id;  
		if(scroll) {
			var pos=$('viaggio_'+id).getPosition();
			var myFx = new Fx.Scroll(window).start(pos['x'],pos['y']-15);
		}
		viaggio_menu(azione,id);
		if(azione=='prenota') {
			$('viaggio_prenota_'+id).setStyle('display','inline');
			$('viaggio_dettaglio_'+id).setStyle('display','none');
		}
		else {
			$('viaggio_'+id).setStyles({'height':'auto','border':'1px dotted #000'});
			$('viaggio_dettaglio_'+id).set("html","<br/><img src='http://www.ciaogo.com/sito/img/loading.gif' title='' alt='' /><br/><br/>");
			$('viaggio_dettaglio_'+id).setStyle('display','inline');
			var req = new Request.HTML({url:'http://www.ciaogo.com/ajax/viaggio/'+azione+'/'+id+'/'+id_ric+'/1.html', 
				onSuccess: function(tree,el,html,js) {
					if(azione=='dettaglio') {
						$('viaggio_dettaglio_'+id).set('html',html);
						//mette in slimbox le immagini
						$('viaggio_dettaglio_'+id).getElements('a.slim').slimbox({}, null, function(el) {
							return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
						});
							
						//attiva il calendario			
						periodi_date={};
						periodi_date['f_hotel_data_in_'+id] = "d-m-Y";
						periodi_date['f_hotel_data_out_'+id] = "d-m-Y";
						//viaggio_calendario=new Calendar(periodi_date,{ pad: 1,navigation:1,direction:1,days:new Array('D','L','M','M','G','V','S'),months:new Array('Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'),offset:1});
					}
					else if (azione=='mappa') {
						$('viaggio_dettaglio_'+id).set('html',html);
					    eval(js);
					}
			
				},
				onFailure: function(error) {
				}
			}).post();
		}
	}
}
function viaggi_parser() {					
	map.clearOverlays(); 					
	bounds = new GLatLngBounds();
//	points=new Array();
	i_point=0; 
	viaggi=$$('.viaggio');
	viaggi.each(function(viaggio,ii) {
		var ids=viaggio.get('id').split('_');
		var id=ids[1];
		var coord=$('coord_'+id).get('value').split('::'); 
		if(coord[0]!="" && coord[1]!="" ) {
			//se è il primo punto setta due coordinate di base per centrare la mappa nel caso in cui ci sia solo un punto in questa destinazione
			var point= new GLatLng(coord[0],coord[1]);
			bounds.extend(point); 
			points[i_point]=point; 
			i_point++;
			var marker=gmap_marker(point,id,viaggio);
			map.addOverlay(marker); 
		}
		viaggio.getElement('.v_mappa').addEvent('click',function(evento) { 
			//var myFx = new Fx.Scroll(window).toElement('mappa');
			evento.preventDefault();
			//gmap_highlight(ii);
			viaggio_op('mappa',id,true);
			
		});
		viaggio.getElement('.v_dettaglio').addEvent('click',function(evento) {
			evento.preventDefault();
			viaggio_op('dettaglio',id,true);
		});
		viaggio.getElement('.v_prenota').addEvent('click',function(evento) {
			evento.preventDefault();
			viaggio_op('prenota',id,true);
		});
		viaggio.addEvent('mouseover',function(){this.setStyle('border','1px dashed #000');});
		viaggio.addEvent('mouseout',function(){if(id!=viaggio_aperto) this.setStyle('border','1px solid #cdcdcd');});
		      
	});  
	gmap_centra(map);
	$('mappa_hover').setStyles({'display':'none'});
}


//risultati intabellati delle vacanze
function risultati_vacanze(mese,anno,area) {
	$('risultati_vacanza').set('html',"<img src='http://www.ciaogo.com/sito/img/loading.gif' title='' alt='' />");
	var req = new Request.HTML({url:'http://www.ciaogo.com/ajax/vacanze/'+anno+'/'+mese+'.html', 
		onSuccess: function(tree,el,html) {
			$('risultati_vacanza').set('html',html);
			//mette in slimbox le immagini
			$('risultati_vacanza').getElements('a.slim2').slimbox({}, null, function(el) {
				return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
			});
			$$('.v_f_filtro').each(function(filtro) {
				filtro.addEvent('mouseover',function () {this.setStyles({'text-decoration':'underline','color':'#0164c1'});});
				filtro.addEvent('mouseout',function () {this.setStyles({'text-decoration':'none','color':'#000'});});
				filtro.addEvent('click',function () {
					var classes=this.getProperty('class').split(" ");
					var classe=classes[1];
						var tipos=classe.split("_");
						var tipo=tipos[0];
					if(tipos[1]=='filtro-tutti') {$$('.'+tipo+'_sfondo').removeClass(tipo+'_sfondo');}
					else {$$('.'+tipo+'_sfondo').removeClass(tipo+'_sfondo');$$('.'+classe).addClass(tipo+'_sfondo');}
					
				});
			});		        
			$$('.slim2').each(function (item, index) {
				var content = item.get('title');  
				item.store('tip:title', "");  
				item.store('tip:text', content);  
			}); 
			var tipz = new Tips('.slim2',{fixed:true,className:'tip_mini'});
			if(area && $('area_'+area)) {
				var myElement = $(document.body);
				var myFx = new Fx.Scroll(myElement).toElement($('area_'+area));
			}

		},
		onFailure: function(error) {
		}
	}).post();		
}

window.addEvent('domready', function() {

	//CALENDARI
    var date=new Array();
    $$('.data_init').each(function(data) {
        var id=data.get('id');
        //se il value dell'input non è vuoto inizializza la data
        if($(id).get('value')) var inizia=[$(id).get('value').substr(6,4),$(id).get('value').substr(3,2)-1,$(id).get('value').substr(0,2)];
        else {
            var ora= new Date();
            var inizia=false;
        }
        //se l'imput ha la classe da_ora o a_ora cambia le date minime e massime
        var adesso= new Date();
        var ora=[adesso.getFullYear(),adesso.getMonth(),adesso.getDate()]
        if($(id).hasClass('a_ora')) var d_to=ora;
        if($(id).hasClass('da_ora')) var d_from=ora;
        var hoy = new Date();
        var salidaFrom = new Date(hoy.getFullYear(),hoy.getMonth(),hoy.getDate()+7);
        salidaFrom = [salidaFrom.getFullYear(),salidaFrom.getMonth(),salidaFrom.getDate()];
        date[id]=$(id).datePicker({
            klass: "datePicker",
            format: '%d-%m-%Y',
            from: d_from,
            to:d_to,
            setInitial: true,
            initial: inizia,
            days: ["Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato"],
            draggable: true,
            position: {x:"right",y:"top"},
            offset: {x:22,y:0},
            updateElement:true,
            firstday: 1,
            onUpdate: function(){
                if($(id).get('rel')) {
                    var legato=$(id).get('rel');
                    //$(legato).set('value')
                    //recupera la prima data
                    var valore=$(id).get('value');
                    var data_1= new Date();
                    data_1.set('date',valore.substr(0,2));
                    data_1.set('month',valore.substr(3,2)-1);
                    data_1.set('year',valore.substr(6,4));
                    //recupera la seconda data
                    var valore=$(legato).get('value');
                    var data_2= new Date();
                    data_2.set('date',valore.substr(0,2));
                    data_2.set('month',valore.substr(3,2)-1);
                    data_2.set('year',valore.substr(6,4));
                    //alert(data_1.diff(data_2));
                    var giorno_dopo=data_1.clone();
                    giorno_dopo.increment('day',1);
                    if(data_1.diff(data_2)<=0) {
                        //se il datepicker del giorno dopo è gia stato inizializzato lo modifica
                        if(date[legato]){
                            date[legato].options.from=[giorno_dopo.get('year'),giorno_dopo.get('month'),giorno_dopo.get('date')];
                            date[legato].setFullDate(giorno_dopo.get('year'),giorno_dopo.get('month'),giorno_dopo.get('date'));
                            date[legato].update();
                        }
                        //altrimenti aggiorna semplicemente il value dell'input in attesa che il datepicker venga creato
                        else {
                            var risultato=giorno_dopo.format("%d-%m-%Y");
                            $(legato).set('value',risultato);
                        }
                    }
                    //aggiorna la data minima della seconda data
                    if(date[legato]){
                        date[legato].options.from=[giorno_dopo.get('year'),giorno_dopo.get('month'),giorno_dopo.get('date')];
                        date[legato].update();
                    }
                }
            }
        },"click");
        if( $(id).getNext('img'))$(id).getNext('img .ico_calendario').addEvent('click',function(evento) {date[id].show();});
       
    });


	//eventuale link di accesso
	if($('accedi')) {
		$('accedi_box').setStyle('opacity','0');
		$('accedi_box').setStyle('display','block');
		$('accedi').addEvent('click',function(evento) {
			evento.preventDefault();
			$('accedi_box').fade(1);
		});
	}
	
	//setta lo stile del menu
	if($('menu_offerte')) $('menu_offerte').addClass('sel');
	
	//rollover su menu
	$('ciaogo_menu').getElement('ul').getElements('li').each(function (item) {
		if(!item.hasClass('sel')) {
			item.addEvent('mouseover',function(evento) {
				var tipo_ar=this.get('id').split('_');
				var tipo=tipo_ar[1];
				this.setStyle('background-position','0px 100px');
			});
			item.addEvent('mouseout',function(evento) {
				var tipo_ar=this.get('id').split('_');
				var tipo=tipo_ar[1];
				this.setStyle('background-position','bottom');
			});
		}
	});
	
	if($('ricerca_top')) {
		var stile_ricerca="offerte";
		if(!$('ricerca_'+stile_ricerca)) stile_ricerca="hotel";
		$('ricerca_'+stile_ricerca).addClass('ricerca_menu_voce_sel');
		$('ricerca_in_'+stile_ricerca).setStyles({'opacity':0,'display':'block'});
		$('ricerca_in_'+stile_ricerca).fade(1);
		var ricerca_ultimo=stile_ricerca;
		$$('.ricerca_menu_voce').each(function(voce,i) {
			//alert(i);
			if(i!=0) {
				voce.addEvent('click',function(evento) {
					var ids=this.get('id').split('_');
					var id=ids[1];
					$('ricerca_'+ricerca_ultimo).removeClass('ricerca_menu_voce_sel');
					$('ricerca_'+ricerca_ultimo).addClass('ricerca_menu_voce');
					$('ricerca_in_'+ricerca_ultimo).setStyle('display','none');
					$('ricerca_in_'+id).setStyles({'opacity':0,'display':'block'});
					$('ricerca_in_'+id).fade(1);
					$('ricerca_'+id).addClass('ricerca_menu_voce_sel');
					ricerca_ultimo=id;
					
				});
			}
		});
	}
	//evetuale autompletere per ricerca localita
	var inputLoc = $('ricerca_localita');
	if(inputLoc) {
		new Autocompleter.Request.HTML(inputLoc, 'http://www.ciaogo.com/ajax/localita.html', {
			'indicatorClass': 'autocompleter-loading',
			'injectChoice': function(choice) {
				// choice is one <li> element
				var text = choice.getFirst();
				if(text) {
				
					// the first element in this <li> is the <span> with the text
					var value = choice.get('value');
					//alert(value);
					//$('f_id_geo').set('value',value); 
					var text = choice.getElement('span');
					var id = choice.getElement('input').get('value');
					var value = text.innerHTML;
					value.replace("<b>","");
					value.replace("</b>","");
					// inputValue saves value of the element for later selection
					choice.inputValue = value;
					choice.id= id;
					// overrides the html with the marked query value (wrapped in a <span>)
					//var valore=this.markQueryValue(value);
					text.set('html', this.markQueryValue(value));
					// add the mouse events to the <li> element
					this.addChoiceEvents(choice);
				}
			}
		});
	}
	
	//eventuali calendar per ricerca
	calendari={};
	var i_cal=0;			
	if($('f_hotel_data_in')) {
		periodi_date={};
		periodi_date['f_hotel_data_in'] = "d-m-Y";
		periodi_date['f_hotel_data_out'] = "d-m-Y";
		//calendari[i_cal]=new Calendar(periodi_date,{ pad: 1,navigation:1,direction:1,days:new Array('D','L','M','M','G','V','S'),months:new Array('Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'),offset:1});
		periodi_date={};
		periodi_date['f_vacanza_data_in'] = "d-m-Y";
		periodi_date['f_vacanza_data_out'] = "d-m-Y";
		//calendari[i_cal]=new Calendar(periodi_date,{ pad: 1,navigation:1,direction:1,days:new Array('D','L','M','M','G','V','S'),months:new Array('Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'),offset:1});
	} 
	

	//rollover sui bottoni di submit
	var bottoni_submit=$$('.buttonSubmit');
	bottoni_submit.each(function (item, index) {
		item.addEvent('mouseover', function() {
			item.setProperty('class','buttonSubmitHovered');
		});		
		item.addEvent('mouseout', function() {
			item.setProperty('class','buttonSubmit');
		});		
	});
	
	//tooltip del sitovar
	            
	$$('.tooltip').each(function (item, index) {
		var content = item.get('title').split('::');  
		item.store('tip:title', content[0]);  
		item.store('tip:text', content[1]);  
	}); 
	var tipz = new Tips('.tooltip');
	


	 
});



function form_radio(form,name,valore,base) {
	var trovato=false;
	$(form).getElements('input').each(function(item, index){
		if(item.getProperty('name')==name) {
			if(item.getProperty('value')==base) radio_base=item;
			if(item.getProperty('value')==valore) {item.setProperty('checked','checked');trovato=true;}
		}
	});
	if(!trovato) {
		radio_base.setProperty('checked','checked');
	}
}
function form_select(id,valore) {
	if($(id)) {
		$(id).getElements('option').each(function(item, index){
			if(item.getProperty('value')==valore) {
				item.setProperty('selected','selected');
			}
			
		});
	}
}

function form_check(id,valore) {
	if($(id) && valore!="") $(id).setProperty('checked','checked');
}

function form_select_multiple(id,valore) {
	if($(id) && valore!='') {
		valori=valore.split(",");
		$(id).getElements('option').each(function(item, index){
			if(valori.indexOf(item.getProperty('value'))!=-1) {
				item.setProperty('selected','selected');
			}
			
		});
	}
}