document.addEvent('click', function() {
	Calendar.close();
});

var interface_url = '/inc/interface.php';

function onInit() {
	if (!Cookie.read('assistence')) {
		Cookie.write('assistence', 'true', {
			domain : 'continuitaterritoriale.it',
			path : '/'
		});

		$('assistence').style.display = 'block';
		setTimeout("$('assistence').style.display = 'none';", 15000);
	}
};

function goToOffset(formID, offset) {
	var form = $(formID);
	if (form) {
		form['offset'].value = offset;
		form.submit();
	}
}

function getFlightList(direction, el) {
	var el = $(el);
	var date = el.title;
	var form = $('book_form');
	var from = direction == 'going' ? form.from.value : form.to.value;
	var to = direction == 'going' ? form.to.value : form.from.value;
	var div = $(direction).getElement('div');
	div.setStyle('height', div.getHeight());
	var params = 'method=getFlightList&from=' + from + '&to=' + to + '&date=' + date + '&direction=' + direction;
	if (direction == 'going')
		form.going_date.value = date;
	else
		form.return_date.value = date;

	// Seleziono il giorno cliccato
	$(direction).getElement('ul.week').getElement('li.selected').removeClass('selected');
	el.getParent().addClass('selected');

	// Nascondo la tabella e mostro l'indicatore di caricamento
	if ($(direction).getElement('div table'))
		$(direction).getElement('div table').fade('hide');
	$(direction).addClass('loading');

	// Faccio la richiesta al server
	new Request({
		url : interface_url,
		onSuccess : function(txt, xml) {
			// Scrivo la nuova tabella
			div.innerHTML = txt;

			// Calcolo le dimensioni della nuova tabella e la nascondo
			var table = $(direction).getElement('div table');
			if (table) {
				var h = table.getHeight();
				table.fade('hide');

				// Ridimensiono il div contenitore e mostro la tabella
				div.set('tween', {
					onComplete : function() {
						$(direction).removeClass('loading');
						table.fade('in');
					}
				});
				div.tween('height', h);
			}
		}
	}).send(params);

	// Cambio anche il ritorno se precedente all'andata
	var oneway = (form.oneway && (form.oneway.checked || form.oneway.value == 1)) ? true : false;
	if (direction == 'going' && !oneway) {
		var g = date.replace(/-/g, '');
		var r = $('return').getElement('ul.week li.selected a').title.replace(/-/g, '');
		if (g <= r)
			return;

		var d = date.split('-');
		var time = new Date(d[0], d[1] - 1, d[2]);

		var ul = Calendar.doWeek(time.getTime(), 'return');
		ul.replaces($('return').getElement('ul.week'));

		// Chiamo la lista per il giorno selezionato
		getFlightList('return', ul.getElement('li a'));
	}
}

function toggleReturn(el) {
	if (el.checked) {
		var div = new Element('div', {
			id : 'glass'
		}).set('opacity', 0).setStyle('height', $('return').getHeight()).inject('return').fade(0.8);
	} else {
		if (!$('glass'))
			return false;

		$('glass').set('tween', {
			onComplete : function() {
				$('glass').destroy();
			}
		});
		$('glass').tween('opacity', 0);
	}
}

function selectRow(tr) {
	var tr = $(tr);

	// Check del radio button
	tr.getElement('input[type="radio"]').checked = "checked";

	// Selezione della riga
	if (tr.getParent().getElement('tr.selected'))
		tr.getParent().getElement('tr.selected').removeClass('selected');
	tr.addClass('selected');
}

function modifyFlights(el) {
	var s = $('payment');
	var f = $('book_form');

	if (!s)
		return false;

	if (el.innerHTML == 'Modifica') {
		s.style.display = 'none';
		f.style.display = 'block';
		el.innerHTML = 'Annulla';
	} else {
		s.style.display = 'block';
		f.style.display = 'none';
		el.innerHTML = 'Modifica';
	}
}

