var Moteur = {
	/*
	 * Affichage du moteur
	 */
	villes: new Array(),
	init: function() {
		$$('.choix_moteur').each(function(radio){
			if (radio.checked) {
				Moteur.afficher(radio.value);
			}
		});
		$$('.choix_moteur').addEvent('click', function(){
			Moteur.afficher(this.value);
		});
	},
	
	/**
	 * Charge un moteur en ajax et l'affiche
	 */
	afficher: function(nom_moteur) {
		// Si modeTest est à true on affiche le loader sans envoyer le formulaire
		var modeTest = false;
		
		if($('moteur_' + nom_moteur)) {
			return;
		}
		$$('.moteur').fade('out');
		new Request({
			url: $('frontUrl').value + 'index.php?action=ajax_moteurs&moteur='+nom_moteur,
			evalScripts: true,
			onComplete: function(retour) {
				var id_univers;
				var divMoteur = $$('.moteur')[0]; 
				divMoteur.set('html', retour);
				divMoteur.fade('in');
				switch (nom_moteur) {
					case 'sejour': 	id_univers = 1;	break;
					case 'vol':		id_univers = 6;	break;
					case 'forfait': id_univers = 4;	break;
					case 'location':id_univers = 9;	break;
					case 'circuit': id_univers = 2;	break;
					case 'hotel': 	id_univers = 4;	break;
					case 'hotel': 	id_univers = 5;	break;
					default: 		id_univers = 1;	break;
				}
				/**
				 * La validation des moteurs ne sont pas codés pareil
				 * Certains sont simples et demande de simplement poster le formulaire
				 * Pour d'autre il faut faire une requete AJAX et évaluer le javascript renvoyer au retour (une redirection, ou un message d'erreur)
				 */
				switch (nom_moteur) { 
					case 'vol':
					case 'forfait':
						$$('.moteur form').addEvent('submit', function(event){
							event.preventDefault();
							new Request({
								url: this.action,
								method: this.method,
								data: $('moteur_' + nom_moteur),
								onSuccess : function (response) {
									if (modeTest) return;
									//Common.hideLoading();
									if ( response!="") {
										eval(response);
									}
								},
								onFailure: function () {
									Common.hideLoading();
								},
								onRequest : function () {
									Common.showLoading('recherche_moteur', id_univers);
								}
							}).send();
						});
						break;
					default:
						if($('LOC')){
							Moteur.villes = $('LOC').getChildren();
						}
						$$('.moteur form').addEvent('submit', function() {
							Common.showLoading('recherche_moteur', id_univers);
							if (modeTest) return false;
						});
						break;
				}
				// Si il y a un autocomplete
				Moteur.attachAutocomplete();
				// Si il y a un calendrier
				if (c = $('calendarContainer')) {
					c.addEvent('mouseleave', function() {
						$('calendarContainer').innerHTML = '';
					});
				}
				// Pour hotel c'est plus compliqué, et comme j'ai pas le temps on va utiliser les fonctions d'alex
				if (nom_moteur == 'hotel') {
					Hotel.init();
				}
			}
		}).send();
	},
	
	attachAutocomplete: function() {
		Autocompleter_vol();
		Autocompleter_hotel();
	},

	/*
	 * Gestion de la radio "aller/retour" ou "aller simple" du moteur Vol 
	 */
	choixTypeVol: function(type){
		if(type=="choix_A"){
			Moteur.dateRetour = $('Retour').value;
			$('Retour').value ="";
			$('choix_retour').style.visibility="hidden";
			$('Retour').set('disabled', true);
		} else {
			$('Retour').set('disabled', false);
			$('Retour').value = Moteur.dateRetour;
			$('choix_retour').style.visibility="visible";			
		}
	},
	dateRetour : '',
	
	majDestinationsLocation: function() {
		$('LOC').getChildren().dispose(); //On vide la liste de villes
		var valeur = $('LOC2').value;
		var regexp = '^' + valeur.replace('.', '\.');
		Moteur.villes.each(function(option){
			str = option.get('value').toString();
			if(option.get('id') == 'optionIndifferent'){
				new Element('option', {
					'id': option.get('id'),
					'value': valeur,
					'text': option.get('text') 
				}).inject($('LOC'));
			}
			if (str.match(regexp)) {
				new Element('option', {
					'id': option.get('id'),
					'value': option.get('value'),
					'text': option.get('text') 
				}).inject($('LOC'));
			}
			$('LOC').value = valeur;
		});
	}
};

