var $myObjects = {
	
	hotelsResultTemplate : null,
	filtersResultTemplate : null,
	pagerButtons : null,
	pagerFirstPageBut : null,
	pagerLastPageBut : null,
	pagerNextPageBut : null,
	pagerPreviousPageBut : null,
	pagers : null,
	loader : null,
	selectCurrency : null,
	filterSummary : null,
	filterSummaryDetails : null,
	comparisonButtons : null,
	brandNameSpan : null,
	sortSelector : null,
	mapContainer : null,
	filterLoader : null,
	filterResult : null,
	
	_init : function(){
		this.hotelsResultTemplate = jQuery("#resultTemplate");
		this.filtersResultTemplate = jQuery("#filtersResult");
		this.titleResultTemplate = jQuery("#titleTemplate");
		this.pagerButtons = jQuery("li.numPage ul");
		this.pagerFirstPageBut = jQuery(".pageNav .firstPage a");
		this.pagerLastPageBut = jQuery(".pageNav .lastPage a");
		this.pagerNextPageBut = jQuery(".pageNav .nextPage a");
		this.pagerPreviousPageBut = jQuery(".pageNav .prevPage a");
		this.pagers = jQuery("div.pageNav");
		this.loader = jQuery("#loading");
		this.selectCurrency = jQuery("#selectCurrency");
		this.filterSummary = jQuery(".tFilterSummary");
		this.filterSummaryDetails = jQuery(".tFilterSummary span");
		this.comparisonButtons = jQuery(".tComparisonButton");
		this.brandNameSpan = jQuery(".tBrand");
		this.sortSelector = jQuery(".filterForm #sort");
		this.mapContainer = jQuery('.tMapWrapper');
	}
}