function loginPanel(showHost) {
	if (showHost) {
		$('loginBox').bookingSubmit.value = 1;
		$('loginBox').getElement('.host').style.display = 'block';
	} else {
		$('loginBox').bookingSubmit.value = 0;
		$('loginBox').getElement('.host').style.display = 'none';
	}

	Panel.open('loginBox');
}

function doLogin() {
	var params = $('loginBox').toQueryString();
	var button = $('loginBox').getElement('.button');
	button.style.display = 'none';

	new Request({
		url : interface_url,
		onSuccess : function(txt, xml) {
			if (txt == '1') {
				if ($('loginBox').bookingSubmit.value == 1)
					$('book_form').submit();
				else
					document.location.href = '/';
			} else {
				$('loginBox').getElement('.error').innerHTML = txt;
				button.style.display = 'inline';
			}
		}
	}).send(params);
}

function checkBookingForm(login, showLoadingPage) {
	// Numero di neonati <= numero di adulti
	if ($('book_form').infants.value > $('book_form').passengers.value) {
		alert('Il numero di neonati non può essere superiore al numero di passeggeri adulti.');
		return false;
	}

	// Verifico che il volo di andata sia stato selezionato
	var andata = false;
	$('book_form').getElements('input[name="going"]').each(function(el) {
		if (el.checked) {
			andata = el.id;
			return;
		}
	});
	if (!andata) {
		alert('Devi selezionare il volo di andata');
		return false;
	}

	// Verifico che il volo di ritorno sia stato selezionato
	if (($('book_form').oneway.type == 'checkbox' && $('book_form').oneway.checked)
			|| ($('book_form').oneway.type != 'checkbox' && $('book_form').oneway.value != ''))
		var oneway = true;
	else
		var oneway = false;

	if (!oneway) {
		var ritorno = false;
		$('book_form').getElements('input[name="return"]').each(function(el) {
			if (el.checked) {
				ritorno = el.id;
				return;
			}
		});
		if (!ritorno) {
			alert('Devi selezionare il volo di ritorno');
			return false;
		}
	}

	// Verifico che il volo di ritorno non sia precedente a quello di andata
	if (!oneway) {
		var andata = andata.replace(/\-|\:|T/g, '');
		var ritorno = ritorno.replace(/\-|\:|T/g, '');
		if (andata > ritorno) {
			alert('La data del volo di ritorno deve essere successiva a quella del volo di andata.');
			return false;
		}
	}

	if (login)
		loginPanel(true);
	else {
		if (showLoadingPage)
			showLoading($('book_form'));
		else
			$('book_form').submit();
	}
}

function validateStep1(form) {
	var inputs = $('step1_form').getElements('.required');
	var ok = true;
	inputs.each(function(el) {
		var name = el.nodeName.toLowerCase();
		switch (name) {
		case 'input':
			if (el.value == '') {
				el.addClass('missed');
				ok = false;
			} else
				el.removeClass('missed');
			break;
		case 'select':
			if (el.value == '') {
				el.addClass('missed');
				ok = false;
			} else
				el.removeClass('missed');
			break;
		}
	});

	if (!ok) {
		$('step1_form').getElement('.missed').focus();
		alert('Uno o più campi non sono stati compilati correttamente.');
		return false;
	}

	// Controllo congruità campi data di nascita
	if (form.getElement('input.str') && form.getElement('input.str').checked) {
		ok = true;
		form.getElements('fieldset').each(function(el) {
			if (!checkDOB(el))
				ok = false;
		});
		if (!ok)
			return false;
	}

	showLoading(form);
}

