if(!ch){
	var ch = {};
}
if(!ch.exmachina){
	ch.exmachina = {};
}
if(!ch.exmachina.bravofly){
	ch.exmachina.bravofly = {};
}
ch.exmachina.bravofly.remote = {
	imgPosition: "http://www3.staticroot.com/suggester/images/"
//	imgPosition: "http://exmwks21/suggester/images/"
};
ch.exmachina.bravofly.language = "it";
ch.exmachina.bravofly.searchImg = "search.png";
ch.exmachina.bravofly.dateFormat = "dd/MM/yyyy";

ch.exmachina.bravofly.properties = {
    it: {
        messages: {
            noAirports: "Selezionare l'aeroporto di partenza e l'aeroporto di destinazione",
            dateInversion: "Attenzione: la data del volo di andata deve essere antecedente a quella del volo di ritorno",
            infantsNumber: "Il numero dei neonati non deve eccedere quello degli adulti!"
        },
        monthNames: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
        logo: "volagratis.png",
        logoLink: "http://www.volagratis.com/vg1/voli.do",
        searchUrl: "http://www.volagratis.com/vg1/searching.do",
        title: "Ricerca voli",
        depAir: "Partenza",
        destAir: "Arrivo",
        outboundDate: "Andata",
        returnDate: "Ritorno",
        adults: "Adulti",
        children: "Bambini",
        infants: "Neonati",
        currency: "Valuta",
        passengers: "Passeggeri",
        depOnly: "Solo andata",
        infantsAge: "0-24 mesi",
        childrenAge: "2-12 anni",
        adultsAge: "da 12 anni",
        days: ["L", "M", "M", "G", "V", "S", "D"],
	    update: "Chiudi",
        currencies: [
            { k: "EUR", v: "EUR" },
            { k: "USD", v: "USD" },
            { k: "GBP", v: "GBP" },
            { k: "SEK", v: "SEK" },
            { k: "PLN", v: "PLN" },
            { k: "CHF", v: "CHF" },
            { k: "RUB", v: "RUB" },
            { k: "DKK", v: "DKK" },
            { k: "JPY", v: "JPY" }
        ]
    },
    fr: {
        messages: {
            noAirports: "Merci de s\351lectionner vos a\351roports",
            dateInversion: "La date de d\351part doit pr\351c\351der la date de retour",
            infantsNumber: "Le nombre de b\351b\351s ne doit pas exc\351der celui des adultes!"
        },
        monthNames: ["Janvier", "F\351vrier", "Mars", "Avril", "Mai", "Juin", "Juliet", "Ao\373t", "Septembre", "Octobre", "Novembre", "D\351cembre"],
        logo: "bravoflybanner_100.png",
        logoLink: "http://www.bravofly.fr/vg1/vols.do",
        searchUrl: "http://www.bravofly.fr/vg1/searching.do",
        title: "Vols",
        depAir: "De",
        destAir: "A",
        outboundDate: "Aller",
        returnDate: "Retour",
        adults: "Adultes",
        children: "Enfants",
        infants: "B&eacute;b&eacute;s",
        currency: "Devise",
        passengers: "Passagers",
        depOnly: "Aller simple",
        infantsAge: "de 0 &agrave; 24 mois",
        childrenAge: "2-12 ans",
        adultsAge: "plus de 12 ans",
        days: ["L", "M", "M", "J", "V", "S", "D"],
	    update: "Fermer",
        currencies: [
            { k: "EUR", v: "EUR" },
            { k: "USD", v: "USD" },
            { k: "GBP", v: "GBP" },
            { k: "SEK", v: "SEK" },
            { k: "PLN", v: "PLN" },
            { k: "CHF", v: "CHF" },
            { k: "RUB", v: "RUB" },
            { k: "DKK", v: "DKK" },
            { k: "JPY", v: "JPY" }
        ]
    },
    en: {
        messages: {
            noAirports: "Choose your airports",
            dateInversion: "Please note: outbound date must be before return date",
            infantsNumber: "It is not possible to book more Infants than Adults"
        },
        monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        logo: "bravoflybanner_100.png",
        logoLink: "http://www.bravofly.com/vg1/searching.do",
        searchUrl: "http://www.bravofly.com/vg1/searching.do",
        title: "Search flights",
        depAir: "Depart. apt",
        destAir: "Arrival apt",
        outboundDate: "Outbound",
        returnDate: "Return",
        adults: "Adults",
        children: "Children",
        infants: "Infants",
        currency: "Currency",
        passengers: "Passengers",
        depOnly: "One way",
        infantsAge: "0 to 24 months",
        childrenAge: "2-12 years old",
        adultsAge: "from 12 years old",
        days: ["M","T","W","T","F","S","S"],
	    update: "Close",
        currencies: [
            { k: "EUR", v: "EUR" },
            { k: "USD", v: "USD" },
            { k: "GBP", v: "GBP" },
            { k: "SEK", v: "SEK" },
            { k: "PLN", v: "PLN" },
            { k: "CHF", v: "CHF" },
            { k: "RUB", v: "RUB" },
            { k: "DKK", v: "DKK" },
            { k: "JPY", v: "JPY" }
        ]
    },
    engb: {
        messages: {
            noAirports: "Choose your airports",
            dateInversion: "Please note: outbound date must be before return date",
            infantsNumber: "It is not possible to book more Infants than Adults"
        },
        monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"],
        logo: "bravoflybanner_100.png",
        logoLink: "http://www.bravofly.co.uk/vg1/searching.do",
        searchUrl: "http://www.bravofly.co.uk/vg1/searching.do",
        title: "Search flights",
        depAir: "Depart. apt",
        destAir: "Arrival apt",
        outboundDate: "Outbound",
        returnDate: "Return",
        adults: "Adults",
        children: "Children",
        infants: "Infants",
        passengers: "Passengers",
        currency: "Currency",
        depOnly: "One way",
        infantsAge: "0 to 24 months",
        childrenAge: "2-12 years old",
        adultsAge: "from 12 years old",
        days: ["M","T","W","T","F","S","S"],
	    update: "Close",
        currencies: [
            { k: "EUR", v: "EUR" },
            { k: "USD", v: "USD" },
            { k: "GBP", v: "GBP" },
            { k: "SEK", v: "SEK" },
            { k: "PLN", v: "PLN" },
            { k: "CHF", v: "CHF" },
            { k: "RUB", v: "RUB" },
            { k: "DKK", v: "DKK" },
            { k: "JPY", v: "JPY" }
        ]
    },
    de: {
        messages: {
            noAirports: "W\344hlen Sie einen Flughafen",
            dateInversion: "Das Abflugdatum muss vor den R\374ckflugtermin gelegt werden",
            infantsNumber: "Die Nummer der Babys darf die Nummer der Erwachsenen nicht ueberschreiten"
        },
        monthNames: ["Januar", "Februar", "M\344rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
        logo: "bravoflybanner_100.png",
        logoLink: "http://www.bravofly.de/vg1/searching.do",
        searchUrl: "http://www.bravofly.de/vg1/searching.do",
        title: "Flugsuche",
        depAir: "Abflughafen",
        destAir: "Zielflughafen",
        outboundDate: "Hinflug",
        returnDate: "R&uuml;ckflug",
        adults: "Erwachsene",
        children: "Kinder",
        infants: "Babys",
        currency: "W\344hrung",
        passengers: "Passagiere",
        depOnly: "Nur Hinflug",
        infantsAge: "0 bis 24 Monate",
        childrenAge: "2-12 Jahre",
        adultsAge: "Ab 12 Jahre",
        days: ["M", "D", "M", "D", "F", "S", "S"],
	    update: "Schliessen",
        currencies: [
            { k: "EUR", v: "EUR" },
            { k: "USD", v: "USD" },
            { k: "GBP", v: "GBP" },
            { k: "SEK", v: "SEK" },
            { k: "PLN", v: "PLN" },
            { k: "CHF", v: "CHF" },
            { k: "RUB", v: "RUB" },
            { k: "DKK", v: "DKK" },
            { k: "JPY", v: "JPY" }
        ]
    },
    es: {
        messages: {
            noAirports: "Selecciona los aeropuertos",
            dateInversion: "La fecha de ida debe de ser anterior a la fecha de regreso",
            infantsNumber: "!El n\372mero de beb\351s no puede superar el de adultos!"
        },
        monthNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
        logo: "bravoflybanner_100.png",
        logoLink: "http://www.bravofly.es/vg1/searching.do",
        searchUrl: "http://www.bravofly.es/vg1/searching.do",
        title: "B&uacute;squeda vuelos",
        depAir: "Salida desde",
        destAir: "Destino",
        outboundDate: "Salida",
        returnDate: "Regreso",
        adults: "Adultos",
        children: "Ni&ntilde;os",
        infants: "Beb&eacute;s",
        currency: "Moneda",
        passengers: "Pasajeros",
        depOnly: "S\363lo ida",
        infantsAge: "de 0 a 24 meses",
        childrenAge: "2-12 a\361os",
        adultsAge: "de 12 a\361os",
        days: ["L", "M", "M", "J", "V", "S", "D"],
	    update: "Cerrar",
        currencies: [
            { k: "EUR", v: "EUR" },
            { k: "USD", v: "USD" },
            { k: "GBP", v: "GBP" },
            { k: "SEK", v: "SEK" },
            { k: "PLN", v: "PLN" },
            { k: "CHF", v: "CHF" },
            { k: "RUB", v: "RUB" },
            { k: "DKK", v: "DKK" },
            { k: "JPY", v: "JPY" }
        ]
    }
};

ch.exmachina.bravofly.DatePicker = function(ctorArgs){
	var node = ctorArgs.node,
		tname = document.createElement("thead"),
		tinfo = document.createElement("thead"),
		thead = document.createElement("thead"),
		tb = document.createElement("tbody"),
		row = null,
		cell = null,
		dateLabel = ctorArgs.dateLabel,
		self = this,
        days = ctorArgs.days
    ;
	this.onShow = ctorArgs.onShow || this.onShow;
	this.onHide = ctorArgs.onHide || this.onHide;
	this.onSetDate = ctorArgs.onSetDate || this.onSetDate;

	this.domNode = document.createElement("table");
	this.calNode = ctorArgs.calNode;

	this.calDateFormat = ctorArgs.calDateFormat || this.calDateFormat;
	this.fieldDateFormat = ctorArgs.fieldDateFormat || this.fieldDateFormat;
    this.monthNames = ctorArgs.monthNames || this.monthNames;
    for(var i = 0, mn = this.monthNames.length; i < mn; i++){
        this.monthNames[i] = this.monthNames[i].substring(0, 3);
    }

	this.date = ctorArgs.date;
	row = document.createElement("tr");

	// testata con identificativo calendario (partenza o ritorno)
	cell = document.createElement("th");
	cell.colSpan = "7";
	cell.style.textAlign = "center";
	cell.appendChild(document.createTextNode(ctorArgs.label || ""));
	row.appendChild(cell);
	tname.appendChild(row);

	row = document.createElement("tr");
	// testata con mese
	cell = document.createElement("th");
	cell.appendChild(document.createTextNode("<"));
    cell.style.cursor = "pointer";
	cell.onclick = function(){
		self.showedMonth--;
		self.showedYear += parseInt((self.showedMonth % 12) / 12);
		self.fillIn({
			month: self.showedMonth,
			year: self.showedYear
		});
	};
	row.appendChild(cell);
	cell = document.createElement("th");
	cell.colSpan = "5";
	this.monthNameNode = cell;
	cell.style.textAlign = "center";
	cell.appendChild(document.createTextNode(this.monthNames[this.date.getMonth()]));
	row.appendChild(cell);
	cell = document.createElement("th");
	cell.appendChild(document.createTextNode(">"));
    cell.style.cursor = "pointer";
	cell.onclick = function(){
		self.showedMonth++;
		self.showedYear += parseInt((self.showedMonth % 12) / 12);
		self.fillIn({
			month: self.showedMonth,
			year: self.showedYear
		});
	};
	row.appendChild(cell);
	tinfo.appendChild(row);
	// fine testata

	row = document.createElement("tr");
	for(var i = 0; i < 7; i++){
		cell = document.createElement("th");
		cell.appendChild(document.createTextNode(days[i]));
		row.appendChild(cell);
	}
	tinfo.appendChild(row);
	for(i = 0; i < 6; i++){
		row = document.createElement("tr");
		for(var j = 0; j < 7; j++){
			cell = document.createElement("td");
			cell.style.textAlign = "center";
            cell.style.cursor = "pointer";
			row.appendChild(cell);
		}
		tb.appendChild(row);
	}

    var xCloser = document.createElement("img");
    xCloser.style.position = "absolute";
    xCloser.style.top = "0";
    xCloser.style.right = "0";
    xCloser.style.cursor = "pointer";
    xCloser.src = ch.exmachina.bravofly.remote.imgPosition + "x.png";
    xCloser.onclick = function(){
        self.hideCal();
    };
    node.style.zIndex = "200";
	this.domNode.appendChild(tname);
	this.domNode.appendChild(thead);
	this.domNode.appendChild(tinfo);
	this.domNode.appendChild(tb);
    this.calNode.appendChild(xCloser);
	this.calNode.appendChild(this.domNode);
	this.fillIn({
		month: this.date.getMonth(),
		year: this.date.getFullYear()
	});

	// date text fields
	var fieldContainer = document.createElement("div")
	;
	this.iconNode = document.createElement("img");
	this.iconNode.src = ch.exmachina.bravofly.remote.imgPosition + "calendar.png";
	this.iconNode.className = "Nbravofly_calendar_icon bravofly_calendar_icon";
	this.iconNode.onclick = function(evt){
		self.showCal();
        var e = evt || window.event;
        e.stopPropagation && e.stopPropagation();
        e.cancelBubble = true;
        return false;
	};
	this.dateField = document.createElement("input");
	this.dateField.className = "Nbravofly_datefield bravofly_datefield";
	this.dateField.readOnly = "true";
	this.dateField.type = "text";
	var s = this.dateField.style;
	s.position = "relative";
	s.left = "-15px";
	this.dateField.onclick = function(evt){
		self.showCal();
        var e = evt || window.event;
        e.stopPropagation && e.stopPropagation();
        e.cancelBubble = true;
        return false;
	};
    var anode = document.createElement("div");
    anode.className = "Nlabel_wrapper label_wrapper";
    anode.innerHTML = dateLabel + " ";

//    fieldContainer.style.textAlign = "left";

    fieldContainer.appendChild(anode);
	fieldContainer.appendChild(this.dateField);
	fieldContainer.appendChild(this.iconNode);
//    anode.style.textAlign = "left";
    this.labelWrapperNode = anode;
	node.appendChild(fieldContainer);
	this.showFormattedDate();
	this.bindEvents();
};
ch.exmachina.bravofly.DatePicker.prototype = {
	fieldDateFormat: "dd/mm/yyyy",
	calDateFormat: "MMM yyyy",
	domNode: null,
	date: null,
	iconNode: null,
	calNode: null,
	dateField: null,
    monthNameNode: null,
	monthNames: ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"],
	showedMonth: 0,
	showedYear: 0,
    disabled: false,
    labelWrapperNode: null,
	// hooks
	onShow: function(){},
	onHide: function(){},
    onSetDate: function(){},
    validate: function(){
        return true;
    },
    disable: function(){
        this.disabled = true;
        this.dateField.disabled = "disabled";
        this.labelWrapperNode.className = "Ndisabled_label_wrapper disabled_label_wrapper";
        this.iconNode.style.visibility = "hidden";
    },
    enable: function(){
        this.disabled = false;
        this.dateField.disabled = "";
        this.labelWrapperNode.className = "Nlabel_wrapper label_wrapper";
        this.iconNode.style.visibility = "visible";
    },
	showFormattedDate: function(){
		var dd = this.date.getDate() < 10 ? "0" + this.date.getDate() : this.date.getDate(),
			MMM = ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["monthNames"][(this.date.getMonth())],
			MM = this.date.getMonth() < 9 ? "0" + (this.date.getMonth() + 1) : this.date.getMonth() + 1,
			yyyy = this.date.getFullYear()
		;
		this.dateField.value = this.fieldDateFormat
			.replace(/dd/, dd)
			.replace(/MMM/, MMM)
			.replace(/MM/, MM)
			.replace(/yyyy/, yyyy)
		;
	},
	showCal: function(){
		this.calNode.style.display = "block";
		this.onShow();
	},
	hideCal: function(stopEvt){
		this.calNode.style.display = "none";
		!stopEvt && this.onHide();
	},
	setCalDate: function(/** Object */args){
		this.monthNameNode.innerHTML = this.calDateFormat
			.replace(/MMM/, args.monthName)
			.replace(/yyyy/, args.year)
		;
	},
	setMonthName: function(/** String */ monthName){
		this.monthNameNode.innerHTML = monthName;
	},
	bindEvents: function(){
		var self = this;
		this.domNode.onclick = function(e){
			self.clickHandler.call(self, e);
		};
	},
	clickHandler: function(e){
        if(this.disabled){ return; }
		var sw = ch.exmachina.bravofly.searchWidget,
			evt = sw.fixEvent(e),
			trg = sw.getTarget(evt)
		;
		if(trg.tagName && (trg.tagName === "span" || trg.tagName === "SPAN") && trg.firstChild.data
                && trg.className && trg.className != "Ndisabled_cell_target"){
            if(isNaN(parseInt(trg.firstChild.data))){ return; }
            if(!this.validate()){ return; };
			this.date.setYear(this.showedYear);
			this.date.setMonth(this.showedMonth);
			this.date.setDate(trg.firstChild.data);
            this.onSetDate.call(this, this.date);
			this.showDate(this.date);
			this.showFormattedDate();
			this.hideCal();
		}
	},
	showDate: function(/** Date */ pDate){
		this.fillIn({
			month: pDate.getMonth(),
			year: pDate.getFullYear()
		});
	},
	setDate: function(/** Date */ pDate){
		this.date = pDate;
	},
	empty: function(){
		var datePickerNode = this.calNode,
			cells = datePickerNode.getElementsByTagName("td"),
			clen = cells.length
		;
		for(var i = 0; i < clen; i++){
			cells[i].style.border = "none";
			cells[i].style.padding = "2px";
			cells[i].innerHTML = "&nbsp;";
		}
	},
    toString: function(){
        return "[ch.exmachina.bravofly.Datepicker]";
    },
	fillIn: function(/** Object */ args){
		var month = args.month,
			year = args.year,
			cDate = new Date(), // current date
            lDayOfMonth,
			lDate = new Date(),  // user for last month day computation
            today = new Date(),
            genericDate,
            cName
		;
		lDate.setYear(year);
		lDate.setDate(1);
		lDate.setMonth(month + 1);
		lDate.setDate(lDate.getDate() - 1);
		lDayOfMonth = lDate.getDate();

		cDate.setYear(year);
		cDate.setMonth(month);
		cDate.setDate(1);

		this.empty();
		var shift = 6, // determined by i18n
			dow = (cDate.getDay() + shift) % 7,
			cells = this.calNode.getElementsByTagName("td"),
			clen = cells.length
		;
		// migliorare questo ciclo for, meglio un while
        genericDate = new Date();
        genericDate.setMonth(cDate.getMonth());
        genericDate.setYear(cDate.getFullYear());
        today.setHours(cDate.getHours(), cDate.getMinutes(), cDate.getSeconds(), cDate.getMilliseconds());
        genericDate.setHours(cDate.getHours(), cDate.getMinutes(), cDate.getSeconds(), cDate.getMilliseconds());
        for(var i = 0; i < clen; i++){
			if(i < lDayOfMonth){
                genericDate.setDate(i + 1);
                cName = genericDate <= today ? "disabled" : "";
				cells[dow + i].innerHTML = "<span class='N" + cName + "_cell_target'>" + parseInt(i + 1) + "</span>";
			}
		}
		this.showedMonth = (month + 12) % 12;
		this.showedYear = cDate.getFullYear();
		this.setCalDate({
			monthName: this.monthNames[this.showedMonth],
			year: this.showedYear
		});
		if(this.showedMonth === this.date.getMonth() && this.showedYear === this.date.getFullYear()){
			var s = cells[dow + this.date.getDate() - 1].style;
			s.border = "2px solid red";
			s.padding = "0";
		}
	}
};
ch.exmachina.bravofly.searchWidget = {
	// nodes
	domNode: null,
	depListNode: null,
	depFieldNode: null,
	arrListNode: null,
	arrFieldNode: null,
	buttonNode: null,
	coverNode: null,
	selectNode: null,
	adultsNode: null,
	childrenNode: null,
	infantsNode: null,
	currencyContainerNode: null,


	depDatePicker: null,
	retDatePicker: null,

	transport: null,
    deptransport: null,
    arrtransport: null,
	minChar: 3,
	selectedItem: {
		dep: 0,
		arr: 0
	},
	detailsUrl: "{$searchUrl}?outboundDay={$outDay}&outboundMonthYear={$outMY}&" +
			"returnDay={$retDay}&returnMonthYear={$retMY}&departureAirport={$depAir}&arrivalAirport={$retAir}&{$adults}&{$children}&{$infants}" +
                "&currency={$currency}&url=search3.do",
	language: "IT",
	searchLimit: 20,
	type: "dep",

	url: "http://www.volagratis.com/suggester/proxy/suggest_remote?{$key}&{$language}&{$limit}&{$type}{$sugQueryString}&jsonp={$cback}({ code:'{$code}', prefix: '{$prefix}', list:\"",

	template: '<table class="Nbravofly_setBlock Nbravofly_main_table_container bravofly_main_table_container" style="position:relative;" cellpadding="0" cellspacing="0"><tbody class="Nbravofly_setBlock">' +
			// rounded corners
			'<tr class="Nbravofly_round_container bravofly_round_container"><td class="bravofly_nw_corner Nbravofly_setBlock"></td><td class="bravofly_top_middle Nbravofly_setBlock"></td><td class="bravofly_ne_corner Nbravofly_setBlock"></td></tr>' +
			'<tr class="Nbravofly_setBlock"><td colspan="3" class="Nbravofly_setBlock">' +
			'<div>' +
			'<div id="Cover{$WidgetId}" style="width:100%;height:300px;top:-20px;background:black;opacity:.7;position:absolute;z-index:200;display:none;filter:alpha(opacity=70);"></div>' +
			'<div id="depCal{$WidgetId}" class="depCalNode{$WidgetId} bravofly_datepicker Nbravofly_departure_datepicker bravofly_departure_datepicker"></div>' +
			'<div id="retCal{$WidgetId}" class="arrCalNode{$WidgetId} bravofly_datepicker Nbravofly_arrival_datepicker bravofly_arrival_datepicker"></div>' +


            '<div class="Nbravofly_widget_container bravofly_widget_container" id="DomNode{$WidgetId}" ' +
				'style="position:relative;">' +

			'<div class="Nbravofly_DepContainer bravofly_DepContainer">' +
				'<div id="DepLabelWrapper{$WidgetId}" class="Nlabel_wrapper label_wrapper"><label>{$depAir} </label></div>' +
				'<input class="Nbravofly_input_text bravofly_input_text" type="text" value="" id="DepTextField{$WidgetId}" />' +
				'<div id="DepList{$WidgetId}" ' +
					'class="Nbravofly_list bravofly_list"></div>' +
			'</div>' +

			'<div class="Nbravofly_RetContainer bravofly_RetContainer">' +
				'<div class="Nlabel_wrapper label_wrapper"><label>{$destAir} </label></div>' +
				'<input class="Nbravofly_input_text bravofly_input_text" type="text" value="" id="ArrTextField{$WidgetId}" />' +
				'<div id="ArrList{$WidgetId}" ' +
					'class="Nbravofly_list bravofly_list"></div>' +
			'</div>' +
			'<div id="DepContainer{$WidgetId}" class="Nbravofly_departure_datepicker_container bravofly_departure_datepicker_container">' +
				'<div id="DepDatePicker{$WidgetId}" class="Nbravofly_datepicker_row bravofly_datepicker_row">' +
				'</div>' +
			'</div>' +
			'<div id="RetContainer{$WidgetId}" class="Nbravofly_arrival_datepicker_container bravofly_arrival_datepicker_container">' +
				'<div id="RetDatePicker{$WidgetId}" class="Nbravofly_datepicker_row bravofly_datepicker_row">' +
				'</div>' +
			'</div>' +

            '<div class="Nbravofly_logo bravofly_logo">' +
				'<a href="{$logoLink}"><img src="' + ch.exmachina.bravofly.remote.imgPosition + '{$logo}" /></a>' +
			'</div>' +


	          '<div id="CurrencyContainer{$WidgetId}" class="Nbravofly_currency_container bravofly_currency_container">' +
	          '<label class="Nbravofly_currency_label bravofly_currency_label">{$currency}</label>' +
	          '<select id="Currencies{$WidgetId}"></select>' +
	          '<div class="Nbravofly_currencies_note bravofly_currencies_note"></div>' +
	          '</div>' +


              '<div class="Nbravofly_deponly_container bravofly_deponly_container">' +
              '<input type="checkbox" id="DepOnly{$WidgetId}" />' +
              '<label class="Nbravofly_deponly_label bravofly_deponly_label">{$deponly}</label>' +
              '<div class="Nbravofly_deponly_note bravofly_deponly_note"></div>' +
              '</div>' +
			'<div id="Select{$WidgetId}" class="Nbravofly_select bravofly_select">' +
					'<div id="AdultsContainer{$WidgetId}" class="Nbravofly_adults_container bravofly_adults_container">' +
					'<label class="Nbravofly_adults_label bravofly_adults_label">{$adults}</label>' +
					'<select id="Adults{$WidgetId}"><option value="1" selected="selected">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>' +
                    '<div class="Nbravofly_adults_note bravofly_adults_note">{$adultsAge}</div>' +
                    '</div>' +
					'<div id="ChildrenContainer{$WidgetId}" class="Nbravofly_children_container bravofly_children_container">' +
					'<label class="Nbravofly_children_label bravofly_children_label">{$children}</label>' +
					'<select id="Children{$WidgetId}"><option value="0" selected="selected">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>' +
                    '<div class="Nbravofly_children_note bravofly_children_note">{$childrenAge}</div>' +
                    '</div>' +
					'<div id="InfantsContainer{$WidgetId}" class="Nbravofly_infants_container bravofly_infants_container">' +
                    '<label class="Nbravofly_children_label bravofly_children_label">{$infants}</label>' +
					'<select id="Infants{$WidgetId}"><option value="0" selected="selected">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>' +
                    '<div class="Nbravofly_infants_note bravofly_infants_note">{$infantsAge}</div>' +
                    '</div>' +
                // start button container
              '<div class="Nbravofly_button_container bravofly_button_container">' +
                  '<div id="Button{$WidgetId}" class="Nbravofly_submit_button bravofly_submit_button"></div>' +
              '</div>' +
        // end button container
        // start panel container
      '<div class="Nbravofly_passengers_panel bravofly_passengers_panel" id="PassengersPanel{$WidgetId}">' +
      '<div class="Nbravofly_panel_body bravofly_panel_body">' +
        // interno del pannello
        '<div class="Nbravofly_panel_adults bravofly_panel_adults"><label>{$adults}</label>' +
        '<select id="panel_adults{$WidgetId}"><option selected="selected" value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>' +
        '<div class="Nbravofly_adults_note bravofly_adults_note">{$adultsAge}</div>' +
        '</div>' +
        '<div class="Nbravofly_panel_children bravofly_panel_children_panel"><label>{$children}</label><select id="panel_children{$WidgetId}"><option value="0" selected="selected">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>' +
        '<div class="Nbravofly_children_note_panel  bravofly_children_note_panel">{$childrenAge}</div>' +
        '</div>' +
        '<div class="Nbravofly_panel_infants bravofly_panel_infants"><label>{$infants}</label><select id="panel_infants{$WidgetId}"><option value="0" selected="selected">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>' +
        '<div class="Nbravofly_infants_note bravofly_infants_note">{$infantsAge}</div>' +
        '</div>' +
        '<div class="Nbravofly_panel_update_button bravofly_panel_update_button"><button id="updatePassengers{$WidgetId}">' +
        '{$Update}</button></div>' +

        '</div><div class="Nbravofly_panel_tab bravofly_panel_tab"></div></div>' +
        // end panel container
        // start panel trigger
              '<div id="PassengersContainer{$WidgetId}" class="Nbravofly_passengers_container bravofly_passengers_container">' +
              '<label class="Nbravofly_passengers_label bravofly_passengers_label">{$passengers}</label>' +
          '<div class="Nbravofly_select_trigger"><div id="PassengersTrigger{$WidgetId}" class="Nbravofly_dropdown_button_container">1<img class="Nbravofly_dropdown_button" src="' + ch.exmachina.bravofly.remote.imgPosition + 'select_button.png" /></div></div>' +
          '</div>' +
        // end panel trigger

            '</div></div>' +
              // end widget_container

			'<div class="Nbravofly_tab_container bravofly_tab_container">' +
            '<div class="Nbravofly_title_tab bravofly_title_tab" id="Title{$WidgetId}">{$title}</div>' +
            '</div></div>' +
			'</td></tr>' +
			'<tr class="Nbravofly_round_container bravofly_round_container"><td class="bravofly_sw_corner Nbravofly_setBlock"></td><td class="bravofly_bottom_middle Nbravofly_setBlock"></td><td class="bravofly_se_corner Nbravofly_setBlock"></td></tr>' +
			'</tbody></table>',
	styleTemplate: '' +
	            '.Nbravofly_main_table_container{ margin-bottom: 30px }' +
	            '.Nbravofly_round_container{ display:none }' +
				'#DomNode{$WidgetId} input{  }' +
				'.depCalNode{$WidgetId} { border:3px solid #fff;background:#ddd;top:133px;left:60px;' +
				'position:absolute;z-index:210;display:none;font:12px Arial,Helvetica,Sans-serif }' +
				'.arrCalNode{$WidgetId} { border:3px solid #fff;background:#ddd;top:153px;left:60px;z-index:200;' +
				'position:absolute;z-in dex:210;display:none;font:12px Arial,Helvetica,Sans-serif }' +
				'.Ndisabled_cell_target{text-decoration: line-through}' +


	            // passengers panel
	            '.Nbravofly_panel_tab{ background: #eee; position:absolute;border:1px solid #ccc;border-bottom:none;height:30px; width:70px; left:180px;padding:0;margin:0 }' +
	            '.Nbravofly_panel_body{ background: #eee; position:absolute; margin:0;padding:0;border:1px solid #ccc;height:170px; width:300px; top:30px;left:0 }' +
	            '.Nbravofly_passengers_panel{ position:absolute; display:none; width:300px; height:200px; left:345px}' +
	            // panel select
	            '.Nbravofly_passengers_panel label{ font-size:13px; color:#666666; font-weight:bold; margin-right:5px;font-family: tahoma,verdana,helvetica }' +
	            '.Nbravofly_panel_adults{position:absolute;text-align:right;width:140px;top:35px;right:180px;}' +
	            '.Nbravofly_panel_children{position:absolute;text-align:right;width:140px;top:35px;right:20px;}' +

	            '.Nbravofly_panel_infants{position:absolute;text-align:right;width:140px;top:95px;right:180px}' +
	            '.Nbravofly_panel_update_button{position:absolute;text-align:right;width:140px;top:95px;right:40px;}' +
 			    '.Nbravofly_panel_update_button button{border:1px solid #999;' +
 				  'font-weight:bold; font-family: tahoma,verdana,helvetica; color: #666;background:#ddd;text-align:center;font-size:13px}' +
	            // dropdownbutton
	            '.Nbravofly_select_trigger{ background:white;position:relative;color:black;text-align:center;float:left;font:normal 13px tahoma,verdana,helvetica;font-size:13px;border:1px solid #999;height:18px;_height:20px;width:60px;}' +
	            '.Nbravofly_dropdown_button{ position:absolute;height:18px;right:0;top:0;width:18px;border:none}' +
				// customizable properties
				'.Nbravofly_calendar_icon{ position:absolute;top:0;left:190px}' +
                '.Ndisabled_label_wrapper{ float:left; margin-left:5px; width:85px;text-align:right; color: #ccc }' +
                '.Nlabel_wrapper{ float:left; margin-left:5px; width:85px;text-align:right;white-space:nowrap}' +
                '.Nbravofly_button_container{text-align:right;position:absolute;top:95px;right:0;height:20px;width:102px;padding:0;margin:0}' +

                // select start
                '.Nbravofly_adults_note{text-align:right;font-size:10px; width:135px;white-space:nowrap}' +
                '.Nbravofly_children_note{text-align:right;font-size:10px; width:110px;white-space:nowrap}' +
	            '.Nbravofly_children_note_panel{text-align:right;font-size:10px; width:135px;white-space:nowrap}' +
                '.Nbravofly_infants_note{text-align:right;font-size:10px;width:135px;white-space:nowrap}' +
                '.Nbravofly_select{position:absolute;top:100px;left:18px;width:260px;font-weight:normal;text-align:right;}' +
                '.Nbravofly_select label{font-weight:bold; margin-right:10px; text-align:right}' +
                '.Nbravofly_select table{width:260px}' +
                '.Nbravofly_select select {border:1px solid #999}' +
                '.Nbravofly_select td {width: 65px}' +
                '.Nbravofly_adults_container{ position:absolute; top:20px;right:135px;width:138px;text-align:right}' +
                '.Nbravofly_children_container{position:absolute; top:20px;right:0px;width:110px;text-align:right;}' +
                '.Nbravofly_infants_container{position:absolute; top:60px;right:135px;width:138px;text-align:right}' +
                '.Nbravofly_currency_container{position:absolute; top:160px;right:20px;width:140px;text-align:right}' +
			   '.Nbravofly_currency_container select{border:1px solid #999}' +
                '.Nbravofly_passengers_container{position:absolute;margin:0;padding:0;top:60px;left:430px;width:190px;text-align:right;display:none;}' +
	            '.Nbravofly_passengers_container label{float:left;padding-right:10px;width:80px}' +

                // select end
                // checkbox
                '.Nbravofly_deponly_container{position:absolute; top:70px;right:10px;width:80px;text-align:left;z-index:90}' +
                '.Nbravofly_deponly_container input {float:left}' +
                '.Nbravofly_deponly_container label {}' +

                // datepickers
                '.Nbravofly_departure_datepicker{position:absolute;top:80px;left:40px;}' +
                '.Nbravofly_arrival_datepicker{position:absolute;top:100px;left:40px;}' +
                '.Nbravofly_departure_datepicker_container{position:absolute; z-index:60;top:65px;left:0;height:20px;width:250px;text-align:left}' +
                '.Nbravofly_arrival_datepicker_container{position:absolute; z-index:60;top:90px;left:0;height:20px;width:250px;text-align:left}' +

                '.Nbravofly_DepContainer{z-index:150;text-align:right;position:absolute;top:5px;left:0;height:20px;width:280px;padding:0;margin:0}' +
                '.Nbravofly_RetContainer{z-index:100;text-align:right;position:absolute;top:35px;left:0px;height:20px;width:280px;padding:0;margin:0}' +

                '.Nbravofly_logo {z-index:100;text-align:center;position:absolute;bottom:15px;left:10px;height:20px;width:100px;padding:0;margin:0}' +
				'.Nbravofly_logo a{display:none}' +
				'.Nbravofly_logo img{border: 0;display: inline}' +
				'.Nbravofly_calendar_cover{width:100%;height:300px;top:-20px;background:black;opacity:.7;position:absolute;z-index:200;display:none;filter:alpha(opacity=70);}' +
				'.Nbravofly_datepicker_row{z-index:10;text-align:right;padding:0;margin:0;width:204px;}' +
                '.Nbravofly_tab_container{display:none; position:absolute;top:0;left:0;border-bottom:none;height:22px;z-index:110;background:#fff}' +
                '.Nbravofly_title_tab{font:bold 13px tahoma, verdana, helvetica;margin-bottom:-2px;color:#2577ac;border:2px solid #2577ac; border-bottom:2px ;width:160px;text-align:center;height:20px;}' +
				'.Nbravofly_submit_button{cursor:pointer;height:25px; width:102px;' +
                'background: #fff url("' + ch.exmachina.bravofly.remote.imgPosition + '{$language}/search.png") 0 0 no-repeat }' +
               '.Nbravofly_list ul{cursor:pointer;border: 2px solid #93bad7;list-style-position:outside;padding:0;text-align:left;list-style:none;margin:0}' +
               '.Nbravofly_list ul li{font:12px Arial,Helvetica,Sans-serif; margin:0; text-align:left; width:100%;}' +
               '.Nbravofly_list ul li span{font:12px Arial,Helvetica,Sans-serif;margin:0}' +
               '.Nbravofly_list ul li span.hilite{ color:#000;font:bold 12px Arial,Helvetica,Sans-serif;margin:0;padding:0 }' +
               '.Nbravofly_list ul li.selected{ background:#93bad7; color:#000;}' +
               '.Nbravofly_list ul li.selected span.hilite{ color:black;font:bold 12px Arial,Helvetica,Sans-serif;margin:0;padding:0 }' +
				'.Nbravofly_list{ display:none;position:absolute;top:22px;right:0px;width:260px}' +
                '.Nbravofly_list{ background:#dce9f2;color:#000;}' +
				'.Nbravofly_datefield{ font:12px Arial,Helvetica,Sans-serif;padding:0;margin:0;height:16px;width:80px;border:1px solid #999} ' +
				'.Nbravofly_input_text{font:12px Arial,Helvetica,Sans-serif;padding:1px;margin:0;height:18px;width:170px;margin-right:0;' +
					'border:1px solid #999}' +
				'.Nbravofly_widget_container{ position:absolute; top:12px; left:0; z-index:100;background: transparent; color:#666; ' +
					'font:bold 13px tahoma, verdana, helvetica; width:300px;height:230px}' +
				'.Nbravofly_setBlock {display:block; z-index:200}' +
			'',
    callsToDo: 0,
    calls: 0,
    parameters: {},
    _currentTab: "",
    _isFirstSetDate: true,
    _defaultTab: 0,
	// methods
    onLoad: function(){},
    _setupTabs: function(){
        var p = this.parameters,
            tabs = p["tabs"],
            tl = tabs ? tabs.length : 0,
            self = this,
            m = self.fnMap,
            t,
            ct,
            tx,
            clickHandler = function(x){
                return function(){
                    if(!tl){ return; }
                    for(var j = 0; j < tl; j++){
                        ct = document.getElementById(tabs[j]["id"]);
                        ct.className = ct.className.replace(/selected/g, "");
                    }
                    tx = document.getElementById(tabs[x]["id"]);
                    tx.className = tx.className + " selected";
                    if(self._currentTab != x){
                        self._currentTab = x;
                        self[m[tabs[x]["action"]]].call(self);
                    }
                };
            };
        ;
        this._defaultTab = p["defaultTab"] || 0;
        for(var i = 0; i < tl; i++){
            t = document.getElementById(tabs[i]["id"]);
            t.onclick = clickHandler(i);
        }
        clickHandler(this._defaultTab)();
    },
	startup: function(){
        this.getParameters();
        var p = this.parameters;
        this.setLocale();
        var searchWidget = ch.exmachina.bravofly.searchWidget,
	         tInstance = ch.exmachina.bravofly.searchWidget.template
                .replace(/{\$WidgetId}/g, ch.exmachina.bravofly.searchWidget.ts),
             dateFormat = p.dateFormat || ch.exmachina.bravofly.dateFormat
            ;
        tInstance = tInstance.replace(/{\$title}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["title"])
            .replace(/{\$depAir}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["depAir"])
            .replace(/{\$destAir}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["destAir"])
            .replace(/{\$outboundDate}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["outboundDate"])
            .replace(/{\$returnDate}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["returnDate"])
            .replace(/{\$adults}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["adults"])
            .replace(/{\$children}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["children"])
            .replace(/{\$infants}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["infants"])
            .replace(/{\$currency}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["currency"])
            .replace(/{\$language}/g, ch.exmachina.bravofly.language)
            .replace(/{\$logo}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].logo)
            .replace(/{\$deponly}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].depOnly)
            .replace(/{\$logoLink}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].logoLink)
            .replace(/{\$infantsAge}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].infantsAge)
            .replace(/{\$adultsAge}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].adultsAge)
            .replace(/{\$childrenAge}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].childrenAge)
            .replace(/{\$passengers}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].passengers)
		    .replace(/{\$Update}/g, ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["update"])

        ;

        ch.exmachina.bravofly.searchWidget.tInstance = tInstance;
		if(p.targetNode && document.getElementById(p.targetNode)){
			document.getElementById(p.targetNode).innerHTML = searchWidget.tInstance;
			var st = document.createElement("style");
			st.type = "text/css";
			if(!st.styleSheet){
				st.textContent = this.attachStyle();
			}else{
				st.styleSheet.cssText = this.attachStyle();
			}
			document.getElementsByTagName("head")[0].appendChild(st);
		}else{
			document.write(searchWidget.tInstance + '<style type="text/css">' + this.attachStyle() + "</style>");
		}

		this.domNode = document.getElementById("DomNode" + this.ts);
		this.depFieldNode = document.getElementById("DepTextField" + this.ts);
		this.arrFieldNode = document.getElementById("ArrTextField" + this.ts);
		this.depFieldNode.id = "";
		this.arrFieldNode.id = "";
		this.depListNode = document.getElementById("DepList" + this.ts);
		this.arrListNode = document.getElementById("ArrList" + this.ts);
		this.depDatePickerNode = document.getElementById("DepDatePicker" + this.ts);
		this.retDatePickerNode = document.getElementById("RetDatePicker" + this.ts);
		this.currencyContainerNode = document.getElementById("CurrencyContainer" + this.ts);

		this.buttonNode = document.getElementById("Button" + this.ts);
		this.coverNode = document.getElementById("Cover" + this.ts);

		this.selectNode = document.getElementById("Select" + this.ts);
		this.adultsNode = document.getElementById("Adults" + this.ts);
		this.childrenNode = document.getElementById("Children" + this.ts);
		this.infantsNode = document.getElementById("Infants" + this.ts);
		this.adultsContainerNode = document.getElementById("AdultsContainer" + this.ts);
		this.childrenContainerNode = document.getElementById("ChildrenContainer" + this.ts);
		this.infantsContainerNode = document.getElementById("InfantsContainer" + this.ts);
		this.passengersContainerNode = document.getElementById("PassengersContainer" + this.ts);
		this.passengersTriggerNode = document.getElementById("PassengersTrigger" + this.ts);

		this.retContainerNode = document.getElementById("RetContainer" + this.ts);
		this.depContainerNode = document.getElementById("DepContainer" + this.ts);

		this.passengersPanelNode = document.getElementById("PassengersPanel" + this.ts);
		this.updatePassengersNode = document.getElementById("updatePassengers" + this.ts);

		this.panelAdultsSelectNode = document.getElementById("panel_adults" + this.ts);
		this.panelChildrenSelectNode = document.getElementById("panel_children" + this.ts);
		this.panelInfantsSelectNode = document.getElementById("panel_infants" + this.ts);


		this.setPassengersAspect();
		this.resetFields();
			// TODO rimuovere gli id dai nodi container
		this.currenciesNode = document.getElementById("Currencies" + this.ts);
		this.roundTripNode = document.getElementById("DepOnly" + this.ts);
		var dates = [new Date(), new Date()],
			self = this,
			depCalNode = document.getElementById("depCal" + this.ts),
			retCalNode = document.getElementById("retCal" + this.ts)
		;
		dates[0].setDate(dates[0].getDate() + 1);
		dates[1].setDate(dates[1].getDate() + 4);
		this.depDatePicker = new ch.exmachina.bravofly.DatePicker({
			node: this.depDatePickerNode,
			dateLabel:  ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["outboundDate"],
			calDateFormat: "MMM yyyy",
			fieldDateFormat: dateFormat,
            monthNames:  ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["monthNames"],
			label: ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["outboundDate"],
			date: dates[0],
			calNode: depCalNode,
            days: ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["days"],
            onSetDate: function(/** Date */ depDate){
                if(self._isFirstSetDate){
                    var arrDate = new Date();
                    arrDate.setMonth(depDate.getMonth());
                    arrDate.setYear(depDate.getFullYear());
                    arrDate.setDate(depDate.getDate() + 3);
                    self.retDatePicker.date = arrDate;
                    self.retDatePicker.showDate(arrDate);
                    self.retDatePicker.showFormattedDate();
                    self._isFirstSetDate = false;
                }
            },
			onShow: function(){
				self.retDatePicker.hideCal(true);
				self.selectNode.style.display = "none";
			},
			onHide: function(){
				if(self.arrListNode.style.display != "block" && self.depListNode.style.display != "block"){
				    self.selectNode.style.display = "block";
				}
			}
		});
		this.retDatePicker = new ch.exmachina.bravofly.DatePicker({
			node: this.retDatePickerNode,
			dateLabel: ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["returnDate"],
            monthNames:  ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["monthNames"],
			label: ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["returnDate"],
			calDateFormat: "MMM yyyy",
			fieldDateFormat: dateFormat,
			date: dates[1],
			calNode: retCalNode,
            days: ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["days"],
            onSetDate: function(){
                self._isFirstSetDate && (self._isFirstSetDate = false);
            },
			onShow: function(){
				self.depDatePicker.hideCal(true);
				self.selectNode.style.display = "none";
			},
			onHide: function(){
				if(self.arrListNode.style.display != "block" && self.depListNode.style.display != "block"){
				    self.selectNode.style.display = "block";
				}
			}
		});
        for(var i = 0, opt, cs = ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language].currencies, l = cs.length; i < l; i++){
            opt = document.createElement("option");
            opt.value = cs[i].k;
            opt.appendChild(document.createTextNode(cs[i].v));
            this.currenciesNode.appendChild(opt);
        }
		var c = p.currency,
			da = p["departureAirport"],
			aa = p["arrivalAirport"]
		;

		c && (this.currenciesNode.value = c);

        // inserire qui il conteggio delle attività asincrone da eseguire all'avvio
        da && this.callsToDo++;
        aa && this.callsToDo++;
        this.onLoad = function(){
            self._setupTabs.call(self);
        };
		if(da){
			this.getAirportFromIata({ prefix: "dep", code: da.toLowerCase() });
			this.depFieldNode.readOnly = "true";
		}
		if(aa){
			this.getAirportFromIata({ prefix: "arr", code: aa.toUpperCase() });
			this.arrFieldNode.readOnly = "true";
		}
        !this.callsToDo && this.onLoad();
		this.bindEvents();
	},
    setLocale: function(){
        ch.exmachina.bravofly.language = this.parameters.language || ch.exmachina.bravofly.language;
    },
    setPassengersAspect: function(){
    	var p = this.parameters.passengers
    	;
    	switch(p){
    		case 'compact':
    			this.adultsContainerNode.style.display = "none";
    			this.infantsContainerNode.style.display = "none";
    			this.childrenContainerNode.style.display = "none";
    			this.passengersContainerNode.style.display = "block";
    		break;
    		default:
    		break;
    	}
    },
    getParameters: function(){
        var scripts = document.getElementsByTagName("script"),
            src = "",
//            pattern = "/suggester/wgt/widget1.3.js",
            pattern = "wgt/widget1.3.js",
            p = ""
        ;
        for(var i = 0; i < scripts.length; i++){
            src = scripts[i].src;
            if(src.lastIndexOf(pattern) == (src.length - pattern.length)){
                p = scripts[i].getAttribute("params");
                this.parameters = p ? eval("(" + p + ")") : {};
            }
        }
    },
	extractAirport: function(args){
		var rawAirport = args.rawAirport,
			start = rawAirport.indexOf("("),
			end = rawAirport.indexOf(")"),
			airport = ""
		;
		if(start != -1 && end != -1){
			airport = rawAirport.substring(start + 1, end);
		}
		return airport;
	},
	fillInDates: function(){
		var dates = [new Date(), new Date()];
		dates[0].setDate(dates[0].getDate() + 1);
		dates[1].setDate(dates[1].getDate() + 7);
		this.depDatePicker.fillIn({
			month: dates[0].getMonth(),
			year: dates[0].getFullYear()
		});
		this.retDatePicker.fillIn({
			month: dates[1].getMonth(),
			year: dates[1].getFullYear()
		});
	},
	getItems: function(args){
		var prefix = args.prefix,
			itemList = this[prefix + "ListNode"].getElementsByTagName("LI")
		;
		if(!itemList.length){
			itemList = this[prefix + "ListNode"].getElementsByTagName("li");
		}
		return itemList;
	},
	moveSelection: function(args){
		var dir = args.direction || "down",
			prefix = args.prefix || "dep",
			itemList = this.getItems({ prefix: prefix}),
			len = itemList.length,
			oldSelectedItem = this.selectedItem[prefix],
			increment = dir === "down" ? 1 : -1
		;
		this.selectedItem[prefix] = (this.selectedItem[prefix] + increment + len) % len;
		itemList[oldSelectedItem].className = "";
		itemList[this.selectedItem[prefix]].className = "selected";

	},
	hoverHandler: function(e){
		var evt = this.fixEvent(e),
			trg = this.getTarget(evt)
		;
		trg.style.backgroundColor = "#eee";
		trg.style.borderColor = "#0c0";
	},
	outHandler: function(e){
		var evt = this.fixEvent(e),
			trg = this.getTarget(evt)
		;
		trg.style.backgroundColor = "#eee";
		trg.style.borderColor = "#999";
	},
	searchHandler: function(){
		var
			depMonth = this.depDatePicker.date.getMonth() < 9 ? "0" + (this.depDatePicker.date.getMonth() + 1) : this.depDatePicker.date.getMonth() + 1,
			depDay = this.depDatePicker.date.getDate() < 10 ? "0" + this.depDatePicker.date.getDate() : this.depDatePicker.date.getDate(),
			retMonth = this.retDatePicker.date.getMonth() < 9 ? "0" + (this.retDatePicker.date.getMonth() + 1) : this.retDatePicker.date.getMonth() + 1,
			retDay = this.retDatePicker.date.getDate() < 10 ? "0" + this.retDatePicker.date.getDate() : this.retDatePicker.date.getDate(),
            p = this.parameters,
            searchUrl = p.searchUrl || ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["searchUrl"],
			filledUrl = this.detailsUrl
				.replace("{$searchUrl}", searchUrl)
				.replace("{$depAir}", this.extractAirport({ rawAirport: this.depFieldNode.value }))
				.replace("{$retAir}", this.extractAirport({ rawAirport: this.arrFieldNode.value }))
				.replace("{$outDay}", depDay)
				.replace("{$outMY}", depMonth + "" + this.depDatePicker.date.getFullYear())
				.replace("{$retDay}", retDay)
				.replace("{$retMY}", retMonth + "" + this.retDatePicker.date.getFullYear())
				.replace(/{\$adults}/, "adults=" + this.adultsNode.value)
				.replace(/{\$children}/, "childs=" + this.childrenNode.value) // ...
				.replace(/{\$infants}/, "infants=" + this.infantsNode.value)
                .replace(/{\$currency}/, this.currenciesNode.options[this.currenciesNode.selectedIndex].value)
		;
        this.roundTripNode.checked && (filledUrl += "&roundtrip=0");
        for(var i in p.url){
            filledUrl += "&" + i + "=" + p.url[i];
        }
        var isFormValid = this.isFormValid();
        if(isFormValid.valid){
            if(!p.proxyForm){
                if(p.searchTarget && p.searchTarget === "_self"){
                    location.href = filledUrl;
                }else{
                    window.open(filledUrl);
                }
            }else{
                var pfData = p.proxyForm,
                        pf = this.proxyForm || (function(){
                            var f = document.createElement("form"),
                                fs = f.style
                            ;
                            f.innerHTML = "<input type='hidden' value='' name='url' />";
                            fs.display="none";
                            fs.position="absolute";
                            document.body.appendChild(f);
                            return f;
                        })();
                    ;
                for(i in pfData){
                    pf[i] = pfData[i];
                }
                pf.url.value = filledUrl;
                pf.submit();
            }
        }else{
            window.alert(isFormValid.msg);
        }
	},
    isFormValid: function(){
        var ret = true,
            ers = ""
        ;
        if(this.infantsNode.value > this.adultsNode.value){
            ret = false;
            ers += ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["messages"]["infantsNumber"] + "\n";
        }
        if(!this.depFieldNode.value.replace(/s/g, "") || !this.arrFieldNode.value.replace(/s/g, "")){
            ret = false;
            ers += ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["messages"]["noAirports"] + "\n";
        }
        if(this.depDatePicker.date > this.retDatePicker.date && !!!this.roundTripNode.checked){
            ret = false;
            ers += ch.exmachina.bravofly.properties[ch.exmachina.bravofly.language]["messages"]["dateInversion"] + "\n";
        }
        return {valid: ret, msg: ers };
    },
	fixEvent: function(e){
		return e || window.event;
	},
	getCharCode: function(e){
		return e.keyCode || e.charCode;
	},
	getTarget: function(e){
		return e.target || e.srcElement;
	},
	clickListHandler: function(e, prefix){
		var evt = this.fixEvent(e),
			trg = this.getTarget(evt),
			item = null
		;
		// event delegation here
		if(trg.tagName && trg.tagName.toLowerCase() === "li" || (trg.tagName.toLowerCase() === "span"
			&& trg.parentNode.tagName && trg.parentNode.tagName.toLowerCase() === "li")){
			item = trg.tagName.toLowerCase() === "li" ? trg : trg.parentNode;
			this.selectItem({ item: item, prefix: prefix });
			this[prefix + "FieldNode"].focus();
            this.fillField({ prefix: prefix });
			this.hideList({ prefix: prefix });
		}
	},
	focusHandler: function(e){
		var evt = this.fixEvent(e),
			trg = this.getTarget(evt)
		;
		trg.value = "";
	},
	blurHandler: function(prefix){
		var self = this;
        setTimeout(function(){
            self.fillField({ prefix: prefix });
            self.hideList({ prefix: prefix });
        }, 250);
	},
	keyUpHandler: function(e, prefix){
		var evt = this.fixEvent(e),
			key = this.getCharCode(evt),
			trg = this.getTarget(evt)
		;
		if(trg.value.length < this.minChar){
			return;
		}
		switch(key){
			case 27: // ESC
				this.hideList({ prefix: prefix });
			break;
			case 40: // down arrow
				this.moveSelection({ direction: "down", prefix: prefix });
			break;
			case 38: // up arrow
				this.moveSelection({ direction: "up", prefix: prefix  });
			break;
			case 13: // enter
				this.fillField({ prefix: prefix });
				this.hideList({ prefix: prefix });
			break;
			default:
				this.getData({ prefix: prefix });
			break;
		}
	},
	selectItem: function(args){
		var prefix = args.prefix,
			items = this.getItems({ prefix: prefix }),
			item = args.item,
			index = 0,
			i = 0
		;
		if(!items.length){ return; }
		items[this.selectedItem[prefix]].className = "";
		if(typeof(args.item) === "number"){
			index = args.item;
		}else{
			while(items[i] !== item){
				i++;
			}
			index = i;
		}
		this.selectedItem[prefix] = index;
		items[this.selectedItem[prefix]].className = "selected";
	},
	fillField: function(args){
		var prefix = args.prefix;
		if(/*this[prefix + "ListNode"].style.display == "none" || */!this.getItems({ prefix: prefix })[this.selectedItem[prefix]]){ return; }
		this[args.prefix + "FieldNode"].value = this.getItems({ prefix: prefix })[this.selectedItem[prefix]].innerHTML.replace(/<\/?[^>]+>/gi, '');
	},
	bindEvents: function(){
		var self = this;
		this.depFieldNode.onfocus = function(evt){ if(self.depFieldNode.readOnly) return; self.focusHandler.call(self, evt, "dep"); };
		this.arrFieldNode.onfocus = function(evt){ if(self.arrFieldNode.readOnly) return; self.focusHandler.call(self, evt, "arr"); };
		this.depFieldNode.onblur = function(){ self.blurHandler.call(self, "dep"); };
		this.arrFieldNode.onblur = function(){ self.blurHandler.call(self, "arr"); };
		this.depFieldNode.onkeyup = function(evt){ if(self.depFieldNode.readOnly) return; self.keyUpHandler.call(self, evt, "dep"); };
		this.arrFieldNode.onkeyup = function(evt){ if(self.arrFieldNode.readOnly) return; self.keyUpHandler.call(self, evt, "arr"); };
		this.buttonNode.onclick = function(evt){ self.searchHandler.call(self, evt); };
		this.buttonNode.onmouseover = function(evt){ self.hoverHandler.call(self, evt); };
		this.buttonNode.onmouseout = function(evt){ self.outHandler.call(self, evt); };
		this.depListNode.onclick = function(evt){ self.clickListHandler.call(self, evt, "dep"); };
		this.arrListNode.onclick = function(evt){ self.clickListHandler.call(self, evt, "arr"); };
        this.domNode.onclick = function(evt){ self.clickHandler.call(self, evt); };
		this.depListNode.onmouseover = function(evt){ self.mouseoverListHandler.call(self, evt, "dep"); };
		this.arrListNode.onmouseover = function(evt){ self.mouseoverListHandler.call(self, evt, "arr"); };
        this.roundTripNode.onclick = function(evt){ self.roundTripHandler.call(self, evt); };
		this.passengersTriggerNode.onclick = function(evt){ self.showPassengersPanel.call(self, evt); };
		this.updatePassengersNode.onclick = function(evt){ self.groupPassengers.call(self, evt); };

		// 3 select passeggeri, raggruppamento
		this.panelAdultsSelectNode.onchange = function(evt){ self.updateSelect(evt, "adults"); };
		this.panelChildrenSelectNode.onchange = function(evt){ self.updateSelect(evt, "children"); };
		this.panelInfantsSelectNode.onchange = function(evt){ self.updateSelect(evt, "infants"); };
	},
	resetFields: function(){
		for(var s = ["adultsNode", "childrenNode", "infantsNode"], sh = ["panelAdultsSelectNode", "panelChildrenSelectNode", "panelInfantsSelectNode"], v = [0, 0, 0], i = 0, l = s.length, sum = 0; i < l; i++){
			this[sh[i]].selectedIndex = this[s[i]].selectedIndex = v[i];
			sum += parseInt(this[s[i]].value);
		}
		this.passengersTriggerNode.firstChild.data = sum;
	},
	updateFields: function(){
		for(var s = ["adultsNode", "childrenNode", "infantsNode"], sh = ["panelAdultsSelectNode", "panelChildrenSelectNode", "panelInfantsSelectNode"], i = 0, l = s.length, sum = 0; i < l; i++){
			this[sh[i]].value = this[s[i]].value;
			sum += parseInt(this[s[i]].value);
		}
		this.passengersTriggerNode.firstChild.data = sum;
	},
	updateSelect: function(e, /*String*/ tSelect){
		var sw = ch.exmachina.bravofly.searchWidget,
		    evt = sw.fixEvent(e),
		    trg = sw.getTarget(evt)
		;
		this[tSelect + "Node"].value = trg.value;
		this.updateFields();
	},
	groupPassengers: function(){
		this.passengersPanelNode.style.display = "none";
	},
	showPassengersPanel: function(){
		this.passengersPanelNode.style.display = "block";
	},
    roundTripHandler: function(e){
        var sw = ch.exmachina.bravofly.searchWidget,
            evt = sw.fixEvent(e),
            trg = sw.getTarget(evt)
        ;
        if(trg.checked){
            this.retDatePicker.disable();
        }else{
            this.retDatePicker.enable();
        }
    },
    mouseoverListHandler: function(e, w){
		var sw = ch.exmachina.bravofly.searchWidget,
			evt = sw.fixEvent(e),
			trg = sw.getTarget(evt),
            curTarget
		;
        var items = this[w + "ListNode"].firstChild.childNodes;
        var tn = trg.tagName.toUpperCase();
        if(!trg || tn == "UL"){ return; }
        for(var i = 0; i < items.length; i++){
            items[i].className = "";
        }
        switch(tn){
            case "LI":
                curTarget = trg;
            break;
            case "SPAN":
                curTarget = trg.parentNode;
            break;
            default:
	            return;
            break;
        }
        curTarget.className = "selected";
    },
    clickHandler: function(){
        this.depDatePicker.hideCal();
        this.retDatePicker.hideCal();
    },
	hideList: function(args){
		var s = this[args.prefix + "ListNode"].style;
		s.display = "none";
		if(this.depDatePicker.calNode.style.display === "none" && this.retDatePicker.calNode.style.display === "none"){
			this.selectNode.style.display = "block";
		}
		this.currencyContainerNode.style.display = "block";
	},
	showList: function(args){
		var prefix = args.prefix,
			ln = this[prefix + "ListNode"],
			s = ln.style
		;
        this.selectNode.style.display = "none";
		this.currencyContainerNode.style.display = "none";
		this.selectItem({ item: 0, prefix: prefix });
		s.display = "block";
	},
	processData: function(){

	},
	getAirportFromIata: function(/* Object */ args){
		var prefix = args.prefix,
			p = this.parameters,
            lan = ch.exmachina.bravofly.language != "engb" ? ch.exmachina.bravofly.language : "en",
			actualUrl = this.url
				.replace(/{\$key}/, "key=" + args.code.toUpperCase() + "")
				.replace(/{\$type}/, "type=" + prefix)
				.replace(/{\$prefix}/, prefix)
				.replace(/{\$language}/, "language=" + lan)
				.replace(/{\$limit}/, "limit=" + this.searchLimit)
				.replace(/{\$code}/, args.code.toUpperCase())
				.replace(/{\$sugQueryString}/, (p.sugQueryString || ""))
				.replace(/{\$cback}/, "ch.exmachina.bravofly.searchWidget.fillInAirport")
		;
		this[prefix + "transport"] = document.createElement("script");
		this[prefix + "transport"].type = "text/javascript";
		this[prefix + "transport"].src = actualUrl;
		document.getElementsByTagName("head")[0].appendChild(this[prefix + "transport"]);
	},
    partialLoad: function(){
        this.calls++;
        (this.calls == this.callsToDo) && this.onLoad();
    },
	fillInAirport: function(args){
		var prefix = args.prefix,
			lines = args["list"].split("</li><li"),
			line = ""
		;
		for(var i = 0, l = lines.length; i < l; i++){
			if(lines.length > 1){
				lines[i] = "<li" + lines[i];
			}

			if(lines[i].replace(/<\/?[^>]+>/gi, '').indexOf("(" + args.code + ")") != -1){
				line = lines[i];
				break;
			}
		}
		this[prefix + "FieldNode"].value = line.replace(/<\/?[^>]+>/gi, '');
        this.partialLoad();
	},
	getData: function(args){
		var prefix = args.prefix,
			p = this.parameters,
            lan = ch.exmachina.bravofly.language != "engb" ? ch.exmachina.bravofly.language : "en",
			actualUrl = this.url
			.replace(/{\$key}/, "key=" + this[prefix + "FieldNode"].value)
			.replace(/{\$type}/, "type=" + prefix)
			.replace(/{\$prefix}/, prefix)
			.replace(/{\$language}/, "language=" + lan)
			.replace(/{\$limit}/, "limit=" + this.searchLimit)
			.replace(/{\$code}/, this[prefix + "FieldNode"].value)
			.replace(/{\$sugQueryString}/, (p.sugQueryString || ""))
			.replace(/{\$cback}/, "ch.exmachina.bravofly.searchWidget.cback")
		;
		this.transport && this.transport.parentNode.removeChild(this.transport);
		this.transport = document.createElement("script");
		this.transport.type = "text/javascript";
		this.transport.src = actualUrl;
		document.getElementsByTagName("head")[0].appendChild(this.transport);
	},
	cback: function(args){
		var prefix = args.prefix;
		this[prefix + "ListNode"].innerHTML = args.list;
		if(!this[prefix + "ListNode"].childNodes.length){ return; }
		var firstItem = this[prefix + "ListNode"].firstChild.firstChild;
		if(firstItem){
			//firstItem.className = "selected";
			this.selectItem({ item: 0, prefix: prefix });
		}
		this.showList({ prefix: prefix });
	},
	attachStyle: function(){
		var styleTemplate = this.styleTemplate
			.replace(/{\$WidgetId}/g, this.ts)
			.replace(/{\$imgPosition}/, ch.exmachina.bravofly.remote.imgPosition)
            .replace(/{\$language}/g, ch.exmachina.bravofly.language)
		;
		return styleTemplate;
	},
    // inverte aeroporto di partenza e di destinazione, ed eventualmente anche gli attributi readOnly
    _invertAirports: function(){
        var ro = this.depFieldNode.readOnly,
            val = this.depFieldNode.value
        ;
        this.depFieldNode.readOnly = this.arrFieldNode.readOnly;
        this.depFieldNode.value = this.arrFieldNode.value;
        this.arrFieldNode.readOnly = ro;
        this.arrFieldNode.value = val;
    },
	toString: function(){
		return "[ch.exmachina.bravofly.searchWidget]";
	}
};
ch.exmachina.bravofly.searchWidget.fnMap = {
    invertAirports: "_invertAirports"
};
ch.exmachina.bravofly.searchWidget.ts = (new Date()).getTime();

ch.exmachina.bravofly.searchWidget.startup();
