var formatDate="";
var delay=0;
ReservationEngine = new Class({
	Implements : Options,
	//options : 
	options : {
		root : 'reservationEngine', //HTMLElement: element parent conteneur de tout (peut être un id), cette variable n'est pas accédée par la suite, tout passe par RapidAccess.container
		fieldsIds : ['resa_destination','resa_village','resa_villedepartLine','resa_villedepart','resa_datedepart','resa_datedepartRMC',
					 'resa_datedepartSelector','resa_dureesejour','resa_nbadultes','resa_nbenfants','resa_childsbirth',
					 'resa_transportavec', 'resa_transportsans', 'resa_ferryhours', 'resa_ferrydeparture', 'resa_ferrydeparture'
					 ],
		pays : ""+paysDyn,
		lang : ""+langDyn,
		flag_transportFerry : flag_ferry, // FLAG transport Ferry
		useGeoZone : bZoneGeo//true 
						/*booleen utilisé pour savoir si on utilise la zone geographique ou non pour 
							afficher les destination. Ca a aussi un impact sur les villages, 
							puisque on n'affichera que les villages
							en rapport avec la zone et le pays sélectionné. Ex : Alpes -> France
						*/
	},
	
	// reference vers les éléments HTML (view)
	resa_destination : null,
	resa_villedepartLine : null, 
	resa_villedepart : null,
	resa_datedepart : null,
	resa_datedepartRMC : null,
	resa_dureesejour : null,
	resa_nbadultes : null,
	resa_nbenfants : null,
	resa_childsbirth : null,
	resa_transportsans : null,
	resa_transportavec : null,
	resa_ferryhours : null,
	resa_ferrydeparture : null,
	resa_ferryretour : null,

	
	templateChildBirthDay:null, //dom element récupéré sur le premier "childBirthday"
	
	initialize : function(options) {
		this.setOptions(options);
		this.root = $(this.options.root);
		//on part si on n'a pas d'objet existant, cela permettra la pérénité de l'application, si on tombe sur une page sans le composant en question
		if (!this.root) return;
		var request = new Request({
			url : this.options.xmlUrl,
			method : 'get',
			datas : {
				LANG : this.options.lang,
				PAYS : this.options.pays
			},
			onComplete : this.langFileLoadedListener.bind(this)
			
		});
		request.send();
		
	},
	
	langFileLoadedListener : function(xmlStr, xmlDom) {
		
		var obj = new XML2OBJ(xmlDom, {arrayForcedAttribute:"_attributes", arrayForcedNode:"['FROM']"}).getJSON();
		obj = obj.root instanceof Array ? obj.root[1] : obj.root; //XML2OBJ bugue sur ce XML et retourne un array de "root"
		this.setDatas(obj);
		
		this._initFields();
		this._fillFieldsFromDatas();
		this._initListeners();
		this._initFieldsDefaultSelection()
	},
	
	_initFieldsDefaultSelection : function() {
		if(this.resa_destination){
			this.resa_destination.selectedIndex = 0;
			this.resa_destination.fireEvent('change');
		}
		if(this.resa_village){
			var sSelectId = window.selectedVillageId;
			var _this = this;
			setTimeout(
				function(){
					if (sSelectId && sSelectId!='') {//alert(window.selectedVillageId)

					$A(_this.resa_village.options).each(function(option, index) {
						if(option.value == sSelectId) {
							_this.resa_village.selectedIndex = index;
						}
					}.bind(_this));
				} else {
					_this.resa_village.selectedIndex = 0;
				}
				_this.resa_village.fireEvent('change');
				},
				200
			);
			
		}
		
		if(this.resa_villedepart){
			this.resa_villedepart.selectedIndex = 0;		
			this.resa_villedepart.fireEvent('change');
		}
		if(this.resa_dureesejour){
			this.resa_dureesejour.selectedIndex = 1;
		}
		this._resa_transportClickHandler();
	},
	
	
	/** 
	 * range les datas récupérées du XML. Cela permet d'uniformiser les données à un seul et unique endroit.
	 * si le schéma du xml change, il faudra juste modifier cette fonction.
	 * On essaye néanmoins de concerver le noeud le plus bas en tant qu'objet.
	 */
	setDatas : function(datas) {
		var rt = datas;
		
		this.datas = {};
		var d = this.datas;
		
		//zones code, récupéré depuis le flux telecom.do
		var zones = [
		 {zonecod:rt.zones.zone[0]._attributes.code, zonelib:rt.zones.zone[0].txt},
		 {zonecod:rt.zones.zone[1]._attributes.code, zonelib:rt.zones.zone[1].txt},
		 {zonecod:rt.zones.zone[2]._attributes.code, zonelib:rt.zones.zone[2].txt},
		 {zonecod:rt.zones.zone[3]._attributes.code, zonelib:rt.zones.zone[3].txt},
		 {zonecod:rt.zones.zone[4]._attributes.code, zonelib:rt.zones.zone[4].txt},
		 {zonecod:rt.zones.zone[5]._attributes.code, zonelib:rt.zones.zone[5].txt},
		 {zonecod:rt.zones.zone[6]._attributes.code, zonelib:rt.zones.zone[6].txt},
		 {zonecod:rt.zones.zone[7]._attributes.code, zonelib:rt.zones.zone[7].txt},
		 {zonecod:rt.zones.zone[8]._attributes.code, zonelib:rt.zones.zone[8].txt}];

		 // tableau contenant les messages d'erreurs
		 var tab_errors = new Array();
		 for (var index=0; index<rt.errors.error.length; index++){
			tab_errors[rt.errors.error[index]._attributes.code] = rt.errors.error[index].txt;
		 }
		 d.errors = tab_errors;

		//villages
		if(!rt.villages.village){ return;}
		else if(!rt.villages.village.push){ d.villages = [rt.villages.village._attributes]; }
		else {
		d.villages = rt.villages.village.map(function(village) { return village._attributes; });
		}
		
		//pays de destination (recupéré depuis d.villages)
		//on créé un tableau zones et chaque zone contient un tableau de pays (destinations);
		//lors de la génération des options, il y aura des <optgroup> pour délimiter les zones.
		d.destinations = [];
		for (var z = 0; z<zones.length; z++) {
			d.destinations.push({
				zonecod : zones[z].zonecod,
				zonelib : zones[z].zonelib,
				pays : new Array()
			});
		}
		d.villages.each(function(village){
			var z = village.zone;
			var dest = null;
			for (var i=0; i<d.destinations.length; i++) {
				if (d.destinations[i].zonecod==z) {
					break;
				}
			}
			dest = d.destinations[i];
			
			if (!dest.pays.contains(village.pays))
				dest.pays.push(village.pays);
		});
		
		d.destinations.each(function(zone) {
			zone.pays.sort();
		});
		
		
		//villes de depart
		d.from = rt.FROM.F.map(function(from){
			return from._attributes;
		});	
		
		//all things about date in the xml are useless we kept only the usefull things
		d.dates = {
			delay : rt.dates._attributes.delay,
			today : rt.dates._attributes.today,
			monthsLabels : {
				'long' : rt.dates.calendrier.mois.m.map(function(m){ return m._attributes.label}),
				'short' : rt.dates.month_list._attributes.systeme.split(', ')
			},
			daysLabels : {
				'short' : rt.dates.calendrier.jours.j.map(function(j){return j._attributes.label}),
				'mid' : rt.dates.day_list._attributes.systeme.split(',')
			},
			dayDefault : rt.dates.day_default._attributes.systeme,
			formatDate : rt.dates.format_date._attributes.systeme,
			durees : {
				jours : rt.dates.durees._attributes.jours.split(','),
				suffixe : rt.dates.durees._attributes.suffixe
			}
		};
		d.dates.dayDefaultIndex = d.dates.daysLabels.mid.indexOf(d.dates.dayDefault);
		delay = d.dates.delay;
		formatDate = d.dates.formatDate;
		
		//labels divers 
		d.labels = rt.labels;
		
		/* Les donnees qui suivent, ne sont pas récupérées depuis un XML ou autre. Elles doivent être passées depuis le fichier HTML du clubmed.
		 * En attendant plus d'infos, ils sont paramétrés en dur ici
		 */
		d.nbAdultes = 6;
		d.nbEnfants = 5;
		
		d.labels = {};
		for (var i in rt.labels) {
			if(rt.labels[i].txt)
				d.labels[i] = rt.labels[i].txt;
		}
	},
	
	
	// recupere les champs de formulaire et colle une reference de chaque champ sur l'objet RapidAccess (attribut/id pour un champ)
	_initFields : function(options) {
		//this.root.action = urlFluxXml
		this.options.fieldsIds.each(function(id) {
			this[id] = $(id);
		}.bind(this));
		
		this.parentChildBirthDay = this.resa_childsbirth.getElement('div.datesEnfants');
		this.templateChildBirthDay = this.resa_childsbirth.getElement('span.dateEnfant').dispose();
		
		this.formTip = new TipsFix(this.root, {
			fixed : true,
			className : 'errorToolTip',
			positionFrom : this.root
		});
	},
	
	// private
	_fillFieldsFromDatas : function() {
		// select destinations
		
		var destOptionsArray = [];
		
		// si on utilise la zone geographique, on affiche les zones geo ainsi que les pays
		while(this.resa_destination && this.resa_destination.firstChild)
			this.resa_destination.removeChild(this.resa_destination.firstChild)
		DomUtils.generateSelectOptions(this.resa_destination, [{text:this.datas.labels.listes_default, value:''}]);
		
		if (this.options.useGeoZone && this.resa_destination) {
			this.datas.destinations.each(function(dest){
				var optgroup = new Element('optgroup',{
					'label' : dest.zonelib
				});
				this.resa_destination.adopt(optgroup);
				dest.pays.each(function(pays){
					optgroup.adopt(new Element('option',{
						value : dest.zonecod+'/'+pays,
						'html' : pays
					}));
				}.bind(this))
			}.bind(this));
		} else { //dans le cas suivant, on n'affiche que les pays, sans se soucier de la zone géographique
			if(this.resa_destination) {
				var countries = this.datas.destinations.map(function(dest) {
					return dest.pays;
				}).flatten().sort().filter(function(item, i, array) {
					if (i>0 && item==array[i-1])
						return false;
					return true;
				})
				countries.each(function(pays){
					this.resa_destination.adopt(new Element('option',{
						value : pays,
						'html' : pays
					}));
				}.bind(this))
			}
		}
		
		//select village sera traité par une autre methode car celui-ci depend de la selection de la destination
		//select ville de depart sera traité par une autre méthode car celui-ci dépend du village sélectionné
		
		//select duree du sejour
		DomUtils.generateSelectOptions(this.resa_dureesejour, this.datas.dates.durees.jours.map(function(duree){
			return {
				text:duree + (duree==1 ? this.datas.dates.durees.suffixe.replace(/(s)$/,'').replace(/ימים/,'יום') : this.datas.dates.durees.suffixe), //1 jour, 2 jours, 1 day, 2 days
				value:duree*1
			};
		}.bind(this)));
		
		
		//this._selectByValue(this.resa_dureesejour, 7);
		//select nombre d'adultes
		DomUtils.generateSelectOptions(this.resa_nbadultes, new Array(this.datas.nbAdultes+1).join(0).split('').map(function(v,i){ ///genere un tableau [0,1,2,3,4..] puis un tableau d'objets pour populer le select
			return {text:i+1, value:i+1};
		}));
		//select nombre d'enfants
		DomUtils.generateSelectOptions(this.resa_nbenfants, new Array(this.datas.nbEnfants+2).join(0).split('').map(function(v,i){
			return {text:i, value:i};
		}));
		
		
		if (this.resa_datedepart) {
			var date = new Date(DomUtils.getFormattedTodayDate2("yyyy/MM/dd", delay));
			if (typeof selectedVillageId == "undefined" || this._dateInRange(selectedVillageId, date))
				this.resa_datedepart.value = DomUtils.getFormattedTodayDate2(formatDate, delay);
			else {
				var codeVillageSplitted = selectedVillageId.split('_');
				var village = this._getVillageByCode(codeVillageSplitted[0], codeVillageSplitted[1]);
				this.resa_datedepart.value = changeDateFormat(village.dep, formatDate);
			}
		}
	},
	
	_dateInRange : function(villageId, date) {
		var village;
		if (typeof villageId != "undefined") {
			var codeVillageSplitted = villageId.split('_');
			village = this._getVillageByCode(codeVillageSplitted[0], codeVillageSplitted[1]);
		}
		if (village) {
			var ouverture = getDateFromStringFr(village.dep, formatDate);
			var fermeture = getDateFromStringFr(village.fin, formatDate);
			if (!(date > ouverture && date < fermeture)) {
				return false;
			}
		}
		return true;
	},
	
	_initListeners : function() {
		// champ date de depart
		
		if (this.resa_datedepart) {
			this.resa_datedepartSelector.addEvent('click', this._dateDepartHandler.bindWithEvent(this, [this.resa_datedepartSelector, this.resa_datedepart]));
			this.resa_datedepart.addEvent('click', function(e) {new Event(e).stop()});
		} else {
			this.resa_datedepartSelector.addEvent('click', this._dateDepartHandler.bindWithEvent(this, [this.resa_datedepartSelector, this.resa_datedepartRMC]));
			this.resa_datedepartRMC.addEvent('click', function(e) {new Event(e).stop()});		
		}
		
		/* Ajout gestion des adultes */
		this.resa_nbenfants.addEvent("focus",this._resa_nbEnfantsClickHandler.bind(this));
		this.resa_nbadultes.addEvent('change', this._resa_nbadultesChangeHandler.bind(this));
		this.resa_nbenfants.addEvent('change', this._resa_nbEnfantChangeHandler.bind(this));
		
		this._participantsCookie();
		if(this.resa_destination){
			this.resa_destination.addEvent('change', this._resa_destinationChangeHandler.bind(this));
		}
		if(this.resa_village){
			this.resa_village.addEvent('change', this._resa_villageChangeHandler.bind(this));
		}
		if(this.resa_villedepart){
			this.resa_villedepart.addEvent('change', this._resa_villedepartChangeHandler.bind(this));
		}
		this.root.addEvent('submit', this._formSubmitHandler.bindWithEvent(this));
		if(this.resa_transportavec){
			this.resa_transportavec.addEvent('click', this._resa_transportClickHandler.bindWithEvent(this));
		}
		if(this.resa_transportsans){
			this.resa_transportsans.addEvent('click', this._resa_transportClickHandler.bindWithEvent(this));
		}
		
	},
	
	_participantsCookie : function (){
		var nbAdults= getCookieVal("nbAdultes");
	   	if (nbAdults != null) {
			this.resa_nbadultes.value = nbAdults;
		}
		var nbEnf= getCookieVal("nbEnfants");
	   	if (nbEnf && nbEnf != "") {
			this.resa_nbenfants.value = nbEnf;
			var ddN="";
			for (var i=1; i<=nbEnf;i++){
				ddN += getCookieVal("bithDate"+ i) + (i<nbEnf?'_':'');
			}
			this._resa_nbEnfantChangeHandler(ddN.split('_'));
		}
	},
	
	// handlers
	_resa_nbEnfantsClickHandler : function(){
		var nbA = parseInt(this.resa_nbadultes.value);
		var myParentEnglobe = this.resa_nbadultes.getParent(".autoBalanceSelect");
		var errorMessage = myParentEnglobe.getElement(".errorMessage");
		if($(errorMessage)){	
			$(errorMessage).addClass("hidden");
			if(nbA > 3){
				$(errorMessage).removeClass("hidden");
			}
		}
	},
	_resa_nbadultesChangeHandler : function(){
		var nbA = parseInt(this.resa_nbadultes.value);
		var myParentEnglobe = this.resa_nbadultes.getParent(".autoBalanceSelect");
		var errorMessage = myParentEnglobe.getElement(".errorMessage");
		if($(errorMessage)){	
			if(nbA <= 3){
				$(errorMessage).addClass("hidden");
			}
		}
	},
	_resa_nbEnfantChangeHandler : function(tab_ddn) {
		var nb = this.resa_nbenfants.value;
		
		var birthInputs = this.resa_childsbirth.getElements('span.dateEnfant');
		//hide all
		birthInputs.each(function(input) {
			$(input).setStyle('display','none');
		})
		if (nb>0) {
			for (var i=1; i<=nb; i++) {
				if (i - 1 < birthInputs.length) {
					$(birthInputs[i - 1]).setStyle('display', '');
				}
				else {
					var inp = this.templateChildBirthDay.clone();
					inp.addEvent('click', this._dateSelectorHandler.bindWithEvent(this, [inp, inp.getElement('input,select')]));
					inp.getElement('input,select').addEvent('click', function(e){
						new Event(e).stop()
					});
					inp.getElement('input,select').onfocus = DomUtils.inputChangeDeleteHandler;
					inp.getElementsByTagName("input")[0].name += i;
					inp.getElementsByTagName("input")[0].id   = inp.getElementsByTagName("input")[0].name;
					if (tab_ddn && tab_ddn.length>0) {
						inp.getElementsByTagName("input")[0].value = tab_ddn[i-1];
					}
					this.parentChildBirthDay.appendChild(inp);
				}
			}
			this.resa_childsbirth.style.display = 'block';
		} else {
			this.resa_childsbirth.style.display = 'none';
		}
	},
	
	_resa_destinationChangeHandler : function(e) {
		this._setVillagesFromDestination();
		if (this.resa_destination.value == "") {
			this.resa_villedepart.setAttribute('disabled','disabled');
			this.resa_villedepart.addClass('greyFilled');
			this._setVilleDepartFromVillage();
		}
	},
	
	_resa_villageChangeHandler : function(e) {
		if (this.resa_village.value != "") {
			this.resa_villedepart.disabled = false;
			var codeVillage = this.resa_village.value;
			var codeVillageSplitted = codeVillage.split('_');
			this.selectedVillage = codeVillageSplitted[0];
			var villageObj = this._getVillageByCode(codeVillageSplitted[0], codeVillageSplitted[1]);
			this._checkVillageAdultStatus(villageObj);
			//select destination by village 'pays' or "zone/pays' value
			var valToTest = this.options.useGeoZone ? villageObj.zone+'/'+villageObj.pays : villageObj.pays; 
			for (var i=0; i<this.resa_destination.options.length; i++) {
				if (this.resa_destination.options[i].value == valToTest) {
					this.resa_destination.selectedIndex = i;
					//on refitlre les villages
					this.resa_destination.fireEvent('change');
					//on selectionne le village sélectionné juste avant
					for (var i=0; i<this.resa_village.options.length;i++) {
						var opt = this.resa_village.options[i];
						if(opt.value == codeVillage) {
							this.resa_village.selectedIndex = i;
						}
					}
					break;
				}
			}
			this.resa_villedepart.addClass('bgWhite borderBlue');
			
			if (this.resa_datedepart && !this._dateInRange(codeVillage, getDateFromStringFr(this.resa_datedepart.value, formatDate))) {
				var ouverture = getDateFromStringFr(villageObj.dep, formatDate);
				var date = new Date(DomUtils.getFormattedTodayDate2("yyyy/MM/dd", delay));
				if (date > ouverture) {
					this.resa_datedepart.value = DomUtils.getFormattedTodayDate2(formatDate, delay);
				} else {
					this.resa_datedepart.value = changeDateFormat(villageObj.dep, formatDate);
				}
			}
		} else {
			this.selectedVillage = null;
			this.resa_villedepart.setAttribute('disabled','disabled');
			this.resa_villedepart.addClass('greyFilled');
		}
		this._setVilleDepartFromVillage();
	},

	
	_formSubmitHandler : function(e) {
		new Event(e).stop();
		//check form
		
		var $j = jQuery.noConflict();
		var error = [];
		if(this.resa_destination && this.resa_destination.selectedIndex==0) {
			error.push(DomUtils.isEmptyToReplace(this.datas.errors["LIB_BR_error_selectDest_2010"], "LIB_BR_error_selectDest_2010"));
		}
		if(this.resa_village && this.resa_village.selectedIndex==0) {
			error.push(DomUtils.isEmptyToReplace(this.datas.errors["LIB_BR_error_selectVillage_2010"], "LIB_BR_error_selectVillage_2010"));
		}
		
		if (!DomUtils.checkDateFormat(this.resa_datedepart.value, this.datas.dates.formatDate)) {
			error.push(DomUtils.isEmptyToReplace(this.datas.errors["LIB_BR_error_dateDep_2010"], "LIB_BR_error_dateDep_2010"));
		}
		
		if (this.resa_transportavec && this.resa_villedepart && this.resa_transportavec.checked && this.resa_villedepart.value=='') {
			error.push(DomUtils.isEmptyToReplace(this.datas.errors["LIB_BR_error_selectVilleDep_2010"], "LIB_BR_error_selectVilleDep_2010"));
		}
		formatDate = this.datas.dates.formatDate;
		var numDatesEnfantsNotOk = this.root.getElements('.dateEnfant input').filter(function(inp){
			return $j(inp).closest('.dateEnfant').css('display') != "none" && !DomUtils.checkDateFormat(inp.value, formatDate); 
		}).length;
		if (numDatesEnfantsNotOk>0) {
			error.push(DomUtils.isEmptyToReplace(this.datas.errors["LIB_BR_error_ddnEnfants_2010"], "LIB_BR_error_ddnEnfants_2010"));
		}else{
			this.formTip.hide();
			
			var ddp = $j("#resa_datedepart").val();
			ddp = formatageDate(ddp);
			var departDate = getDateFromFormat(ddp, formatDate); // Date de depart
			var nbKids = $j("#resa_nbenfants").val();
			for(var i = 1; i <= nbKids; i++){
				if($j("#ddn_enfant"+i).closest('.dateEnfant').css('display') != "none") {
					var dtn = $j("#ddn_enfant"+i).val();
					if(dtn == formatDate){ error.push(DomUtils.isEmptyToReplace(this.datas.errors["RESA_JSERROR_invalidbirthdate"], "RESA_JSERROR_invalidbirthdate")); break; }
					var dateNaissance = DomUtils.getFormattedDate(dtn, formatDate);
					if(!isKid(dateNaissance, departDate)){ error.push(DomUtils.isEmptyToReplace(this.datas.errors["RESA_JSERROR_invalidbirthdate"], "RESA_JSERROR_invalidbirthdate")); break; }
				}
			}
		}

		if (error.length>0) { // erreur pas de submit
			this.formTip.text = error.join('<br/>\n');
			this.formTip.show();
			new Event(e).stop();
		} else { // pas d'erreur : on submit
			if (this.resa_village.value.indexOf("ALBV",0) != -1 &&  flag_FormVilla) { // SI  (village_choisi = villa  ET pays_commercialise_villa ) ALORS on affiche popup contactForm  ==> on reste sur la page de home
				var popUrl = 'http://' + host + contextPath + '/contactForm.do?PAYS=' + paysDyn + '&LANG='+langDyn;
				window.open(popUrl, '', 'width=790, height=825, scrollbars=1, resizable=1');
			} else { // on redirige vers la resa OU vers fiche villa
				this.root.appendChild(ajouterElement('nbParticipants', (parseInt(document.getElementById("resa_nbadultes").value) + parseInt(document.getElementById("resa_nbenfants").value))));
				if (this.options.flag_transportFerry) {
					if( (typeof(document.getElementById("resa_ferrydeparture"))!='undefined') && (document.getElementById("resa_ferrydeparture").value != null) && (document.getElementById("resa_ferrydeparture").value != -1)) {
						if( (typeof(document.getElementById("resa_ferryretour"))!='undefined') && (document.getElementById("resa_ferryretour").value != null) && (document.getElementById("resa_ferryretour").value != -1)){
							this.root.appendChild(ajouterElement('horaireFerryDepart', document.getElementById("resa_ferrydeparture").value));
							this.root.appendChild(ajouterElement('horaireFerryRetour', document.getElementById("resa_ferryretour").value));
						}
					}
				}
				
				// on ne n'envoie que le code village (et pas la saison) dans le formulaire
				var codeVillageSplitted = this.resa_village.value.split('_');
				this.resa_village[this.resa_village.selectedIndex].value = codeVillageSplitted[0];
				
				// création des champs pour les enfants
				if (document.getElementById("resa_nbenfants").value > 0){
					var birthInputs = this.resa_childsbirth.getElements('span.dateEnfant').filter(function(inp){
						return $j(inp).css('display') != "none"; 
					});
					birthInputs = birthInputs.getElement('input');
					var listeDDN = "";
					for (var i=0; i<birthInputs.length; i++){
						if (i>0) 
							listeDDN += ',';
						listeDDN += birthInputs[i].value;
						birthInputs[i].setAttribute('disabled', 'true');
					}
					this.root.appendChild(ajouterElement('dateDeNaissance', listeDDN));
				}
				
				var goToVilla = this.resa_village.value.indexOf("ALBV",0) != -1;
				if (goToVilla) { // on change l'action et les paramètres pour aller sur la fiche villa
					// le formulaire est en <GET>.  Donc, on met tous les attributs qu'on ne veut pas passer dans l'URL à disabled
					document.getElementById("resa_destination").setAttribute('disabled', 'true');
					document.getElementById("resa_village").setAttribute('disabled', 'true');
					document.getElementById("resa_transportavec").setAttribute('disabled', 'true');
					document.getElementById("resa_transportsans").setAttribute('disabled', 'true');
					document.getElementById("resa_datedepart").setAttribute('disabled', 'true');
					document.getElementById("resa_dureesejour").setAttribute('disabled', 'true');
					document.getElementById("resa_nbadultes").setAttribute('disabled', 'true');
					document.getElementById("resa_nbenfants").setAttribute('disabled', 'true');
					document.getElementById("resa_villedepart").setAttribute('disabled', 'true');
					document.getElementById("nbParticipants").setAttribute('disabled', 'true');
					if (typeof(document.getElementById("resa_ferrydeparture")) != 'undefined' && document.getElementById("resa_ferrydeparture") != null) {
						document.getElementById("resa_ferrydeparture").setAttribute('disabled', 'true');
						document.getElementById("resa_ferryretour").setAttribute('disabled', 'true');
					}
					this.root.appendChild(ajouterElement('CODLSC', this.resa_village.value));
					this.root.action = "http://" + host + contextPath + "/villagesHeading.do?";
				}
				
				// affichage de la popup
				if (!goToVilla && this.options.lang == "HE" && this.options.pays == "196") {
					new FogManager('bookingLayer', {locked:false});
				} else {
					disableFields();
					this.root.submit();
				}
			}
		}
		new Event(e).stop();
	},
	
	_resa_transportClickHandler : function(e){
		//resa_villedepartLine
		if(this.resa_villedepartLine && this.resa_transportavec){
			$(this.resa_villedepartLine).setStyle('display', this.resa_transportavec.checked ? '' : 'none');
		}
	},
	
	_resa_villedepartChangeHandler : function(e) {
		if(!this.resa_ferryhours) return;
		if (this.resa_villedepart.value == 'LUX' && (this.resa_village.value == 'RBIC' || this.resa_village.value == 'RBICH')) {
			this.resa_ferryhours.setStyle('display', 'block');
		} else {
			this.resa_ferryhours.setStyle('display', 'none');
		}
	},
		
	_dateDepartHandler : function(e, span, input) {
		new Event(e).stop();
		
		var forbiddenDays = {
			period : ['before today'],
			date : []
			/*period : [
				'20/11/2009 to 26/11/2009', //ATTENTION CECI EST UN EXEMPLE IL FAUDRA L'ENLEVER PLUS TARD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
				'before today'
			]*/
		};
		
		var dateMask = this.datas.dates.formatDate.toUpperCase();
		if (this.resa_village) {
			var codeVillageSplitted = this.resa_village.value.split('_');
			this.selectedVillage = codeVillageSplitted[0];
			var village = this._getVillageByCode(codeVillageSplitted[0], codeVillageSplitted[1]);
		}
		if (village) {
			// DEBUT : comparer la date d'ouverture du village à la date d jour et recuperer la plus recente
			var forbiddenDeparture = new Date();
			forbiddenDeparture.setDate(forbiddenDeparture.getDate() + parseInt(delay));
			forbiddenDeparture = ((forbiddenDeparture.getDate()<10)?'0'+forbiddenDeparture.getDate() : forbiddenDeparture.getDate())
								+ '/' + ((forbiddenDeparture.getMonth()+1<10)?'0'+(forbiddenDeparture.getMonth()+1) : (forbiddenDeparture.getMonth()+1))
								+ '/' + forbiddenDeparture.getFullYear();
			var split_dep = village.dep.split('/');
			var split_today = forbiddenDeparture.split('/');
			if (split_dep[2] > split_today[2]  ||  (split_dep[2] == split_today[2] && split_dep[1] > split_today[1])  
				||  (split_dep[2] == split_today[2] && split_dep[1] == split_today[1] && split_dep[0] > split_today[0])){
				forbiddenDeparture = village.dep;
			}
			//FIN
			forbiddenDays.period.push('before '+changeDateFormat(forbiddenDeparture, dateMask)+'-1'); //on retire le jour donné pour éviter qu'il soit interdit 
			forbiddenDays.period.push('after '+changeDateFormat(village.fin, dateMask)+'+1'); //idem mais +1
		}
		else {
			var d = new Date();
			d.setMonth(d.getMonth()+18);
			var dstr = dateToStr(d, dateMask);
			forbiddenDays.period.push('after ' + dstr);
		}

		new DatePicker().show(span, {
			destField: input,
			daysNames: this.datas.dates.daysLabels.short,
			monthsNames: this.datas.dates.monthsLabels.long,
			firstWeekDay: this.datas.dates.dayDefaultIndex,
			dateMask: this.datas.dates.formatDate.toUpperCase(), // on applique toUpperCase car dans le DatePicker le format de la date est toujours en majuscule
			forbiddenDays: forbiddenDays
		}); 
	},
	
	// form fields handlers
	_dateSelectorHandler : function(e, span, input) {
		new Event(e).stop();
		new DatePicker().show(span, {
			destField:input,
			daysNames: this.datas.dates.daysLabels.short,
			monthsNames: this.datas.dates.monthsLabels.long,
			firstWeekDay: this.datas.dates.dayDefaultIndex,
			dateMask: this.datas.dates.formatDate.toUpperCase() // on applique toUpperCase car dans le DatePicker le format de la date est toujours en majuscule
		});
	},
	
	// private methods
	_checkVillageAdultStatus : function(village) {
		if (village.adulte==1) {
			this.resa_nbenfants.selectedIndex = 0;
			this._resa_nbEnfantChangeHandler();
			this.resa_nbenfants.disabled = 'disabled';
		} else {
			this.resa_nbenfants.disabled = '';
		}
	},
	
	_getVillageByCode : function(code, periode) {
		if (!code) return null;
		for (var i=0; i<this.datas.villages.length; i++) {
			var v = this.datas.villages[i];
			if (v.id == code && v.percod == periode)
				return v;
		}
		return null;
	},
	_selectByValue : function(select, value) {
		for (var i=0; i<select.options.length; i++) {
			var option = select.options[i];
			if (option.value.toLowerCase() == value.toLowerCase()) {
				(function(){option.selected = true;}).delay(100,this);
				break;
			}
		} 
	},
	
	_setVillagesFromDestination : function() {
		var zone = '';
		if (this.options.useGeoZone) {
			var d = this.resa_destination.value.split('/');
			var zone = d[0];
			var pays = d[1];
		} else {
			var pays = this.resa_destination.value;
		}
		this.resa_village.empty();
		//var dest = this.datasXml.destination[index];
	 	
		var villages = this.datas.villages.filter(function(village){ //filtrage des villages, (si useZoneGeo==true) en fonction de la zone geographique et du pays, sinon juste sur le pays 
			if(!pays || pays=='') return true;
			if (this.options.useGeoZone) {
				return village.zone==zone && village.pays==pays;
			}				
			return village.pays==pays;
		}.bind(this)).map(function(village, index){ //construction de l'array d'objets qui servira à créer le select
			return {text:village.label+', '+village.pays, value:village.id+'_'+village.percod};
		}).sort(function(el1, el2){ //tri
			return el1.text>el2.text;
		});
		DomUtils.generateSelectOptions(this.resa_village, [{text:this.datas.labels.listes_default, value:''}].concat(villages));
	},
	
	_setVilleDepartFromVillage : function() {
		var codeVillageSplitted = this.resa_village.value.split('_');
		var villageCode = codeVillageSplitted[0];
		this.resa_villedepart.empty();
		if (!villageCode || villageCode=='') return;
		var cities = this._getVillageByCode(villageCode, codeVillageSplitted[1]).ville;
		
		var citiesOptions = this.datas.from.filter(function(ville){
			if(cities.indexOf(ville.code)!=-1) {
				return true;
			}
			return false;
		}).map(function(ville){
			if   (ville.code != '') // pour ne pas afficher l'element <Sans Transport>
				return {text:ville.label, value:ville.code} ;
		}).sort(function(el1, el2){ //tri
			return el1.text>el2.text;
		});
		DomUtils.generateSelectOptions(this.resa_villedepart, [{text:this.datas.labels.listes_default, value:''}].concat(citiesOptions));
		this.resa_villedepart.fireEvent('change');
		
		// on met à 'sans transport' s'il n'y a pas de villages proposés dans la liste
		if (this.resa_villedepart.length < 2) {
			this.resa_transportsans.click();
		} else {
			this.resa_transportavec.click();
		}
	}
});

