/** 
 * Objet javascript permettant de gerer les donnees d'affichage
 * du de la liste hotels.
 */

var HotelsList = {
    bookingEngineViewBean: null,
    activityViewBean: null,
    leisureGroupBookingEngineViewBean: null,
    rfpCriteriaViewBean: null,
    originViewBean: null,
    hotelSelectorViewBean: null,
    hotelsViewBean: null,
    bookOnlineHotels: new Array(),
    bookOnlineSelectedHotels: 0,
    rfpOnlineSelectedHotels: 0,
    rfpOfflineSelectedHotels: 0,
    
    /**
    * Liste des noms d'objets a utiliser.
    */
    getBeans: function()
    {
      return "BookingEngineViewBean;ActivityViewBean;LeisureGroupBookingEngineViewBean;"
            +"RfpCriteriaViewBean;OriginViewBean;HotelSelectorViewBean;HotelsViewBean";
    },
      
    /**
    * Initialisation/Mise a jour de la variable JSON
    */
    initJSON: function()
    {
        var num;
        try {
            for( num in beans)
            {
                // A cause de prototype, il ne faut recuperer que nos objet et pas ceux de prototype.
                if(beans.hasOwnProperty(num)) {
                    if("BookingEngineViewBean" == beans[num].nom && null != beans[num].bean)
                        this.bookingEngineViewBean = beans[num].bean;
                        
                    if("ActivityViewBean" == beans[num].nom && null != beans[num].bean) 
                        this.activityViewBean = beans[num].bean;
                      
                    if("LeisureGroupBookingEngineViewBean" == beans[num].nom && null != beans[num].bean) 
                        this.leisureGroupBookingEngineViewBean = beans[num].bean;

                    if("RfpCriteriaViewBean" == beans[num].nom && null != beans[num].bean) 
                        this.rfpCriteriaViewBean = beans[num].bean;
                        
                    if("OriginViewBean" == beans[num].nom && null != beans[num].bean) 
                        this.originViewBean = beans[num].bean;

                    if("HotelSelectorViewBean" == beans[num].nom && null != beans[num].bean) 
                        this.hotelSelectorViewBean = beans[num].bean;

                    if("HotelsViewBean" == beans[num].nom && null != beans[num].bean) 
                        this.hotelsViewBean = beans[num].bean;
                }
            }
        }
        catch(e)
        {
            //console.log(e);
            //alert(e);
        }
    },
    
    rewrite: function() {
        // Ecrit l'intro et le bloc de tri (gere dans hotelsSort.js)
        //this.triInit();
        // L'iframe est agrandit à la taille de la page intérieure.
        this.adaptIframeSize("iframe_liste_hotel");
        // Reecriture des informations moteur de reservation (partie groupe loisir)
        if(this.hotelsViewBean.context == "leasureGroup"){
        	this.buildLeisureGroupBookingEngineView(this.leisureGroupBookingEngineViewBean);
      	}
        // Gestion de la selection des hotels
        this.rewriteSelection();
        // reecriture des urls d'elargissement de la recherche geo.
        this.rewriteEnlargeSearch();
        
        this.attachCalendarPopin();
        this.rewriteResaButtonLink();
        
        // On observe le rechargement lors du changement de page.
        Event.observe(
            $("iframe_liste_hotel"),
            "load",
            function() {
                HotelsList.adaptIframeSize("iframe_liste_hotel");
                // Reecriture des informations moteur de reservation (partie groupe loisir)
                if(HotelsList.hotelsViewBean.context == "leasureGroup"){
				        	HotelsList.buildLeisureGroupBookingEngineView(HotelsList.leisureGroupBookingEngineViewBean);
				      	}
                // Gestion de la selection des hotels
                HotelsList.rewriteSelection();
                // reecriture des urls d'elargissement de la recherche geo.
                HotelsList.rewriteEnlargeSearch();
                
                HotelsList.attachCalendarPopin();
                HotelsList.rewriteResaButtonLink();
        });
        
        // Ecrit le chemin de fer
        this.writeHeader();
        
        // Handling legend block
        /*if(this.bookingEngineViewBean.nightsNumber > 1 && this.hotelsViewBean.context == "thalassa"){
        	$('div_legende').style.display = "block";
        }*/
        
        
        if(this.hotelsViewBean.context != "meetingBookOnline"){
        	this.buildBookingEngineView(this.bookingEngineViewBean, this.activityViewBean, this.hotelsViewBean);
      	}
      	
      	if(this.hotelsViewBean.context == "rfp" || this.hotelsViewBean.context == "leasureGroup"
      			|| this.hotelsViewBean.context == "advantagePlus" || this.hotelsViewBean.context == "accorAdvantagePlus")
      	{
      		this.buildContextNewSearchView(this.bookingEngineViewBean, this.hotelsViewBean);
      	}
      	else if(this.hotelsViewBean.context == "thalassa"){
      		this.buildThalassaNewSearchView(this.bookingEngineViewBean, this.hotelsViewBean);
      		/*if($('div_legende').style.display == "block"){
      			var tr_thalassa = $('div_legende').select('tr.thalassa')[0];
      			if(tr_thalassa) tr_thalassa.style.display = "";
      		}*/
      	}
      	else{
      		this.buildDefaultNewSearchView(this.bookingEngineViewBean, this.hotelsViewBean);
      	}
    },
    
    /**
     * Gestion de la selection des hotels (appelle sur le load de LH et sur MAJ selection)
     * Reset les input et pour donner un aquittement
     */
    rewriteSelection:function() {
        var LHframe = $("iframe_liste_hotel");
        
        
        
    	if (LHframe && LHframe.contentWindow.document.forms["compareHotels"]) {
    		var nbProducts = 0;
    		var minSelectedForComparison = 1;
    		var compareInputs = LHframe.contentWindow.document.getElementsByName("comp");
            // cochage des hôtels selectionnes.
    		if (this.hotelSelectorViewBean && this.hotelSelectorViewBean.products && compareInputs) {
    			minSelectedForComparison = this.hotelSelectorViewBean.minSelected;
    			var products = this.hotelSelectorViewBean.products;
    			nbProducts = products.length;
    			
    			// on remet a zero les compteurs, car le script passe toujours par ici.
    			this.rfpOfflineSelectedHotels = this.hotelSelectorViewBean.rfpOfflineHotelsNb;
    			this.rfpOnlineSelectedHotels = this.hotelSelectorViewBean.rfpOnlineHotelsNb;
    			this.bookOnlineSelectedHotels = this.hotelSelectorViewBean.meetingOnlineHotelsNb;
    			this.userSelectBookOnline();
    			
    			for (var i=0 ; i < compareInputs.length ; i++) {
    				for (var j=0 ; j < nbProducts ; j++) {
    				    compareInputs[i].checked = (products[j]==compareInputs[i].id);
    				    if (compareInputs[i].checked) {
    						break;
    					}
    				}
    			}
    		}
    
    		if(this.leisureGroupBookingEngineViewBean)
    			this.enableCompareButton(LHframe.contentWindow.document, nbProducts >= minSelectedForComparison, "leisureGroup");
    	  else if(this.hotelsViewBean.context == "meetingBookOnline") 
    	    this.enableCompareButton(LHframe.contentWindow.document, nbProducts >= minSelectedForComparison, "meetingBookOnline");
    		else {
    			this.enableCompareButton(LHframe.contentWindow.document, nbProducts >= minSelectedForComparison, "default");  			  
  			  if(LHframe.contentWindow.document.getElementById('s_devise') &&
  			  LHframe.contentWindow.document.getElementById('s_devise').nodeName == 'SELECT') {
  			 	  Currencies.registerEverythingFromPage(Currencies.CrtCurrency);
		 		    Currencies.observeSelect(LHframe.contentWindow.document.getElementById('s_devise')) ;
		 		  }
  			}
  		}
    },
    
    /**
     * Changement d etat sur l id d'hotel (selectionne / deselectionne)
     */
    userChangedSelection: function(id) {
    	var LHframe = $("iframe_liste_hotel");
    	if (LHframe && id){
    		var e = LHframe.contentWindow.document.getElementById(id);
    		if (this.hotelSelectorViewBean
    				&& this.hotelSelectorViewBean.products
    				&& this.originViewBean
    				&& (this.hotelSelectorViewBean.products.length >= this.hotelSelectorViewBean.maxSelected)
    				&& e
    				&& e.checked) {
    			alert(I18N.getFormatedText("hotels.list","You may select a maximum", this.hotelSelectorViewBean.maxSelected));
    			this.rewriteSelection();
    		} else {
    		    // la mise a jour reecrit la page appel a rewrite depuis rewriteView
    		    updateView("hotelSelector", "hotelSelector", "id=" + id + "&beans=OriginViewBean;HotelSelectorViewBean;LeisureGroupBookingEngineViewBean");
    		}
    	}
    },
    
    buildBookingEngineView : function(bookingEngineViewBean, activityViewBean, hotelsViewBean){
			if(bookingEngineViewBean){
				var e = document.getElementById("destination");
				if(bookingEngineViewBean.destination && e && ( (e.tagName).toUpperCase()=='SPAN' || (e.tagName).toUpperCase()=='DIV')){
					document.getElementById("destination").innerHTML=bookingEngineViewBean.destination;
				}
				if(activityViewBean){
					if(activityViewBean.secondActivityLabel && activityViewBean.secondActivityLabel!=activityViewBean.firstActivityLabel){
						if(document.getElementById("doubleActivityLabel") && activityViewBean.firstActivityLabel)
							document.getElementById("doubleActivityLabel").innerHTML=activityViewBean.firstActivityLabel+" & "+activityViewBean.secondActivityLabel;			
						if(document.getElementById("doubleActivityBlock"))				
							document.getElementById("doubleActivityBlock").style.display="block";					
					} else {
						if(document.getElementById("singleActivityLabel") && activityViewBean.firstActivityLabel)
							document.getElementById("singleActivityLabel").innerHTML=activityViewBean.firstActivityLabel;			
						if(document.getElementById("singleActivityBlock"))				
							document.getElementById("singleActivityBlock").style.display="block";						
					}
					
					if(document.getElementById("recipientLabel") && activityViewBean.recipientLabel)
						document.getElementById("recipientLabel").innerHTML=activityViewBean.recipientLabel;
		
					if(document.getElementById("packageActivityBlock") && activityViewBean.firstActivityLabel!=null && activityViewBean.recipientLabel!=null)
						document.getElementById("packageActivityBlock").style.display="block";
		
					if(document.getElementById("packageDateIn"))
						document.getElementById("packageDateIn").innerHTML=bookingEngineViewBean.dayIn+"/"+bookingEngineViewBean.monthIn+"/"+bookingEngineViewBean.yearIn;
					if(document.getElementById("packageDateOut"))
						document.getElementById("packageDateOut").innerHTML=bookingEngineViewBean.dayOut+"/"+bookingEngineViewBean.monthOut+"/"+bookingEngineViewBean.yearOut;
		
					if(document.getElementById("packageStayDateBlock"))
						document.getElementById("packageStayDateBlock").style.display="block";
				} else {
		
					if(bookingEngineViewBean.dayIn){
						if(document.getElementById("dateIn"))
							document.getElementById("dateIn").innerHTML=bookingEngineViewBean.dayIn+"/"+bookingEngineViewBean.monthIn+"/"+bookingEngineViewBean.yearIn;
						if(bookingEngineViewBean.nightsNumber){
							if(bookingEngineViewBean.nightsNumber==1 && document.getElementById("singleNightBlock")){
								document.getElementById("singleNightBlock").style.display="block";
							} else if(document.getElementById("severalNightNumber")){
								document.getElementById("severalNightNumber").innerHTML=bookingEngineViewBean.nightsNumber;
								if(document.getElementById("severalNightBlock"))
									document.getElementById("severalNightBlock").style.display="block";
							}
						}
						if(document.getElementById("stayDateBlock"))
							document.getElementById("stayDateBlock").style.display="block";
					}
				}
				
				if(hotelsViewBean.ridSearch == true) {
						if(hotelsViewBean.ridSearch){
							if($('nbRid')) $('nbRid').innerHTML = hotelsViewBean.hotelsNumber; 
							$('ridBlock').style.display = "block";
							$('ridLinkBlock').style.display = "block";
							$('destinationBlock').style.display="none";
							if(hotelsViewBean.hotelsNumber == 0 && $('no_result_multirid')) $('no_result_multirid').style.display ="block";  
						}
						else{
							document.getElementById("destinationBlock").style.display="none";
						}
				}

				if(bookingEngineViewBean.companyReserverName && document.getElementById("companyReserverBlock")){
					document.getElementById("companyReserverBlock").style.display="block";
					document.getElementById("companyReserverName").innerHTML=bookingEngineViewBean.companyReserverName;
				} else if(bookingEngineViewBean.agencyReserverName && document.getElementById("agencyReserverBlock")){
					document.getElementById("agencyReserverBlock").style.display="block";
					document.getElementById("agencyReserverName").innerHTML=bookingEngineViewBean.agencyReserverName;
				}
		
				if(bookingEngineViewBean.preferentialCode && document.getElementById("preferentialCodeBlock")){
					document.getElementById("preferentialCodeBlock").style.display="block";
					document.getElementById("preferentialCode").innerHTML=bookingEngineViewBean.preferentialCode;
				}
		
				if(bookingEngineViewBean.searchLabels && document.getElementById("searchLabelBlock")){
					document.getElementById("searchLabelBlock").style.display="block";
					document.getElementById("searchLabel").innerHTML=bookingEngineViewBean.searchLabels;
				}
		
				if(bookingEngineViewBean.fidelityCardName && document.getElementById("fidelityCardBlock")){
					document.getElementById("fidelityCardBlock").style.display="block";
					document.getElementById("fidelityCardName").innerHTML=bookingEngineViewBean.fidelityCardName;
				}
			}
		},
		
		buildContextNewSearchView : function(bookingEngineViewBean, hotelsViewBean){
			if(bookingEngineViewBean && hotelsViewBean && $('newSearch_context')){
				var linkSearch = $('newSearch_context').select('a')[0];
				if(linkSearch) linkSearch.href=bookingEngineViewBean.newSearchUrl;
				
				if(hotelsViewBean.context == "rfp"){
					if(linkSearch)linkSearch.addClassName('btgdrouge_promice');
				}
				else{
					if(linkSearch) linkSearch.addClassName('btgdvert_promice');
				}
				$('newSearch_context').show();
			}
		},
		
		buildThalassaNewSearchView : function(bookingEngineViewBean, hotelsViewBean){
			if(bookingEngineViewBean && hotelsViewBean){
				var linkSearch = $('newSearch_thalassa').select('a')[0];
				if(linkSearch) linkSearch.href=bookingEngineViewBean.newSearchUrl;
				
				$('newSearch_thalassa').show();
			}
		},
		
		buildDefaultNewSearchView : function(bookingEngineViewBean, hotelsViewBean){
			if(bookingEngineViewBean && hotelsViewBean && $('newSearch_global')){
							
				if($('jour_arrivee')){
					var index = 0;
					var selectIndex = -1;
				
					$('jour_arrivee')[index++]=new Option("-", "");
				
					for(var i=1; i< 31+1; i ++){
						$('jour_arrivee').options[index] = new Option(i,i);
						index++;
					}
				}
				
				if($('mois_arrivee')){
					var index = 0;
					var selectIndex = -1;
				
					$('mois_arrivee')[index++]=new Option("-", "");
				
					for(var i=1; i< 12+1; i ++){
						$('mois_arrivee').options[index] = new Option(i,i);
						index++;
					}
				}
				
				var today = new Date();
				var maxDate = new Date(today.getTime() + bookingEngineViewBean.maxPeriod * 24 * 60 * 60 * 1000);
				
				if($('annee_arrivee')){
					var index = 0;
					var selectIndex = -1;
				
					$('annee_arrivee')[index++]=new Option("-", "");
				
					for(var i=today.getFullYear(); i< maxDate.getFullYear()+1; i ++){
						$('annee_arrivee').options[index] = new Option(i,i);
						index++;
					}
				}
				
				if($('nb_nuit')){
					var index = 0;
					var selectIndex = -1;
				
					$('nb_nuit')[index++]=new Option("-", "");
				
					for(var i=1; i< bookingEngineViewBean.maxStay+1; i ++){
						$('nb_nuit').options[index] = new Option(i,i);
						index++;
					}
				}
				
				this.updateNewSearchBookingEngine(bookingEngineViewBean);
				
				$('newSearch_global').show();
			}
		},
		
		updateNewSearchBookingEngine : function(bookingEngineViewBean){
			if(bookingEngineViewBean){
				if(document.getElementById('nom_ville') && bookingEngineViewBean.destination)
					document.getElementById('nom_ville').value = bookingEngineViewBean.destination;

				if(document.getElementById('jour_arrivee') && (document.getElementById('jour_arrivee').tagName).toUpperCase()=='SELECT'
					&& document.getElementById('mois_arrivee') && (document.getElementById('mois_arrivee').tagName).toUpperCase()=='SELECT'
					&& document.getElementById('annee_arrivee')  && (document.getElementById('annee_arrivee').tagName).toUpperCase()=='SELECT'
					&& bookingEngineViewBean.dayIn && bookingEngineViewBean.monthIn && bookingEngineViewBean.yearIn){
					document.getElementById('jour_arrivee').selectedIndex = bookingEngineViewBean.dayIn;
					document.getElementById('mois_arrivee').selectedIndex = bookingEngineViewBean.monthIn;
					for(i=0; i<document.getElementById('annee_arrivee').options.length; i++){
						if(document.getElementById('annee_arrivee').options[i].value == bookingEngineViewBean.yearIn){
							document.getElementById('annee_arrivee').selectedIndex = i;
						}
					}
				}
				
				if(document.getElementById('nb_nuit') && (document.getElementById('nb_nuit').tagName).toUpperCase()=='SELECT' && bookingEngineViewBean.nightsNumber && bookingEngineViewBean.nightsNumber != 0){
					document.getElementById('nb_nuit').selectedIndex = bookingEngineViewBean.nightsNumber;
				}
				
				
				// variables necessaires a dateresa.js : d_maxPeriod, d_contextGeo, d_stayDates, d_imagePath
				d_maxPeriod = this.bookingEngineViewBean.maxPeriod;
				d_contextGeo = this.hotelsViewBean.context;
				if(HotelsList.bookingEngineViewBean.dayIn != null && HotelsList.bookingEngineViewBean.monthIn != null && HotelsList.bookingEngineViewBean.yearIn != null){
					d_stayDates = {
						dayIn : HotelsList.bookingEngineViewBean.dayIn,
						monthIn : HotelsList.bookingEngineViewBean.monthIn,
						yearIn : HotelsList.bookingEngineViewBean.yearIn,
						nbNights : HotelsList.bookingEngineViewBean.nightsNumber
					};
				}
				
				d_imagePath = HotelsList.originViewBean.codeLangDirectory;
			}
		},
    
    /**
     * Affichage des donnees du moteur de reservation pour le groupe loisir
     */
    buildLeisureGroupBookingEngineView:function(leisureGroupBookingEngineViewBean){
    	if(leisureGroupBookingEngineViewBean){
    		if(document.getElementById("leisureGroupBlock")){
    			document.getElementById("leisureGroupBlock").style.display="block";
    
    			if(leisureGroupBookingEngineViewBean.singleRoomNumber>0 && document.getElementById("singleRoomBlock")){
    				document.getElementById("singleRoomBlock").style.display="block";
    				document.getElementById("singleRoomNumber").innerHTML=leisureGroupBookingEngineViewBean.singleRoomNumber;
    			}
    
    			if(leisureGroupBookingEngineViewBean.doubleRoomNumber>0 && document.getElementById("doubleRoomNumber")){
    				document.getElementById("doubleRoomBlock").style.display="block";
    				document.getElementById("doubleRoomNumber").innerHTML=leisureGroupBookingEngineViewBean.doubleRoomNumber;
    			}
    
    			if(leisureGroupBookingEngineViewBean.twinRoomNumber>0 && document.getElementById("twinRoomBlock")){
    				document.getElementById("twinRoomBlock").style.display="block";
    				document.getElementById("twinRoomNumber").innerHTML=leisureGroupBookingEngineViewBean.twinRoomNumber;
    			}
    
    			if(leisureGroupBookingEngineViewBean.tripleRoomNumber>0 && document.getElementById("tripleRoomBlock")){
    				document.getElementById("tripleRoomBlock").style.display="block";
    				document.getElementById("tripleRoomNumber").innerHTML=leisureGroupBookingEngineViewBean.tripleRoomNumber;
    			}
    
    			if(leisureGroupBookingEngineViewBean.quadrupleRoomNumber>0 && document.getElementById("quadrupleRoomBlock")){
    				document.getElementById("quadrupleRoomBlock").style.display="block";
    				document.getElementById("quadrupleRoomNumber").innerHTML=leisureGroupBookingEngineViewBean.quadrupleRoomNumber;
    			}
    
    			if(leisureGroupBookingEngineViewBean.tourReference && document.getElementById("tourReferenceBlock")){
    				document.getElementById("tourReferenceBlock").style.display="block";
    				document.getElementById("tourReference").innerHTML=leisureGroupBookingEngineViewBean.tourReference;
    			}
    		}
    	}
    },
    
    /**
     * Affichage des message d'erreur dans la page de gestion des tris.
     */
    /*rewriteHotelsSortBlock:function() {
        if(this.hotelsViewBean.hotelsNumber > 0) {
            // variable pour gerer l'affichage du mot hôtel au singulier ou au pluriel.
            var plural = false
    		if (this.hotelsViewBean.hotelsNumber>1) {
    		    plural = true;
    		}
    		    
    	    var destination = this.bookingEngineViewBean.destination;
    	    var widdenDestination = this.hotelsViewBean.widdenDestination;
    		if(typeof(widdenDestination)!="undefined" && widdenDestination!=""){
    			if (this.hotelsViewBean.ridSearch) {
    			    var element = document.getElementById('noHotelsFound');
    			    element.style.display="block";
    			} else {
    			    var element = document.getElementById('NoHotelsButWidden');
    			    element.style.display="block"
    			    element.select('span.destination').innerHTML = destination;
    			    element.select('span.hotelsNumber').innerHTML = this.hotelsViewBean.hotelsNumber;
    			    element.select('span.widdenDestination').innerHTML = widdenDestination;
    			    this.displayWordSingularPlural(element, plural);
    			}
    		}
    		else
    		    {
    			
    			if (this.hotelsViewBean.ridSearch) {
    			    var element = document.getElementById('hotelsNumber');
    			    element.style.display="block"
    			    element.select('span.hotelsNumber').innerHTML = this.hotelsViewBean.hotelsNumber;
    				this.displayWordSingularPlural(element, plural);
    			} else {
    			    var element = document.getElementById('hotelsNumber');
    			    element.style.display="block"
    			    element.select('span.hotelsNumber').innerHTML = this.hotelsViewBean.hotelsNumber;
    				if (this.hotelsViewBean.thalassa!=null){
    					destination = destination + ' - '+this.hotelsViewBean.thalassa.spaName;
    				}
    			    element.select('span.destination').innerHTML = destination;
    				this.displayWordSingularPlural(element, plural);
    			}
    		}
    	}
    },*/
    
    /**
     * gestion de l'affichage d'un même mot en plurier ou singuler
     */
    displayWordSingularPlural: function(element, plural) {
        if(plural) {
            element.select('span.plural').style.display="inline";
            element.select('span.singular').style.display="none";
        }
        else {
            element.select('span.plural').style.display="none";
            element.select('span.singular').style.display="inline";
        }
    },
    
    /**
     * Gestion des liens d'elargissement de la recherche geographique.
     */
    rewriteEnlargeSearch: function() {
        var urlEnlargeSearch     = "/rechercheGeographique.svlt?search_mode=2&alternative_search=1&nom_ville=" + this.bookingEngineViewBean.destination;
        var urlEnlargeRateSearch = "/rechercheGeographique.svlt?pro_search_mode=2&nom_ville=" + this.bookingEngineViewBean.destination;
        var urlRateSearch = "/rechercheGeographique.svlt?pro_search_mode=1&nom_ville=" + this.bookingEngineViewBean.destination;
        if(this.bookingEngineViewBean.dayIn && this.bookingEngineViewBean.monthIn && this.bookingEngineViewBean.yearIn && this.bookingEngineViewBean.nightsNumber) {
            var urlStayDatesPart = '&jour_arrivee=' + this.bookingEngineViewBean.dayIn;
            urlStayDatesPart += '&mois_arrivee=' + this.bookingEngineViewBean.monthIn;
            urlStayDatesPart += '&annee_arrivee=' + this.bookingEngineViewBean.yearIn;
            urlStayDatesPart += '&nb_nuit=' + this.bookingEngineViewBean.nightsNumber;
            urlEnlargeSearch += urlStayDatesPart;
            urlEnlargeRateSearch += urlStayDatesPart;
            urlRateSearch+=urlStayDatesPart;
        }
        if (document.getElementById('enlarge_search'))
            document.getElementById('enlarge_search').href=urlEnlargeSearch;
        
        if (document.getElementById('enlarge_search_codePref'))
            document.getElementById('enlarge_search_codePref').href=urlEnlargeSearch;
        
        if (document.getElementById('enlarge_search_pro'))
            document.getElementById('enlarge_search_pro').href=urlEnlargeSearch;
        
        if (document.getElementById('enlarge_rate_search'))
            document.getElementById('enlarge_rate_search').href=urlEnlargeRateSearch;
    
        if(1 == this.hotelsViewBean.geoSearchProMode)
            if (document.getElementById('bloc_lien_autres_tarifs')){
                document.getElementById('bloc_lien_autres_tarifs').style.display="block";
                document.getElementById('lien_autres_tarifs').href=urlEnlargeRateSearch;
            }
    
        if(2 == this.hotelsViewBean.geoSearchProMode)
        if (document.getElementById('bloc_lien_tarifs_pro')){
            document.getElementById('bloc_lien_tarifs_pro').style.display="block";
            document.getElementById('lien_tarifs_pro').href=urlRateSearch;
        }
    },
    
    /**
     * Desactiver / activer le bouton de comparaison
     */
    enableCompareButton:function(element, value, context) {
        try { // ne pas enlever (les boutons peut ne pas etre present sur la page)
    	  var topButton = element.getElementById("compareButtonTop");
    		var bottomButton = null;
    		if(element.getElementById("compareButtonDown"))
    		    bottomButton = element.getElementById("compareButtonDown");
    		if (value) {
    				topButton.onmouseover=	function() {this.style.cursor='pointer'};
    				topButton.onclick=function() {parent.HotelsList.submitCompare();};
    				if(bottomButton) {
        				bottomButton.onmouseover=	function() {this.style.cursor='pointer'};
        				bottomButton.onclick=function() {parent.HotelsList.submitCompare();};
    				}
    				    
    		} else {
    				topButton.onmouseover=	function() {this.style.cursor='pointer'};
    				topButton.onclick=function() {};
    				if(bottomButton) {
        				bottomButton.onmouseover=	function() {this.style.cursor='pointer'};
        				bottomButton.onclick=function() {};
    				}
    		}
            var lang = this.originViewBean.codeLangDirectory;
    				var buttonPath = "/"+lang+"/images/reservation/";
    		
    		if(context=="leisureGroup") {
    			var alertCompareLG=new Array();
    			if (value){
    				topButton.src =  buttonPath + "comparez-haut-groupe.gif";
    				if(null != bottomButton)
    				    bottomButton.src = buttonPath + "comparez-bas-groupe.gif";
    			}else {
    				topButton.onclick=function(){alert(I18N._("hotels.list","You have to select at least"));};
    				topButton.src =  buttonPath + "comparez-haut-groupe.gif";
    				if(null != bottomButton)
    				    bottomButton.src = buttonPath + "comparez-bas-groupe.gif";
    			}
    			topButton.alt = I18N.getFormatedText("hotels.list", "You may select up to", this.hotelSelectorViewBean.maxSelected);
                topButton.title = I18N.getFormatedText("hotels.list", "You may select up to", this.hotelSelectorViewBean.maxSelected);
                if(null != bottomButton) {
    			    bottomButton.alt = I18N.getFormatedText("hotels.list", "You may select up to", this.hotelSelectorViewBean.maxSelected);
                    bottomButton.title = I18N.getFormatedText("hotels.list", "You may select up to", this.hotelSelectorViewBean.maxSelected);
                }
    		} 
    		else if (context=="meetingBookOnline") {
    			// context "meetingBookOnline"
    			topButton.alt = I18N._("hotels.list", "Compare");
    			topButton.title = I18N._("hotels.list", "Compare");
    			if (value) {
    			    //topButton.onclick=function(){};
    				//topButton.src =  buttonPath + "comparez-haut.gif";
    				//if(null != bottomButton)
    				//    bottomButton.src = buttonPath + "comparez-bas.gif";
    			} else {
    				topButton.onclick=function(){alert(I18N._("hotels.list", "You should select at least to make a comparison"));};
    				if(null != bottomButton)
    				    bottomButton.onclick=function(){alert(I18N._("hotels.list", "You should select at least to make a comparison"));};
    			}
    		}
    		else {
    			// context "default"
    			topButton.alt = I18N._("hotels.list", "Compare");
    			topButton.title = I18N._("hotels.list", "Compare");
    			if (value) {
    				topButton.src =  buttonPath + "comparez-haut.gif";
    				if(null != bottomButton)
    				    bottomButton.src = buttonPath + "comparez-bas.gif";
    			} else {
    				topButton.onclick=function(){alert(I18N._("hotels.list", "You should select at least to make a comparison"));};
    				topButton.src =  buttonPath + "comparez-haut.gif";
    				if(null != bottomButton)
    				    bottomButton.src = buttonPath + "comparez-bas.gif";
    			}
    		}
    
    		if(null != bottomButton) {
    		    bottomButton.onmouseover = topButton.onmouseover;
        		bottomButton.onclick = topButton.onclick;
        		bottomButton.alt = topButton.alt;
        		bottomButton.title = topButton.title;
    	    }
    
    	} catch (e) {
    	    //console.log(e);
    	}
    },
    
    /**
     * Submit de la comparaison GP + GL
     */
    submitCompare:function(){
        parent.frames["iframe_liste_hotel"].document.forms["compareHotels"].target='_top';
    	parent.frames["iframe_liste_hotel"].document.forms["compareHotels"].submit();
    },
    
    /**
     * Submit de la demande bol
     */
    submitBookOnline:function() {
        location.href="/selectPax.svlt?hotel_ville="+this.hotelSelectorViewBean.products[0];
    },
    
    /**
     * Submit pour la demande de devis
     */
    submitRequest:function() {
        // A-t'on coche des hotels?
        if ( (this.rfpOnlineSelectedHotels + this.rfpOfflineSelectedHotels)>0){
            // Si l'on a coche des hotels rfp online et offline, ca va pas.
            // on ne peut avoir qu'un seul type de RFP.
            if (this.rfpOnlineSelectedHotels > 0 && this.rfpOfflineSelectedHotels > 0){
                pop_v("/"+this.originViewBean.codeLangDirectory+"/reservation/pop_devis.html",450,220);
            } else {
                var myForm = parent.frames["iframe_liste_hotel"].document.forms["compareHotels"];
                if (this.rfpOnlineSelectedHotels>0){
                    myForm.target='_top';
                    myForm.action="/frm_rfp.svlt";
                    myForm.action_servlet.value="rfp_online";
                } 
                else {
                    myForm.target='_top';
                    myForm.action="/frm_rfp.svlt";
                    myForm.action_servlet.value="rfp_offline";
                }
                myForm.submit();
            }
        } else {
            var language = this.originViewBean.codeLangDirectory;
            alert(I18N._("hotels.list","You have to select at least"));
        }
    },
    
    /**
     * On compte le type d'hôtels selectionne, et on masque ou non 
     * le bouton permettant de realiser la demande de devis.
     */
    userSelectBookOnline:function() {
        var LHFrame = parent.frames["iframe_liste_hotel"].document;
        if(undefined != LHFrame 
            && undefined != LHFrame.getElementById("listing_button") 
            && undefined != LHFrame.getElementById("listing_button_bottom")) {
        		var actionButton = LHFrame.getElementById("listing_button").getElementsByTagName('a')[0];
        		var actionButtonBottom = LHFrame.getElementById("listing_button_bottom").getElementsByTagName('a')[0];
            // Gestion du cas d'une liset hotel avec un seul hotel bol.
            if(this.hotelsViewBean.bolOnly) {
               //actionButton.removeClassName('smmButtonOff');
               actionButton.className='smmButton';
               actionButtonBottom.className='smmButton';
               actionButton.className +=' xReserver';
               actionButtonBottom.className +=' xReserver';
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.submitBookOnline();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].href="javascript:void(0);";
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.submitBookOnline();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].href="javascript:void(0);";
            }
            // Le bouton "Reservez" est affiche si un seul hotel bookonline est selectionne et rien d'autre.
            else if(this.bookOnlineSelectedHotels == 1 && this.rfpOnlineSelectedHotels==0 && this.rfpOfflineSelectedHotels==0) {
               //actionButton.removeClassName('smmButtonOff');
               actionButton.className='smmButton';
               actionButtonBottom.className='smmButton';
               actionButton.className +=' xReserver';
               actionButtonBottom.className +=' xReserver';
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.submitBookOnline();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].href="javascript:void(0);";
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.submitBookOnline();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].href="javascript:void(0);";
            }
			//Le bouton "Reservez" n'est pas affiche si plus de 1 hotel "BookOnline" (BOL) est selectionne
			else if(this.bookOnlineSelectedHotels > 1 ) {
               actionButton.className='smmButtonOff';
               actionButtonBottom.className='smmButtonOff';
			   actionButton.className +=' xReserver';
               actionButtonBottom.className +=' xReserver';
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.firePopup();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].href="javascript:void(0);";
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.firePopup();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].href="javascript:void(0);";
            }
            // si l'on a un melange d'hotels rfp et bol, on n'affiche aucun des boutons.
            else if(this.bookOnlineSelectedHotels > 0 && (this.rfpOnlineSelectedHotels!=0 || this.rfpOfflineSelectedHotels!=0)) {
               //actionButton.removeClassName('smmButton');
               actionButton.className='smmButtonOff';
               actionButtonBottom.className='smmButtonOff';
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.firePopup();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].href="javascript:void(0);";
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Book');
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.firePopup();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].href="javascript:void(0);";
            }
            // le bouton n'est pas affiché si l'on a plus de 3 hôtels rfp off/online.
            else if(this.bookOnlineSelectedHotels == 0 && (this.rfpOnlineSelectedHotels>3 || this.rfpOfflineSelectedHotels>3)) {
               //actionButton.removeClassName('smmButton');
               actionButton.className='smmButtonOff';
               actionButtonBottom.className='smmButtonOff';
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Request a proposal');
			   $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.firePopup();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].href="javascript:void(0);";
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Request a proposal');
			   $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.firePopup();}
               $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].href="javascript:void(0);";
            }
            // Le bouton "Demande de devis" est affiche si seulement des hotels rfp ou rien n'est selectionne.
            else {
                //actionButton.removeClassName('smmButtonOff');
                actionButton.className='smmButton';
                actionButtonBottom.className='smmButton';
                actionButton.className +=' xDevis';
                actionButtonBottom.className +=' xDevis';
                //$('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').style.display="block";
                $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Request a proposal');
                $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.submitRequest();}
                $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button').getElementsByTagName('a')[0].href="javascript:void(0);";
                $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML = I18N.gettext('hotels.list', 'Request a proposal');
                $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].onclick=function(){parent.HotelsList.submitRequest();}
                $('iframe_liste_hotel').contentWindow.document.getElementById('listing_button_bottom').getElementsByTagName('a')[0].href="javascript:void(0);";
            }
            
        }
    },
    
    firePopup : function(){
    	DivPopup.openPopup('rates_sales_policies', 600, 280, null, '/'+this.originViewBean.codeLangDirectory+'/reservation/hotels-list-type.shtml');
    	var newPopup = $$('body.liste-hotel')[0].firstChild;
    	var iframe = newPopup.select('iframe')[0];
    	Event.observe(
    		iframe,
    		'load',
    		function(){
    				var newCloseButton = iframe.contentWindow.document.getElementsByTagName('a')[0];
						if(newCloseButton){
							Event.observe(
								newCloseButton,
								'click',
								function(event){
									Windows.close(newPopup.id, event);
								}
							);
						}
    		}
    	);
			
    },
    
    /**
     * Methode permettant d'elargir l'iframe a la taille de la page qu'elle appelle.
     */
    adaptIframeSize : function(id) {
        var height = $(id).contentWindow.document.getElementsByTagName("body")[0].clientHeight;
        $(id).style.height = (height+100)+"px";
        
        if(navigator.userAgent.search(/MSIE 7/) != -1 )
        {
            var height = $(id).contentWindow.document.getElementsByTagName("body")[0].clientHeight;
            $(id).style.height = (height+10)+"px";
        }
        if(navigator.userAgent.search(/MSIE 6/) != -1 && navigator.userAgent.search(/opera/) == -1)
        {    
            var last = $(id).contentWindow.document.getElementsByTagName("span").length-1;
                var span = $(id).contentWindow.document.getElementsByTagName("span")[last];
                    if(span){
	                    if(span.className.search(/extra-bottom/) !== -1)
	                    {
	                        var height2= $(id).getHeight();
	                        span.style.bottom = "auto";
	                        span.style.top = (height2)+"px";
	                    }
                  	}
        }
        
        /*if(navigator.userAgent.search(/Safari/) != -1 )
        {    
            var last = $(id).contentWindow.document.getElementsByTagName("span").length-1;
                var span = $(id).contentWindow.document.getElementsByTagName("span")[last];
                    if(span.className.search(/extra-bottom/) !== -1)
                    {
                        var height= $(id).getHeight();
                        span.style.bottom = "auto";
                        span.style.top = (height-10)+"px";
                    }
             console.log(span);
        }*/
    },
    
    // Ecrit le chemin de fer selon le contexte
    writeHeader : function(){
    	var context = this.hotelsViewBean.context;

    	switch(context){
    		case "leasureGroup":
    			if($('context_leasureGroup')) $('context_leasureGroup').show();
    			break;
    			
    		case "rfp":
    			if($('context_rfp')) $('context_rfp').show();
    			break;
    			
    		case "thalassa":
    			if($('context_thalassa')) $('context_thalassa').show();
    			break;
    			
    		default:
    			if($('context_default')) $('context_default').show();
    			break;
    	}
    	
    },
    
    attachCalendarPopin : function(){
    	var iframeDocument = $("iframe_liste_hotel").contentWindow.document;
    	var listeHotelContainer = $(iframeDocument.getElementById('liste_hotels'));  
    
    	if(this.bookingEngineViewBean.freeNight ==  true){
    		var linkListFreeNight = listeHotelContainer.select('a.freenightCalendar');
	    	linkListFreeNight.each(function(el){
	    		if(el){
	    			Event.observe(
	    				el,
	    				'click',
	    				function(evt){
	    					Event.stop(evt);
	    					if(iframeDocument.getElementById("s_devise") && iframeDocument.getElementById("s_devise").nodeName == 'SELECT')	DivPopup.openPopup('freenight_calendar', 690, 420, null, el+'&currencyCode='+iframeDocument.getElementById("s_devise").value);
	    					else DivPopup.openPopup('dispo_calendar', 690, 420, null, el);
	    				}
	    			);
	    		}
	    	});
    	}
		var linkList = listeHotelContainer.select('a.disposCalendar');
		linkList.each(function(el){
			if(el){
				Event.observe(
					el,
					'click',
					function(evt){
						Event.stop(evt);
						if(iframeDocument.getElementById("s_devise") && iframeDocument.getElementById("s_devise").nodeName == 'SELECT')	DivPopup.openPopup('dispo_calendar', 695, 625, null, el+'&currencyCode='+iframeDocument.getElementById("s_devise").value);
						else DivPopup.openPopup('dispo_calendar', 695, 625, null, el);
					}
				);
			}
		});
    	
    },
    
    rewriteResaButtonLink : function(){
    	var iframeDocument = $("iframe_liste_hotel").contentWindow.document;
    	var listeHotelContainer = $(iframeDocument.getElementById('liste_hotels'));
    	
    	if(iframeDocument.getElementById("s_devise") && iframeDocument.getElementById("s_devise").nodeName == 'SELECT'){
	    	var buttonList = listeHotelContainer.select('div.listehotel_boutonresa');
	    	buttonList.each(function(elt){
	    		if(elt){
	    			var eltLink = elt.select('a')[0];
	    			if(eltLink && !eltLink.hasClassName('disposCalendar') && !eltLink.hasClassName('externalHotel')){
	    				Event.observe(
	    					eltLink,
	    					'click',
	    					function(evt){
	    						Event.stop(evt);
	    						document.location.href= eltLink.href + '&currencyCode='+iframeDocument.getElementById("s_devise").value;
	    					}
	    				);
	    			}
	    				//eltLink.href += '&currencyCode='+iframeDocument.getElementById("s_devise").value;
	    		}
	    	});
    	}
    }
}

core.push(HotelsList);