function validateStep2(form) {
	// Verifico che siano state scelte le tariffe per ogni passeggero/gruppo
	var passengers = $('payment').group ? 1 : $('book_form').passengers.value;
	var checked = 0;
	var mustBeChecked = $('book_form').oneway.value != '' ? 1 : 2;
	$('payment').getElements('input.fare').each(function(el) {
		if (el.checked)
			checked++;
	});

	if (checked < mustBeChecked) {
		alert('Devi scegliere una tariffa per ogni volo');
		return false;
	}

	// Verifico che il sia stato selezionato un centro di costo dalla relativa
	// selectBox
	if ($('normalPayment') && !$('normalPayment').checked) {
		if ($('costCenterID') && $('costCenterID').value == '') {
			alert('Devi selezionare un centro di costo o inserire gli estremi dii una carta di credito');
			$('costCenterID').focus();
			return false;
		}

		var id = $('costCenterID') ? $('costCenterID').value : 0;
		var creditCardSelect = $('ccFor' + id).getElement('select');
		if (creditCardSelect && creditCardSelect.value == '') {
			alert('Devi selezionare una carta di credito o inserire gli estremi di una carta di credito');
			creditCardSelect.focus();
			return false;
		}
	}

	// Verifico che i campi sul pagamento "manuale" siano compilati
	if (!$('normalPayment') || ($('normalPayment') && $('normalPayment').checked)) {
		var inputs = $('payment').getElement('fieldset').getElements('.required');
		var ok = true;
		inputs.each(function(el) {
			var name = el.nodeName.toLowerCase();
			switch (name) {
			case 'input':
				if (el.value == '') {
					el.addClass('missed');
					ok = false;
				} else
					el.removeClass('missed');
				break;
			case 'select':
				if (el.value == '') {
					el.addClass('missed');
					ok = false;
				} else
					el.removeClass('missed');
				break;
			}
		});

		if (!ok) {
			$('payment').getElement('fieldset').getElement('.missed').focus();
			alert('Uno o più campi non sono stati compilati correttamente.');
			return false;
		}
	}

	if (!$('payment').accettazione.checked) {
		alert('Devi accettare le condizioni generali di contratto');
		$('payment').accettazione.focus();
		return false;
	}

	showLoading(form);
}

function validateRegistrationForm(form) {
	form = $(form);

	var inputs = form.getElements('.required');
	var ok = true;
	inputs.each(function(el) {
		var name = el.nodeName.toLowerCase();
		switch (name) {
		case 'input':
			if (el.value == '') {
				el.addClass('missed');
				ok = false;
			} else
				el.removeClass('missed');
			break;
		case 'select':
			if (el.value == '') {
				el.addClass('missed');
				ok = false;
			} else
				el.removeClass('missed');
			break;
		}
	});

	if (!ok) {
		form.getElement('.missed').focus();
		alert('Uno o più campi non sono stati compilati correttamente.');
		return false;
	}

	// Verifica della password
	if (form.password && form.password_verify && form.password.value != form.password_verify.value) {
		form.password.focus();
		alert('La password non coincide con quello di verifica');
		return false;
	}

	// Controllo sulla congruità delle date di nascita
	if (form.getElement('input.str') && form.getElement('input.str').checked) {
		if (!checkDOB(form.getElement('fieldset')))
			return false;
	}

	form.submit();
}

function openPassengerTypes() {
	var form = $('step1_form');
	var display = form.getElement('input.str') && form.getElement('input.str').checked ? true : false;
	form.getElements('.lista_tipi').each(function(el) {
		el.style.display = display ? 'block' : 'none';
	});
}

function checkDOB(fieldset) {
	var ok = true;

	fieldset.getElements('input.passengerType').each(function(el) {
		if (el.checked && (el.value == 'YTH' || el.value == 'SRC' || el.value == 'STU')) {
			var now = new Date();
			var years = now.getFullYear() - fieldset.getElement('select.year').value;
			switch (el.value) {
			case 'YTH':
				if (years < 12 || years > 21) {
					alert('L\'età deve essere compresa tra i 12 e i 21 anni');
					el.focus();
					ok = false;
				}
				break;
			case 'SRC':
				if (years < 70) {
					alert('L\'età deve essere maggiore di 70 anni');
					el.focus();
					ok = false;
				}
				break;
			case 'STU':
				if (years < 18 || years > 27) {
					alert('L\'età deve essere compresa tra i 18 e i 27 anni');
					el.focus();
					ok = false;
				}
				break;
			}
		}
	});

	return ok;
}