var hotelsUtils = {
	mainDatas : null,
	currenciesViewBean : null,
	searchCriteriaViewBean: null,
	hotelsPerPage : 8,
	currentPage : 0,
	totalPages : 0,
	selectedBrands : null,
	availableBrands : null,
	selectedAmenities : null,
	availableAmenities : null,
	selectedPrice : null,
	templateDatas : {
		hotelsCalendar : {},
		hotelsAccess : {},
		geoZones : {
			enlargeZone : null,
			enlargeRadius : null,
			enlargeSearch : null,
			enlargeResult : null
		},
		brandName : new String()
	},
	lang : jQuery("html").attr("lang"),
	currentCurrency : null,
	mandatoryBrandCode : new Array(),
	hotelToCompare : new Array(),
	hotelType : new Array(),
	
	brandHotels : {
		hotels100 : new Array(),
		hotels50Rated : new Array(),
		hotels50 : new Array(),
		hotelsKO : new Array()
	},
	
	complementaryBrandHotels : {
		hotels100 : new Array(),
		hotels50Rated : new Array(),
		hotels50 : new Array(),
		hotelsKO : new Array()
	},
	
	titleDatas : {
		brandNames : new String(),
		totalHotelsNb : 0,
		nbBrandHotels100 : 0,
		nbBrandHotels50 : 0,
		totalBrandHotels : 0,
		totalComplementaryHotels : 0,
		isRidSearch : false,
		destination : new String(),
		originDestination : new String(),
		isEnlargedSearch : false,
		enlargeRadius : null,
		minorZones : null,
		isAccorhotels : true,
		wordingError : false
	},

	hotelsOnMap : new String(),
	hotelsAvailabilityOnMap : new String(),
	pricesListOnMap : null,
	hotelsOnMapOrder : null,
	mapDisplayed : false,
	retryFocus : true,
	retryUpdate : true,
	isMapOn : false,
	
	
	siteCode : "ALL",
	maporamaDirectory : "accor",
	maporamaSiteOrigin : "ALL",
	allowClick : true,
	isAccorhotels : true,
	
	_init : function(mainViewBean, currenciesViewBean, searchCriteriaViewBean, originViewBean){
		if(this.lang == "en") this.lang = "gb";
		
		// appel des templates
		$myObjects.titleResultTemplate.setTemplateURL("/"+this.lang+"/templates-v66/booking/hotels-list-title.tpl");
		$myObjects.hotelsResultTemplate.setTemplateURL("/"+this.lang+"/templates-v66/booking/hotels-list-hotels.tpl");
		$myObjects.filtersResultTemplate.setTemplateURL("/"+this.lang+"/templates-v66/booking/hotels-list-filters.tpl");
		
		// stockage des donnes recuperees en ajax dans les objets locaux
		this.mainDatas = mainViewBean;
		this.currenciesViewBean = currenciesViewBean;
		this.searchCriteriaViewBean = searchCriteriaViewBean;
		if(typeof mainViewBean.comparedHotelCodes != "undefined") this.hotelToCompare = mainViewBean.comparedHotelCodes;
	
		// recupere le code marque en regardant le premier element de l'objet mandatoryBrandFilters
		this.siteCode = originViewBean.siteCode;
		this.isAccorhotels = originViewBean.accorhotels;
		this.maporamaDirectory = originViewBean.maporamaDirectory;
		this.maporamaSiteOrigin = originViewBean.maporamaSiteOrigin;

		// initialisation de la gestion des devises (remplissage select) et declaration de l'event observer
		Currencies._init(this.currenciesViewBean, "selectCurrency");
		$myObjects.selectCurrency.change(function(){
			var select = this;
			var unique = false;
			jQuery("#resultTemplate .priceMask").animate({ left: "0px" }, 300, function(){
				if(unique == false){
					Currencies._convert(Currencies.ratesTab.currencies, select.value);
					hotelsUtils._roundDisplayedPrices();
					jQuery("#resultTemplate .priceMask").animate({ left: "-134px" }, 300);
				}
				unique= true;
			});
			jQuery(".tMonthCalendar").each(function(){
				var originUrl = jQuery(this).data("originUrl");
				this.href = originUrl + "&currencyCode=" + $myObjects.selectCurrency.val();
				jQuery(this).data("popin").url = originUrl + "&currencyCode=" + $myObjects.selectCurrency.val();
			});
		});
		
		// initialisation des templates : bloc precisez votre recherche et liste hotels
		hotelsUtils._initFiltersTemplate();
		hotelsUtils._initTemplate();
		hotelsUtils.updateComparisonButtonsLink();
		
		if(this.searchCriteriaViewBean != null && this.searchCriteriaViewBean.idBox != null && this.searchCriteriaViewBean.idBox.commission == true)
			utils.initCommissionBox(true, this.lang);
		
		//stockage de la premiere valeur affichée de la devise (valeur par défaut de l'utilisateur)
		var defaultUserCurrency = $myObjects.selectCurrency.val();
		
		// declaration de l'event observer pour la gestion des onglets Liste / Carte
		jQuery('.tMenuTab li').click(function(){
			if(!jQuery(this).hasClass('on')){
				jQuery(this).parent().children('li').removeClass('on');
				jQuery(this).addClass('on');
			}
			if(jQuery(this).attr('id') == 'map' && jQuery(this).hasClass('on')){
				if(hotelsUtils.mapDisplayed == false)hotelsUtils.initMap(defaultUserCurrency);
				$myObjects.mapContainer.show().removeClass('off');
				if(hotelsUtils.isMapOn==false) {
					hotelsUtils.isMapOn = true; 
					hotelsUtils._updateHotelAvailabilityOnMap();
				}
				else {
					hotelsUtils.isMapOn = true;
				}
				
				jQuery(".aclubPopin, a.tMonthCalendar").live("click", function(){
					
					jQuery(".tMapWrapper").css('visibility','hidden');
					
					jQuery(".ui-icon").click(function(){
						jQuery(".tMapWrapper").css('visibility','visible');
					});
					jQuery(document).keyup(function(e) {
						if (e.keyCode == 27) { jQuery(".tMapWrapper").css('visibility','visible');}
					});
				});
				
			} else {
				$myObjects.mapContainer.hide().addClass('off');
				hotelsUtils.isMapOn = false;
			}
			return false;
		});
		
		if(this.mainDatas.search && this.mainDatas.search != null && this.mainDatas.search.displayOnMap == true)
			jQuery("li#map").click();
		
		jQuery("#hotelsList .leftContent .filterEngine").css("display", "block");
	},
	
	/******/
	/* FONCTIONS D'INITIALISATION
	/******/
	
	// Creation des listes de filtres via le template
	_initFiltersTemplate : function(){
		
		// recuperation de la liste des filtres a creer
		var filtersDatas = {
			forkPrices : hotelsUtils.mainDatas.forkPrices,
			serviceFilters : hotelsUtils.mainDatas.serviceFilters,
			activityFilters : hotelsUtils.mainDatas.activityFilters,
			brandFilters : hotelsUtils.mainDatas.brandFilters,
			lodgingFilters : hotelsUtils.mainDatas.lodgingFilters
		}
		$myObjects.filtersResultTemplate.processTemplate(filtersDatas);
		if(jQuery("#forkPrices :radio[checked='true']").length == 0) jQuery("#forkPrices #noFork").prop("checked", "true");
		
		// initialisation des compteurs affichant le nombre d'hotels dispos pour chaque filtre
		this.availableAmenities = jQuery("#filtersResult .amenities :checkbox");
		this.availableAmenities.each(function(){
			this.count = 0;
		});
		
		this.availableBrands = jQuery("#brandFilters :checkbox");
		this.availableBrands.each(function(){
			this.count = 0;
		});
		
		// creee le masque pour les filtres
		jQuery("#filtersResult").prepend("<div id='filter-loading-layer'/>");
		$myObjects.filterLoader = jQuery("#filter-loading-layer");
		$myObjects.filterResult = jQuery("#filtersResult");
		
		// initialise les fonctionnalites des filtres au click sur un filtre
		this._initFilters();
		
		// les filtres crees par le template contiennent des prix / devises, il faut donc lancer la fonction qui permettra aux conversions de fonctionner
		Currencies._save(jQuery("#forkPrices .tPrice"));
		Currencies._convert(Currencies.ratesTab.currencies, $myObjects.selectCurrency.val(), jQuery("#forkPrices .tPrice"));
		hotelsUtils._roundDisplayedPrices();
		
		// stocke ds l'objet local les listes des filtres a prendre en compte pr le tri
		this._getFiltersParams();
		
		$myObjects.filtersResultTemplate.find('span.legend').toggle(
			function(){
				$fieldset = jQuery(this).parent();
				$fieldset.find('.checkboxs').slideUp('slow',function(){
					$fieldset.removeClass('on').addClass('off');
				});
			},
			function(){
				$fieldset = jQuery(this).parent();
				$fieldset.find('.checkboxs').slideDown('slow',function(){
					$fieldset.removeClass('off').addClass('on');																
				});
			}
		);
	},
	
	// initialisation des filtres sur les marques
	// n'est appele qu'une fois par _initFiltersTemplate()
	_initFilters : function(){
		jQuery("#filtersResult input").click(function(){
			if(hotelsUtils.allowClick == true){
				hotelsUtils.allowClick = false;
				hotelsUtils.currentCurrency = $myObjects.selectCurrency.val();
				hotelsUtils._getFiltersParams();	
				hotelsUtils.availableAmenities.each(function(){
					this.count = 0;
				});
				hotelsUtils.availableBrands.each(function(){
					this.count = 0;
				});
				
				hotelsUtils._resetCategorizedArrays();
				$myObjects.filterLoader.css("height", $myObjects.filterResult.height()+"px").show();
				
				$myObjects.loader.css("height", $myObjects.hotelsResultTemplate.height()+"px").fadeIn("normal", function(){					
					hotelsUtils._launchFilteringMethod();							
					hotelsUtils._setSortFormValue();
					
					if(hotelsUtils.mainDatas.rateSearch == true){
						hotelsUtils._setRateCompliantHotels();
					}
					if($myObjects.sortSelector.val() == "1") hotelsUtils._orderHotelsByPrice();
					else if($myObjects.sortSelector.val() == "2")hotelsUtils._orderHotelsByDistance();
				
					hotelsUtils.currentPage = 0;
					hotelsUtils._updateTemplate(0);
					hotelsUtils._writePager();
					hotelsUtils._updateAvailableHotelsCounter();
					
					hotelsUtils._updateHotelAvailabilityOnMap();
					//clearInterval(hotelsUtils.interval);
					//hotelsUtils.interval = setInterval('hotelsUtils._moveToTop()', 10);
					hotelsUtils._moveToTop();
					$myObjects.loader.css("height", $myObjects.hotelsResultTemplate.height()+"px").fadeOut("normal");
					$myObjects.filterLoader.css("height", $myObjects.filterResult.height()+"px").hide();
				});
			}
		});
	},
	
	// Creation de la premiere page affichee de la liste d'hotels
	_initTemplate : function(){
		//recuperation du param de marque obligatoire (sur les sites marques)
		var aBrandsLabel = new Array();
		for(var i in this.mainDatas.mandatoryBrandFilters){
			var brand = this.mainDatas.mandatoryBrandFilters[i];
			if(brand.selected == true){
				aBrandsLabel.push(brand.label);
				this.mandatoryBrandCode.push(brand.code);
			}
		}
		
		//mise a jour du nom de la marque
		if(aBrandsLabel.length > 0){
			var s = aBrandsLabel.join(", ");
			this.titleDatas.brandNames = s;
		}
		
		if(this.mainDatas.enlargeRadius == null) $myObjects.sortSelector.find("option[value='2']").remove();
		
		this._setSortFormValue();
		
		// stocke la devise en cours dans l'objet local pour pouvoir faire les conversions dans le cas du tri par prix
		this.currentCurrency = $myObjects.selectCurrency.val();
		
		// tri des hotels ouverts selon les filtres coches
		this._launchFilteringMethod();	
		
		// dans le cas d'une recherche ac code pref ou carte fid ou carte abo
		if(this.mainDatas.rateSearch == true){
			this._setRateCompliantHotels();
		}
		
		// si le select de tri par prix / distance est sur prix, on retrie les hotels par prix
		if($myObjects.sortSelector.val() == "1") this._orderHotelsByPrice();
		else if($myObjects.sortSelector.val() == "2")hotelsUtils._orderHotelsByDistance();
		
		// stocke les hotels fermes dans l'objet local approprie
		this._storeClosedHotels();		
		
		if(this.mainDatas.zone) this.titleDatas.destination = this.mainDatas.zone.geoZoneName;
		if(this.mainDatas.search.hotelCodes != null) this.titleDatas.isRidSearch = true;
		this.titleDatas.totalBrandHotels = this.mainDatas.brandHotelsNb;
		this.titleDatas.totalComplementaryHotels = this.mainDatas.complementaryBrandHotelsNb;
		this.titleDatas.totalHotelsNb = this.titleDatas.totalBrandHotels + this.titleDatas.totalComplementaryHotels;
		if(this.mainDatas.search != null)this.titleDatas.originDestination = this.mainDatas.search.destination;
		this.titleDatas.isAccorhotels = this.isAccorhotels;
		
		this.titleDatas.isRatedSearch = this.mainDatas.rateSearch;
		if(this.mainDatas.enlargedResult == true){
			this.titleDatas.isEnlargedSearch = true;
			if(this.mainDatas.enlargeRadius != null){
				this.titleDatas.enlargeRadius = this.mainDatas.enlargeRadius;
			}
		}
		
		if(this.mainDatas.minorZones && this.mainDatas.minorZones.length > 0) this.titleDatas.minorZones = this.mainDatas.minorZones;
		
		if(this.mainDatas.enlargedResult == false && this.mainDatas.search != null && this.mainDatas.search.geoZone == null && this.mainDatas.search.destination != null && isNaN(this.mainDatas.search.destination.replace(/,/g, ''))){						 
			var convStr = this.mainDatas.search.destination.split(",")[0];
			convStr = escape(convStr);
			
			convStr = convStr.toUpperCase();
			
			var zoneName = escape(this.mainDatas.zone.geoZoneName);
			zoneName = zoneName.toUpperCase();

			var result = true;
			try{
				var patt = new RegExp(convStr);
				result = patt.test(zoneName);
			}
			catch(e){
				result = false;
			}
			if(result == false){
				this.titleDatas.wordingError = true;
			}
		}
		
		if(this.mainDatas.zone != null){
			// on stocke les donnees de la zoneGeo correspondant a la recherche initiale
			this.templateDatas.geoZones.geoZoneType = this.mainDatas.zone.geoZoneType;
			this.templateDatas.geoZones.geoZoneCode = this.mainDatas.zone.geoZoneCode;
			this.templateDatas.geoZones.geoZoneName = this.mainDatas.zone.geoZoneName;
			
			// on stocke les donnees d'elargissement (qui ne changent pas) dans l'objet templateDatas
			if(typeof this.mainDatas.enlargeGeoZone != "undefined") this.templateDatas.geoZones.enlargeZone = this.mainDatas.enlargeGeoZone;
			if(typeof this.mainDatas.enlargeRadius != "undefined") this.templateDatas.geoZones.enlargeRadius = this.mainDatas.enlargeRadius;
			if(typeof this.mainDatas.enlargeSearch != "undefined") this.templateDatas.geoZones.enlargeSearch = this.mainDatas.enlargeSearch;
			if(typeof this.mainDatas.enlargeResult != "undefined") this.templateDatas.geoZones.enlargeResult = this.mainDatas.enlargeResult;
		}
		
		if(this.mainDatas.search.radius != null) this.templateDatas.geoZones.raduisUnit = this.mainDatas.search.radius.unit.toLowerCase();
		else this.templateDatas.geoZones.raduisUnit = "km";
		
		// infos pour appel calendrier 1 mois
		
		// si des dates sont en session on prend ces dates la
		if(this.mainDatas.search.dayIn != null &&
			this.mainDatas.search.monthIn != null &&
			this.mainDatas.search.yearIn != null){
			this.templateDatas.monthCalendarParams = {
				calendarDay : 1,
				calendarMonth : this.mainDatas.search.monthIn,
				calendarYear : this.mainDatas.search.yearIn,
				userDay : this.mainDatas.search.dayIn,
				userMonth : this.mainDatas.search.monthIn,
				userYear : this.mainDatas.search.yearIn,
				adultNumber : this.mainDatas.adultNumber,
				lengthStay : this.mainDatas.search.nightNb
			};
		}
		// sinon on prend la date du jour
		else{
			var currentDate = new Date();
			this.templateDatas.monthCalendarParams = {
				calendarDay : currentDate.getDate(),
				calendarMonth : currentDate.getMonth()+1,
				calendarYear : currentDate.getFullYear(),
				userDay : 0,
				userMonth : 0,
				userYear : 0,
				adultNumber : this.mainDatas.adultNumber,
				lengthStay : 1
			};
		}

		// on lance la generation du template
		if(this.titleDatas.totalHotelsNb > 0){
			this._updateTemplate(hotelsUtils.currentPage);
			// initialisation et ecriture de la pagination
			this._initNavigationPager();
			this._writePager();
			this._initOrderBySelector();
		}
		
		// mise a jour des nombres d'hotels dispos pour chaque filtre
		this._updateAvailableHotelsCounter(true);
	},
	
	
	// declaration de l'event observer pour le combo de tri par prix, distance, defaut
	_initOrderBySelector : function(){
		$myObjects.sortSelector.change(function(){
			$myObjects.loader.css("height", $myObjects.hotelsResultTemplate.height()+"px").fadeIn("normal", function(){
				// on n'a pas a reappliquer les filters, seulement a ordonner les hotels selon le critere
				switch($myObjects.sortSelector.val()){
					// par prix
					case "1" : 
						hotelsUtils._orderHotelsByPrice();
						break;
					
					// par distance	
					case "2" : 
						hotelsUtils._orderHotelsByDistance();
						break;
						
					// par nom d'hotel
					case "3" : 
						hotelsUtils._orderHotelsByName();
						break;
						
					// ordre par defaut, ici on reapplique le tri pour retrouver l'ordre tars qui a ete renvoye
					case "0" : 
						hotelsUtils._resetCategorizedArrays();
						hotelsUtils._launchFilteringMethod();	
						
						if(hotelsUtils.mainDatas.rateSearch == true){
							hotelsUtils._setRateCompliantHotels();
						}

						hotelsUtils._storeClosedHotels();
						break;
				}
				
				// on regenere ensuite le template depuis la page 1
				hotelsUtils.currentPage = 0;
				hotelsUtils._updateTemplate(0);
				hotelsUtils._writePager();
				$myObjects.loader.css("height", $myObjects.hotelsResultTemplate.height()+"px").fadeOut("normal");
			});
			
		});
	},
	
	// declaration des events observer sur les liens de chaque bloc hotel permettant d'ouvrir le bloc contenant les infos complementaires
	_initDetailsLinks : function($detailsLinks){
		
		$detailsLinks.each(function(){
			this._context = hotelsUtils._getDetailsLinksParams(this);
		});
		
		$detailsLinks.click(function(){
			if(this._context){
				var $blocHotel = jQuery(this).parents("div.blocHotel");
				switch(this._context){
					case "tGallery":
						hotelsUtils._displayGallery(this, $blocHotel);
						hotelsUtils._setAndDisplayDetails($blocHotel, "tGallery");
						break;
						
					case "tDescription":
						hotelsUtils._setAndDisplayDetails($blocHotel, "tDescription");
						break;
						
					case "tAccess":
						hotelsUtils._setAndDisplayDetails($blocHotel, "tAccess");
						hotelsUtils._callAccessDatas($blocHotel);
						break;
					
					case "tAvailability":
						hotelsUtils._setAndDisplayDetails($blocHotel, "tAvailability");
						hotelsUtils._callWeekCalendar(this, $blocHotel);
						break;
				}
			}
			return false;
		});
		
		// close link
		jQuery('.blocHotel .moreDetails .tabs .tCloseLink').click(function(){
			jQuery(this).parents('.tMoreDetails').slideUp('slow').addClass('off');
			return false;
		});
	},
	
	// Initialise la pagination
	_initNavigationPager : function(){
		
		hotelsUtils.totalPages = Math.floor(hotelsUtils.mainList.length/hotelsUtils.hotelsPerPage);
		if(hotelsUtils.mainList.length%hotelsUtils.hotelsPerPage > 0) hotelsUtils.totalPages += 1;
		
		if(hotelsUtils.totalPages > 1){
			$myObjects.pagerFirstPageBut.click(function(){
				if(!$myObjects.pagerFirstPageBut.hasClass("disabled")){
					hotelsUtils.currentPage = 0;
					hotelsUtils._doTransition();
				}
				return false;
			});
			
			$myObjects.pagerLastPageBut.click(function(){
				if(!$myObjects.pagerLastPageBut.hasClass("disabled")){
					hotelsUtils.currentPage = hotelsUtils.totalPages-1;
					hotelsUtils._doTransition();
				}
				return false;
			});
			
			$myObjects.pagerPreviousPageBut.click(function(){
				if(!$myObjects.pagerPreviousPageBut.hasClass("disabled")){
					hotelsUtils.currentPage -= 1;
					hotelsUtils._doTransition();
				}
				return false;
			});
			
			$myObjects.pagerNextPageBut.click(function(){
				if(!$myObjects.pagerNextPageBut.hasClass("disabled")){
					hotelsUtils.currentPage += 1;
					hotelsUtils._doTransition();
				}
				return false;
			});
		}
		else{
			$myObjects.pagers.hide();
		}
	},
			
	// declaration des event observe sur les checkbox de selection des hotels a comparer
	_initComparisonSelectors : function(){
		var $selectors = jQuery(".blocHotel :checkbox");
		// initialise les donnees pour l'affichage du popin en cas d'erreur
		var datas = {
        modal: true,
        drag: false,
        redim: false,
        iframe: false,
        ajax: false,
        width: 280,
        height: null,
        type: "alert",
        ref: "search"
    };
    
		$selectors.click(function(){
			var selector = this;
			
			
			if(selector.checked == true && (jQuery.inArray(selector.className, hotelsUtils.hotelToCompare) == -1)){
				if(hotelsUtils.hotelToCompare.length >= hotelsUtils.mainDatas.maxComparableHotels){
					selector.checked = false;
					jQuery("div.search p, div.search div.btn").hide();
					popins.openPopin(jQuery('div.' + datas.ref), datas);
					jQuery("#tComparisonTooManyHotels").find("span.maxComparableHotels").text(hotelsUtils.mainDatas.maxComparableHotels);
					jQuery("#tComparisonTooManyHotels, #comparisonPopinButtons").show();
				}
				else{
					var elemToCompare = selector.className.split(' ');
					hotelsUtils.hotelToCompare.push(elemToCompare[0]);
				}
			}
			else if(selector.checked == false){
				var elemToCompare = selector.className.split(' ');
				hotelsUtils.hotelToCompare = jQuery.grep(hotelsUtils.hotelToCompare, function (a) { return a != elemToCompare[0]; });

			}

		});
		
		
		
		$myObjects.comparisonButtons.click(function(){
				hotelsUtils.hotelType = new Array;
				jQuery(hotelsUtils.hotelToCompare).each(function(){
					for(var i=0; i< hotelsUtils.mainList.length; i++){
						if(hotelsUtils.mainList[i].datas.tarsCode == this){
								if(hotelsUtils.mainList[i].cat == "hotels100") hotelsUtils.hotelType.push('1');
								else hotelsUtils.hotelType.push('0');
							}
						}
					})
							
													
				if(hotelsUtils.hotelToCompare.length < hotelsUtils.mainDatas.minComparableHotels){
					jQuery("div.search p, div.search div.btn").hide();
					popins.openPopin(jQuery('div.' + datas.ref), datas);
					jQuery("#tComparisonNotEnoughHotels").find("span.minComparableHotels").text(hotelsUtils.mainDatas.minComparableHotels);
					jQuery("#tComparisonNotEnoughHotels, #comparisonPopinButtons").show();
				}
				else{
					hotelsUtils.updateComparisonButtonsLink();
					ajaxRequest._executeByUrl(
						this.href+"&currencyCode="+$myObjects.selectCurrency.val(),
						"tAjaxError", 
						"hotelsUtils._successComparison(errors, response)"
					);
				}
				return false;
		});
	},
	
	
	// Fin FONCTION D'INITIALISATION
	
	/******/
	/* FONCTIONS LIEES A LA GENERATION DU TEMPLATE
	/******/
	
	_updateTemplate : function(start){
		
		this.titleDatas.nbBrandHotels100 = this.brandHotels.hotels100.length;
		this.titleDatas.nbBrandHotels50 = this.brandHotels.hotels50.length;
		
		this.mainList = new Array();
		jQuery.merge(this.mainList, this.brandHotels.hotels100);
		jQuery.merge(this.mainList, this.brandHotels.hotels50Rated);
		jQuery.merge(this.mainList, this.brandHotels.hotels50);
		jQuery.merge(this.mainList, this.brandHotels.hotelsKO);
		jQuery.merge(this.mainList, this.complementaryBrandHotels.hotels100);
		jQuery.merge(this.mainList, this.complementaryBrandHotels.hotels50Rated);
		jQuery.merge(this.mainList, this.complementaryBrandHotels.hotels50);
		jQuery.merge(this.mainList, this.complementaryBrandHotels.hotelsKO);
				
		var shortList = new Array();
		for(i=start*this.hotelsPerPage; i<((start*this.hotelsPerPage)+this.hotelsPerPage); i++){
			if(this.mainList[i]) shortList.push(this.mainList[i]);
		}
		
		var separatorStatus = {
			"brandHotels" : {
				"hotels50Rated" : false,
				"hotels50" : false,
				"hotelsKO" : false
			},
			
			"complementaryBrandHotels" : {
				"hotels100" : false,
				"hotels50" : false,
				"hotels50Rated" : false,
				"hotelsKO" : false
			}
		}
		
		var finalList = new Array();
		
		// si le premier hotel n'est pas un 100% on affiche le bandeau de la categorie en haut de la liste
		if(shortList[0]){
			switch(shortList[0].cat){
				case "hotels50":
					finalList.push({"type":"separator", "cat":"hotels50", "datas":{"nbHotels" :this[shortList[0].list].hotels50.length, "catg" : shortList[0].list}});
					separatorStatus[shortList[0].list]["hotels50"] = true;
					break;
					
				case "hotels50Rated":
					finalList.push({"type":"separator", "cat":"hotels50Rated", "datas":{"nbHotels" :this[shortList[0].list].hotels50Rated.length, "catg" : shortList[0].list}});
					separatorStatus[shortList[0].list]["hotels50Rated"] = true;
					break;
					
				case "hotelsKO":
					finalList.push({"type":"separator", "cat":"hotelsKO", "datas":{"nbHotels" :this[shortList[0].list].hotelsKO.length, "catg" : shortList[0].list}});
					separatorStatus[shortList[0].list]["hotelsKO"] = true;
					break;
					
				case "hotels100":
				if(shortList[0].list == "complementaryBrandHotels"){
					finalList.push({"type":"separator", "cat":"complementaryBrandHotels", "datas":{"nbHotels" :this.complementaryBrandHotels.hotels100.length}});
					separatorStatus[shortList[0].list]["hotels100"] = true;
				}
				break;
			}	
		}
		var lastCat = shortList[0].list + "-hotels100";
		for(i=0; i<shortList.length; i++){
			if(shortList[i].type == "hotel"){
				
				if((shortList[i].list+"-"+shortList[i].cat) != lastCat && separatorStatus[shortList[i].list][shortList[i].cat] == false){
					
					switch(shortList[i].cat){
						case "hotels50":
							finalList.push({"type":"separator", "cat":"hotels50", "datas":{"nbHotels" :this[shortList[i].list].hotels50.length, "catg" : shortList[i].list}});
							separatorStatus[shortList[0].list]["hotels50"] = true;
							break;
							
						case "hotels50Rated":
							finalList.push({"type":"separator", "cat":"hotels50Rated", "datas":{"nbHotels" :this[shortList[i].list].hotels50Rated.length, "catg" : shortList[i].list}});
							separatorStatus[shortList[0].list]["hotels50Rated"] = true;
							break;
							
						case "hotelsKO":
							finalList.push({"type":"separator", "cat":"hotelsKO", "datas":{"nbHotels" :this[shortList[i].list].hotelsKO.length, "catg" : shortList[i].list}});
							separatorStatus[shortList[0].list]["hotelsKO"] = true;
							break;
							
						case "hotels100":
						if(shortList[i].list == "complementaryBrandHotels"){
							finalList.push({"type":"separator", "cat":"complementaryBrandHotels", "datas":{"nbHotels" :this.complementaryBrandHotels.hotels100.length}});
							separatorStatus[shortList[i].list]["hotels100"] = true;
						}
						break;
					}
					lastCat = shortList[i].list+"-"+shortList[i].cat;
				}
			}
			finalList.push(shortList[i]);
		}
		
		if(this.templateDatas.geoZones.enlargeSearch == true){
			if(this.templateDatas.geoZones.enlargeZone != null){
				finalList.push({"type":"separator", "cat":"enlargeAuto", "datas":this.templateDatas.geoZones});
			}
			else if(this.templateDatas.geoZones.enlargeRadius != null){
				finalList.push({"type":"separator", "cat":"enlargeManu", "datas":this.templateDatas.geoZones});
			}
		}
		
		var datas = new Object();
		datas = {
			"list" : finalList,
			"monthCalendarParams" : this.templateDatas.monthCalendarParams
		}
		
		var ridList = new Array();
		var availabilityList = new Array();
		this.pricesListOnMap = new Array();
		for(var i=0; i< this.mainList.length; i++){
			ridList.push(this.mainList[i].datas.tarsCode);
			if(this.mainList[i].cat == "hotels100"){
				availabilityList.push("1");
			}
			else if(this.mainList[i].cat == "hotels50" || this.mainList[i].cat == "hotels50Rated"){
				availabilityList.push("2");
			}
			else{
				availabilityList.push("0");
			}			

			if(this.hotelsOnMapOrder != null){
				this.hotelsOnMapOrder[this.mainList[i].datas.tarsCode] = availabilityList[availabilityList.length-1];
			}

			if(this.mainList[i].datas.bar != null)
				this.pricesListOnMap.push({'amount' : this.mainList[i].datas.bar.averagePrice.amount, 'currency' : this.mainList[i].datas.bar.averagePrice.currency});
			else
				this.pricesListOnMap.push({'amount' : 0, 'currency' : ''});
		}
		this.hotelsOnMap = "";
		this.hotelsOnMap = ridList.join("|");
		
		this.hotelsAvailabilityOnMap = "";
		this.hotelsAvailabilityOnMap = availabilityList.join("|");
		
		$myObjects.hotelsResultTemplate.setParam('centerType', this.mainDatas.centerType);
		$myObjects.hotelsResultTemplate.setParam('hotelToCompare', this.hotelToCompare);
		$myObjects.hotelsResultTemplate.setParam('radiusUnit', this.templateDatas.geoZones.raduisUnit);
		$myObjects.hotelsResultTemplate.setParam('isRatedSearch', this.mainDatas.rateSearch);
		$myObjects.hotelsResultTemplate.setParam('brandNames', this.titleDatas.brandNames);	
		$myObjects.hotelsResultTemplate.setParam('mainListHotels', this.hotelsOnMap);
		$myObjects.hotelsResultTemplate.setParam('amenitiesLabel', this.mainDatas.amenitiesLabels);
		$myObjects.hotelsResultTemplate.setParam('accorSite', this.isAccorhotels);
		$myObjects.titleResultTemplate.processTemplate(this.titleDatas);
		$myObjects.hotelsResultTemplate.processTemplate(datas);
		this._updateFiltersSummary();
		Currencies._save(jQuery("#resultTemplate .tPrice"));
		Currencies._convert(Currencies.ratesTab.currencies, $myObjects.selectCurrency.val(), jQuery("#resultTemplate .tPrice"));
		this._roundDisplayedPrices();
		this._initDetailsLinks(jQuery("#resultTemplate div.blocHotel .tDetailsLink"));
		utils.tooltips.init(jQuery("#resultTemplate .tooltip"));
		popins.init(jQuery("#resultTemplate .popin"));		
		jQuery('#resultTemplate .tShowMap').click(function(){
			jQuery('.tMenuTab li#map').click();							   
			var rid = jQuery(this).parents(".blocHotel").attr('id');
			hotelsUtils.focusMap(rid);
		});
		if(this.isAccorhotels && this.searchCriteriaViewBean.reserverId==null) jQuery(".lnk-advancedsearchContract").css("display","inline")
		this._initComparisonSelectors();
		utils.initComplementaryBrandHotelAlert(jQuery("a.tCompBrandHotel"), true);
		utils.initExternalHotelAlert(jQuery("a.tExternalHotel"), true);
		utils.addCurrencyParamToBookLinks($myObjects.hotelsResultTemplate.find("a.tBookLink"), "selectCurrency");
		if(this.mainDatas.minorZones && this.mainDatas.minorZones.length > 0) this._initMinorZonesForm();

		// creation d'une table de reference hotels / page pour les fonctionnalites de Maporama
		hotelsUtils.totalPages = Math.floor(hotelsUtils.mainList.length/hotelsUtils.hotelsPerPage);
		if(hotelsUtils.mainList.length%hotelsUtils.hotelsPerPage > 0) hotelsUtils.totalPages += 1;
		this.hotelsRefTab = new Object();
		
		for(var i=0; i < this.totalPages; i++){
			for(j=i*this.hotelsPerPage; j<((i*this.hotelsPerPage)+this.hotelsPerPage); j++){
				if(this.mainList[j]){
					this.hotelsRefTab[this.mainList[j].datas.tarsCode] = i;
				}
			}
		}
	},
	
	_roundDisplayedPrices : function(prices){
		prices = prices || jQuery(".middleContent .tPrice");
		prices.each(function(){
			jQuery(this).find(".tAmount").text(Math.round(Number(jQuery(this).find(".tAmount").text())));
		});
		
		var forkPrices = jQuery("#forkPrices .tPrice, .tFilterSummary .tPrice");
		var val;
		forkPrices.each(function(){
				var $tAmount = jQuery(this).find(".tAmount");
				val = Math.round(Number($tAmount.text()));
				val = Math.floor((val+5)/10)*10;
				$tAmount.text(val);
		});
		
		this._rewriteForkPricesValues();
	},
	
	displaySearchedDistance : function(dist){
		var convertedDist = dist/1000;
		var sDist = convertedDist.toString();
		if(sDist.indexOf(".") == -1)return(convertedDist);
		else return(convertedDist.toFixed(1));
	},
	
	_rewriteForkPricesValues : function(){
		jQuery("#forkPrices li.checkbox").each(function(){
			var $li = jQuery(this);
			var $minBound = $li.find("span.tMinBound").find("span.tAmount");
			var $maxBound = $li.find("span.tMaxBound").find("span.tAmount");
			var $input = $li.find("input");
			
			if($minBound.length == 0 && $maxBound.length > 0){
				$input.val("0|"+$maxBound.text());
			}
			else if($minBound.length > 0 && $maxBound.length >0){
				$input.val($minBound.text()+"|"+$maxBound.text());
			}
			else if($minBound.length > 0 && $maxBound.length == 0){
				$input.val($minBound.text()+"|0");
			}
		});
	},
	
	_setAndDisplayDetails : function($blocHotel, tab){
		$blocHotel.find("div.tMoreDetails div.on").removeClass('on').addClass('off');
		$blocHotel.find("div.tMoreDetails div."+tab).removeClass('off').addClass('on');
		
		$blocHotel.find("ul.tabs li").removeClass('selected');
		$blocHotel.find("ul.tabs li."+tab+"Tab").addClass('selected');
		
		var $blocDetails = $blocHotel.find('.tMoreDetails');
		if($blocDetails.hasClass('off')){
			$blocDetails.slideDown('slow').removeClass('off');
		}
	},
	
	_updateFiltersSummary : function(){
		$myObjects.filterSummaryDetails.empty();
		if(this.selectedPrice!= null){
			var labelPrice = jQuery("#forkPrices :radio[checked='true']").next("label")
			$myObjects.filterSummaryDetails.append(jQuery.trim(labelPrice.html()));
		}
		if(this.selectedAmenities.length > 0){
			if($myObjects.filterSummaryDetails.html() != "") $myObjects.filterSummaryDetails.append(", ");
			jQuery(this.selectedAmenities).each(function(i){
				var label = jQuery(this).next("label").text();
				label = label.substr(0, (label.indexOf("(")-1));
				$myObjects.filterSummaryDetails.append(label);
				if(i != hotelsUtils.selectedAmenities.length-1) $myObjects.filterSummaryDetails.append(", ");
			});
		}
		
		if(this.selectedBrands.length > 0){
			if($myObjects.filterSummaryDetails.html() != "") $myObjects.filterSummaryDetails.append(", ");
			jQuery(this.selectedBrands).each(function(i){
				var label = jQuery(this).next("label").text();				
				$myObjects.filterSummaryDetails.append(label);
				if(i != hotelsUtils.selectedBrands.length-1) $myObjects.filterSummaryDetails.append(", ");
			});
		}
		if($myObjects.filterSummaryDetails.html() != "") $myObjects.filterSummary.show();
		else $myObjects.filterSummary.hide();
	},
	
	_initMinorZonesForm : function(){
		var $listeMinorZones = jQuery("#minorZonesList");
		$listeMinorZones.change(function(){
			if(this.value != "0"){
				var geoType = this.value.split("-")[0];
				var geoCode = this.value.split("-")[1];
				document.location.href = jQuery("#minorZones").attr("action")+"?search.geoZone.geoZoneCode="+geoCode+"&search.geoZone.geoZoneType="+geoType;
			}
		});
	},
	// Fin FONCTIONS LIEES A LA GENERATION DU TEMPLATE
	
	/******/
	/* FONCTIONS LIEES AUX TRIS / FILTRES
	/******/
	_setSortFormValue : function(){
		if(this.mainDatas.radiusDisplayMode == true) $myObjects.sortSelector.val("2");		
		if(this.selectedPrice != null) $myObjects.sortSelector.val("1");
	},
	
	_launchFilteringMethod : function(){
		jQuery(hotelsUtils.mainDatas.brandHotels.openHotels).each(function(){
			hotelsUtils._doFilter(this, "brandHotels");
		});
		
		jQuery(hotelsUtils.mainDatas.complementaryBrandHotels.openHotels).each(function(){
			hotelsUtils._doFilter(this, "complementaryBrandHotels");
		});
	},
	
	// permet d'effectuer le tri pour remonter les hotels correspondants aux filtres coches
	_doFilter : function(hotel, listType){
			if(hotelsUtils._doCompliantPredicate(hotel)){
				if(hotelsUtils._doPricePredicate(hotel)){
					if(hotelsUtils._doBrandsPredicate(hotel)){
						if(hotelsUtils._doAmenitiesPredicate(hotel)){
							hotelsUtils._insertInCategorizedArrays(listType, "hotels100", hotel);
						}
						else{
							hotelsUtils._insertInCategorizedArrays(listType, "hotels50", hotel);
						}
					}
					else{
						hotelsUtils._insertInCategorizedArrays(listType, "hotels50", hotel);
					}
				}
				else{
					hotelsUtils._insertInCategorizedArrays(listType, "hotels50", hotel);
				}
			}
			else{				
				hotelsUtils._insertInCategorizedArrays(listType, "hotels50", hotel);
			}
	},
	
	_insertInCategorizedArrays : function(listType, categoryType, hotelDatas){
		hotelsUtils[listType][categoryType].push({"list":listType, "type":"hotel", "cat":categoryType, "datas":hotelDatas});
	},
	
	_storeClosedHotels : function(){
		if(hotelsUtils.mainDatas.brandHotels.closedHotels){
			for(i=0; i<hotelsUtils.mainDatas.brandHotels.closedHotels.length; i++){
				this.brandHotels.hotelsKO.push({"list":"brandHotels", "type":"hotel", "cat": "hotelsKO", "datas":hotelsUtils.mainDatas.brandHotels.closedHotels[i]});
			}
		}
		
		if(hotelsUtils.mainDatas.complementaryBrandHotels.closedHotels){
			for(i=0; i<hotelsUtils.mainDatas.complementaryBrandHotels.closedHotels.length; i++){
				this.complementaryBrandHotels.hotelsKO.push({"list":"complementaryBrandHotels", "type":"hotel", "cat": "hotelsKO", "datas":hotelsUtils.mainDatas.complementaryBrandHotels.closedHotels[i]});
			}
		}
		// puis on les trie par ordre alphabetique
		hotelsUtils._orderHotelsByName("hotelsKO");
	},
	
	_setRateCompliantHotels : function(){
		
		if(this.brandHotels.hotels50 && this.brandHotels.hotels50.length > 0){			
			var tempHotels50 = new Array();
			for(var i=0; i < this.brandHotels.hotels50.length; i++){
				if(this.brandHotels.hotels50[i].datas.rateCompliant == true){
					this.brandHotels.hotels50Rated.push({"list": "brandHotels", "type":"hotel", "cat":"hotels50Rated", "datas":this.brandHotels.hotels50[i].datas});
				}
				else{
					tempHotels50.push({"list": "brandHotels", "type":"hotel", "cat":"hotels50", "datas":this.brandHotels.hotels50[i].datas});
				}
			}
			this.brandHotels.hotels50 = new Array();
			for(i=0; i< tempHotels50.length; i++){
				this.brandHotels.hotels50.push(tempHotels50[i]);
			}
		}
		
		if(this.complementaryBrandHotels.hotels50 && this.complementaryBrandHotels.hotels50.length > 0){
			var tempCompHotels50 = new Array();
			for(var i=0; i < this.complementaryBrandHotels.hotels50.length; i++){
				if(this.complementaryBrandHotels.hotels50[i].datas.rateCompliant == true){
					this.complementaryBrandHotels.hotels50Rated.push({"list": "complementaryBrandHotels", "type":"hotel", "cat":"hotels50Rated", "datas":this.complementaryBrandHotels.hotels50[i].datas});
				}
				else{
					tempCompHotels50.push({"list": "complementaryBrandHotels", "type":"hotel", "cat":"hotels50", "datas":this.complementaryBrandHotels.hotels50[i].datas});
				}
			}
			this.complementaryBrandHotels.hotels50 = new Array();
			for(i=0; i< tempCompHotels50.length; i++){
				this.complementaryBrandHotels.hotels50.push(tempCompHotels50[i]);
			}
		}
	},
	
	// ordonne les hotels par ordre de prix croissant
	// datas : array of hotels
	_orderHotelsByPrice : function(cat){		
		function sortPrice(hotel1, hotel2){
		
			if(hotel1.datas.bar != null && hotel2.datas.bar != null) {

				if(hotelsUtils.currentCurrency != hotel1.datas.bar.averagePrice.currency || hotelsUtils.currentCurrency != hotel2.datas.bar.averagePrice.currency){
					var convertedBar = Math.floor(hotel1.datas.bar.averagePrice.amount/ (Currencies.ratesTab.currencies[hotelsUtils.currentCurrency] / Currencies.ratesTab.currencies[hotel1.datas.bar.averagePrice.currency]));
					var convertedBar2 = Math.floor(hotel2.datas.bar.averagePrice.amount/ (Currencies.ratesTab.currencies[hotelsUtils.currentCurrency] / Currencies.ratesTab.currencies[hotel2.datas.bar.averagePrice.currency]));
					
				}
				else{
					var convertedBar = Math.floor(hotel1.datas.bar.averagePrice.amount);
					var convertedBar2 = Math.floor(hotel2.datas.bar.averagePrice.amount);
				}	
				return convertedBar - convertedBar2;	
		}
		

			
			else if(hotel1.datas.bar == null && hotel2.datas.bar != null) return 1;
			else if(hotel2.datas.bar == null && hotel1.datas.bar != null) return -1;
			else if(hotel1.datas.bar == null && hotel2.datas.bar == null) return 0;
		}
		
		if(cat && cat != ""){
			hotelsUtils._orderHotelsByName(cat);
			switch(cat){
				case "hotels100" : 
					hotelsUtils.brandHotels.hotels100.sort(sortPrice);
					hotelsUtils.complementaryBrandHotels.hotels100.sort(sortPrice);
					break;
					
				case "hotels50" : 
					hotelsUtils.brandHotels.hotels50.sort(sortPrice);
					hotelsUtils.complementaryBrandHotels.hotels50.sort(sortPrice);
					break;
					
				case "hotels50Rated" : 					
					hotelsUtils.brandHotels.hotels50Rated.sort(sortPrice);
					hotelsUtils.complementaryBrandHotels.hotels50Rated.sort(sortPrice);
					break;
			}
		}
		else{			
			hotelsUtils._orderHotelsByName();
			hotelsUtils.brandHotels.hotels100.sort(sortPrice);
			hotelsUtils.brandHotels.hotels50.sort(sortPrice);
			hotelsUtils.brandHotels.hotels50Rated.sort(sortPrice);
			hotelsUtils.complementaryBrandHotels.hotels100.sort(sortPrice);
			hotelsUtils.complementaryBrandHotels.hotels50.sort(sortPrice);
			hotelsUtils.complementaryBrandHotels.hotels50Rated.sort(sortPrice);
		}
	},
	
	// ordonne les hotels par ordre alphabetique
	// datas : array of hotels
	_orderHotelsByName : function(cat){
		function sortName(hotel1, hotel2) {
			var name1 = hotel1.datas.name.toUpperCase();
			var name2 = hotel2.datas.name.toUpperCase();
			if (name1 < name2) return -1;
			if (name1 > name2) return 1;
			return 0;
		}
		
		if(cat && cat != ""){
			switch(cat){
				case "hotelsKO" : 
					hotelsUtils.brandHotels.hotelsKO.sort(sortName);
					hotelsUtils.complementaryBrandHotels.hotelsKO.sort(sortName);
					break;
					
				case "hotels100" : 
					hotelsUtils.brandHotels.hotels100.sort(sortName);
					hotelsUtils.complementaryBrandHotels.hotels100.sort(sortName);
					break;
					
				case "hotels50" : 
					hotelsUtils.brandHotels.hotels50.sort(sortName);
					hotelsUtils.complementaryBrandHotels.hotels50.sort(sortName);
					break;
					
				case "hotels50Rated" : 
					hotelsUtils.brandHotels.hotels50Rated.sort(sortName);
					hotelsUtils.complementaryBrandHotels.hotels50Rated.sort(sortName);
					break;
			}
		}
		else{
			hotelsUtils.brandHotels.hotels100.sort(sortName);
			hotelsUtils.brandHotels.hotels50.sort(sortName);
			hotelsUtils.brandHotels.hotels50Rated.sort(sortName);
			hotelsUtils.brandHotels.hotelsKO.sort(sortName);
			hotelsUtils.complementaryBrandHotels.hotels100.sort(sortName);
			hotelsUtils.complementaryBrandHotels.hotels50.sort(sortName);
			hotelsUtils.complementaryBrandHotels.hotels50Rated.sort(sortName);
			hotelsUtils.complementaryBrandHotels.hotelsKO.sort(sortName);
		}
	},
	
	// ordonne les hotels par ordre de distance croissante
	// datas : array of hotels
	_orderHotelsByDistance : function(cat){		
		function sortDistance(hotel1, hotel2){
			if(hotel1.datas.distance != null && hotel2.datas.distance != null) return hotel1.datas.distance - hotel2.datas.distance;
			else if(hotel1.datas.distance == null && hotel2.datas.distance != null) return 1;
			else if(hotel2.datas.distance == null && hotel1.datas.distance != null) return -1;
			else if(hotel1.datas.distance == null && hotel2.datas.distance == null) return 0;
		}
		
		if(cat && cat != ""){
			hotelsUtils._orderHotelsByName(cat);
			switch(cat){
				case "hotels100" : 					
					hotelsUtils.brandHotels.hotels100.sort(sortDistance);
					hotelsUtils.complementaryBrandHotels.hotels100.sort(sortDistance);
					break;
					
				case "hotels50" : 
					hotelsUtils.brandHotels.hotels50.sort(sortDistance);
					hotelsUtils.complementaryBrandHotels.hotels50.sort(sortDistance);
					break;
					
				case "hotels50Rated" : 
					hotelsUtils.brandHotels.hotels50Rated.sort(sortDistance);
					hotelsUtils.complementaryBrandHotels.hotels50Rated.sort(sortDistance);
					break;
			}
		}
		else{
			hotelsUtils._orderHotelsByName();
			hotelsUtils.brandHotels.hotels100.sort(sortDistance);
			hotelsUtils.brandHotels.hotels50.sort(sortDistance);
			hotelsUtils.brandHotels.hotels50Rated.sort(sortDistance);
			hotelsUtils.complementaryBrandHotels.hotels100.sort(sortDistance);
			hotelsUtils.complementaryBrandHotels.hotels50.sort(sortDistance);
			hotelsUtils.complementaryBrandHotels.hotels50Rated.sort(sortDistance);
		}
	},
	
	// fait le tri sur la propriete compliant de l'objet hotel initial
	_doCompliantPredicate : function(hotel){
		if(hotel.compliant != null){
			return hotel.compliant;
		}
		else{
			return true;	
		}
	},
	
	// applique le tri obligatoire sur la marque dans le cas d'un site marque
	_doMandatoryBrandPredicate : function(hotel){
		if(hotelsUtils.mandatoryBrandCode.length > 0){
			var matched = false;
			jQuery(hotelsUtils.mandatoryBrandCode).each(function(){					
					if(hotel.brandCode == this.value){matched = true; return;}
			});
			return matched;
		}
		else{
			return true;	
		}
	},
	
	// fait le tri sur les marques
	_doBrandsPredicate : function(hotel){
		if(hotelsUtils.selectedBrands.length > 0){
			var matched = false;
			hotelsUtils.selectedBrands.each(function(){					
					if(hotel.brandCode == this.value){matched = true; return;}
			});
			return matched;
		}
		else{
			return true;	
		}
	},
	
	// fait le tri sur les amenities
	_doAmenitiesPredicate : function(hotel){
		if(hotelsUtils.selectedAmenities.length > 0){
			var matched = true;
			var allAmenities = new Array();
			for(i=0; i< hotel.descriptiveAmenities.length; i++){
				allAmenities.push(hotel.descriptiveAmenities[i].code);
			}
			for(i=0; i< hotel.lodgingAmenities.length; i++){
				allAmenities.push(hotel.lodgingAmenities[i]);
			}
			
			hotelsUtils.selectedAmenities.each(function(){
					if(allAmenities) matched = matched&&(jQuery.inArray(this.value, allAmenities) != -1);
			});
			return matched;
		}
		else{
			return true;	
		}
	},
	
	// tri selon la fourchette de prix selectionnee
	_doPricePredicate : function(hotel){
		if(hotelsUtils.selectedPrice != null){
			var matched = false;					
			if(hotel.bar != null && hotel.bar.averagePrice != null && hotel.bar.averagePrice.amount != null){
				
				if(hotelsUtils.currentCurrency != hotel.bar.averagePrice.currency)
					var convertedBar = Math.floor(hotel.bar.averagePrice.amount/ (Currencies.ratesTab.currencies[hotelsUtils.currentCurrency] / Currencies.ratesTab.currencies[hotel.bar.averagePrice.currency]));
				else
					var convertedBar = Math.floor(hotel.bar.averagePrice.amount);
				
				if(hotelsUtils.selectedPrice.max != 0){
					if(convertedBar >= hotelsUtils.selectedPrice.min && convertedBar <= hotelsUtils.selectedPrice.max){matched = true;}
				}
				else{
					if(convertedBar >= hotelsUtils.selectedPrice.min){matched = true;}
				}
			}
			return matched;
		}
		else{
			return true;	
		}
	},
	
	_getBrandsFilterParam : function(){
		return jQuery("#brandFilters :checkbox[checked='true']");
	},
	
	_getAmenitiesFilterParam : function(){
		return jQuery("#filtersResult .amenities :checkbox[checked='true']");
	},
	
	_setPriceFilterParam : function(){
		var forkPrice = jQuery("#forkPrices :radio[checked='true']");
		if(forkPrice.length > 0){
			jQuery.each(forkPrice, function(){
				if(this.value != 0){
					var min = Number(this.value.split("|")[0]);
					var max = Number(this.value.split("|")[1]);
					hotelsUtils.selectedPrice = {"min":min, "max":max};
				}
				else{
					hotelsUtils.selectedPrice = null;
				}
			});
		}
	},
	
	_getFiltersParams : function(){
		this.selectedBrands = this._getBrandsFilterParam();
		this.selectedAmenities = this._getAmenitiesFilterParam();
		this._setPriceFilterParam();
	},
	
	_updateAvailableHotelsCounter : function(first){
		jQuery(hotelsUtils.brandHotels.hotels100).each(function(index, hotel){			
			var allAmenities = new Array();
			for(i=0; i< hotel.datas.descriptiveAmenities.length; i++){
				allAmenities.push(hotel.datas.descriptiveAmenities[i].code);
			}
			for(i=0; i< hotel.datas.lodgingAmenities.length; i++){
				allAmenities.push(hotel.datas.lodgingAmenities[i]);
			}
			
			hotelsUtils.availableAmenities.each(function(){
				if(allAmenities) if(jQuery.inArray(this.value, allAmenities) != -1) this.count+=1;
			});
			
			if(first){
				hotelsUtils.availableBrands.each(function(){
					if(hotel.datas.brandCode == this.value) this.count+=1;
				});
			}
		});
		
		hotelsUtils.availableAmenities.each(function(){
			var $input = jQuery(this);
			$input.next().find("span").text("("+this.count+")");
			if(this.count == 0){
				if(first){
					switch($input.parents("ul").attr("id")){
						case "lodgingFilters":
							if(hotelsUtils.mainDatas.lodgingFilters[this.value].selected != true)jQuery(this).prop("disabled", true);
							break;
							
						case "serviceFilters":
							if(hotelsUtils.mainDatas.serviceFilters[this.value].selected != true)jQuery(this).prop("disabled", true);
							break;
							
						case "activityFilters":
							if(hotelsUtils.mainDatas.activityFilters[this.value].selected != true)jQuery(this).prop("disabled", true);
							break;
							
						default:
							jQuery(this).prop("disabled", true);
							break;
					}
				}
				else{
					jQuery(this).prop("disabled", true);
				}
				
				jQuery(this).parent("li").addClass("disabled");
			}
			else{
				jQuery(this).prop("disabled", false);
				jQuery(this).parent("li").removeClass("disabled");
			}
		});
		
		/*if(first){
			hotelsUtils.availableBrands.each(function(){
				jQuery(this).next().find("span").text("("+this.count+")");
			});
		}*/
	},
	// Fin FONCTIONS LIEES AUX TRIS / FILTRES
	
	
	/******/
	/* FONCTIONS LIEES A LA COMPARAISON
	/******/
	// l'appel ajax lance par les boutons de comparaison est cense redirige sur la page de comparaison via le targetUrl
	// en cas d'erreur, cette fonction sera executee pour traiter l'affichage des erreurs
	_successComparison : function(){
		if(errors && errors.length > 0){
			ajaxRequest.showErrors(errors, "tAjaxError");			
		}
	},
	
	// met a jour les liens sur les boutons permettant de lancer la comparaison
	
	
	updateComparisonButtonsLink : function(){
		if(this.hotelToCompare.length > 0){
			var initialLink = $myObjects.comparisonButtons[0].href.split("?")[0];
			var newLink = initialLink+"?hotelCodes="+hotelsUtils.hotelToCompare.join(";")+"&hotelsCompliancy="+hotelsUtils.hotelType.join(";");
			$myObjects.comparisonButtons.attr("href", newLink);
		}
	},
	// Fin FONCTIONS LIEES A LA COMPARAISON
	
	/******/
	/* FONCTIONS LIEES A L'AFFICHAGE DES DONNEES D'ACCES A L'HOTEL
	/******/
	_callAccessDatas: function($blocHotel){
		var tarsCode = $blocHotel.attr("id");
		var $blocAccess = $blocHotel.find("div.tAccess");
		
		if(!$blocAccess.hasClass("tRequestedOnce")){
			if(!hotelsUtils.templateDatas.hotelsAccess[tarsCode]){
				var datasUrl = "/fh/scripts-v66/"+tarsCode+"_"+this.lang+".js";
				$blocAccess.find("p.tAjaxError").hide();
				$blocAccess.find("p.tAjaxLoading").show();
				
				var externalHotel = $blocHotel.find("input[name='externalHotel']").val();
				var foreignBrandHotel = $blocHotel.find("input[name='foreignBrandHotel']").val();
				var brandCode = $blocHotel.find("input[name='brandCode']").val();
				
				jQuery.getJSON(
					datasUrl,
					function(json){
						$blocAccess.setTemplateURL("/"+hotelsUtils.lang+"/templates-v66/booking/hotels-list-access.tpl");
						$blocAccess.setParam('externalHotel', externalHotel);
						$blocAccess.setParam('foreignBrandHotel', foreignBrandHotel);
						$blocAccess.setParam('brandCode', brandCode);
						hotelsUtils._processAccessDatas(json, tarsCode);
						if(hotelsUtils.hotelsOnMap == "") $blocAccess.find('.tShowMap').remove(); 
					}
				);
			}
		}
		else{
			hotelsUtils._processAccessDatas(hotelsUtils.templateDatas.hotelsAccess[tarsCode], tarsCode, true);
		}
	},
	
	_processAccessDatas : function(json, tarsCode, localDatas){
		var accessDatas = null;
		var $blocHotel = jQuery("div.blocHotel[id='"+tarsCode+"']");
		accessDatas = json;
		if(localDatas == false){
			hotelsUtils.templateDatas.hotelsCalendar[$blocHotel.attr("id")] = json;
		}
		
		if(accessDatas != null){
			var $blocAccess = $blocHotel.find("div.tAccess");
			$blocAccess.setParam('mainListHotels', this.hotelsOnMap);
			$blocAccess.setParam('accorSite', this.isAccorhotels);
			$blocAccess.processTemplate(accessDatas);
			$blocAccess.addClass("tRequestedOnce");
			$blocAccess.find('.tShowMap').click(function(){
				jQuery("#map").click();
				var rid = jQuery(this).parents(".blocHotel").attr('id');
				
				hotelsUtils.focusMap(rid);						   
			});
			utils.initComplementaryBrandHotelAlert($blocAccess.find("a.tCompBrandHotel"), true);
			utils.initExternalHotelAlert($blocAccess.find("a.tExternalHotel"), true);
		}
	},
	// Fin FONCTIONS LIEES A L'AFFICHAGE DES DONNEES D'ACCES A L'HOTEL
	
	/******/
	/* FONCTIONS LIEES A L'AFFICHAGE DU CALENDRIER 7 JOURS
	/******/
	_callWeekCalendar : function(clickedLink, $blocHotel){
		var $clickedLink = jQuery(clickedLink);
		var $blocCalendar = $blocHotel.find("div.tAvailability");
		var tarsCode = $blocHotel.attr("id");
		
		if(!$blocCalendar.hasClass("tRequestedOnce")){
			var externalHotel = $blocHotel.find("input[name='externalHotel']").val();
			var foreignBrandHotel = $blocHotel.find("input[name='foreignBrandHotel']").val();
			var brandCode = $blocHotel.find("input[name='brandCode']").val();
			$blocCalendar.setTemplateURL("/"+this.lang+"/templates-v66/booking/hotels-list-calendar.tpl");
			
			$blocCalendar.setParam('externalHotel', externalHotel);
			$blocCalendar.setParam('foreignBrandHotel', foreignBrandHotel);
			$blocCalendar.setParam('brandCode', brandCode);
			$blocCalendar.setParam('accorSite', this.isAccorhotels);
			
			if(!hotelsUtils.templateDatas.hotelsCalendar[tarsCode]){
				var currentDate = new Date();
				var searchDate = new Object();
				if(hotelsUtils.mainDatas.search.dayIn !=  null &&
					hotelsUtils.mainDatas.search.monthIn != null &&
					hotelsUtils.mainDatas.search.yearIn != null &&
					hotelsUtils.mainDatas.search.nightNb != null){
					searchDate.day = hotelsUtils.mainDatas.search.dayIn;
					searchDate.month = hotelsUtils.mainDatas.search.monthIn;
					searchDate.year = hotelsUtils.mainDatas.search.yearIn;
					searchDate.nightNb = hotelsUtils.mainDatas.search.nightNb;
					searchDate.calendarDay = searchDate.day;
					searchDate.calendarMonth = searchDate.month;
					searchDate.calendarYear = searchDate.year;
				}
				else{
					searchDate.nightNb=1;
					searchDate.calendarDay = currentDate.getDate();
					searchDate.calendarMonth = currentDate.getMonth()+1;
					searchDate.calendarYear = currentDate.getFullYear();
				}
				var requestInfos = {
					calendarDay : searchDate.calendarDay,
					calendarMonth : searchDate.calendarMonth,
					calendarYear : searchDate.calendarYear,
					dayIn : searchDate.day,
					monthIn : searchDate.month,
					yearIn : searchDate.year,
					nightNb : searchDate.nightNb,					
					adultNumber : hotelsUtils.mainDatas.adultNumber,
					clientDay : currentDate.getDate(),
					clientMonth : currentDate.getMonth()+1,
					clientYear : currentDate.getFullYear(),
					url : new String()
				}
				
				requestInfos.url = $clickedLink.attr("href");
				requestInfos.url += "&planningDate.day="+requestInfos.calendarDay;
				requestInfos.url += "&planningDate.month="+requestInfos.calendarMonth;
				requestInfos.url += "&planningDate.year="+requestInfos.calendarYear;
				if(hotelsUtils.mainDatas.search.dayIn !=  null &&
					hotelsUtils.mainDatas.search.monthIn != null &&
					hotelsUtils.mainDatas.search.yearIn != null)
				{
					requestInfos.url += "&requestedDate.day="+requestInfos.dayIn;
					requestInfos.url += "&requestedDate.month="+requestInfos.monthIn;
					requestInfos.url += "&requestedDate.year="+requestInfos.yearIn;
				}
				requestInfos.url += "&lengthOfStay="+requestInfos.nightNb;
				requestInfos.url += "&clientDate.day="+requestInfos.clientDay;
				requestInfos.url += "&clientDate.month="+requestInfos.clientMonth;
				requestInfos.url += "&clientDate.year="+requestInfos.clientYear;
				requestInfos.url += "&adultNumber="+requestInfos.adultNumber;
				
				$blocCalendar.find("p.tAjaxError").hide();
				$blocCalendar.find("p.tAjaxLoading").show();
				ajaxRequest._executeByUrl(
					requestInfos.url,
					"tAjaxError", 
					"hotelsUtils._processWeekCalendarDatas(errors, response,'"+tarsCode+"')"
				);
			}
			else{
				hotelsUtils._processWeekCalendarDatas(null, hotelsUtils.templateDatas.hotelsCalendar[tarsCode], tarsCode, true);
			}
		}
	},
	
	_processWeekCalendarDatas : function(errors, json, tarsCode, localDatas){
		if(errors && errors.length > 0){
			var $blocHotel = jQuery("div.blocHotel[id='"+tarsCode+"']");
			var $errorField = $blocHotel.find("p.tAjaxError");
			$blocHotel.find("p.tAjaxLoading").hide();
			if(errors.length > 0) $errorField.html(errors.join("<br />")).show();
		}
		else{ 
			var planningDatas = null;
			var $blocHotel = jQuery("div.blocHotel[id='"+tarsCode+"']");
			if(localDatas == true){
				planningDatas = json;
			}
			else if(json && json.viewBeans && json.viewBeans.StayWeekPlanningViewBean){
				planningDatas = json.viewBeans.StayWeekPlanningViewBean;
				hotelsUtils.templateDatas.hotelsCalendar[$blocHotel.attr("id")] = json.viewBeans.StayWeekPlanningViewBean;
			}
			
			if(planningDatas != null){
				var $blocCalendar = $blocHotel.find("div.tAvailability");
				if($blocCalendar.hasClass("tCompBrandHotelCalendar")){
					$blocCalendar.setParam("complementaryBrand", true);
				}
				else{
					$blocCalendar.setParam("complementaryBrand", false);
				}
				$blocCalendar.setParam('mainListHotels', this.hotelsOnMap);
				$blocCalendar.processTemplate(planningDatas);
				var calendarPrices = $blocCalendar.find(".tPrice");
				Currencies._save(calendarPrices);
				Currencies._convert(Currencies.ratesTab.currencies, $myObjects.selectCurrency.val(), calendarPrices);
				hotelsUtils._roundDisplayedPrices(calendarPrices);
				$blocCalendar.find('table.t7DaysTable td:not(.noVacancies)').click(function(){
					hotelsUtils._selectCalendarDates(this);
				});				
				hotelsUtils._writeDatesSummary($blocCalendar, planningDatas.requestedYearIn, planningDatas.requestedMonthIn, planningDatas.requestedDayIn, planningDatas.lengthOfStay);
				popins.attachLinks($blocCalendar.find(".popin"));
				utils.addCurrencyParamToBookLinks($blocCalendar.find("a.tBookLink"), "selectCurrency");
				utils.initComplementaryBrandHotelAlert($blocCalendar.find("a.tCompBrandHotel"), true);
				utils.initExternalHotelAlert($blocCalendar.find("a.tExternalHotel"), true);
				jQuery(".tMonthCalendar").each(function(){
					jQuery(this).data("originUrl", this.href);
					this.href += "&currencyCode=" + $myObjects.selectCurrency.val();
					jQuery(this).data("popin").url = this.href;
				});
				$blocCalendar.addClass("tRequestedOnce");
			}
		}
	},
	
	_selectCalendarDates : function(td){
		var $td = jQuery(td);
		var $table = $td.parents("table");
		$table.find('td.selected').removeClass('selected');
		$table.find('input').prop('checked',false);
		$td.addClass('selected');
		var $input = $td.find('input');
		$input.prop('checked',true);
		hotelsUtils._updateDatesSummary($input);
	},
	
	_updateDatesSummary : function($input){
		var $blocCalendar = $input.parents(".tAvailability");
		var chosenDate = $input.val();
		var lengthOfStay = Number($blocCalendar.find("input[name='lengthOfStay']").val());
		if(chosenDate != ""){
			var yearIn = chosenDate.split("-")[0];
			var monthIn = chosenDate.split("-")[1];
			var dayIn = chosenDate.split("-")[2];
			
			hotelsUtils._writeDatesSummary($blocCalendar, yearIn, monthIn, dayIn, lengthOfStay);
		}
	},
	
	_writeDatesSummary : function($blocCalendar, yearIn, monthIn, dayIn, lengthOfStay){
		if(yearIn != 0 && monthIn != 0 && dayIn != 0){
			$blocCalendar.find("span.dayIn").text(utils.formatDateElement(dayIn));
			$blocCalendar.find("span.monthIn").text(utils.formatDateElement(monthIn));
			$blocCalendar.find("span.yearIn").text(utils.formatDateElement(yearIn));
			
			var arrivalDate = new Date(yearIn, Number(monthIn-1), dayIn, 12, 0, 0);
			var departureDate = new Date();
			departureDate.setTime(arrivalDate.getTime() + (lengthOfStay*3600*24*1000));
			$blocCalendar.find("span.dayOut").text(utils.formatDateElement(departureDate.getDate()));
			$blocCalendar.find("span.monthOut").text(utils.formatDateElement(Number(departureDate.getMonth()+1)));
			$blocCalendar.find("span.yearOut").text(utils.formatDateElement(departureDate.getFullYear()));
			$blocCalendar.find("td.dates").css("visibility", "visible");
			//update Link
			var newBookingLink = $blocCalendar.find("input[name='bookingUrl']").val() + "&search.nightNb=" + lengthOfStay + "&search.dayIn=" + dayIn + "&search.monthIn=" + monthIn + "&search.yearIn=" + yearIn;
			$blocCalendar.find("a.bookingLink").attr("href", newBookingLink);
		}
		else{
			$blocCalendar.find("td.dates").css("visibility", "hidden");
		}
	},
	// Fin FONCTIONS LIEES A L'AFFICHAGE DU CALENDRIER 7 JOURS
	
	/******/
	/* FONCTIONS LIEES A L'AFFICHAGE DE LA GALERIE PHOTOS
	/******/
	_displayGallery : function(clickedLink, blocHotel){
		var $clickedLink = jQuery(clickedLink);
		var $blocHotel = blocHotel;
		var $blocGallery = $blocHotel.find("div.tGallery");
		
		if(!$blocGallery.hasClass("tRequestedOnce")){
			var so = new SWFObject($clickedLink.attr("href"), "galeriePhotos", "632", "280", "8", "#ffffff");
			so.addParam("quality", "best");
			so.addParam("allowScriptAccess", "true");
			so.addParam("wmode", "transparent");
			$blocHotel.find("div.tGalleryDisplayer").each(function(){
				so.write(this);
				$blocGallery.addClass("tRequestedOnce");
			});
		}
	},
	// Fin FONCTIONS LIEES A L'AFFICHAGE DE LA GALLERIE PHOTOS
	
	/******/
	/* FONCTIONS LIEES A LA PAGINATION
	/******/
	_writePager : function(){
		$myObjects.pagerButtons.empty();
		for(var i=0; i < hotelsUtils.totalPages; i++){
			if(hotelsUtils.currentPage != i) $myObjects.pagerButtons.append("<li><a href='#'>"+(i+1)+"</a></li>");
			else $myObjects.pagerButtons.append("<li><span>"+(i+1)+"</span></li>");
		}
		
		if(hotelsUtils.currentPage ==  0){
			$myObjects.pagerFirstPageBut.addClass("disabled");
			$myObjects.pagerPreviousPageBut.addClass("disabled");
		}
		else{
				if($myObjects.pagerFirstPageBut.hasClass("disabled"))$myObjects.pagerFirstPageBut.removeClass("disabled");
				if($myObjects.pagerPreviousPageBut.hasClass("disabled"))$myObjects.pagerPreviousPageBut.removeClass("disabled");
		}
		
		if(hotelsUtils.currentPage ==  hotelsUtils.totalPages-1){
			$myObjects.pagerLastPageBut.addClass("disabled");
			$myObjects.pagerNextPageBut.addClass("disabled");
		}
		else{
				if($myObjects.pagerLastPageBut.hasClass("disabled"))$myObjects.pagerLastPageBut.removeClass("disabled");
				if($myObjects.pagerNextPageBut.hasClass("disabled"))$myObjects.pagerNextPageBut.removeClass("disabled");
		}
		
		jQuery("li.numPage a").click(function(){
			hotelsUtils.currentPage = jQuery(this).text()-1;
			hotelsUtils._doTransition();
			return false;
		});
	},
	
	_doTransition : function(){
		$myObjects.pagers.slideUp("normal");
		$myObjects.loader.css("height", $myObjects.hotelsResultTemplate.height()+"px").fadeIn("normal", function(){
			hotelsUtils._updateTemplate(hotelsUtils.currentPage);
			hotelsUtils._writePager();
			//clearInterval(hotelsUtils.interval);
			//hotelsUtils.interval = setInterval('hotelsUtils._moveToTop()', 10);
			hotelsUtils._moveToTop()
			$myObjects.pagers.slideDown("normal");
			jQuery(this).css("height", $myObjects.hotelsResultTemplate.height()+"px").fadeOut("normal");
		});
	},
	// Fin FONCTIONS LIEES A LA PAGINATION
	
	/******/
	/* FONCTIONS POUR LE SCROLL AUTO
	/******/
	// gere le scroll automatique pour faire remonter la page
	_moveToTop : function(){
		/*var currentScroll = hotelsUtils._getScrollPosition();
		var distance = Math.round(currentScroll / 10);
		if((distance < 10)){
				hotelsUtils._setScrollPosition(0);
				clearInterval(hotelsUtils.interval);
				hotelsUtils.allowClick = true;
		}
		else{hotelsUtils._setScrollPosition(currentScroll - distance);}*/
		hotelsUtils._setScrollPosition(0);
		hotelsUtils.allowClick = true;
	},
	
	_getScrollPosition : function(){
		if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
	},
	
	_setScrollPosition : function(pos){
		window.scrollTo(0,pos);
	},
	// Fin FONCTIONS POUR LE SCROLL AUTO
	
	/******/
	/* FONCTIONS AFFICHAGE CARTO
	/******/
	initMap : function(currency){
		
		// Conversion et formatage de la liste des prix
		var convertedPricesList = new Array();
		var finalPricesList = new String("");
		if(this.pricesListOnMap != null){
			for(i=0; i < this.pricesListOnMap.length; i++){
				if(this.pricesListOnMap[i].amount != 0){
					if($myObjects.selectCurrency.val() != this.pricesListOnMap[i].currency)
						var convertedPrice = Math.round(this.pricesListOnMap[i].amount/ (Currencies.ratesTab.currencies[$myObjects.selectCurrency.val()] / Currencies.ratesTab.currencies[this.pricesListOnMap[i].currency]));
					else
						var convertedPrice = Math.round(this.pricesListOnMap[i].amount);
					
					convertedPricesList.push(convertedPrice);
				}
				else
					convertedPricesList.push("NA");
			}
			
			finalPricesList = convertedPricesList.join("|");
		}
		// Fin
		
		// Stockage de l'ordre initial des hotels envoyés à B_list
		var tmpRidList = hotelsUtils.hotelsOnMap.split("|");
		var tmpStatusList = hotelsUtils.hotelsAvailabilityOnMap.split("|");
		this.hotelsOnMapOrder = new Object();
		for(i=0; i<tmpRidList.length; i++){
			this.hotelsOnMapOrder[tmpRidList[i]] = tmpStatusList[i];
		}
		
		$myObjects.mapContainer.empty();
		var mapLang = jQuery("html").attr("lang");
		var so = new SWFObject("/flash/booking/carto/listehotel.swf", "listehotel", "672", "517", "10", "#ffffff");
		if(typeof this.mainDatas.hotel != "undefined" && this.mainDatas.hotel != null && this.mainDatas.hotel.tarsCode != ""){
			so.addVariable("PB_start", this.mainDatas.hotel.tarsCode);
			hotelsUtils.hotelsOnMap += "|"+this.mainDatas.hotel.tarsCode;
			hotelsUtils.hotelsAvailabilityOnMap += "|0";
		}
		so.addParam("quality", "best");
		so.addParam("allowScriptAccess", "always");
		//so.addParam("wmode", "transparent");
		so.addVariable("PB_list", hotelsUtils.hotelsOnMap);
		so.addVariable("PB_free", hotelsUtils.hotelsAvailabilityOnMap);
		so.addVariable("siteOrigine", this.maporamaSiteOrigin);
		so.addVariable("Lang", mapLang);
		so.addVariable("Search", "List");
		so.addVariable("DNS", "http://accor.maporama.com/idl/"+this.maporamaDirectory+"/");		
		
		
		// passage du param de la devise
		if(currency != null || currency != "undefined") so.addVariable("Currency", currency);
		
		// si des prix la LH a des prix, on passe le param à la carte
		if(finalPricesList != "") so.addVariable("PB_price", finalPricesList);
		
		// passage du param pr contextualiser la mention prix en fct du nb de nuit
		if(this.searchCriteriaViewBean && this.searchCriteriaViewBean.period != null){
			if(this.searchCriteriaViewBean.period.nbDay == 1 || this.searchCriteriaViewBean.period.nbDay >= 4)
				so.addVariable("PB_nights", 1);
			else
				so.addVariable("PB_nights", 2);
		}
		// Fin
		
		// passage param pr contextualiser la legende sous la carte selon recherche GP ou rated
		if(this.mainDatas.rateSearch == true) so.addVariable("PB_rates", 2);
		else so.addVariable("PB_rates", 1);
		$myObjects.mapContainer.each(function(){
			so.write(this);
		});
		hotelsUtils.mapDisplayed = true;
	},
	
	tryFocusMap : function(ridHotel){
		if(hotelsUtils.retryFocus == true){
			try{
				hotelsUtils.retryFocus = false;
				document.getElementById("listehotel").focusHotel(ridHotel);
			}
			catch(e){
				hotelsUtils.retryFocus = true;
			}
		}
		else{
			clearInterval(hotelsUtils.intervalMap);
			hotelsUtils.retryFocus = true;
		}
	},
	
	focusMap : function(ridHotel){
		if(ridHotel && ridHotel != ""){
			// éviter l'empilement d'appels vers la carte
			if (hotelsUtils.intervalMap) {
				clearInterval(hotelsUtils.intervalMap);
			}
			hotelsUtils.intervalMap = setInterval(function(){hotelsUtils.tryFocusMap(ridHotel)}, 500);
		}
	},
	
	displayHotelFromMap : function(rid, tab){
		
		if(this.hotelsRefTab[rid] != undefined){ // si on est sur la liste hotel (vs page recherche alternative dispo)
			if(this.hotelsRefTab[rid] != this.currentPage){
				this.currentPage = this.hotelsRefTab[rid];
				this._updateTemplate(this.currentPage);
				this._writePager();
			}
		}
		document.location.href = "#"+rid;
		if(tab == "description")jQuery("#"+rid).find("a.params-tDescription").click();
		else if(tab == "photos")jQuery("#"+rid).find("a.params-tGallery").click();
	},
	
	compareHotelFromMap : function(rid){
		var datas = {
        modal: true,
        drag: false,
        redim: false,
        iframe: false,
        ajax: false,
        width: 280,
        height: null,
        type: "alert",
        ref: "search"
    };
		
		if(jQuery.inArray(rid, this.hotelToCompare) == -1){
			
			if(this.hotelToCompare.length >= this.mainDatas.maxComparableHotels){
				jQuery("div.search p, div.search div.btn").hide();
				popins.openPopin(jQuery('div.' + datas.ref), datas);
				jQuery("#tComparisonTooManyHotels").find("span.maxComparableHotels").text(this.mainDatas.maxComparableHotels);
				jQuery("#tComparisonTooManyHotels, #comparisonPopinButtons").show();
			}
			else{

				this.hotelToCompare.push(rid);
				if(jQuery("#"+rid).length >= 1){
					jQuery("#"+rid).find(":checkbox").prop("checked", true);
				}
			}
		}
		else{
			this.hotelToCompare = jQuery.grep(this.hotelToCompare, function (a) { return a != rid; });

			
			if(jQuery("#"+rid).length >= 1){
				jQuery("#"+rid).find(":checkbox").prop("checked", false);
			}
		}

		this.updateComparisonButtonsLink();
	},
	
	tryUpdateHotelAvailabilityOnMap : function(ridList){
		if(hotelsUtils.retryUpdate == true){
			try{
				hotelsUtils.retryUpdate = false;					
				document.getElementById("listehotel").updateHotelFree(ridList.join("|"));
			}
			catch(e){
				hotelsUtils.retryUpdate = true;
			}
		}
		else{
			clearInterval(hotelsUtils.intervalMapAvailability);
			hotelsUtils.retryUpdate = true;
		}
	},
	
	_updateHotelAvailabilityOnMap : function(){
		if(this.mapDisplayed == true && this.hotelsOnMapOrder != null && this.isMapOn == true){
			var newAvailabilityList = new Array();
			
			for(var i in this.hotelsOnMapOrder){
				newAvailabilityList.push(this.hotelsOnMapOrder[i]);
			}	
			// éviter l'empilement d'appels vers la carte
			if (hotelsUtils.intervalMapAvailability) {
				clearInterval(hotelsUtils.intervalMapAvailability);
			}
			hotelsUtils.intervalMapAvailability = setInterval(function(){hotelsUtils.tryUpdateHotelAvailabilityOnMap(newAvailabilityList)}, 500);
		}
	},
	
	// FONCTIONS AFFICHAGE CARTO
	
	/******/
	/* FONCTIONS DIVERSES
	/******/	
	_getDetailsLinksParams : function(link){
		var $link = jQuery(link);
		var exp;

		if (null != (exp = /params-(\w+)/i.exec($link.attr("class"))) ) {
			return exp[1];
		}
		else return null;
	},
	
	_resetCategorizedArrays : function(){
		for(var tab in this.brandHotels){
			if(tab != "hotelsKO") this.brandHotels[tab] = new Array();
		}
		for(var tab in this.complementaryBrandHotels){
			if(tab != "hotelsKO") this.complementaryBrandHotels[tab] = new Array();
		}
	}
}