function dateToStr (d, m) {
	return m.replace('DD',this.getZero(d.getDate()))
			.replace('MM',this.getZero(d.getMonth()+1))
			.replace('YYYY',d.getFullYear());
}

function changeDateFormat(dateStr, format) {
	if (format.toUpperCase() == 'MM/DD/YYYY') {
		var dateTab = dateStr.split('/');
		return dateTab[1] + '/' + dateTab[0] + '/' + dateTab[2];
	} else if (format.toUpperCase() == 'YYYY/MM/DD') {
		var dateTab = dateStr.split('/');
		return dateTab[2] + '/' + dateTab[1] + '/' + dateTab[0];
	}
	return dateStr;
}

function getDateFromStringFr(dateStr, format) { 
	var dateStr_slices = dateStr.split("/");
	var d = new Date(dateStr_slices[2], dateStr_slices[1], dateStr_slices[0]);
	d.setMonth(d.getMonth()-1);
	return d;
}

// Etre enfant c'est moins de 18 et plus de 0 ans a la date de depart
function isKid(birthDate, departDate){
	var oneyear = 31536000000; // Une annee en millisecondes
	var nbYearDiff = (departDate.getTime()-birthDate.getTime())/oneyear;
	//alert(nbYearDiff);
	if (nbYearDiff > 18 || nbYearDiff < 0)
		return false;

	return true;
}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val, format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
		}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y" || token=="aaaa" || token=="jjjj" || token=="YYYY" || token=="YY" || token=="Y" || token=="AAAA" || token=="JJJJ") {
			if (token=="jjjj") { x=4;y=4; }
			if (token=="aaaa") { x=4;y=4; }
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			if (token=="JJJJ") { x=4;y=4; }
			if (token=="AAAA") { x=4;y=4; }
			if (token=="YYYY") { x=4;y=4; }
			if (token=="YY")   { x=2;y=2; }
			if (token=="Y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 20) { year=1900+(year-0); }
				else { year=2000+(year-0); }
			}
		}
		else if (token=="MM"||token=="M"||token=="m"||token=="mm") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;
		}
		else if (token=="dd"||token=="d"||token=="jj"||token=="gg"||token=="tt"||token=="DD"||token=="D"||token=="JJ"||token=="GG"||token=="TT") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;
		}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;
		}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
		}
	}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate;
}