function showLoading(form) {
	var l = new Element('div').addClass('loading2').inject('content');
	new Element('img', {
		src : '/img/logo.gif'
	}).inject(l);
	l.style.display = 'block';
	l.setStyle('height', $('content').getHeight() - $('footer').getHeight());
	(function() {
		form.submit();
	}).delay(1000);
}

function updateTotalFare(el) {
	var tot = 0;
	var par = 0;
	var tr = $(el).getParent().getParent();
	var table = tr.getParent();

	// Parziale passeggero
	table.getElements('input.fare').each(function(el) {
		if (!el.checked)
			return false;

		var total = el.getParent().getParent().getElement('td.totale').innerHTML.toFloat();
		par += total;
	});
	par = par.round(2);
	table.getElement('td.partial').innerHTML = par + ' €';

	// Totale
	$('payment').getElements('input.fare').each(function(el) {
		if (!el.checked)
			return false;

		var total = el.getParent().getParent().getElement('td.totale').innerHTML.toFloat();
		tot += total;
	});
	tot = tot.round(2);
	$('totalFare').innerHTML = tot + ' €';
	$('paymentAmount').value = tot;
}

function deleteOperator() {
	if (!confirm('Sei sicuro di voler cancellare questo operatore?'))
		return false;

	var f = $('updateOperatorForm');
	f.method.value = 'deleteOperator';
	f.submit();
}

function deleteCostCenter() {
	if (!confirm('Sei sicuro di voler cancellare questo centro di costo?'))
		return false;

	var f = $('updateCostCenterForm');
	f.method.value = 'deleteCostCenter';
	f.submit();
}

function deleteCreditCard() {
	if (!confirm('Sei sicuro di voler cancellare questa carta di credito?'))
		return false;

	var f = $('updateCreditCardForm');
	f.method.value = 'deleteCreditCard';
	f.submit();
}

function deleteUserCreditCard() {
	if (!confirm('Sei sicuro di voler cancellare questa carta di credito?'))
		return false;

	var f = $('updateUserCreditCardForm');
	f.method.value = 'deleteUserCreditCard';
	f.submit();
}

function deleteContact() {
	if (!confirm('Sei sicuro di voler cancellare questo contatto?'))
		return false;

	var f = $('updateContactForm');
	f.method.value = 'deleteContact';
	f.submit();
}

function deleteBooking(form) {
	if (!confirm('Sei sicuro di voler cancellare questa prenotazione?'))
		return false;

	var form = $(form);
	form.submit.value = 'Operazione in corso...';
	var table = $(form.pnr.value + 'Table');
	var params = $(form).toQueryString();
	new Request({
		url : interface_url,
		onSuccess : function(txt, xml) {
			if (txt == 1) {
				form.innerHTML = '<span style="color:red;">Prenotazione cancellata</span>';
				table.fade(.3);
			}
		}
	}).send(params);
}

function printPage() {
	window.print();
}

function showNormalPayment(el) {
	if (el.checked) {
		// Resetto tutte le carte di credito
		$('payment').getElements('.ccLabel').each(function(el) {
			el.style.display = 'none';
			el.getElement('select').name = 'creditCardID-disabled';
			el.getElements('option').each(function(option) {
				option.selected = '';
			});
		});

		$('normalPaymentDiv').style.display = 'block';
	} else {
		$('normalPaymentDiv').style.display = 'none';
		var id = $('costCenterID') ? $('costCenterID').value : 0;
		if ($('ccFor' + id)) {
			$('ccFor' + id).getElement('select').name = 'creditCardID';
			$('ccFor' + id).style.display = 'block';
		}
	}
}

