/*
 * IBE - Quickbooking
 */

// LABELS
MooTools.lang.set('it-IT', 'Date', {
	months: ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre']
	, days: ['Domenica', 'Lunedi', 'Martedi', 'Mercoledi', 'Giovedi', 'Venerdi', 'Sabato']
	, dateOrder: ['giorno', 'mese', 'anno', '/']
});
MooTools.lang.set('it-IT', 'Message', {
	dateOutLimit: ['Data fuori dei limiti!']
	, totNights: ['notti']
	, errorMsg: ['Errore, campi non compilati']
	, sendingData: ['Invio dati in corso...']
	, pleaseWait: ['Attendere prego']
});
MooTools.lang.set('en-EN', 'Date', {
	months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
	, days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	, dateOrder: ['day', 'month', 'year', '/']
});
MooTools.lang.set('en-EN', 'Message', {
	dateOutLimit: ['Date out of bounds!']
	, totNights: ['nights']
	, errorMsg: ['Error, empty field']
	, sendingData: ['Sending data ...']
	, pleaseWait: ['Please wait']
});
MooTools.lang.set('fr-FR', 'Date', {
	months: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
	, days: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi']
	, dateOrder: ['jour', 'mois', 'année ', '/']
});
MooTools.lang.set('fr-FR', 'Message', {
	dateOutLimit: ['Date en dehor des limits!']
	, totNights: ['nuits']
	, errorMsg: ['Erreur, rubrique pas remplit']
	, sendingData: ['Envoyer ...']
	, pleaseWait: ['Attendez s\'il vous plaît']
});

Element.implement({
    addLiveEvent: function(event, selector, fn){
        this.addEvent(event, function(e){
            var t = $(e.target);

            if (!t.match(selector)) return false;
                fn.apply(t, [e]);
        }.bindWithEvent(this, selector, fn));
    }
});

// HASHES
var varsHash = new Hash ({
	'dateFormat':     '%d/%m/%Y'
  , 'dateFormatLong': '%a, %B %d, %Y'
  , 'lang':           'en-EN'
  , 'totNights':      '1'
  , 'period':         365 // max checkin selection in days
  , 'selection':      31 // max checkout selection in days
});

var calInVarsHash = new Hash ({
	  'pickFunction': function(date) {
			$$('.start_date').set('value', date.get('date')+'/'+(date.get('month')+1)+'/'+date.get('year'));
		}
	, 'theme': 'boscolo'
	, 'prefill': true
	, 'defaultDate': new Date()
	, 'linkWithInput': true
	, 'minDate': new Date()
	, 'maxDate': new Date().increment('day', varsHash.get('period'))
	, 'alwaysShow': true
	, 'injectInsideTarget': true
	, 'format': varsHash.get('dateFormat')
	, 'alignX': 'left'
	, 'alignY': 'top'
	, 'createHiddenInput': true
	, 'hiddenInputName': 'checkinforse'
	, 'hiddenInputFormat': varsHash.get('dateFormat')
});

var calOutVarsHash = new Hash ({
	  'pickFunction': function(date) { $$('.end_date').set('value', date.get('date')+'/'+(date.get('month')+1)+'/'+date.get('year')); printDateSelect(); /*closeOpt();*/}
	, 'theme': 'boscolo'
	, 'prefill': true
	, 'defaultDate': new Date().increment('day', 1)
	, 'linkWithInput': true
	, 'minDate': new Date().increment('day', 1)
	, 'maxDate': new Date().increment('day', varsHash.get('selection')) //checkincal.selectedDate.increment('day', 31)
	, 'alwaysShow': true
	, 'injectInsideTarget': true
	, 'format': varsHash.get('dateFormat')
	, 'alignX': 'left'
	, 'alignY': 'top'
	, 'createHiddenInput': true
	, 'hiddenInputName': 'checkoutforse'
	, 'hiddenInputFormat': varsHash.get('dateFormat')
});

MooTools.lang.setLanguage(varsHash.get('lang'));

// Chiude le opzioni aperte
function closeOpt(cla) {
	if (cla) {
		$$('div.options[class$='+cla+']').setStyle('display', 'none');
	} else {
		$$('div.options').setStyle('display', 'none');
	}
}

function errore(valore, parametro) { alert('Errore: problemi col parametro ' + parametro + ' = ' + valore); }