function getZero(num) {
	return num < 10 ? '0'+num : num;
}

function formatageDate(sdate) {
	var tabDate = sdate.split('/');
	if(tabDate.length == 1){
		if(tabDate[0].length == 1){
			tabDate[0] = '0'+tabDate[0];
		}
			return tabDate[0];
		}
	if(tabDate.length == 3){
			if(tabDate[0].length == 1){
				tabDate[0] = '0'+tabDate[0];
			}
		if(tabDate[1].length == 1){
			tabDate[1] = '0'+tabDate[1];
		}
		
	return(tabDate[0]+'/'+tabDate[1]+'/'+tabDate[2]);
	}
			return null;
}

function _getInt(str, i, minlength, maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
	}
	return null;
}

function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
	}
	return true;
}

function submitFormEN() {
	document.forms["appForm"].LANG.value = "EN";
	document.forms["appForm"].PAYS.value = "196";
	disableFields();
	document.forms["appForm"].submit();
}
function disableFields() {
	if (document.getElementById("resa_nbenfants").value == 0){
		document.getElementById("resa_nbenfants").setAttribute('disabled', 'true');
	}
	if (document.getElementById('resa_transportsans').checked == true) {
		document.getElementById("resa_villedepart").setAttribute('disabled', 'true');
	}
	document.getElementById("resa_transportavec").setAttribute('disabled', 'true');
	document.getElementById("resa_transportsans").setAttribute('disabled', 'true');
	document.getElementById("resa_nbadultes").setAttribute('disabled', 'true');
}