function hideNormalPayment(el) {
	$('normalPayment').checked = false;
	$('normalPaymentDiv').style.display = 'none';
}

function selectThisCostCenter() {
	$('payment').getElements('input[name="creditCardID"]').each(function(el) {
		if (el.value != '')
			el.checked = false;
	});
}

function autoCompleteagencyID(el) {
	$('agencyID').innerHTML = el.value;
}

function selectSelect(val, sel) {
	for ( var i = 0; i < $(sel).options.length; i++) {
		if ($(sel).options[i].value == val)
			break;
	}

	$(sel).options.selectedIndex = i;
}

function reportFormSubmit(form) {
	$(form).exp.value = 0;
	$(form).submit();
}

function reportExport() {
	$('reportForm').exp.value = 1;
	$('reportForm').submit();
}

function showSTRTypes(i, el) {
	var div = $('types' + i);
	div.style.display = $(el).checked ? 'block' : 'none';
}

function dobRequired(i, status) {
	var div = $('dob' + i);
	if (!div)
		return false;

	div.getElement('em').innerHTML = status ? '*' : '&nbsp;';

	div.getElements('select').each(function(el) {
		if (status)
			el.addClass('required');
		else {
			el.removeClass('required');
			el.removeClass('missed');
		}
	});
}

function tuttiContinuita(checkbox) {
	$('step1_form').getElements('.lista_tipi').each(function(el) {
		el.style.display = $(checkbox).checked ? 'block' : 'none';
	});
}

function showClassRuleDescription(address) {
	var win = window.open("./classRules.php?rule=" + address, "rulesWindow", "location=0,menubar=0,scrollbars=1,resizable=0,status=1,width=600,height=400");
	win.moveTo(400, 150);
}

function openInPopup(a) {
	var win = window.open(a.href, "popupWindow", "location=0,menubar=0,scrollbars=1,resizable=0,status=1,width=600,height=400");
	win.moveTo(400, 150);
}

function showCreditCardsFor(select) {
	var id = select.options[select.selectedIndex].value;

	// Resetto tutte le carte di credito
	$('payment').getElements('.ccLabel').each(function(el) {
		el.style.display = 'none';
		el.getElement('select').name = 'creditCardID-disabled';
		el.getElements('option').each(function(option) {
			option.selected = '';
		});
	});

	// Mostro quella selezionata
	if (id) {
		$('ccFor' + id).getElement('select').name = 'creditCardID';
		$('ccFor' + id).style.display = 'block';
	}
}

function selectContact(pNum, json) {
	var F = $('step1_form');

	if (pNum == '-1') {
		F['p_cognome'].value = json.lastName;
		F['p_nome'].value = json.firstName;

		// F['p_prefisso'].value = json.phonePrefix;
		F['p_cellulare'].value = json.phone;

		F['p_email'].value = json.email;
	} else {
		F['cognome[' + pNum + ']'].value = json.lastName;
		F['nome[' + pNum + ']'].value = json.firstName;

		if(F['continuita[' + pNum + ']']) {
			var str = (json.str == 'true');
		
			F['continuita[' + pNum + ']'].checked = str;
			var div = $('types' + pNum);
			div.style.display = str ? 'block' : 'none';
		
			var types = F['passengerType[' + pNum + ']'];
			for ( var i = 0; i < types.length; i++) {
				types[i].checked = (types[i].value == json.passengerType);
			}
		}

		if (json.dob) {
			var v = json.dob.split("-");
			F['D[' + pNum + ']'].value = v[2];
			F['M[' + pNum + ']'].value = v[1];
			F['Y[' + pNum + ']'].value = v[0];
		}

		for ( var i = 0; i < json.freqFlyers.length; i++) {
			F['frequentflyer' + json.freqFlyers[i].airline + '[' + pNum + ']'].value = json.freqFlyers[i].code;
		}

		if (json.cdc)
			F['cdc[' + pNum + ']'].value = json.cdc;
	}
	Panel.close("selectContact");
}