window.addEvent('domready', function(){
	Moteur.init(); 
	/*
	 * Calendrier
	 */
	if(typeof YAHOO!="undefined") {
		YAHOO.namespace("calendrier");
		function handleSelect(type, args, obj) {
			var selected = args[0]; 
			selected = this.toDate(selected[0]); 
			var day = selected.getDate();
			if (day<10) {
				day = "0" + day;
			}
			var month = selected.getMonth()+1;
			if (month < 10) {
				month = "0" + month;
			}
			var year = selected.getFullYear();
			this.input.value = day + '/' + month + '/' + year;
			
			// Si inputFin est renseigné, alors on le change à J+5
			if(this.inputFin) {
				selected.setTime(selected.getTime() + 1000*60*60*24*5);
				day = selected.getDate();
				if (day<10) {
					day = "0" + day;
				}
				month = selected.getMonth()+1;
				if (month < 10) {
					month = "0" + month;
				}
				year = selected.getFullYear();
				selected =  day + '/' + month + '/' + year;
				this.inputFin.value = selected;
			}
			$('calendarContainer').innerHTML = '';
		}

		YAHOO.calendrier.init = function(input, debut, fin) {
			var input = $(input), debut = $(debut), fin = $(fin);
			if(debut.value.length == 0){
				today = new Date();
				j = today.getDate();
				if(j < 10){
					j = '0' + j;
				}
				m = today.getMonth() + 1;
				if(m < 10){
					m = '0' + m;
				}
				y = today.getFullYear();
				debut.value = j + '/' + m + '/' + y; 
			}
			// Si on choisit la date de debut, alors on recalculera la fin
			dateDebut = debut.value.split('/');
			dateFin = fin.value.split('/');
			var selected_date = dateDebut[1] + "/" + dateDebut[0] + "/" + dateDebut[2] + " - " + dateFin[1] + "/" + dateFin[0] + "/" + dateFin[2];
			var page_date = dateDebut[1] + "/" + dateDebut[2];
			// Calcul de la date mini (J+2)
			var minDate = new Date();
			var timestamp = minDate.getTime();
			timestamp += 60*60*24*2*1000;	// = 2 jours en millisec
			minDate.setTime(timestamp);
			
			YAHOO.calendrier.cal = new YAHOO.widget.CalendarGroup("calendrier", "calendarContainer", {PAGES:2});
			YAHOO.calendrier.cal.input = input;
			if (input == debut && fin.get('disabled') == false) {
				// En renseignant l'inputFin, il sera automatiquement position à J+5
				YAHOO.calendrier.cal.inputFin = fin;
			}
			YAHOO.calendrier.cal.cfg.setProperty("MONTHS_SHORT",   ["Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Jui", "Aou", "Sep", "Oct", "Nov", "Dec"]); 
			YAHOO.calendrier.cal.cfg.setProperty("MONTHS_LONG",    ["Janvier", "F&eacute;vrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "D&egrave;cembre"]); 
			YAHOO.calendrier.cal.cfg.setProperty("WEEKDAYS_1CHAR", ["D", "L", "M", "M", "J", "V", "S"]); 
			YAHOO.calendrier.cal.cfg.setProperty("WEEKDAYS_SHORT", ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"]); 
			YAHOO.calendrier.cal.cfg.setProperty("WEEKDAYS_MEDIUM",["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]); 
			YAHOO.calendrier.cal.cfg.setProperty("WEEKDAYS_LONG",  ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"]); 

			YAHOO.calendrier.cal.cfg.setProperty("selected", selected_date);
			YAHOO.calendrier.cal.cfg.setProperty("MULTI_SELECT", true);
			
			YAHOO.calendrier.cal.cfg.setProperty("START_WEEKDAY", "1");	
			YAHOO.calendrier.cal.cfg.setProperty("mindate", minDate);
			YAHOO.calendrier.cal.cfg.setProperty("pagedate", page_date);
			YAHOO.calendrier.cal.name = input.id;
			
			YAHOO.calendrier.cal.render();
			YAHOO.calendrier.cal.selectEvent.subscribe(handleSelect, YAHOO.calendrier.cal, true);
			YAHOO.calendrier.cal.deselectEvent.subscribe(handleSelect, YAHOO.calendrier.cal, true);
		};
	}
});


/**
 * Code récupéré depuis Autocompleter.config_vol
 */
var tab_depart=new Hash();
var tab_destination=new Hash();
function Autocompleter_vol() {
	tab_depart=new Hash();
	tab_destination=new Hash();
	if ($('ville_depart')) {
		var inputWord1 = $('ville_depart');
		new Autocompleter.Request.HTML(inputWord1, 'index.php?action=autocompleter_vol', {
			'indicatorClass': 'autocompleter-loading',
			'injectChoice': function(choice) {
				var text = choice.getFirst();
				var value = choice.getLast();

				tab_depart[text.innerHTML]=value.innerHTML;
				
				// inputValue saves value of the element for later selection
				choice.inputValue = text.innerHTML;
				
				// overrides the html with the marked query value (wrapped in a <span>)
				text.set('html', this.markQueryValue(text.innerHTML));
				
				// add the mouse events to the <li> element
				this.addChoiceEvents(choice);
			}
		});
		$('ville_depart').addEvent('change',function () {
			updateCode('ville_depart',inputWord1);
		});
	}

	if ($('destination')) {
		var inputWord2 = $('destination');
		new Autocompleter.Request.HTML(inputWord2, 'index.php?action=autocompleter_vol', {
			'indicatorClass': 'autocompleter-loading',
			'injectChoice': function(choice) {
				var text = choice.getFirst();
				var value = choice.getLast();

				tab_destination[text.innerHTML]=value.innerHTML;
				
				// inputValue saves value of the element for later selection
				choice.inputValue = text.innerHTML;
				
				// overrides the html with the marked query value (wrapped in a <span>)
				text.set('html', this.markQueryValue(text.innerHTML));
				
				// add the mouse events to the <li> element
				this.addChoiceEvents(choice);
			}
		});
		$('destination').addEvent('change',function () {
			updateCode('destination',inputWord2);
		});
	}
};
function updateCode(orig,obj) {
	var tab=new Hash();
	if (orig=='ville_depart') {
		tab=tab_depart;
		code_iata1=$('ville_depart_iata').value;
	} else {
		tab=tab_destination;
		code_iata1=$('destination_iata').value;
	}
	if (tab[obj.value.trim()]) {
		$(orig + '_iata').value = tab[obj.value.trim()];
	} else {
		$(orig + '_iata').value = '';
	}
}

/**
 * Code récupéré depuis Autocompleter.config_hotel
 */
var tab_destination = new Hash();
function Autocompleter_hotel() {
	if ($('search_libelle')) {
		var inputWord1 = $('search_libelle');
		new Autocompleter.Request.HTML(inputWord1, 'index.php?action=poi_hotel', {
			'indicatorClass': 'autocompleter-loading',
			'injectChoice': function(choice) {
				var elements=choice.getElements('span');
				if (elements.length>1) {
					var text = elements[0];
					var value = elements[1];
					
					tab_destination[text.innerHTML]=value.innerHTML;
					
					//console.log(value.innerHTML+'#'+text.innerHTML+'\n');
					
					// inputValue saves value of the element for later selection
					choice.inputValue = text.innerHTML;
		
					// overrides the html with the marked query value (wrapped in a <span>)
					text.set('html', this.markQueryValue(text.innerHTML));
					
					// add the mouse events to the <li> element
					this.addChoiceEvents(choice);
				}
			}
		});
		
		$('search_libelle').addEvent('change', function () {
			Hotel.updateCode(inputWord1);
		});
		
	}
}
/*
function updateCode(obj) {
	if (tab_destination[obj.value.trim()]) {
		$('search_code').value = tab_destination[obj.value.trim()];
	} else {
		$('search_code').value='';
	}
}*/