function openRooms(num) {
	if (num > 1) {
		$('mainGroup').setStyle('display', 'none');
		$$('.group').setStyle('display', 'none'); // new mod
		for (i=1;i<=num;i++) {
			//$$('.group.num' + i).setStyle('display', 'block');
			$$('.group.num' + i).reveal();
		}
		if ($$('#mainGroup #children').get('value') != 0 && $$('#mainGroup #children').get('value') != '') {
			var val = $$('#mainGroup #children').get('value');
			openAge(val, 1);
		}
	} else {
		//$('mainGroup').setStyle('display', 'block');
		$('mainGroup').reveal();
		$$('.group').setStyle('display', 'none');
	}
}
function openAge(num, group) {
	if (num > 0) {
		$$('p.age').setStyle('display', 'none');
		for (i=1;i<=num;i++) {
			//$$('p.eta_'+group+'_'+i).setStyle('display', 'block');
			$$('p.eta_'+group+'_'+i).reveal();
		}
	} else {
		$$('p.age').setStyle('display', 'none');
	}
}

function gracefulDegradation(element) {
	var bg = String(element.getStyle('background-image'));
	if (bg.contains('.png')) {
		bg = bg.replace('.png', '.gif');
	}
	element.setStyle('background-image', bg);
}

function opacities(a) {
	if (a == 'onload') {
		$('checkinDisplay').set('opacity', '1');
		$('checkoutDisplay').set('opacity', '.3');
	} else {
		$('checkinDisplay').set('opacity', '.3');
		$('checkoutDisplay').set('opacity', '1');
	}
}

function isNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
	return false;

	return true;
}

function formValidation(form) {
	var error = 0;
	var mandatory = form.getElements('p.mandatory');

	mandatory.each(function(e) {
		var campo    = e.getElements('input');
		var idCampo  = campo.get('id');
		var valCampo = campo.get('value');

		if (idCampo == 'cityhotels') {
			if (valCampo == '') {
				error = 1;
				campo.addClass('errorInput');
				//campo.highlight('#ddf');
			} else { campo.removeClass('errorInput');}
		}
		if (idCampo == 'number_rooms' || idCampo == 'adults') {
		//if (idCampo == 'number_rooms' || idCampo.match(\badults)) {
			if (valCampo == '' || valCampo == 0) {
				error = 1;
				campo.addClass('errorInput');
			} else { campo.removeClass('errorInput');}
		}
	});

	if (error == 0) {
		return true;
	} else {
		return false;
	}
};

// GESTIONE CALENDARI
/*   checkIN | totNights | checkOUT
 *   -------------------------------
 * 1 CAMBIO  | fisso     | ricalcola
 * 2 fisso   | CAMBIO    | ricalcola
 * 3 fisso   | ricalcolo | CAMBIO
 *
 * 1.ricalcola = checkin + 1 gg
 * 2.ricalcola = checkin + totNights
 * 3.ricalcola = checkout - checkin
 *
 * checkin.minDate: oggi
 * checkin.maxDate: oggi + 365 gg
 * checkout.minDate: oggi + 1gg
 * checkout.maxDate: checkin.selected + 31gg
 * totNights: max 31gg
 */ 
function createCalendars() {
	var checkincal = new CalendarEightysix('checkinDisplay', {
		  'pickFunction':       calInVarsHash.get('pickFunction')
		, 'theme':              calInVarsHash.get('theme')
		, 'prefill':            calInVarsHash.get('prefill')
		, 'defaultDate':        calInVarsHash.get('defaultDate')
		, 'linkWithInput':      calInVarsHash.get('linkWithInput')
		, 'minDate':            calInVarsHash.get('minDate')
		, 'maxDate':            calInVarsHash.get('maxDate')
		, 'alwaysShow':         calInVarsHash.get('alwaysShow')
		, 'injectInsideTarget': calInVarsHash.get('injectInsideTarget')
		, 'format':             calInVarsHash.get('format')
		, 'alignX':             calInVarsHash.get('alignX')
		, 'alignY':             calInVarsHash.get('alignY')
		, 'createHiddenInput':  calInVarsHash.get('createHiddenInput')
		, 'hiddenInputName':    calInVarsHash.get('hiddenInputName')
		, 'hiddenInputFormat':  calInVarsHash.get('hiddenInputFormat')
	});
	var checkoutcal = new CalendarEightysix('checkoutDisplay', {
		  'pickFunction':       calOutVarsHash.get('pickFunction')
		, 'theme':              calOutVarsHash.get('theme')
		, 'prefill':            calOutVarsHash.get('prefill')
		, 'defaultDate':        calOutVarsHash.get('defaultDate')
		, 'linkWithInput':      calOutVarsHash.get('linkWithInput')
		, 'minDate':            calOutVarsHash.get('minDate')
		, 'maxDate':            calOutVarsHash.get('maxDate')
		, 'alwaysShow':         calOutVarsHash.get('alwaysShow')
		, 'injectInsideTarget': calOutVarsHash.get('injectInsideTarget')
		, 'format':             calOutVarsHash.get('format')
		, 'alignX':             calOutVarsHash.get('alignX')
		, 'alignY':             calOutVarsHash.get('alignY')
		, 'createHiddenInput':  calOutVarsHash.get('createHiddenInput')
		, 'hiddenInputName':    calOutVarsHash.get('hiddenInputName')
		, 'hiddenInputFormat':  calOutVarsHash.get('hiddenInputFormat')
	});
}

