/**
 * @class ch.exmachina.bravofly.pricefinderSearch
 * @author nicola
 */
if(!ch){
	var ch = {};
}
if(!ch.exmachina){
	ch.exmachina = {};
}
if(!ch.exmachina.bravofly){
	ch.exmachina.bravofly = {};
}
/*
http://www.bravofly.com/airports/servlet/Autofilter?key=mi%27%20or%201%20%3D%201%20--&type=dep&language=en&limit=15&routeFilter=
*/
/**
 * @namespace ch.exmachina.bravofly.pricefinderSearch
 * @description Oggetto principale
 */
ch.exmachina.bravofly.pricefinderSearch = {
	/**
	 * @private
	 * @type {Object}
	 * @description Oggetto contenente le fasce di giorni
	 */
	_distanceHash: {
			1: {
				start: 1,
				end: 5
			},
			6: {
				start: 6,
				end: 12
			},
			13: {
				start: 13,
				end: 19
			},
			20: {
				start: 20,
				end: 26
			}
		},
	/**
	 * @private
	 * @type {String}
	 * @description Url di completamento per le aree geografiche
	 */
	 _geoCompleteUrl: "",
	/**
	 * @private
	 * @type {String}
	 * @description Url di completamento per gli aeroporti
	 */
	_airportCompleteUrl: "",
	/**
	 * @private
	 * @type {String}
	 * @description Url che fornisce i dati sulla raggiungibilita' oraria
	 */
	_airportReachabilityUrl: "",
	/**
	 * @private
	 * @type {String}
	 * @description Lingua corrente dell'applicazione
	 */
	_currentLanguage: "EN",
	/**
	 * @private
	 * @type {Boolean}
	 * @description Stato della visibilita' dell'oggetto che controlla la distanza chilometrica
	 */
	_isKnobVisible: true,
	/**
	 * @private
	 * @type {Array}
	 * @description Messaggi localizzati relativi ai calendari
	 */
	_calMessages: [],
	/**
	 * @type {Number}
	 * @description Numero minimo di mesi selezionabili
	 */
	minSelectableMonths: 1,
	/**
	 * @type {Number}
	 * @description Numero massimo di mesi selezionabili
	 */
	maxSelectableMonths: 5,
	/**
	 * @type {Object}
	 * @description Oggetto che contiene la manopola indicante la distanza oraria
	 */
	knob: null,
	/**
	 * @description Per ora restituisce solo una stringa riportante il tipo, modificare per avere informazioni piu'
	 * utili in debug
	 * @returns {String}
	 */
	toString: function(){
		return "[ch.exmachina.bravofly.pricefinderSearch]";
	},
	/**
	 * @type {Object}
	 * @description Utilita' per ottenere html non escaped; funziona per casi semplici, alcuni caratteri non vengono
	 * trattati correttamente, usare modaratamente
	 */
	utils: {
		_node: document.createElement("div"),
		unescapeHTML: function(/**String*/s){
			ch.exmachina.bravofly.pricefinderSearch.utils._node.innerHTML = s;
			return ch.exmachina.bravofly.pricefinderSearch.utils._node.innerText || s.unescapeHTML();
		}
	},
	/**
	 * @type {Object}
	 * @description Contiene l'effetto pulseBg
	 */
	effects: {
		pulseBg: function(/** String */nodeId, count){
			var bgColor = (count % 2) ? "#ff9999" : "#ffffff";
			var callback = arguments.callee;
			new Effect.Morph(nodeId,{
				style: {
					background: bgColor
				},
				duration: 0.7,
				afterFinishInternal: function(){
					if(count == 0){ 
						$(nodeId).style.background = "";
						return; 
					}else{
						count--;
						callback(nodeId, count);
					}
				}
			});
		}
	},
	/* members */
	/* groups, new implementation */
	/**
	 * @type {Object}
	 * @description Gruppo di campi di partenza legati alla ricerca per distanza oraria
	 */
	departureKnobGroup: {},
	/**
	 * @type {Object}
	 * @description Gruppo di campi di partenza legati alla ricerca per aeroporti
	 */
	departureAirportsGroup: {},
	/**
	 * @type {Object}
	 * @description Gruppo di campi di partenza legati alle ricerca per aree geografiche
	 */
	departureAreaGroup: {},
	/**
	 * @type {Object}
	 * @description Gruppo di campi di ritorno legati alle ricerca per aeroporti
	 */
	returnAirGroup: {},
	/**
	 * @type {Object}
	 * @description Gruppo di campi di ritorno legati alle ricerca per aree geografiche
	 */
	returnAreaGroup: {},
	/* counters */
	/**
	 * @type {Number}
	 * @description Numero di giorni selezionati per la partenza
	 */
	selectedDepDays: 0,
	/**
	 * @type {Number}
	 * @description Numero di giorni selezionati per il ritorno
	 */
	selectedRetDays: 0,
	/**
	 * @type {Number}
	 * @description Numero di mesi selezionati
	 */
	selectedMonths: 0,
	
	/* tabs */
	/**
	 * @type {Object}
	 * @description Gruppi di tab
	 */
	tabGroups: {
		/**
		 * @type {Object}
		 * @description Gruppo dei tab di partenza
		 */
		partenzaGroup: {
			selected: "ta_partenzaTab0",
			tabs: {
				aeroportiZonaRadio: {
					panel: "ta_partenzaTab0",
					fields: [
						"departureAirports0",
						"departureAirports1",
						"departureAirports2"
					]
				},
				aeroportiManualeRadio: {
					panel: "ta_partenzaTab1",
					fields: [
						"departureGeographicalArea0",
						"departureGeographicalArea1"
					]
				}
			}
		},
		/**
		 * @type {Object}
		 * @description Gruppo dei tab legati alla durata
		 */
		durataGroup: {
			selected: "ta_durataTab1",
			tabs: {
				ta_weekendRadio: {
					panel: "ta_durataTab0",
					fields: []
				},
				ta_giorniRadio: {
					panel: "ta_durataTab1",
					fields: []
				}
			}
		},
		/**
		 * @type {Object}
		 * @description Gruppo dei tab di ritorno
		 */
		ritornoGroup: {
			selected: "ta_ritornoTab0",
			tabs: {
				ta_aeroportoRitornoRadio: {
					panel: "ta_ritornoTab0",
					fields: [
						"arrivalAirports0",
						"arrivalAirports1",
						"arrivalAirports2"
					]
				},
				ta_areaRitornoRadio: {
					panel: "ta_ritornoTab1",
					fields: [
						"arrivalGeographicalArea0",
						"arrivalGeographicalArea1"
					]
				}
			}
		}
	},

	/* methods */
	/**
	 * @private
	 * @description Metodo invocato alla partenza dell'applicazione, si occupa di caricare le configurazioni da file
	 * esterno. Todo: usare un tag script invece di una chiamata ajax per recuperare queste informazioni
	 */
	_setCfg: function(){
		var cfg = this.cfg, self = this;
		new Ajax.Request(cfg.name + '.action', {
			asynchronous: false,
	  		method: 'GET',
	  		parameters: {"ts": (new Date()).getTime()}, // avoid caching in IE
			evalJSON: true,
			onSuccess: function(transport){
				var d = transport.responseJSON;
				// refactor
				self.assistant.messages = d["assistant"];
				self._currentLanguage = d["currentLanguage"];
				self._prompts = d["prompts"];
				self._geoCompleteUrl = d["geoCompleteUrl"];
				self._airportCompleteUrl = d["airportCompleteUrl"];
				self._airportReachabilityUrl = d["airportReachabilityUrl"];
				self._nationCompleteUrl = d["nationCompleteUrl"];
				self._areaPrompt = d["areaPrompt"];
				self._nationPrompt = d["nationPrompt"];
				self._monthMap = d["monthMap"];
				self._calMessages = d["calendar"];
			},
			onFailure: function(){
//				window.alert("Failure loading the configuration file");
			},
			onException: function(req, exc){
//				window.alert("[pricefinder] Error loading external cfg file! " + exc);
			}
		});
	},
	/**
	 * @type method *private
	 * @description show/hide weekend tab in duration Group
	 */
	_showHideWeekend: function(evt) {
		if(evt){
			owcheck = evt.element()
		}else{
			owcheck = $("ta_one_way_cb");
		}
		if(owcheck.checked){
	        $("ta_return_days").setStyle({
	            visibility: "hidden"
	        });
	        $("distanceDays").setStyle({
	            visibility: "hidden"
	        });
	        var weekendSelected = $('ta_giorniRadio');
	        if (this.tabGroups['durataGroup'].selected == "ta_durataTab0") {
	    		var grp = this.tabGroups['durataGroup'].tabs;
	    		this._showTab(weekendSelected, grp);         	
	        }
			$("durataSoggiorno").addClassName("ta_disabledBlock");
		}else{
	        $("ta_return_days").setStyle({
	            visibility: "visible"
	        });
	        $("distanceDays").setStyle({
	            visibility: "visible"
	        });
			$("durataSoggiorno").removeClassName("ta_disabledBlock");
		}		
	},
	/**
	 * @type {Object}
	 * @namespace ch.exmachina.bravofly.pricefinderSearch.assistant
	 * @description Oggetto contenente l'assistente, con i metodi per mostrare e nascondere i messaggi
	 */
	assistant: {
		locked: false,
		_lastPosition: "",
		_isFirstMessage: true,
		initialLock: false, 
		visible: false,
		currentMessage: "",
		/**
		 * @description Si occupa di nascondere la finestra dell'assistente
		 */
		hideInfo: function(){
			this.visible = false;
			new Effect.Fade("ta_tooltip", {
				duration: .1
			});			
		},
		/**
		 * @description Mostra il messaggio dell'assistente con lo stile legato alla notifica d'errore
		 */
		showError: function(){
			$("ta_tooltip_text").removeClassName("ta_tooltip_content_inside");
			$("ta_tooltip_text").addClassName("ta_tooltip_content_inside_error");
			this.showInfo();
		},
		/**
		 * @description Metodo per mostrare un messaggio generico
		 * @param {Object} args Composto da <br />
		 * {String} msg il messaggio
		 */
		showInfo: function(args){
			//if(this.visible){ return; }
			this.visible = true;
			var message = args.msg,
				aTop = args.top,
				aLeft = args.left,
				lastPosition = args.position,
				force = args.force,
				dir = args.dir,
				duration = args.duration,
				type = args.type || "info"
			;
			//if((/*this._lastPosition === lastPosition && */!force)/* || this._initialLock*/){ return; }
			if(this._isFirstMessage){
				this._initialLock = true; 
			}
			if(type === "info" ){
				$("ta_tooltip_text").removeClassName("ta_tooltip_content_inside_error");
				$("ta_tooltip_text").addClassName("ta_tooltip_content_inside");
			}else{
				$("ta_tooltip_text").removeClassName("ta_tooltip_content_inside");
				$("ta_tooltip_text").addClassName("ta_tooltip_content_inside_error");
			}
			var self = this;
			var al = $("ta_tooltip");
			for(var i = 0, d = ["top", "right", "bottom", "left" ]; i < d.length; i++){
				al.removeClassName("ta_tooltip_" + d[i]);
			}
			if(dir){
				al.addClassName("ta_tooltip_" + dir);
			}
			clearTimeout(this._assistantTimeout); 
			this.bSay(message); 
			with(al.style){
				top = aTop;
				left = aLeft;
			}
			new Effect.Appear("ta_tooltip", {
				duration: .5
			});			
//			this._assistantTimeout = setTimeout(function(){
//				self._isFirstMessage = false;
//				self._initialLock = false; 
//				self.hideInfo();
//			}, duration);
			this._lastPosition = lastPosition;
			//this.say(message, force); 
		},
		/**
		 * @description Cambia il contenuto del messaggio mostrato dalla assistente
		 * @param {String} msg Testo da far comparire nel messaggio dell'assistente
		 */
		bSay: function(msg){
			$("ta_tooltip_text").innerHTML = msg;
		},
		/**
		 * @description Cambia il contenuto del messaggio mostrato dalla assistente
		 * @param {String} message Testo da far comparire nel messaggio dell'assistente
		 * @param {Boolean} force
		 */
		error: function(message, force){
			this._say(message, force, "errorMessage");
		},
		/**
		 * @description Cambia il contenuto del messaggio mostrato dalla assistente
		 * @param {String} message Testo da far comparire nel messaggio dell'assistente
		 * @param {Boolean} force Se true, impone in ogni caso che il messaggio sia cambiato, indipendentemente
		 * dallo stato attuale dell'assistente
		 */
		say: function(message, force){
			this._say(message, force, "");
		},
		/**
		 * @private
		 * @description Metodo generico utilizzato internamente per notificare i messaggi, riceve anche il parametro che
		 * determina la classe del div che conterrà il testo
		 * @param message Messaggio da visualizzare
		 * @param force
		 * @param msgClass
		 */
		_say: function(message, force, msgClass){
			if((this.currentMessage !== message && !this.locked) || force){
				var aMessage = $('ta_assistant_message'); 
				aMessage.innerHTML = "<span class=\"" + msgClass + "\">" + ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(message) + "</span>";
				aMessage.hide();
				new Effect.Appear('ta_assistant_message', { duration: .5 });
				this.currentMessage = message; 
			}
		},
		lock: function(/** number */ time){
			var self = this;
			this.locked = true;
			setInterval(function(){ self.locked = false}, time);
		},
		messages: {}
	},
	makeFieldGroups: function(){
		var self = this;
		this.departureKnobGroup = new ch.exmachina.bravofly.FieldGroup({
			domNode: "ta_knobGroup",
			minFields: 1,
			maxFields: 1,
			type: "dep",
			promptText: ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(self._prompts.air),
			dirty: false,
			autocompleteURL: this._airportCompleteUrl,
			searchLanguage: this._currentLanguage,
			onClean: function(){
				self.knob.disable();
			},
			onComplete: function(){
    			if(!self._isKnobVisible) { return; }
	    		new Ajax.Request(self._airportReachabilityUrl, {
			  		method: 'POST',
			  		parameters: {
			  			airport: encodeURIComponent(this.getValue()),
			  			max_hour: "5.00" // usa una variabile per questo
			  		}, 
					evalJSON: true,
					onSuccess: function(transport){
						var d = transport.responseJSON,
							rSet = d["availableHours"]
						;
						if(rSet.length > 1){
							self.knob.enable();
							self.knob.setReachabilitySet(rSet);
						}else{
							self.knob.disable();
						}
					},
					onFailure: function(){
						//window.alert("Failure loading the airport distance info");
					},
					onException: function(req, exc){
						//window.alert("[pricefinder] Error loading airport distance info: " + exc);
					}
	    		});
	    		// aggiungere chiamata a keyuphandler
	    	//	$("listaPartenza" + x).style.display = "block"; 
			}
		});
		this.departureAirportsGroup = new ch.exmachina.bravofly.FieldGroup({
			domNode: "ta_departureAirGroup",
			addNode: "ta_add_departure_airport",
			minFields: 1,
			maxFields: 3,
			type: "dep",
			promptText: ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(self._prompts.air),
			dirty: false,
			autocompleteURL: self._airportCompleteUrl,
			searchLanguage: self._currentLanguage,
			onComplete: function(){
				var pGroup = this.pGroup;
				if(pGroup.fields.length < pGroup.maxFields){
					$("ta_add_departure_airport").className = "ta_new_airport";
				}
			}
		});
		// 05-jan-2008b
//		this.departureAreaGroup = new ch.exmachina.bravofly.FieldGroup({
//			domNode: "ta_departureAreaGroup",
//			addNode: "ta_add_departure_area",
//			minFields: 1,
//			maxFields: 2,
//			type: "dep",
//			promptText: ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(self._prompts.area),
//			dirty: false,
//			autocompleteURL: self._geoCompleteUrl,
//			searchLanguage: self._currentLanguage,
//			onComplete: function(){
//				var pGroup = this.pGroup;
//				if(pGroup.fields.length < pGroup.maxFields){
//					$("ta_add_departure_area").className = "ta_new_airport";
//				}
//			}
//		});
		this.departureAreaGroup = new ch.exmachina.bravofly.GeographicGroup({
			autocompleteURL: self._geoCompleteUrl, 
            nationCompleteUrl: self._nationCompleteUrl,// absent
			domNode: "ta_departure_geo_input",
            aspect: "overlapped",
//			containerNode: "ta_departureAreaGroup",
			containerNode: "ta_departure_geo_input",
			addNode: "ta_add_departure_area",
            datasource: "net",
            //areaDataKey: depAreaDataKey, //"availableDepartureGeoArea",
            asynchAreaLoad: true,
            nationUnderlined: false,
			areaPrompt: ch.exmachina.bravofly.utils.unescapeHTML(this._areaPrompt),//ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(this._areaPrompt),
			nationPrompt: ch.exmachina.bravofly.utils.unescapeHTML(this._nationPrompt),//ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(this._nationPrompt),
			searchLanguage: this._currentLanguage,
//            nationReadOnly: false,
//            defaultNation: defaultNation,
            selectContentType: "json",
            selectUrl:  self._geoCompleteUrl,//"suggest/GeographicalArea",
            onAddChild: function(){
	        	if(this.fields.length === this.maxFields){
	        		this.hideAddNode();
	        	}
			},
            onRemoveChild: function(){
		        if(this.atLeastOneValid()){
		            this.addNode && this.enableAddNode();
		        }else{
		        	this.addNode && this.disableAddNode();
		        }
			},
            onChangeArea: function(){
				// controllare che sia valida la select
				// in caso positivo, eseguire i soliti controlli sulla validitÃ  di gruppo
                if(this.enclosingObject.pGroup.atLeastOneValid()){
                    if(this.enclosingObject.pGroup.fields.length < this.enclosingObject.pGroup.maxFields){
                        this.enclosingObject.pGroup.enableAddNode();
                    }
                }
			},
			onComplete: function(){
			}
		});
		// 05-jan-2008e

		this.returnAirGroup = new ch.exmachina.bravofly.FieldGroup({
			domNode: "ta_returnAirGroup",
			addNode: "ta_add_return_air",
			minFields: 1,
			maxFields: 3,
			promptText: ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(self._prompts.air),
			dirty: false,
			type: "ret",
			autocompleteURL: self._airportCompleteUrl,
			searchLanguage: self._currentLanguage,
			onComplete: function(){
				var pGroup = this.pGroup;
				if(pGroup.fields.length < pGroup.maxFields){
					$("ta_add_return_air").className = "ta_new_airport";
				}
			}
		});
		// 05-jan-2008b
//		this.returnAreaGroup = new ch.exmachina.bravofly.FieldGroup({
//			domNode: "ta_returnAreaGroup",
//			addNode: "ta_add_return_area",
//			minFields: 1,
//			maxFields: 2,
//			promptText: ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML(self._prompts.area),
//			dirty: false,
//			type: "ret",
//			autocompleteURL: self._geoCompleteUrl,
//			searchLanguage: self._currentLanguage,
//			onComplete: function(){
//				var pGroup = this.pGroup;
//				if(pGroup.fields.length < pGroup.maxFields){
//					$("ta_add_return_area").className = "ta_new_airport";
//				}
//			}
//		});
		this.returnAreaGroup = new ch.exmachina.bravofly.GeographicGroup({
			autocompleteURL: self._geoCompleteUrl, 
            nationCompleteUrl: self._nationCompleteUrl,// absent
			domNode: "ta_return_geo_input",
            selectContentType: "json",
            aspect: "overlapped",
//			containerNode: "ta_returnAreaGroup",
			containerNode: "ta_return_geo_input",
			addNode: "ta_add_return_area",
            datasource: "net",
            //areaDataKey: depAreaDataKey, //"availableDepartureGeoArea",
            asynchAreaLoad: true,
            nationUnderlined: false,
			areaPrompt: ch.exmachina.bravofly.utils.unescapeHTML(this._areaPrompt),
			nationPrompt: ch.exmachina.bravofly.utils.unescapeHTML(this._nationPrompt),
			searchLanguage: this._currentLanguage,
//            nationReadOnly: false,
//            defaultNation: defaultNation,
            selectUrl:  self._geoCompleteUrl,//"suggest/GeographicalArea",
            onAddChild: function(){
	        	if(this.fields.length === this.maxFields){
	        		this.hideAddNode();
	        	}
			},
            onRemoveChild: function(){
		        if(this.atLeastOneValid()){
		            this.addNode && this.enableAddNode();
		        }else{
		        	this.addNode && this.disableAddNode();
		        }
			},
            onChangeArea: function(){
				// controllare che sia valida la select
				// in caso positivo, eseguire i soliti controlli sulla validitÃ  di gruppo
                if(this.enclosingObject.pGroup.atLeastOneValid()){
                    if(this.enclosingObject.pGroup.fields.length < this.enclosingObject.pGroup.maxFields){
                        this.enclosingObject.pGroup.enableAddNode();
                    }
                }
			},
			onComplete: function(){
			}
		});
		// 05-jan-2008e
	},
	startup: function(){
		var self = this;
		this._setCfg();
		// caricamento calendario
		// la monthMap deve essere ricavata dal server, questo Ãš uno stub
//		this._monthMap = [{"date":"2009\/03\/23","month":"Mar"},{"date":"2009\/04\/23","month":"Apr"},{"date":"2009\/05\/23","month":"Mag"},{"date":"2009\/06\/23","month":"Giu"},{"date":"2009\/07\/23","month":"Lug"},{"date":"2009\/08\/23","month":"Ago"},{"date":"2009\/09\/23","month":"Set"},{"date":"2009\/10\/23","month":"Ott"},{"date":"2009\/11\/23","month":"Nov"},{"date":"2009\/12\/23","month":"Dic"},{"date":"2010\/01\/23","month":"Gen"},{"date":"2010\/02\/23","month":"Feb"}];
		var Calendar = function(){};
		ch.exmachina.bravofly.inherits(Calendar, ch.exmachina.bravofly.Calendar);
		Calendar.prototype.onClickHandler = function(/* Event */ evt){
			var trg = evt.target,
				self = ch.exmachina.bravofly.pricefinderSearch, // use a parameter instead,
				msgs = self.assistant.messages
			;
			if(trg.tagName.toLowerCase() === "td" && trg.hasClassName("available")){
				var sm = this.getSelectedMonths();
				if(!trg.hasClassName("selected")){
					if(sm.length == self.maxSelectableMonths){
						// messaggio nuovo qui!
						self.assistant.showInfo({
							msg: msgs.MAX_MONTH,
							top: "205px",
							left: "0px",
							position: "when",
							force: true,
							dir: "bottom",
							duration: 5000,
							type: "error"
						});
//						this.unselectMonth({ elem: trg });
				    }else{
						this.selectMonth({ elem: trg });
					}
				}else{
					if(sm.length == self.minSelectableMonths){
						self.assistant.showInfo({
							msg:msgs.AT_LEAST_A_MONTH,
							top: "205px",
							left: "0px",
							position: "when",
							force: true,
							dir: "bottom",
							duration: 5000,
							type: "error"
						});
//						this.unselectMonth({ elem: trg });
					} else{
						this.unselectMonth({ elem: trg });
					}
				}
			}
		};
		this.calendar = new Calendar();
		this.calendar.setMessages(this._calMessages);
		this.calendar.init({
		    node: "ta_quandoMesi",
		    monthMap: this._monthMap
		});
		this.makeFieldGroups();
		// visualizzo il messaggio iniziale, benvenuto o errore.
		var type = "info";
		if($("errorPage").value == "true"){
			this.assistant.lock(15000);
			type = "error";
		}
		var msg = $("ta_assistant_message").innerHTML;
		if(msg.replace(/ |\n|\r|\t/g, "") !== ""){
			this.assistant.showInfo({
				msg: msg, 
				top: "2px",
				left: "2px", 
				position: "initial",
				force: false, 
				dir: "", 
				duration: 10000,
				type: type
			});
		}
		
		// knob widget
		this.knob = new ch.exmachina.bravofly.Knob({
			nodeId: "ta_knob_container",
			enabled: false,
			onSetStatus: function(){
				//$("hourTolerance").value = this.value;
			}
		}); 
		// EVENTS
        var owcheck = $("ta_one_way_cb");
        owcheck.observe("click", self._showHideWeekend.bindAsEventListener(self));
		// airports text fields behaviour
		$("ta_close_tooltip").observe("click", function(){
			self.assistant._initialLock = false;
			self.assistant._isFirstMessage = false;
			clearTimeout(self._assistantTimeout);
			self.assistant.hideInfo(); 
		});
		// assistant
		var msgs = this.assistant.messages;
        var showDurationHelp = function(){
			if(this.tabGroups.durataGroup.selected === "ta_durataTab1"){
				self.assistant.showInfo({
					msg: msgs.DURATION, 
					top: "55px",
					left: "420px",
					position: "duration",
					force: false, 
					dir: "right",
					duration: 4000
				});
			}else{
				self.assistant.showInfo({ 
					msg: msgs.DURATION_WEEKEND, 
					top: "55px",
					left: "420px",
					position: "duration_weekend",
					force: false, 
					dir: "right",
					duration: 4000
				});
			}
		};
        $$('#ta_duration_title > div')[0].observe('click', (showDurationHelp).bindAsEventListener(self));


        var showKnobHelp = function(evt){
			self.assistant.showInfo({
				msg: msgs.KNOB,
				top: "75px",
				left: "325px",
				position: "when",
				force: false,
				dir: "bottom",
				duration: 4000
			});
        };
		$('ta_knob_helper').observe('click', (showKnobHelp).bindAsEventListener(self));

        var showWhenHelp = function(evt){
			self.assistant.showInfo({
				msg: msgs.WHEN,
				top: "185px",
				left: "0px",
				position: "when",
				force: false,
				dir: "bottom",
				duration: 4000
			});
        };
		$('ta_when_title').observe('click', (showWhenHelp).bindAsEventListener(self));
		$('ta_when_helper').observe('click', (showWhenHelp).bindAsEventListener(self));
		
		// request start
		$('trovaVoli').observe('click', this.startRequest.bindAsEventListener(self, this));

		// tab actions (refactor)
		var radioNode = $('aeroportiZonaRadio');
		radioNode.observe('click', this.showTab.bindAsEventListener(self, this));
		$(radioNode.readAttribute("labelNode")).observe('click', (function(){ self.showTab.call(self, {target: $('aeroportiZonaRadio')}) }).bindAsEventListener());

		radioNode = $('aeroportiManualeRadio');
		radioNode.observe('click', this.showTab.bindAsEventListener(self, this));
		$(radioNode.readAttribute("labelNode")).observe('click', (function(){ self.showTab.call(self, {target: $('aeroportiManualeRadio')}) }).bindAsEventListener());

		radioNode = $('ta_weekendRadio');
		radioNode.observe('click', this.showTab.bindAsEventListener(self, this));
		$(radioNode.readAttribute("labelNode")).observe('click', (function(){ self.showTab.call(self, {target: $('ta_weekendRadio')}) }).bindAsEventListener());

		radioNode = $('ta_aeroportoRitornoRadio');
		radioNode.observe('click', this.showTab.bindAsEventListener(self, this));
		$(radioNode.readAttribute("labelNode")).observe('click', (function(){ self.showTab.call(self, {target: $('ta_aeroportoRitornoRadio')}) }).bindAsEventListener());

		radioNode = $('ta_areaRitornoRadio');
		radioNode.observe('click', this.showTab.bindAsEventListener(self, this));
		$(radioNode.readAttribute("labelNode")).observe('click', (function(){ self.showTab.call(self, {target: $('ta_areaRitornoRadio')}) }).bindAsEventListener());

		radioNode = $('ta_giorniRadio');
		radioNode.observe('click', this.showTab.bindAsEventListener(self, this));
		$(radioNode.readAttribute("labelNode")).observe('click', (function(){ self.showTab.call(self, {target: $('ta_giorniRadio')}) }).bindAsEventListener());
		
		// radio related messages
		var al = $("ta_alert"), si = self.assistant.showInfo, as = self.assistant;
        var showDepartureHelp = function(){
			if(this.tabGroups.partenzaGroup.selected === "ta_partenzaTab0"){
				si.call(as, {
					msg: msgs.START_AIRPORT_ZONE,
					top: "10px",
					left: "570px",
					position: "start",
					force: false,
					dir: "left",
					duration: 4000
				});
			}else{
				si.call(as, {
					msg: msgs.START_AIRPORT_MANUAL,
					position: "start_man",
					top: "220px",
					left: "270px",
					dir: "top",
					force: false,
					duration: 4000
				});
			}
		};
		$$('#ta_departure_title > span')[0].observe('click', (showDepartureHelp).bindAsEventListener(self));
		$('ta_departure_helper').observe('click', (showDepartureHelp).bindAsEventListener(self));
        var showDestinationHelp = function(){
			if(this.tabGroups.ritornoGroup.selected === "ta_ritornoTab0"){
				si.call(as, {
					msg: msgs.ARRIVAL_AIRPORT_ZONE,
					position: "arrival_airport",
					top: "310px",
					left: "390px",
					force: false,
					dir: "left",
					duration: 4000
				});
			}else{
				si.call(as,{
					msg: msgs.ARRIVAL_GEOGRAPHIC_AREA,
					top: "310px",
					left: "390px",
					position: "arrival_airport_zone",
					force: false,
					dir: "left",
					duration: 4000
				});
			}
		};
		$$('#ta_return_title > span')[0].observe('click', (showDestinationHelp).bindAsEventListener(self));
		$('ta_destination_helper').observe('click', (showDestinationHelp).bindAsEventListener(self));

		this.resetForm();
		// "checkbox" fields
		var checkWeekNode = $('ta_check_weekend');
		checkWeekNode.observe('click', this.toggleCheck);
		$(checkWeekNode.readAttribute("labelNode")).observe('click', function(){ self.toggleCheck.call(checkWeekNode) }); 
		
		// rifattorizza: qua posso usare una funzione per entrambi i casi di 
		// check singolo rimasto, a patto di parametrizzare il messaggio
		// e il contatore
		for(var i = 0; i < 7; i++){
			$('ta_check_partenza_' + i).observe('click',
				function(){
					if(self.selectedDepDays == 1 && (this.readAttribute("class") === "ta_check_on")){
						self.assistant.showInfo({
							msg:msgs.AT_LEAST_A_DEP_DAY, 
							top: "245px",
							left: "640px", 
							position: "duration", 
							force: true, 
							dir: "top", 
							duration: 5000,
							type: type
						});
						return;
					}else{
						self.selectedDepDays += (this.readAttribute("class") === "ta_check_on") ? -1 : 1;
						self.toggleCheck.call(this); 
					}
				} 
			); 
			$('ta_check_ritorno_' + i).observe('click',
				function(){
					if(self.selectedRetDays == 1 && (this.readAttribute("class") === "ta_check_on")){

						self.assistant.showInfo({
							msg:msgs.AT_LEAST_A_RET_DAY, 
							top: "245px",
							left: "640px", 
							position: "duration",
							force: true, 
							dir: "top", 
							duration: 5000,
							type: type
						});
						return;
					}else{
						self.selectedRetDays += (this.readAttribute("class") === "ta_check_on") ? -1 : 1;
						self.toggleCheck.call(this); 
					}
				} 
			); 
		}

		// Autocompleters
		var airportSearchBox_language = this._currentLanguage;
		
		//document.observe("onkey");
		
		$("ta_show_airports").observe("click", function(){
			self.hideKnobPanel.call(self);
		});		
		$("ta_show_distance").observe("click", function(){
			self.showKnobPanel.call(self);
		});		
	},
	showKnobPanel: function(){
		var self = this;
		this._isKnobVisible = true;
		$("ta_show_distance_container").style.display = "none";
		$("ta_knob_message").style.display = "block";
		$("ta_knob_container").style.display = "block";
//		$("ta_departureAirportsWrapper1").className = "invisible";
//		$("ta_departureAirportsWrapper2").className = "invisible";
		$("ta_knobGroup").style.display = "block";
		$("ta_departureAirGroupContainer").style.display = "none";
		$("ta_add_airport_container").style.display = "block";
		ch.exmachina.bravofly.FieldGroup.copy({
			dest: self.departureKnobGroup.fields[0],
			src: self.departureAirportsGroup.fields[0]
		});
		if(self.departureKnobGroup.fields[0].disabled){
			this.findKnobInfo();
		}else{
			this.knob.disable();
		}
	},
	hideKnobPanel: function(args){
		var self = this;
		this._isKnobVisible = false;
		$("ta_add_airport_container").style.display = "none";
		$("ta_knob_message").style.display = "none";
		$("ta_knob_container").style.display = "none";
		$("ta_knobGroup").style.display = "none";
		$("ta_departureAirGroupContainer").style.display = "block";
		$("ta_show_distance_container").style.display = "block";
		if(!args || (args && !args.noCopy)){
			ch.exmachina.bravofly.FieldGroup.copy({
				src: self.departureKnobGroup.fields[0],
				dest: self.departureAirportsGroup.fields[0]
			});
			this.departureAirportsGroup.collapse();
			if(this.departureAirportsGroup.allFreezed() && 
				this.departureAirportsGroup.fields.length < this.departureAirportsGroup.maxFields){
				this.departureAirportsGroup.enableAddNode();
			}
		}
		this.knob.setStatus(0.0);
		//this.unfreezeField($('fld_departureAirports0')); --> deve finire nell'oggetto interessato			
	},
	freezeField: function(/** input */ elem){
		elem.className = "fixed";
		elem.disabled = true;
	},
	unfreezeField: function(/** input */ elem){
		this.knob.disable();
		elem.className = "";
		elem.disabled = false;
	},
	toggleCheck: function(){
		var ref = this.readAttribute("labelRef"), fieldRef = this.readAttribute("fieldRef"), refElem;
		if(ref){
			refElem = $(ref);
			refElem.className = refElem.className == "ta_labelOff" ? "ta_labelOn" : "ta_labelOff"; 
		}
		this.className = this.className == "ta_check_off" ? "ta_check_on" : "ta_check_off";
	},
	_showTab: function(trg, grp){
		/* if target is disabled - do nothing  */
		if (trg.id == "ta_weekendRadio" && $("ta_one_way_cb").checked) {
			return;
		}
		for(var i in grp){
			$(grp[i].panel).removeClassName("enabledTabContainer").addClassName("disabledTabContainer");
			$(i).removeClassName("ta_radio_on").addClassName("ta_radio_off");
		}
		var toShowTab = $(trg.id), toShowPanel = $(grp[trg.id].panel);
		toShowTab.addClassName("ta_radio_on").removeClassName("ta_radio_off");
		toShowPanel.addClassName("enabledTabContainer").removeClassName("disabledTabContainer");
		this.tabGroups[trg.readAttribute("tabGroup")].selected = grp[trg.id].panel;
	},
	showTab: function(/** DOM node */evt){
		var trg = evt.target, grp = this.tabGroups[trg.readAttribute("tabGroup")].tabs;
		this._showTab(trg, grp);
	},
	resetHiddenForm: function(){
		var flds = document.searchForm.getElementsByTagName("input"); 
		for(var i = 0; i < flds.length; i++){
			flds[i].value = "";
		}
		$("hourTolerance").value = "0";
		$("numberOfRowsToDisplay").value = "50";
	},
	startRequest: function(){
		this.resetHiddenForm();
		var uncompleteFields = false;
		if(this.tabGroups.partenzaGroup.selected === "ta_partenzaTab0"){
			if((this._isKnobVisible && !this.departureKnobGroup.allValid())
				|| (!this._isKnobVisible && !this.departureAirportsGroup.allValid())){
				uncompleteFields = true;
			}
		}
		if(this.tabGroups.partenzaGroup.selected === "ta_partenzaTab1" && !this.departureAreaGroup.allValid()){
			uncompleteFields = true;
		}
		if(this.tabGroups.ritornoGroup.selected === "ta_ritornoTab0" && !this.returnAirGroup.allValid()){
			uncompleteFields = true;
		}
		if(this.tabGroups.ritornoGroup.selected === "ta_ritornoTab1" && !this.returnAreaGroup.allValid()){
			uncompleteFields = true;
		}
		var msgs = this.assistant.messages;
		if(uncompleteFields){
			this.assistant.lock(8000);
			this.assistant.showInfo({
				msg: msgs.FIELD_NOT_FIXED, 
				top: "0px",
				left: "0px", 
				position: "not fixed",
				force: false, 
				dir: "", 
				duration: 5000,
				type: "dep"
			});
			return;
		}
		// departure airports or distance
		if(this._isKnobVisible){
			$("departureAirports0").value = this.departureKnobGroup.getField(0).isFreezed() ?
				this.departureKnobGroup.getField(0).getValue() : "";
		}else{
			for(var i = 0; i < this.departureAirportsGroup.fields.length; i++){
				$("departureAirports" + i).value = this.departureAirportsGroup.getField(i).isFreezed() ?
					this.departureAirportsGroup.getField(i).getValue() : ""; 
			}
		}
		// departure areas
        for(i = 0; i < this.departureAreaGroup.fields.length; i++){
            var isFreezed = this.departureAreaGroup.getField(i).isFreezed();
            $("ta_depCountry" + i).value = isFreezed ?
                this.departureAreaGroup.getField(i).getNationValue() + ":" + this.departureAreaGroup.getField(i).nationField.getStoredId() : "";
            $("departureGeographicalArea" + i).value = isFreezed ?
                this.departureAreaGroup.getField(i).areaField.getKey() : "";
        }
//		for(i = 0; i < this.departureAreaGroup.fields.length; i++){
//			$("departureGeographicalArea" + i).value = this.departureAreaGroup.getField(i).isFreezed() ?
//				this.departureAreaGroup.getField(i).fieldNode.readAttribute("data") : "";
//			$("departureGeographicalAreaLabel" + i).value = this.departureAreaGroup.getField(i).isFreezed() ?
//				this.departureAreaGroup.getField(i).getValue() : "";
//		}
		// return airports
		for(i = 0; i < this.returnAirGroup.fields.length; i++){
			$("arrivalAirports" + i).value = this.returnAirGroup.getField(i).isFreezed() ?
				this.returnAirGroup.getField(i).getValue() : ""; 
		}
		// return areas
        for(i = 0; i < this.returnAreaGroup.fields.length; i++){
            isFreezed = this.returnAreaGroup.getField(i).isFreezed();
            $("ta_arrCountry" + i).value = isFreezed ?
                this.returnAreaGroup.getField(i).getNationValue() + ":" + this.returnAreaGroup.getField(i).nationField.getStoredId() : "";
            $("arrivalGeographicalArea" + i).value = isFreezed ?
                this.returnAreaGroup.getField(i).areaField.getKey() : "";
        }

		$("hourTolerance").value = this.knob.disabled ? 0 : this.knob.getStatus();

		// month start
        var cal = this.calendar,
		    sm = cal.getSelectedMonths()
		;
		for(i = 0; i < 5; i++){
			$("departureMonths" + i).value = "";
		}
        for(var l = sm.length, i = 0; i < l; i++){
			$("departureMonths" + i).value = sm[i].readAttribute("valueon");
		}
		// month end

		// checkboxes buttons
		for(var j = 0, da = ["departure", "arrival"], pa = ["partenza", "ritorno"]; j < da.length; j++){
			for(i = 0; i < 7; i++){
				var dd = $("ta_check_" + pa[j] + "_" + i);
				var dField = $(dd.readAttribute("fieldRef")); 
				dField.value = dd.className == "ta_check_on" ? dd.readAttribute("valueOn") || "" : dd.readAttribute("valueOff") || "";
			}
		}
		var we = $("ta_check_weekend"), weField = $(we.readAttribute("fieldRef")); 
		weField.value = we.className == "ta_check_on" ? we.readAttribute("valueOn") || "" : we.readAttribute("valueOff") || "";
		// month start
		// month end
		// end checkboxes
		
		// radio buttons start
		var tGroups = this.tabGroups;
		var selectedTabId;
		for(j in tGroups){
			selectedTabId = tGroups[j].selected;
			for(i in tGroups[j]["tabs"]){
				var currentTab = $(i);
				if(currentTab.readAttribute("fieldRef")){
					if(selectedTabId != tGroups[j]["tabs"][i]["panel"]){
						$(currentTab.readAttribute("fieldRef")).value = currentTab.readAttribute("valueOff");
					}else{
						$(currentTab.readAttribute("fieldRef")).value = currentTab.readAttribute("valueOn");
					}
				}
			}
		}
		// radio buttons end


        $("ta_oneway").value = "" + $("ta_one_way_cb").checked;

		// svuoto i campi relativi ai tab non attivi
		var flds, grp, tab;
		for(j in tGroups){
			grp = tGroups[j];
			tab = grp["tabs"];
			for(i in tab){
				flds = tab[i]["fields"];
				if(grp.selected != tab[i]["panel"]){
					for(var k = 0; k < flds.length; k++){
						$(flds[k]).value = "";
					}
				}
			}
		}
		// svuoto i campi relativi ai tab non attivi [fine]

		var did = $$("[name=distanceInDays]");
		for(i = 0, l = did.length; i < l; i++){
			if(did[i].checked){
				var val = this._distanceHash[did[i].value];
				document.searchForm["minDistanceInDays"].value = val.start;
				document.searchForm["maxDistanceInDays"].value = val.end;
			}
		}
 		document.searchForm.submit();
	},
	resetForm: function(){
		var self = this;
		this.calendar.enableAllMonths();
		if($F("errorPage") != "true" && $F("ta_searchAgain") != "true"){
			// abilitazione di test del primo mese
			for(var i = 0; i < 3; i++){
				this.calendar.selectMonth({ index: i });
			}
			// fine calendario
			for(i = 0; i < 2; i++){ 
				$("departureGeographicalArea" + i).value = "";
				$("arrivalGeographicalArea" + i).value = "";
			}
			
			for(i = 0; i < 7; i++){
				$("departureDays" + i).value = "true";
				$("arrivalDays" + i).value = "true";
			}
			this.selectedDepDays = 7;
			this.selectedRetDays = 7;
			
			for(i = 0; i < 5; i++){
				$("departureMonths" + i).value = "";
			}
			var airP, aP;
			
			/* months initialization */			
			this.selectedMonths = 3;
			
			$("longWeekend").value = "";
			$("weekend").value = "";
			var uH = ch.exmachina.bravofly.pricefinderSearch.utils.unescapeHTML;
			
		}else{
			// error or searchAgain page
			if($("ta_oneway").value === "true"){
				$("ta_one_way_cb").checked = true;
				$("ta_return_days").setStyle({
				    visibility: "hidden"
				});
				$("distanceDays").setStyle({
				    visibility: "hidden"
				});
				this._showHideWeekend();
			}

			// RichFields
			var val = "",
				hourTolerance = $F("hourTolerance"),
				lastField,
				trgField,
				showKnob = false,
				counter = 0,
				depAreaCounter = 0,
				fHourTolerance = 0
			;
			fHourTolerance = parseFloat(hourTolerance);
			
			for(i = 0; i < 3; i++){
				counter += val = $("departureAirports" + i).value ? 1 : 0;
			}
			for(i = 0; i < 2; i++){
				depAreaCounter += $("departureGeographicalArea" + i).value ? 1 : 0;
			}
			
			if(fHourTolerance > 0 || (fHourTolerance == 0 && counter < 2 && !depAreaCounter)){
				lastField = this.departureKnobGroup.getLastField();
				lastField.setValue($("departureAirports0").value);
				lastField.freeze();
			}else{
				this.hideKnobPanel({
					noCopy: true
				});
				for(i = 0; i < 3; i++){
					val = $("departureAirports" + i).value;
					if(val){
						lastField = this.departureAirportsGroup.getLastField();
						if(lastField.isFreezed()){
							trgField = this.departureAirportsGroup.createField();
						}else{
							trgField = lastField;
						}
						trgField.setValue(val);
						trgField.freeze();
					}				
				}
			}
			for(i = 0; i < 3; i++){
				val = $("arrivalAirports" + i).value;
				if(val){
					lastField = this.returnAirGroup.getLastField();
					if(lastField.isFreezed()){
						trgField = this.returnAirGroup.createField();
					}else{
						trgField = lastField;
					}
					trgField.setValue(val);
					trgField.freeze();
				}				
			}
			for(i = 0; i < 2; i++){
				val = $("ta_depCountry" + i).value;
				if(val){
					lastField = this.departureAreaGroup.getLastField();
					if(val && i){// lastField.isFreezed() && this.cfg.type != "cibavisionsearch"){
						trgField = this.departureAreaGroup.createField();
					}else{// spurio, non sarÃ  mai cibavision
						trgField = lastField;
					}
					var values = val.split(":");
					trgField.areaField.onLoadOnce = function(x){
						return function(){
							this.setKey($("departureGeographicalArea" + x).value);
						}
					}(i);
					trgField.nationField.storedId = values[1];
					trgField.nationField.setValue(values[0]);
					trgField.areaField.autoLoad = true;
					trgField.nationField.freeze();
				}
				val = $("ta_arrCountry" + i).value;
				if(val){
					lastField = this.returnAreaGroup.getLastField();
					if(val && i){//lastField.isFreezed()){
						trgField = this.returnAreaGroup.createField();
					}else{
						trgField = lastField;
					}
					values = val.split(":");
					trgField.areaField.onLoadOnce = function(x){
						return function(){
							this.setKey($("arrivalGeographicalArea" + x).value);
						}
					}(i);
					trgField.nationField.storedId = values[1];
					trgField.nationField.setValue(values[0]);
					trgField.areaField.autoLoad = true;
					trgField.nationField.freeze();
				}
			}
			// "addNode" validation // parametrize this!
			if(this.departureAirportsGroup.allFreezed() && 
				this.departureAirportsGroup.fields.length < this.departureAirportsGroup.maxFields){
				this.departureAirportsGroup.enableAddNode();
			}
			if(this.returnAirGroup.allFreezed() && 
				this.returnAirGroup.fields.length < this.returnAirGroup.maxFields){
				this.returnAirGroup.enableAddNode();
			}
			if(this.departureAreaGroup.allFreezed() && 
				this.departureAreaGroup.fields.length < this.departureAreaGroup.maxFields){
				this.departureAreaGroup.enableAddNode();
			}
			if(this.returnAreaGroup.allFreezed() && 
				this.returnAreaGroup.fields.length < this.returnAreaGroup.maxFields){
				this.returnAreaGroup.enableAddNode();
			}
			// departure and arrival days
			for(i = 0; i < 7; i++){
				$("ta_check_partenza_" + i).className = $($("ta_check_partenza_" + i).readAttribute("fieldRef")).value == "true" ? "ta_check_on" : "ta_check_off";
				this.selectedDepDays += $("ta_check_partenza_" + i).className === "ta_check_on" ? 1 : 0; 
				$("ta_check_ritorno_" + i).className = $($("ta_check_ritorno_" + i).readAttribute("fieldRef")).value == "true" ? "ta_check_on" : "ta_check_off";
				this.selectedRetDays += $("ta_check_ritorno_" + i).className === "ta_check_on" ? 1 : 0;
			}

			// departure months

			// text fields

			$("ta_check_weekend").className = $("longWeekend").value === $("ta_check_weekend").readAttribute("valueOn") ? "ta_check_on" : "ta_check_off";

			// tab selezionati
			if($("weekend").value == "true"){
				var trg = $("ta_weekendRadio");
				var grp = this.tabGroups[trg.readAttribute("tabGroup")].tabs;
				this._showTab(trg, grp);
			}
			
			if($("departureGeographicalArea0").value != ""){
				trg = $("aeroportiManualeRadio"), grp = this.tabGroups[trg.readAttribute("tabGroup")].tabs;
				this._showTab(trg, grp);
			}else{
			}
			if($("arrivalGeographicalArea0").value != ""){
				trg = $("ta_areaRitornoRadio"), grp = this.tabGroups[trg.readAttribute("tabGroup")].tabs;
				this._showTab(trg, grp);
			}
			var errorFields = document.getElementsByName("errorFields");
			// knob
			// altra situazione d'errore per lo knob
			if($F("departureGeographicalArea0") == ""){ // first tab selected
				if($F("departureAirports1")){ // hidden knob
					// hide knob panel here
					this.hideKnobPanel({
						noCopy: true
					});
				}else{ // the knob is visible
					var	cback = function(){
							self.knob.setStatus(hourTolerance);
						}
					;
					self.findKnobInfo({
						cback: cback 
					});
				}
			}
			var cal = this.calendar;
			cal.unselectAllMonths();
			for(i = 0; i < 5; i++){
				var m = $("departureMonths" + i).value.replace(/\//g, "").substring(0, 6);
				cal.selectMonth({ date: m });
			}
			// distance in days

			var distanceVal = this._distanceHash[$("minDistanceInDays").value].start, radioDistances = $$("[name=distanceInDays]"), l = 0;
			for (i = 0, l = radioDistances.length; i < l; i++) {
				if (radioDistances[i].value == distanceVal) {
					radioDistances[i].checked = "checked";
				}
			}
		} // ERROR end
	},
	findKnobInfo: function(/** Object*/ args){
		var self = this;
		var cback = args ? args.cback || function(){} : function(){};
		new Ajax.Request(this._airportReachabilityUrl, {
	  		method: 'POST',
	  		parameters: {
	  			airport: encodeURIComponent(self.departureKnobGroup.getField(0).getValue()),/*encodeURIComponent($F('fld_departureAirports0')),*/
	  			max_hour: "5.00" // usa una variabile per questo
	  		}, 
			evalJSON: true,
			onSuccess: function(transport){
				var d = transport.responseJSON;
				var rSet = d["availableHours"];
				if(rSet.length > 1){
					self.knob.enable();
					self.knob.setReachabilitySet(rSet);
					cback();
				}else{
					self.knob.disable();
				}
			},
			onFailure: function(){
				//window.alert("Failure loading the airport distance info");
			},
			onException: function(req, exc){
				//window.alert("[pricefinder] Error loading airport distance info: " + exc);
			}
		});
	}
};

Event.observe(document, 'dom:loaded', 
	ch.exmachina.bravofly.pricefinderSearch.startup.bindAsEventListener(ch.exmachina.bravofly.pricefinderSearch)
);
Event.observe(window, 'unload', function(){});