var Panel = {
	open : function(id) {
		if ($('blocker'))
			$('blocker').destroy();
		var blocker = new Element('div', {
			id : 'blocker'
		}).set('opacity', 0).addEvent('click', function() {
			Panel.close(id);
		}).inject(document.body, 'top');

		new Fx.Tween(blocker, {
			property : 'opacity',
			duration : 'short',
			onComplete : function() {
				$(id).style.display = 'block';

				var scrollTop = $(document.body).getScrollTop();
				var top = (window.innerHeight / 2) - ($(id).getHeight() / 2) + scrollTop;
				$(id).set('tween', {
					onComplete : null
				});
				$(id).tween('top', 0);
			}
		}).start(.8);
	},

	close : function(id) {
		$(id).set('tween', {
			onComplete : function() {
				$('blocker').destroy();
				$(id).style.display = 'none';
			}
		});
		$(id).tween('top', -$(id).getHeight());

	},

	edit : function(id, form, el) {
		var params = 'method=' + form + '&id=' + id;

		$(el).getParent().addClass('loading');

		new Request({
			url : interface_url,
			onSuccess : function(txt, xml) {
				$(form).innerHTML = txt;
				Panel.open(form);
				$(el).getParent().removeClass('loading');
			}
		}).send(params);
	}
}