function changeDate(calendar, date, minDate, maxDate) {
	if (varsHash.get('dateFormat') == '%d/%m/%Y') {
		var pieces = date.split('/');
		var newDate = new Date(pieces[1]+'/'+pieces[0]+'/'+pieces[2]);
	} else if (varsHash.get('dateFormat') == '%m/%d/%Y') {
		var newDate = new Date(date);
	} else {
		newDate = date;
	}

	if (newDate >= minDate && maxDate > newDate) {
		return newDate;
	} else {
		//alert(MooTools.lang.get('Message', 'dateOutLimit'));
		return minDate;
	}
}

function giorniDifferenza(data1, data2) {
	if ($type(data1) == 'string') {
		var pieces1 = data1.split('/');
		var data1 = new Date(pieces1[1]+'/'+pieces1[0]+'/'+pieces1[2]);
	}
	if ($type(data2) == 'string') {
		var pieces2 = data2.split('/');
		var data2 = new Date(pieces2[1]+'/'+pieces2[0]+'/'+pieces2[2]);
	}

	if (data1.isValid() && data2.isValid()) {
		calcolo = data2.getTime()-data1.getTime();
		differenza = new String(calcolo/86400000);
		return differenza;
	} else {
		return false;
	}
}

function printDateSelect() {
	var checkIn      = $('start_date').getProperty('value');
	var checkOut     = $('end_date').getProperty('value');
	var totNights    = parseInt(varsHash.get('totNights'));
	var piecesIn     = checkIn.split('/');
	var checkInDate  = new Date(piecesIn[1]+'/'+piecesIn[0]+'/'+piecesIn[2]).format('%a, %B %d, %Y');
	var piecesOut    = checkOut.split('/');
	var checkOutDate = new Date(piecesOut[1]+'/'+piecesOut[0]+'/'+piecesOut[2]).format('%a, %B %d, %Y');
	$('dates').setProperty('value', checkInDate + ' - ' + checkOutDate + ' (' + totNights + ' ' + MooTools.lang.get('Message', 'totNights') + ')');
}

function calcTotNights(checkIn, checkOut) {
	// se non sono date, trasformo in date!
	if ($type(checkIn) == 'string') {
		var piecesIn = checkIn.split('/');
		var checkIn = new Date(piecesIn[1]+'/'+piecesIn[0]+'/'+piecesIn[2]);
		var piecesOut = checkOut.split('/');
		var checkOut = new Date(piecesOut[1]+'/'+piecesOut[0]+'/'+piecesOut[2]);
	} else if ($type(checkIn) == 'array') {
		var piecesIn = checkIn[0].split('/');
		var checkIn = new Date(piecesIn[1]+'/'+piecesIn[0]+'/'+piecesIn[2]);
		var piecesOut = checkOut[0].split('/');
		var checkOut = new Date(piecesOut[1]+'/'+piecesOut[0]+'/'+piecesOut[2]);
	}
	differenza = checkOut-checkIn;
	//totNights = new String(differenza/86400000);
	totNights = Math.round(differenza/86400000);

	totNights = (totNights == 0 ? 1 : totNights);
	varsHash.set('totNights', totNights);	
	$$('input[id$=totnights]').setProperty('value', varsHash.get('totNights') +  ' ' +  MooTools.lang.get('Message', 'totNights'));
	$$('div.options[class$=totnights] li').removeClass('selected');
	$$('div.options[class$=totnights] li').each(function(e) {
		var thisOne = e.getChildren('a[title='+varsHash.get('totNights')+']');
		if (thisOne != '') {e.addClass('selected');}
	});

	//closeOpt();
	return totNights;
}

function transformDate(oldDate) {
	var date = oldDate[0].split('/');
	var newDate = date[2]+'-'+date[1]+'-'+date[0];
	return newDate;
	//var datum = new Date(Date.UTC(date[2],date[0],date[1]));
}

window.addEvent('domready', function() {
	//opacities('onload');

	// Creo i calendari con valori di default
	var checkincal = new CalendarEightysix('checkinDisplay', {
		  'pickFunction':       calInVarsHash.get('pickFunction')
		, 'theme':              calInVarsHash.get('theme')
		, 'prefill':            calInVarsHash.get('prefill')
		, 'defaultDate':        calInVarsHash.get('defaultDate')
		, 'linkWithInput':      calInVarsHash.get('linkWithInput')
		, 'minDate':            calInVarsHash.get('minDate')
		, 'maxDate':            calInVarsHash.get('maxDate')
		, 'alwaysShow':         calInVarsHash.get('alwaysShow')
		, 'injectInsideTarget': calInVarsHash.get('injectInsideTarget')
		, 'format':             calInVarsHash.get('format')
		, 'alignX':             calInVarsHash.get('alignX')
		, 'alignY':             calInVarsHash.get('alignY')
		, 'createHiddenInput':  calInVarsHash.get('createHiddenInput')
		, 'hiddenInputName':    calInVarsHash.get('hiddenInputName')
		, 'hiddenInputFormat':  calInVarsHash.get('hiddenInputFormat')
	});
	var checkoutcal = new CalendarEightysix('checkoutDisplay', {
		  'pickFunction':       calOutVarsHash.get('pickFunction')
		, 'theme':              calOutVarsHash.get('theme')
		, 'prefill':            calOutVarsHash.get('prefill')
		, 'defaultDate':        calOutVarsHash.get('defaultDate')
		, 'linkWithInput':      calOutVarsHash.get('linkWithInput')
		, 'minDate':            calOutVarsHash.get('minDate')
		, 'maxDate':            calOutVarsHash.get('maxDate')
		, 'alwaysShow':         calOutVarsHash.get('alwaysShow')
		, 'injectInsideTarget': calOutVarsHash.get('injectInsideTarget')
		, 'format':             calOutVarsHash.get('format')
		, 'alignX':             calOutVarsHash.get('alignX')
		, 'alignY':             calOutVarsHash.get('alignY')
		, 'createHiddenInput':  calOutVarsHash.get('createHiddenInput')
		, 'hiddenInputName':    calOutVarsHash.get('hiddenInputName')
		, 'hiddenInputFormat':  calOutVarsHash.get('hiddenInputFormat')
	});
	varsHash.include('selectedIn', checkincal.selectedDate);
	varsHash.include('selectedOut', checkoutcal.selectedDate);

	calInVarsHash.set('pickFunction', function(date) {
		$$('.start_date').set('value', date.get('date')+'/'+(date.get('month')+1)+'/'+date.get('year'));
		varsHash.set('selectedIn', checkincal.selectedDate);
		calOutVarsHash.set('minDate', new Date(calInVarsHash.get('defaultDate')).increment('day', 1));
		//calOutVarsHash.set('minDate', new Date(calInVarsHash.get('defaultDate')).increment());
		//checkoutcal.options.minDate = calOutVarsHash.get('minDate');
		//calOutVarsHash.set('maxDate', new Date(varsHash.get('selectedOut')).increment('day', varsHash.get('selection')));
		calOutVarsHash.set('maxDate', new Date(date).increment('day', varsHash.get('selection')));
		checkoutcal.options.maxDate = calOutVarsHash.get('maxDate');
		var newOutDate = new Date(varsHash.get('selectedIn')).increment('day', parseInt(varsHash.get('totNights')));
		checkoutcal.setDate(newOutDate);
		varsHash.set('selectedOut', checkoutcal.selectedDate);

		printDateSelect();
	});

	checkincal.options.pickFunction = calInVarsHash.get('pickFunction');

	calOutVarsHash.set('pickFunction', function(date) {
		$$('.end_date').set('value', date.get('date')+'/'+(date.get('month')+1)+'/'+date.get('year'));
		varsHash.set('selectedOut', checkoutcal.selectedDate);
		var diff = giorniDifferenza(varsHash.get('selectedIn'), varsHash.get('selectedOut'));
		if (diff <= 0) {
			checkincal.setDate(varsHash.get('selectedOut').decrement('day', 1));
			varsHash.set('selectedIn', checkincal.selectedDate);
			calcTotNights(varsHash.get('selectedIn'), varsHash.get('selectedOut'));
		} else if (diff >= 2) {
			calcTotNights(varsHash.get('selectedIn'), varsHash.get('selectedOut'));
		}
		printDateSelect();
		//closeOpt();
	});

	//$(document.body).addLiveEvent('click', 'div.canClick', function(e){
	$('checkoutDisplay').addLiveEvent('click', 'div.canClick', function(e){
		//if (this.getParent('div#checkoutDisplay')) { closeOpt(); }
		closeOpt();
	});

	checkoutcal.options.pickFunction = calOutVarsHash.get('pickFunction');

	// 1. Seleziono checkin da INPUT
	$('start_date').addEvents({
		'blur': function(){
			var date = $(this).getProperty('value');
			var newDate = changeDate('checkincal', date, calInVarsHash.get('minDate'), calInVarsHash.get('maxDate'));

			calInVarsHash.set('defaultDate', newDate);
			checkincal.setDate(calInVarsHash.get('defaultDate'));
			varsHash.set('selectedIn', checkincal.selectedDate);
			calOutVarsHash.set('minDate', calInVarsHash.get('defaultDate').increment('day', 1));
			checkoutcal.options.minDate = calOutVarsHash.get('minDate');
			calOutVarsHash.set('maxDate', varsHash.get('selectedOut').increment('day', varsHash.get('selection')));
			checkoutcal.options.maxDate = calOutVarsHash.get('maxDate');
			var newOutDate = new Date(varsHash.get('selectedIn')).increment('day', parseInt(varsHash.get('totNights')));
			checkoutcal.setDate(newOutDate);
			varsHash.set('selectedOut', checkoutcal.selectedDate);

			printDateSelect();
			//opacities();
		}
	});

	// 2. Seleziono checkout da INPUT
	$('end_date').addEvents({
		'blur': function(){
			var date = $(this).getProperty('value');
			var newDate = changeDate('checkoutcal', date, checkoutcal.options.minDate, checkoutcal.options.maxDate);
			checkoutcal.setDate(newDate);
			varsHash.set('selectedOut', checkoutcal.selectedDate);
			var diff = giorniDifferenza(varsHash.get('selectedIn'), varsHash.get('selectedOut'));
			if (diff <= 0) {
				checkincal.setDate(varsHash.get('selectedOut').decrement('day', 1));
				varsHash.set('selectedIn', checkincal.selectedDate);
				calcTotNights(varsHash.get('selectedIn'), varsHash.get('selectedOut'));
			} else if (diff >= 2) {
				calcTotNights(varsHash.get('selectedIn'), varsHash.get('selectedOut'));
			}
			printDateSelect();
			closeOpt();
		}
	});

	// 3. Seleziono totNights da select
	calcTotNights($$('.start_date').getProperty('value'), $$('.end_date').getProperty('value'));

	var qb   = $('quickbooker')
	  , lang = $('quickbooker').getProperty('lang')
	  , xx   = $('chiudi')
	  , pc   = $('promocodes')
	  , sel  = $$('.select')
	  , opt  = $$('.options')
	  , opta = $$('.options a')
	  , arw  = $$('.arrow')
	  , grp  = $$('.group')
	  , peta = $$('p.age')
	  , adu  = $('adults')
	  , chi  = $('children')
	  , adu1 = $('adults_1')
	  , chi1 = $('children_1')
	  , defH = $$('input#hotel').getProperty('value')
	  ;
	var qd       = $('quickdestinations')
	  , spot     = $$('a img.spot')
	  , hotList  = $$('ul.singleHotel')
	  , destList = $$('ul.destinations a')
	  ;

	// Gestione del menu
	// sostituisco gif con png se non IE6
	// vedi file /js/ie6qbfix.js

	//Setto la lingua
	if (lang == 'IT') {
		varsHash.set('lang', 'it-IT');
	} else if (lang == 'FR')  {
		varsHash.set('lang', 'fr-FR');
	}  else if (lang == 'DE')  {
		varsHash.set('lang', 'de-DE');
	} else  {
		varsHash.set('lang', 'en-EN');
	}
	MooTools.lang.setLanguage(varsHash.get('lang'));

	//Nascondo tutto
	opt.setStyle('display', 'none');
	grp.setStyle('display', 'none');
	peta.setStyle('display', 'none');

	// gestisco l'hotel di default (se esiste)
	if (defH.length == 1
	 && $type(defH) == 'array'
	 && defH[0].length == 3 ) {
		var thisHotel = $(defH[0]).getProperty('title');
		$(defH[0]).addClass('selected');
		$$('input[id$=cityhotels]').setProperty('value', thisHotel);		
	}

	// gestisco la posizione del campo children
	if ($('children')) {
		var padre = $('children').getParent();
		$('children').setStyle('width', '96px');
		padre.setStyle('width', '96px');
		padre.setStyle('float', 'right');
	}

	$$('div.ibeMenu a').addEvent('click', function(e){
		e.stop();
		var which  = this.getProperty('class');
		//$$('div.box:not([class*='+which+'])').removeClass('aperto');
		//$$('div.box[class*='+which+']').toggleClass('aperto');
		$$('div.box:not([class*='+which+'])').removeClass('aperto');
		$$('div.box[class*='+which+']').toggleClass('aperto');
		var unoAperto = $$('div.aperto').length;
		if (unoAperto) {
			$('chiudi').addClass('aperto');
		} else {
			$('chiudi').removeClass('aperto');
		}
	});
	$('chiudi').addEvent('click', function(e){
		e.stop();
		$$('div.box').removeClass('aperto');
		this.removeClass('aperto');
	});

	spot.each(function(e) {
		var src       = e.get('src');
		var extension = src.substring(src.lastIndexOf('.'),src.length);
		var hotelCode = e.get('id');
		e.addEvents({
			'mouseover': function() {
				hotList.setStyle('display', 'none');
				e.setProperty('src',src.replace(extension,'-on' + extension));
				//$$('ul[class$='+hotelCode+']').setStyle('display', 'block');
			}
		  , 'mouseout': function() {
				e.setProperty('src',src);
			}
		 , 'click': function(e) {
			 	if ($$('ul[class$='+hotelCode+'] ul.destinations li').length == 1) {
					var dest = $$('ul[class$='+hotelCode+'] ul.destinations li a').getProperty('href');
					var text = $$('ul[class$='+hotelCode+'] ul.destinations li a').get('html');
					$$('input[id$=cityhotels]').setProperty('value', text);
					$$('input#hotel').setProperty('value', dest);
					$$('div.box').toggleClass('aperto');
				} else {
					//$$('ul[class$='+hotelCode+']').setStyle('display', 'block');
					$$('ul[class$='+hotelCode+']').reveal();
				}
			  	e.stop();
			}
		});
/*		e.addEvent('mouseover', function() {
			e.setProperty('src',src.replace(extension,'-on' + extension));
			$$('ul[class$='+hotelCode+']').setStyle('display', 'block');
		});
		e.addEvent('mouseout', function() {
			e.setProperty('src',src);
			$$('ul[class$='+hotelCode+']').setStyle('display', 'none');
		});*/
		/*e.addEvent('click', function(el) {
			$$('div.quickdestinations div.map .spot').destroy();
			//$$('div.quickdestinations div.map .message').set('text', 'text goes here');
			var spotMessage = new Element('p', {
				'id' : 'spotMessage',
				'html' : MooTools.lang.get('Message', 'sendingData')
				, 'styles': {
					'position': 'absolute'
				  , 'top' : '73px'
				  , 'left' : '20px'
				  , 'width' : '343px'
				  , 'height' : '30px'
				  , 'background-color' : '#fafafa'
				  , 'line-height' : '30px'
				  , 'text-align' : 'center'
				  , 'z-index' : '999'
				}
			});
			spotMessage.inject(qd, 'top');
			$$('#spotForm #qd_hotel').setProperty('value', 'hotel_code:' + hotelCode);
			$('spotForm').submit();
			el.stop();
		});*/
	});
	destList.addEvent('click', function(e) {
		e.stop();
		var dest = this.getProperty('href');
		var text = this.get('html');
		$$('input[id$=cityhotels]').setProperty('value', text);
		$$('input#hotel').setProperty('value', dest);
		$$('div.box').toggleClass('aperto');
	});
	$$('span.close a').addEvent('click', function(e) {
		//console.debug(e);
		var hotelCode = this.get('class');
		$$('ul[class$='+hotelCode+']').setStyle('display', 'none');
		e.stop();
	});



	// Gestisco il movimento del quickbooker
	if (qb) {
		/*var status = {
			'true': 'open',
			'false': 'close'
		};

		var verticalQB = new Fx.Slide('quickbooker');
		$$('a.openBooking').addEvent('click', function(e){
			e.stop();
			verticalQB.toggle();
		});*/

		// Gestisco il movimento del promocode
		if (pc) {
			pc.setStyle('display', 'none');

			$$('a.openPC').addEvent('click', function(e){
				e.stop();
				var statusPC = pc.getStyle('display');
				closeOpt();
				if (statusPC == 'block') {
					//pc.setStyle('display', 'none');
					pc.dissolve();
					$$('p.promo').setStyle('background-image', 'url(/skin/website/widgets/ibeUi/ico-arrow.gif)');
				} else {
					//pc.setStyle('display', 'block');
					pc.reveal();
					$$('p.promo').setStyle('background-image', 'url(/skin/website/widgets/ibeUi/ico-arrow2.gif)');
				}
			});
			/*var statusPC = {
				'true': 'url(/skin/website/widgets/ibeUi/ico-arrow2.gif)',
				'false': 'url(/skin/website/widgets/ibeUi/ico-arrow.gif)'
			};
	
			var verticalPC = new Fx.Slide('promocodes').hide();
			$$('a.openPC').addEvent('click', function(e){
				e.stop();
				verticalPC.toggle();
			});
			
			verticalPC.addEvent('complete', function() {
				$$('p.promo').setStyle('background-image', statusPC[verticalPC.open]);
			});*/
		}
		
		//gestisco l'apertura delle opzioni
		arw.each(function(e) {  
			e.addEvent('click', function(el) {
				var myClass   = e.getProperty('class');
				var thisClass = myClass.substring(6);
				var myOpt     = $$('div.options[class$='+thisClass+']');
				var myInput   = $$('input[id$='+thisClass+']');
				var newTop    = parseInt($(thisClass).getParent('p').offsetTop);
				var newLeft   = $(thisClass).getParent('p').offsetLeft;
				var newHeight = parseInt(myInput.getHeight());

				if (myOpt.getStyle('display') == 'none') {
					if (thisClass != 'totnights') {closeOpt();}
					if (Browser.Engine.gecko) {
						newTop = newTop - 11;
						newLeft = newLeft - 27;
					}
					myOpt.setStyle('top', (newTop + newHeight + 14));
					myOpt.setStyle('left', newLeft);
					//myOpt.setStyle('display', 'block');
					myOpt.reveal();
				} else {
					myOpt.setStyle('display', 'none');
					//if (thisClass != 'totnights') {printDateSelect();}
				}
			}); 
		});

		// gestisco l'apertura delle opzioni anche focus del campo
		$$('input[readonly]').each(function(e) {
			e.addEvent('focus', function(el) {
				var thisClass   = e.get('name');
				/*var myOpt     = $$('div.options[class$='+thisClass+']');
				var newTop    = parseInt(e.offsetParent.offsetTop);
				var newHeight = parseInt(e.offsetParent.getHeight());
				if (myOpt.getStyle('display') == 'none') {
					if (thisClass != 'totnights') {closeOpt();}
					myOpt.setStyle('top', (newTop + newHeight - 1));
					myOpt.setStyle('left', e.offsetParent.offsetLeft);
					myOpt.setStyle('display', 'block');
				} else {
					myOpt.setStyle('display', 'none');
				}*/
				var myOpt     = $$('div.options[class$='+thisClass+']');
				var myInput   = $$('input[id$='+thisClass+']');
				var newTop    = parseInt($(thisClass).getParent('p').offsetTop);
				var newLeft   = $(thisClass).getParent('p').offsetLeft;
				var newHeight = parseInt(myInput.getHeight());

				if (myOpt.getStyle('display') == 'none') {
					if (thisClass != 'totnights') {closeOpt();}
					if (Browser.Engine.gecko) {
						newTop = newTop - 11;
						newLeft = newLeft - 27;
					}
					myOpt.setStyle('top', (newTop + newHeight + 14));
					myOpt.setStyle('left', newLeft);
					//myOpt.setStyle('display', 'block');
					myOpt.reveal();
				} else {
					myOpt.setStyle('display', 'none');
					//if (thisClass != 'totnights') {printDateSelect();}
				}
			}); 
		});
		$$('div.options.withClose').each(function(e) {
			var btCloseOpt = new Element('a', {
				'class': 'btCloseOpt',
				'html': '<img src="/skin/website/widgets/ibeUi/bt-check_opt.png" alt="Close" />',
				'styles': {
					'position': 'absolute'
				  , 'display': 'block'
				  , 'top': '-10px'
				  , 'right': '-10px'
				  , 'width': '25px'
				  , 'height': '25px'
				},
				'events': {
					'click': function(){
						closeOpt();
					},
					'mouseover': function(){
						btCloseOpt.setStyle('background', 'none');
					}
				}
			});
			e.grab(btCloseOpt, 'top');
		});
		
		//gestisco il click su una opzione
		opta.each(function(e) {
			e.addEvent('click', function(el) {
				el.stop();
				var myClass   = e.getProperty('class');
				var myTitle   = e.getProperty('title');
				var myHref    = e.getProperty('href');
				var thisClass = myClass.substring(6);
				var myInput   = $$('input[id$='+thisClass+']');
				var myId      = e.getProperty('id');
				var myFather  = e.getParent();
				var allLi     = $$('div.options[class$='+thisClass+'] li');

				if (thisClass == 'number_rooms') {
					openRooms(myTitle);
					/*peta.each(function(e) {
						
					});*/
				}
				if (thisClass.substr(0,9) == 'children_') {
					openAge(myTitle, thisClass.substr(9, 1));
					$('children').setProperty('value', myTitle);
				} else if (thisClass.substr(0,9) == 'children') {
					openAge(myTitle, 0);
					$('children_1').setProperty('value', myTitle);
				}
				if (thisClass.substr(0,9) == 'adults') {
					$('adults_1').setProperty('value', myTitle);
				} else if (thisClass.substr(0,9) == 'adults_1') {
					$('adults').setProperty('value', myTitle);
				}
				if (thisClass.substr(0,6) == 'eta_0_') {
					var splitted = thisClass.split('_');
					var toChange = 'eta_1_' + splitted[2];
					$(toChange).setProperty('value', myTitle);
				} else if (thisClass.substr(0,6) == 'eta_1_') {
					var splitted = thisClass.split('_');
					var toChange = 'eta_0_' + splitted[2];
					$(toChange).setProperty('value', myTitle);
				}

				if (thisClass == 'totnights') {
					var currentIn = varsHash.get('selectedIn');
					
					calOutVarsHash.set('minDate', new Date(checkincal.selectedDate).increment('day', 1));
					checkoutcal.options.minDate = calOutVarsHash.get('minDate');
					var newOutDate = new Date(varsHash.get('selectedIn')).increment('day', parseInt(myTitle));
					checkoutcal.setDate(newOutDate);
					varsHash.set('selectedOut', checkoutcal.selectedDate);
					varsHash.set('totNights', myTitle);

					printDateSelect();

					//closeOpt(thisClass);
					closeOpt();
					myInput.setProperty('value', myTitle +  ' ' +  MooTools.lang.get('Message', 'totNights'));
				} else if (thisClass == 'cityhotels') {
					$$('.options a').removeClass('selected');
					e.addClass('selected');
					myInput.setProperty('value', myTitle);
					$$('input#hotel').setProperty('value', myHref + ':' + myId);
					closeOpt();
				} else {
					myInput.setProperty('value', myTitle);
					closeOpt();
				}
				allLi.removeClass('selected');
				myFather.addClass('selected');
			}); 
		});

		// gestisco la valorizzazione del campo data select
		if ($('dates')) {
			printDateSelect();
		}

		// gestione focus nei campi text con value predefinito
		$$('form#ibeUi input[class!=select]').each(function(e) {
			var myVal = e.get('value');
			e.addEvents({
				'focus': function() { e.set('value', '');}
			  , 'blur': function() {
					if (e.get('value') == '') { e.set('value', myVal);}
				}
			});
		});

		// validazione form
		/*$$('input[id^=eta_]').addEvent('keypress', function(e) {					
			return isNumberKey(e);
		});*/
		$('proceed').addEvent('click', function(e) {
			if ($$('fieldset.errorMsg')) {$$('fieldset.errorMsg').destroy();}
			var form = $('ibeUi');

			var validate = formValidation(form);
			if (validate == false) {
				var errorMsg = new Element('fieldset', {
					'class': 'errorMsg',
					'html': '<p>' + MooTools.lang.get('Message', 'errorMsg') + '</p>',
					'styles': {
						'display': 'block'
					}
				});				
				form.grab(errorMsg, 'top');
				return false;
			}

			// ripulita ai campi form non utili al post
			$$('form#ibeUi fieldset[class!=proceed]').each(function(e) {
				e.setStyle('display', 'none');
			});
			var sendingData = new Element('fieldset', {
				'class': 'sendingData',
				'html': '<p>' + MooTools.lang.get('Message', 'sendingData') + '</p>',
				'styles': {
					'display': 'block'
					, 'height': '141px'
				}
			});				
			form.grab(sendingData, 'top');
			this.setProperty('value', MooTools.lang.get('Message', 'pleaseWait'));

			$$('input#cityhotels').destroy();
			$$('input#dates').destroy();
			$$('input#totnights').destroy();
			$$('input[name=checkinforse]').destroy();
			$$('input[name=checkoutforse]').destroy();
			$$('input#adults').destroy();
			$$('input#children').destroy();
			$$('form#ibeUi input[id^=eta_0]').destroy();

			$$('form#ibeUi input[id^=adults_]').each(function(e) {
				var val = e.getProperty('value');
				if (val == '') { e.destroy();}
			});

			$$('form#ibeUi input[id^=children_]').each(function(e) {
				var val = e.getProperty('value');
				if (val == '') { e.destroy();}
			});

			$$('form#ibeUi input[id^=eta_]').each(function(e) {
				var val = e.getProperty('value');
				if (val == '') {
					e.destroy();
				} else {
					e.setProperty('value', '12');
				}
			});

			var startD = transformDate($$('.start_date').getProperty('value'));
			$$('.start_date').setProperty('value', startD);
			var endD = transformDate($$('.end_date').getProperty('value'));
			$$('.end_date').setProperty('value', endD);

			var bclub = $$('input#bclub').getProperty('value');
			if (bclub == 'Number') {
				$$('input#bclub').setProperty('value', '');
			}
			var bclubpass = $$('input#bclubpass').getProperty('value');
			if (bclubpass == 'Password') {
				$$('input#bclubpass').setProperty('value', '');
			}
			$$('div#promocodes input').each(function(e) {
				var val = e.getProperty('value');
				if (val == '') { e.destroy();}				
			});
		});
	}
});