var Calendar = {
	months : new Array('Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'),
	mLen : new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
	nDays : new Array(7, 1, 2, 3, 4, 5, 6),
	wDays : new Array('L', 'M', 'M', 'G', 'V', 'S', 'D'),
	now : null,
	target : null,

	close : function(next) {
		if ($('calendar'))
			$('calendar').destroy();
	},

	show : function(event, direction) {
		var event = new Event(event);
		event.stop();

		// Chiudo un eventuale precedente calendario
		if ($('calendar'))
			this.close();

		// Incollo il calendario nel luogo corretto
		this.target = new Element('div', {
			'id' : 'calendar'
		}).inject(document.body);
		this.target.setStyles({
			top : event.page.y,
			left : event.page.x - this.target.getWidth()
		});

		Calendar.create(direction);
	},

	create : function(direction, now, selected) {
		this.now = now ? new Date(now) : new Date();
		var target = this.target;
		var selected = selected ? new Date(selected) : new Date();

		// Eccezione per febbraio
		if (this.now.getFullYear() % 4 == 0)
			this.mLen[1] = 29;
		else
			this.mLen[1] = 28;

		// Creo il contenuto del calendario
		var first = new Date(this.now.getFullYear(), this.now.getMonth(), 1);
		if ($('calendario'))
			$('calendario').destroy();
		var container = new Element('div', {
			'id' : 'calendario'
		}).inject(target);
		var mesi = new Element('div').addClass('mesi').inject(container);
		var giorni = new Element('div').addClass('giorni').inject(container);

		// Mese e Anno
		var prev = new Date(this.now.getTime());
		prev.setMonth(prev.getMonth() - 1);
		var next = new Date(this.now.getTime());
		next.setMonth(next.getMonth() + 1);

		// Previous month
		new Element('span').addClass('prev').addEvent('mousedown', function(event) {
			new Event(event).stop();
			Calendar.create(direction, prev.getTime());
		}).set('html', '&nbsp;').inject(mesi);

		// Current month
		new Element('span').addClass('month').addEvent('mousedown', function(event) {
			new Event(event).stop();
			Calendar.create(direction);
		}).set('html', this.months[this.now.getMonth()] + ' ' + this.now.getFullYear()).inject(mesi);

		// Next month
		new Element('span').addClass('next').addEvent('mousedown', function(event) {
			new Event(event).stop();
			Calendar.create(direction, next.getTime());
		}).set('html', '&nbsp;').inject(mesi);

		// Giorni della settimana
		var div = new Element('div').addClass('weekdays').inject(giorni);
		for ( var i = 0; i < this.wDays.length; i++) {
			new Element('span').set('html', this.wDays[i]).inject(div);
		}

		// Giorni del mese
		var day = new Date(this.now.getTime());
		var settimana = new Element('div').addClass('week').inject(giorni);
		var currentMonthLength = this.mLen[this.now.getMonth()];
		var currentDate = new Date();
		for (x = 1, y = 1; x <= currentMonthLength; x++, y++) {
			day.setDate(x);

			if (y >= this.nDays[first.getDay()]) {
				var d = day.getDate() > 9 ? day.getDate() : '0' + day.getDate();
				var m = (day.getMonth() + 1) > 9 ? (day.getMonth() + 1) : '0' + (day.getMonth() + 1);

				var a = new Element('a', {
					href : './',
					title : day.getTime()
				}).set('html', x).inject(settimana);

				if (day.getTime() > currentDate.getTime() - 86400000) {
					a.addClass('active');
					a.addEvent('click', function(event) {
						new Event(event).stop();
						Calendar.select(this, direction);
						return false;
					});
				} else {
					a.addClass('inactive');
					a.addEvent('click', function(event) {
						new Event(event).stop();
						return false;
					});
				}

				// Seleziono il giorno corrente
				// if(selected.getDate() == day.getDate() && selected.getMonth()
				// ==
				// day.getMonth() && selected.getYear() == day.getYear())
				// a.addClass('selected');
			} else {
				x--;
				var a = new Element('a').set('html', '&nbsp;').inject(settimana);
			}

			if (!(y % 7) && x != currentMonthLength)
				settimana = new Element('div').addClass('week').inject(giorni);

			if (!(y % 7))
				a.addClass('sunday');
		}
	},

	select : function(el, direction) {
		var current = el.title.toInt();

		// Recupero i prossimi 7 giorni partendo da quello specificato
		var ul = this.doWeek(current, direction);
		ul.replaces($(direction).getElement('ul.week'));

		// Chiamo la lista per il giorno selezionato
		getFlightList(direction, ul.getElement('li a'));

		// Chiudo il calendario
		this.close();
	},

	doWeek : function(time, direction) {
		var ms = 86400000;
		var ul = new Element('ul').addClass('week');
		for ( var i = 0; i < 7; i++) {
			var x = new Date(time + ms * i);
			var Y = x.getFullYear();
			var d = x.getDate() > 9 ? x.getDate() : '0' + x.getDate();
			var m = x.getMonth() + 1 > 9 ? x.getMonth() + 1 : '0' + (x.getMonth() + 1);
			var date = Y + '-' + m + '-' + d;

			var li = new Element('li').inject(ul);
			var a = new Element('a', {
				href : './',
				title : date
			}).set('html', d).addEvent('click', function() {
				getFlightList(direction, this);
				return false;
			}).inject(li);
			var span = new Element('span').set('html', this.months[x.getMonth()] + ' ' + x.getFullYear()).inject(a);

			// Elemento corrente
			if (i == 0)
				li.addClass('selected');
		}
		var li = new Element('li').inject(ul);
		new Element('img', {
			src : '/img/calendario.gif',
			alt : 'Calendario'
		}).addEvent('click', function(event) {
			Calendar.show(event, direction);
		}).inject(li);

		return ul;
	}
}

var Calendar2 = {
	months : new Array('Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'),
	mLen : new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
	nDays : new Array(7, 1, 2, 3, 4, 5, 6),
	wDays : new Array('L', 'M', 'M', 'G', 'V', 'S', 'D'),
	now : null,
	target : null,

	close : function(next) {
		if ($('calendar'))
			$('calendar').destroy();
	},

	show : function(event, direction) {
		var event = new Event(event);
		event.stop();

		// Chiudo un eventuale precedente calendario
		if ($('calendar'))
			this.close();

		// Incollo il calendario nel luogo corretto
		this.target = new Element('div', {
			'id' : 'calendar'
		}).inject(document.body);
		this.target.setStyles({
			top : event.page.y,
			left : event.page.x
		});

		Calendar2.create(direction);
	},

	create : function(direction, now, selected) {
		this.now = now ? new Date(now) : new Date();
		var target = this.target;
		var selected = selected ? new Date(selected) : new Date();

		// Eccezione per febbraio
		if (this.now.getFullYear() % 4 == 0)
			this.mLen[1] = 29;
		else
			this.mLen[1] = 28;

		// Creo il contenuto del calendario
		var first = new Date(this.now.getFullYear(), this.now.getMonth(), 1);
		if ($('calendario'))
			$('calendario').destroy();
		var container = new Element('div', {
			'id' : 'calendario'
		}).inject(target);
		var mesi = new Element('div').addClass('mesi').inject(container);
		var giorni = new Element('div').addClass('giorni').inject(container);

		// Mese e Anno
		var prev = new Date(this.now.getTime());
		prev.setMonth(prev.getMonth() - 1);
		var next = new Date(this.now.getTime());
		next.setMonth(next.getMonth() + 1);

		// Previous month
		new Element('span').addClass('prev').addEvent('mousedown', function(event) {
			new Event(event).stop();
			Calendar2.create(direction, prev.getTime());
		}).set('html', '&nbsp;').inject(mesi);

		// Current month
		new Element('span').addClass('month').addEvent('mousedown', function(event) {
			new Event(event).stop();
			Calendar2.create(direction);
		}).set('html', this.months[this.now.getMonth()] + ' ' + this.now.getFullYear()).inject(mesi);

		// Next month
		new Element('span').addClass('next').addEvent('mousedown', function(event) {
			new Event(event).stop();
			Calendar2.create(direction, next.getTime());
		}).set('html', '&nbsp;').inject(mesi);

		// Giorni della settimana
		var div = new Element('div').addClass('weekdays').inject(giorni);
		for ( var i = 0; i < this.wDays.length; i++) {
			new Element('span').set('html', this.wDays[i]).inject(div);
		}

		// Giorni del mese
		var day = new Date(this.now.getTime());
		var settimana = new Element('div').addClass('week').inject(giorni);
		var currentMonthLength = this.mLen[this.now.getMonth()];
		var currentDate = new Date();
		for (x = 1, y = 1; x <= currentMonthLength; x++, y++) {
			day.setDate(x);

			if (y >= this.nDays[first.getDay()]) {
				var d = day.getDate() > 9 ? day.getDate() : '0' + day.getDate();
				var m = day.getMonth() + 1 > 9 ? day.getMonth() + 1 : '0' + (day.getMonth() + 1);

				var a = new Element('a', {
					href : './',
					title : day.getTime()
				}).set('html', x).inject(settimana);
				a.addClass('active');
				a.addEvent('click', function(event) {
					new Event(event).stop();
					Calendar2.select(this, direction);
					return false;
				});
			} else {
				x--;
				var a = new Element('a').set('html', '&nbsp;').inject(settimana);
			}

			if (!(y % 7) && x != currentMonthLength)
				settimana = new Element('div').addClass('week').inject(giorni);

			if (!(y % 7))
				a.addClass('sunday');
		}
	},

	select : function(el, direction) {
		var current = el.title.toInt();
		var data = new Date(current);

		var d = data.getDate();
		if (d < 10)
			d = '0' + d;
		var m = data.getMonth() + 1;
		if (m < 10)
			m = '0' + m;
		var Y = data.getFullYear();

		$(direction).value = d + '/' + m + '/' + Y;
		$(direction + 'TS').value = Math.round(current / 1000);

		// Chiudo il calendario
		this.close();
	}
}
