/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR   = 60 * Date.MINUTE;
Date.DAY    = 24 * Date.HOUR;
Date.WEEK   =  7 * Date.DAY;

/**
 * Javascript object to deal with User Reservation infos
 * 
 */
var ReservationSummary = {
	
    /**
     * stores booking data coming from Json Object
     */
    bookingEngineViewBean: null,
    /*
     * stores user profile data coming from Json object
     */
    profileViewBean: null,
    /*
     * stores fidelity cards and fid attributes
     */
    fidelityCardsViewBean: null,
    basketViewBean: null,
    /*
     * stores aclub special attribs
     */
    aClubViewBean: null,
    /*
     * stores the arrival date throughout runtime
     */
    arrival_date: null,
    departure_date: null,
    nights_nb: null,
    /**
     * used to indicate if the dates of stay are to be modified or just displayed
     */
    dates_can_be_modified: true,
    /**
     * used to indicate if we actually display dates block on page
     */
    show_dates: false,
    /*
     * used to indicate whether we received dates from the Json object
     */
    has_initial_dates: false,
    /**
     * 
     */
    sections: new Array(['hotel'], ['dates-et-nb-chambres'], ['chambre-et-tarif'], ['upsale'], ['detail-clients','confirmation']),
    
    /**
     * Beans to be used.
     * 
     * @return String a string of the nalmes of the Beans to be used in this class
     * 
     */
		getBeans: function()
		{
        return "BookingEngineViewBean;ProfileViewBean;BasketViewBean;AClubViewBean";
    },
    /**
     * assigning values from JSON object to global variables
     * 
     * @return void
     * 
     */
    initJSON: function()
    {
      bookingEngineViewBean = viewBeans["BookingEngineViewBean"];
      profileViewBean = viewBeans["ProfileViewBean"];
      basketViewBean = viewBeans["BasketViewBean"];
      this.aClubViewBean = viewBeans["AClubViewBean"];
    },
    
    /**
     * get the booking engine bean
     * 
     * @return Object the json object for booking engine values
     * 
     */
     
    getBookingEngineViewBean: function()
    {
        return bookingEngineViewBean;
    },
    /**
     * get the profile bean
     * 
     * @return Object the json object for user profile
     * 
     */
    getProfileViewBean: function()
    {
        return profileViewBean;
    },
    
    /**
     * get the basket bean
     * 
     * @return Object the json object for basket informations
     * 
     */
    getBasketViewBean: function()
    {
        return (typeof(basketViewBean) != 'undefined')? basketViewBean : null;
    }, 
    
    
    /**
     * wrapper method to execute init functions for the page
     * 
     * also deals with adapting the left menu to the different pages the menu is displayed on
     * ReservationSummary is called on every page since it manages the left menu
     * 
     * called on page load
     * 
     * @return void
     * 
     * 
     */
    rewrite: function()
    {
	    
	    this.rewriteRecap();
      this.rewriteAvantage();
			this.highLightMenu();
			this.decorateMenu();
			this.setupBasketLink();
			this.setTitle();
      this.rewriteAclub();
      this.testChoixCouchage();
        
        var basket_bean = this.getBasketViewBean();
		var showCentralDates = this.getBookingEngineViewBean().displayDate;
		var modifDates = this.getBookingEngineViewBean().modifDate;
	    //different actions depending on the page
		
			switch(document.body.id) {
				
				case "dates-et-nb-chambres":
	    			this.setupBeddingBlock();
	    			if($("rooms_nb") && bookingEngineViewBean.roomsNb)
                  {
                    $("rooms_nb").value = bookingEngineViewBean.roomsNb;
                  }
                    
                    //special case when we want to add a second room or more and display the dates in the center of the page
                    //if((basket_bean && basket_bean.displayBasket)) {
					if(showCentralDates)
					{
              this.has_initial_dates = false;
	    			  this.show_dates = false;
					    this.dates_can_be_modified = true;
              this.setArrivalDate();
				      this.setNightsNb(
					        (this.getBookingEngineViewBean().nightsNumber) ? this.getBookingEngineViewBean().nightsNumber : 1
					    );
	    	      if($("arrivee"))
							{
								this.setupRoomsDatesCalendar("arrivee");
							}
							if($("arrivee_calendar_side"))
							{
								this.setupRoomsDatesCalendar("arrivee_calendar_side");
							}
              if($("nb_nuit") && bookingEngineViewBean.hotelMaxStay)
              {
                this.setupMaxStayDropDown("nb_nuit");
              }
						 if($("nb_nuit_calendar_side") && bookingEngineViewBean.hotelMaxStay)
                  {
                    this.setupMaxStayDropDown("nb_nuit_calendar_side");
                  }
              }
              else{
                  this.show_dates = true;
					    		this.dates_can_be_modified = false;
              }
	    			
	    		break;
	    		
				case "chambre-et-tarif":
				
					this.show_dates = true;
					if(modifDates){
					   this.dates_can_be_modified = true;
					}else{
             this.dates_can_be_modified = false;
          }
				
				break;
				
				case "upsale":
				
					this.show_dates = true;
					this.dates_can_be_modified = false;
					
					$('chambre-tarif').down('ul').removeClassName('hide');
					
					
				break;
				
				case 'detail-clients':
				break;
				
				case 'confirmation':
					
				break;
				
			}
			
			if(this.show_dates) {
				
				this.setArrivalDate();
				this.setNightsNb(
					(this.getBookingEngineViewBean().nightsNumber)? this.getBookingEngineViewBean().nightsNumber: 1
					);
	    	this.setupRoomsDatesStayDatesBlock();
				
				
			}
    	
    	
    	if(this.show_dates && $('dates-nb-chambres').down('ul')) 
    		//show dates block in reservation summary column
    		$('dates-nb-chambres').down('ul').removeClassName('hide');
    	
    	//if the dates can be modified or (to deal with 'in page' dates setup) if there are no dates in the bean
    	// AND we want to show the dates
    	if(
        	(
        	  this.dates_can_be_modified
        	  || !this.has_initial_dates
        	 )
        	 && this.show_dates 
    	 )
    	{
    	  if(document.getElementById("side-availability"))
    	  {
        	  var input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "nb_personne";
        	  input.value = bookingEngineViewBean.adultsNb?bookingEngineViewBean.adultsNb:"";
              document.getElementById("side-availability").appendChild(input);
        	  input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "nb_enfant";
        	  input.value = bookingEngineViewBean.childrenNb?bookingEngineViewBean.childrenNb:"";
        	  document.getElementById("side-availability").appendChild(input);
        	  
        	  input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "bedding";
        	  input.value = bookingEngineViewBean.bedding?bookingEngineViewBean.bedding:"";
        	  document.getElementById("side-availability").appendChild(input);
        	  
        	  input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "rooms_nb";
        	  input.value = bookingEngineViewBean.roomsNb?bookingEngineViewBean.roomsNb:"";
        	  document.getElementById("side-availability").appendChild(input);
        	  
        	  input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "type_carte_fidelite";
        	  input.value = bookingEngineViewBean.fidelityCardType?bookingEngineViewBean.fidelityCardType:"";
        	  document.getElementById("side-availability").appendChild(input);
        	  
        	  input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "num_carte_fidelite";
        	  input.value = bookingEngineViewBean.fidelityCardNumber?bookingEngineViewBean.fidelityCardNumber:"";
        	  document.getElementById("side-availability").appendChild(input);
        	  
        	  input = document.createElement("input");
        	  input.type = "hidden";
        	  input.name = "code_avantage";
        	  input.value = bookingEngineViewBean.preferentialCode?bookingEngineViewBean.preferentialCode:"";
        	  document.getElementById("side-availability").appendChild(input);
        		Event.observe(
    					document.getElementById("depart_calendar_side").getElementsByTagName("a")[0],
    					"click",
    					function(e)
    					{
    					  Event.stop(e);
    					  document.getElementById("side-availability").submit();
    					}
    				);
    	    }
    		//remove fixed dates block
	    	if($('side-stay-dates')) $('side-stay-dates').remove();
    		
    		if($("arrivee"))
			{
				this.setupRoomsDatesCalendar("arrivee");
			}
			if($("arrivee_calendar_side"))
			{
				this.setupRoomsDatesCalendar("arrivee_calendar_side");
			}
			if($("nb_nuit") && bookingEngineViewBean.hotelMaxStay)
			{
			  this.setupMaxStayDropDown("nb_nuit");
			}
			 if($("nb_nuit_calendar_side") && bookingEngineViewBean.hotelMaxStay)
			{
			  this.setupMaxStayDropDown("nb_nuit_calendar_side");
			}
    		
    	}
    	else {
    		
    		//remove stay dates form
	    	if($('side-availability')) $('side-availability').remove();
	    	
            //if(basket_bean && !basket_bean.displayBasket) {
			if(!showCentralDates){
    		    this.displayNightsNb();
            }
    		
    	}
    	
    	
    	this.displayArrivalDate();
    	if(this.arrival_date != undefined) this.updateDepartureDate();
		
    },
    
    /**
     * 
     * alllow to show the beeding block if bookingEngineViewBean.hotelPaxPolicies.twinOrDouble is true in Bean
     * 
     * @return void
     * 
     */
    setupBeddingBlock: function()
    {
    	if(bookingEngineViewBean.hotelPaxPolicies.twinOrDouble != true)
			{
				if($("type-couchage"))
				{
					$("type-couchage").remove();
				}
			}
			else
			{
				if($("type-couchage") && $("nb_personne").value != 2 && (!$("nb_enfant") || $("nb_enfant").value != 0))
				{
					$("type-couchage").hide();
				}
				if($("nb_personne"))
				{
					Event.observe(
						$("nb_personne"),
						"change",
						ReservationSummary.testChoixCouchage
					);
				}
				if($("nb_enfant"))
				{
					Event.observe(
						$("nb_enfant"),
						"change",
						ReservationSummary.testChoixCouchage
					);
				}
			}
    },
    /**
     * Display or not the type couchage
     * 
     * @return void
     * 
     */
    testChoixCouchage: function()
	{
		if($("type-couchage")){
			if($("nb_personne").value != 2)
			{
				$("type-couchage").hide();
			}
			else
			{
			    if($("nb_enfant") && $("nb_enfant").value != 0)
			    {
				    $("type-couchage").hide();
				}
				else
			    {
			        $("type-couchage").show();
			    }
			}
		}
	},
	
	
	 /**
     * adapt the position of the span bottom depending on the contener height
     * 
     * @return void
     * 
     */
	adaptSpanBottom:function(referer, nbPix)
	{
				if($(referer))
				{
					var last = $(referer).getElementsByTagName("span").length-1;
					var span = $(referer).getElementsByTagName("span")[last];
		                //console.log(span);
		                if(span.className.search(/extra-bottom/) !== -1)
		                {
		                    var height= $(referer).getHeight();
		                    span.style.bottom = "auto";
		                    span.style.top = (height-nbPix)+"px";
		                }
				}
	},
	
    /**
     * highlights right item in the left menu
     * 
     * @return void
     * 
     */
    highLightMenu: function()
    {
		
		var idBody = document.body.id;
		switch(idBody)
		{
			case 'dates-et-nb-chambres':
				if($("dates-nb-chambres"))
				{
					$('dates-nb-chambres').addClassName('current');
				}
				break;
			case 'chambre-et-tarif':
				if($("dates-nb-chambres"))
				{
					$('chambre-tarif').addClassName('current');
				}
				break;
			case 'upsale':
				if($("options"))
				{
					$('options').addClassName('current');
				}
				break;
			
			case 'detail-clients':
				if($("recap-reservation"))
				{
					$('recap-reservation').addClassName('current');
				}
				break;
                
            case 'confirmation':
				break;
            
			default: break;
		}
    },
    
    /**
     * 
     * changes the class of the menu sections based on position in reservation process
     * items that are before the current step are assigned a .visited className (and the .main className is removed)
     * 
     * @return void
     * 
     */
    decorateMenu: function() {
    	
  
    	var idBody = document.body.id;
    	var base_element = $('side-content');
    	var titles = base_element.getElementsBySelector('.main');
    	
    	var _class = 'visited';
    	for(var i = 0 ; i < titles.length; i++) {
    		
    		var section = this.sections[i];
    		
    		if(section.indexOf(idBody) != -1 && idBody != 'confirmation') { // if not on the confirmation page where all the items must be shown as visited
    			
    			_class = null;
    			
    		}
    		
    		if(_class) {
    			
    			titles[i].removeClassName('main');
    			titles[i].addClassName(_class);
    			
    		}
    		
    		
    	}
    	
    },
    
    /**
     * Writes infos in the Personal infos block of the left menu
     * 
     * @return void
     */
    rewriteAvantage: function()
    {
        var bAffiche = false;
      if($("avantage"))
      {
		  	if(bookingEngineViewBean.preferentialCode != null && bookingEngineViewBean.preferentialCode.length)
  			{
			    bAffiche = true;
			    $("avantage_preferentialCode").innerHTML = bookingEngineViewBean.preferentialCode;
			    $("avantage_preferentialCode").up().removeClassName('hide');
  			}
  			if(bookingEngineViewBean.fidelityCardName != null && bookingEngineViewBean.fidelityCardName.length)
  			{
			    bAffiche = true;
			    $("avantage_fidelityCardName").innerHTML = bookingEngineViewBean.fidelityCardName;
			    $("avantage_fidelityCardName").up().removeClassName('hide');
  			}
  			if(bookingEngineViewBean.companyReserverName != null && bookingEngineViewBean.companyReserverName.length)
  			{
			    bAffiche = true;
			    $("avantage_companyReserveName").innerHTML = bookingEngineViewBean.companyReserverName;
			    $("avantage_companyReserveName").up().removeClassName('hide');
  			}
  			if(bookingEngineViewBean.agencyReserverName != null && bookingEngineViewBean.agencyReserverName.length)
  			{
  			   bAffiche = true;
  		    $("avantage_agencyReserverName").innerHTML = bookingEngineViewBean.agencyReserverName;
  		    $("avantage_agencyReserverName").up().removeClassName('hide');
  	    }
        if(bAffiche)
  	    {
          $("avantage").removeClassName('hide');
  	    }
		  }
    },
    
    
    /**
     * Writes Aclub img for non eco brands + ase  
     */
    rewriteAclub: function() {
      var elm = $('aclub');
      if (elm && this.aClubViewBean && this.aClubViewBean.aclubVisible && this.aClubViewBean.aclubPartner)
        elm.removeClassName('hide');
    }, 
    
		
		/**
		 * Writes infos about the reservation in the left menu
		 * @return void
		 */
    rewriteRecap: function()
    {
      
      //write the title of the reservation block, title which changes on the confirmation page
      var target ='';
      target = document.getElementById("side-content").getElementsByTagName("h2")[0];
      
      if(document.body.id != 'confirmation'){
        if(target != undefined){
            target.innerHTML = I18N._('confirmation','Your selection');
        }
      }
      else if(document.body.id == 'confirmation'){
        if(target != undefined){
            target.innerHTML = I18N._('confirmation','Your confirmed booking');
        }
      }
      
      if( $('recap_hotelname') )
		  {
  			$('recap_hotelname').removeClassName('hide');
  			$('recap_hotelname').innerHTML = "<a href='/frm_fiche_hotel.svlt?code_hotel="+bookingEngineViewBean.hotelCode+"'>"+bookingEngineViewBean.hotelName+"</a>";
  		}
      if(bookingEngineViewBean.destination != null && bookingEngineViewBean.destination.length)
	    {
	  	    if( $('recap_destination') )
	  			{
	  				$('recap_destination').removeClassName('hide');
	  				$('recap_destination').innerHTML = bookingEngineViewBean.destination;
	  			}
				
			var back_urldestination = bookingEngineViewBean.hotelsListUrl;
			
			if(back_urldestination != null)
			{
				if( $('recap_destinationurl') )
		  			{
		  				$('recap_destinationurl').removeClassName('hide');
						$('recap_destinationurl').href = back_urldestination; 
		  			}
			}
			else{
				$('recap_destinationurl').style.display="none";
			}
  		}
  		else
  		{
  		  document.getElementById("recap_destinationurl").style.display = "none";
  		}
      if( $('recap_newsearchurl') )
  		{
  			$('recap_newsearchurl').href = bookingEngineViewBean.newSearchUrl;
  		}
      if( $('recap_adultsnb') )
  		{
  			$('recap_adultsnb').innerHTML = bookingEngineViewBean.adultsNb;
  		}
      if( $('recap_childrennb') && $('recap_children') && bookingEngineViewBean.childrenNb!=null && bookingEngineViewBean.childrenNb!=0 )
  		{
  			$('recap_children').removeClassName('hide');
  			$('recap_childrennb').innerHTML = bookingEngineViewBean.childrenNb;
  		}
        
        var roomsNb = bookingEngineViewBean.roomsNb;
        if(roomsNb > 1 && $('recap_roomsnb')){
            $('recap_roomsnb').removeClassName('hide');
            
            if(roomsNb == 2){
                $('recap_roomsnb').innerHTML = I18N._('multirates',"Rooms 1 and 2");
            }
            else{
                $('recap_roomsnb').innerHTML = I18N._('multirates',"Rooms 1, 2 and 3");
            }
        }
        if (this.getBasketViewBean()) {
        	if ($('chambre-tarif')&& null != basketViewBean.currentRoom) {
		        if (document.body.id == "upsale" && basketViewBean.currentRoom.famillyOffer && $('recap_roomsnb')) {
		          $('recap_roomsnb').innerHTML = I18N._('upsale','2 chambres en famille');
		          $('recap_roomsnb').removeClassName('hide');
		        }
	         	if (document.body.id == "chambre-et-tarif" && basketViewBean.currentRoom.famillyOffer && $('recap_roomsnb')) {
		          $('recap_roomsnb').innerHTML = I18N._('multirates',"Rooms 1 and 2");
		          $('recap_roomsnb').removeClassName('hide');
		        }	
		        //displays reserved room infos
		        if(basketViewBean.currentRoom.label && $('chambre-tarif').down('.label')) {
		  				$('chambre-tarif').down('.label').innerHTML = basketViewBean.currentRoom.label;
		  			}
		  			
		  			if(basketViewBean.currentRoom.tariffLabel && $('chambre-tarif').down('.tariffLabel')) {
		  				$('chambre-tarif').down('.tariffLabel').innerHTML = basketViewBean.currentRoom.tariffLabel;
		  			}
		  			this.writeRoomPrice();
	        }
        }
        
    },
    writeRoomPrice: function () {
			if(typeof(basketViewBean) != 'undefined' && $('chambre-tarif')) {
  			if(null != basketViewBean.currentRoom) {
	  	   	if(basketViewBean.currentRoom.price && $('prix_total').down('.techPrice')) {
	  				$('prix_total').down('.techPrice').innerHTML = basketViewBean.currentRoom.price;
	  			}
	  			if(basketViewBean.currentRoom.currency && $('prix_total').down('.mdevise')) {
	  				$('prix_total').down('.mdevise').innerHTML = basketViewBean.currentRoom.currency;
	  			}
	  		}
  		}
    },
    
    /**
     * manages whether the stay dates are to be selected in the page or in the left column
     * if data in Bean => remove stay dates block in page
     * else remove the stay dates block in left menu
     * the html page contains elements with same ids but since we remove a block, we're left with unique ids
     * 
     * TODO the management of displayiong the stay dates block in left menu has been moved to rewrite method
     * so it is probably not necessary to actualy remove the left menu stay dates block if there is no data in the bean
     * 
     * @return void
     * 
     */
    setupRoomsDatesStayDatesBlock: function()
    {
    	
    	if(
    		(bookingEngineViewBean.dayIn != null && bookingEngineViewBean.dayIn.length) && 
    		(bookingEngineViewBean.monthIn != null && bookingEngineViewBean.monthIn.length) && 
    		(bookingEngineViewBean.yearIn != null && bookingEngineViewBean.yearIn.length) && 
    		(bookingEngineViewBean.nightsNumber != null && bookingEngineViewBean.nightsNumber.length)
    	)
    	{
    		//remove stay dates block in page if exists (its the case in rooms dates page)
    		if($('rooms-dates-stay-dates')) {
    			
    			$('rooms-dates-stay-dates').remove();
    			
    		}
      		
    	}
    	else
    	{
  			//remove stay dates block in reservation summary column
  			$('dates-nb-chambres').down('ul').remove();
      		
    	}
    	
    },
    
    /**
     * 
     * Sets the arrival date as a class ppty
     * to be used throughout the dates functions
     * 
     * @return void
     * 
     */
    setArrivalDate: function()
    {
    	
    	
    	if(
    		(bookingEngineViewBean.dayIn != null && bookingEngineViewBean.dayIn.length) && 
    		(bookingEngineViewBean.monthIn != null && bookingEngineViewBean.monthIn.length) && 
    		(bookingEngineViewBean.yearIn != null && bookingEngineViewBean.yearIn.length) && 
    		(bookingEngineViewBean.nightsNumber != null && bookingEngineViewBean.nightsNumber.length)
    	)
    	{
    		this.arrival_date = new Date(
    		  parseInt(bookingEngineViewBean.yearIn),
    			Number(bookingEngineViewBean.monthIn) - 1,
    			Number(bookingEngineViewBean.dayIn)
    		);
    		
    		this.has_initial_dates = true;
    		
    	}
    	else {
    										
    			
			this.arrival_date = new Date();
    		
    	}
    	
    },
    
    /**
     * 
     * displays the arrival date
     * there is a  distinction made between when the date can or can not be modified
     * there are 2 blocks with elements with same ids , we remove one of the block 
     * depending on whether we need a form to modify the date or not
     * this depends on the page we are on
     * 
     * @return void
     * 
     */
    displayArrivalDate: function() {
	
    		if(!this.arrival_date) return;
    					   
    		var str_date = this.arrival_date.print(Calendar._TT["DEF_DATE_FORMAT"]);
    		
    		if($("arrivee_display"))
			{
	    			$("arrivee_display").down("span.date").innerHTML = str_date;
	    			if($("arrivee_display").down('span.jour')) $("arrivee_display").down('span.jour').innerHTML = Calendar._DN[this.arrival_date.getDay()];
    		}
			if($("arrivee_calendar_side"))
			{
				$("arrivee_calendar_side").value = str_date;
	    		if($("arrivee_calendar_side").previous('span.jour')) $("arrivee_calendar_side").previous('span.jour').innerHTML = Calendar._DN[this.arrival_date.getDay()];
			}
			if($("arrivee"))
			{
				$("arrivee").value = str_date;
	    		if($("arrivee").previous('span.jour')) $("arrivee").previous('span.jour').innerHTML = Calendar._DN[this.arrival_date.getDay()];
			}
			
    },
    
    /**
     * sets the nights number
     * 
     * @return void
     * 
     */
    setNightsNb: function(value) {
    	
    	
    	this.nights_nb = value;
    	
    },
    
    /**
     * displays the nights number on page
     * 
     * @return void
     * 
     */
    displayNightsNb: function() {
    	
    	$('nb_nuit_display').innerHTML = this.nights_nb;
    },
    
	/**
	 * sets up calendar for arrival dates
	 * 
	 * @return void
	 * 
	 */
	setupRoomsDatesCalendar: function(input_calendar_text)
	{
			
			if($(input_calendar_text))
			{
			  //since we want to be able to create a calendar when focusin or clicking on the field
			  //but we don't want manual input int the field
			  //blur it when focus is gained
			  Event.observe(
			  		$(input_calendar_text),
			  		'focus',
			  		function(e) {
			  			Event.element(e).blur();
			  		}
			  );
	      var calendarDate = null;
	      if(typeof(this.arrival_date) != "undefined" && this.arrival_date)
	      {
	        var calendarDate = this.arrival_date;
	        this.setDateHiddenFieldsValue(this.arrival_date);
	      }
	   
	      Calendar.setup( 
	        {
	          inputField : input_calendar_text,
	          button : 'date_'+input_calendar_text+'_img',
	          button_eventNames : ['click'],
	          inputField_eventNames : ['click','focus'],
	          ifFormat : Calendar._TT["DEF_DATE_FORMAT"],
	          singleClick : true,
	          align : 'T 	R',
	          onSelect : this.arrivalDateOnselect.bind(this, input_calendar_text),
	          dateStatusFunc : this.disableDates.bind(this)
	        }
	      );
	    }
	},
	
	/**
	 * date select handler
	 * 
	 * @param Calendar object cal the calendar object on which a date has been selected
	 * @param Date date the selected date
	 * 
	 * @return void
	 * 
	 */
	arrivalDateOnselect: function(input_calendar_text, cal, date) {
			//console.log("arrivalDateOnselect args: ", arguments);
	        //computes departure date (date selected + nights number selected)
			
	        if(!this.departure_date) this.departure_date  = new Date();
	        this.departure_date.setTime(cal.date.getTime() + (this.nights_select_index+1)*Date.DAY + Date.HOUR);  	// ajout d'une heure pour compenser le cas du passage de l'heure d'été à l'heure d'hiver
	        //if departure date out of bounds => do nothing
	        if(!this.checkDate(this.departure_date))
	        {
	          return false;
	        }
	        
	        if(cal.dateClicked)
	        {
	          this.arrival_date = cal.date;
	          this.setDateHiddenFieldsValue(cal.date);
			  
	          if($(input_calendar_text).previous('span.jour')) $(input_calendar_text).previous('span.jour').innerHTML = Calendar._DN[cal.date.getDay()]; 
			  
	          this.updateDepartureDate();
	          $(input_calendar_text).value = date;
	          cal.hide();
	        }
	        
	        return true;
	        
		
		
	},
	
	/**
	 * methd used by Calendar to disable dates that are before current day and after current + max reservation period
	 * 
	 * @see Calendar class documentation
	 * 
	 * @return Boolean
	 * 
	 */
	disableDates: function(dDate, y, m, d)
	      {
	       
	        var now = new Date();
	        
	        if(dDate.getTime() < now.getTime()-Date.DAY)
	        {
	          return true;
	        }
	        
	        var max_period = now.getTime() + 
	          (Date.DAY*((bookingEngineViewBean.hotelMaxPeriod)? bookingEngineViewBean.hotelMaxPeriod : 405)) -
	          (Date.DAY* (this.nights_select_index+1));
	       
	        if(dDate.getTime() > max_period)
	        {
	          return true;
	        }
	        
	        return false;
	        
	      },
	
	/**
	 * 
	 * check whether the passed date is within reservation bounds
	 * 
	 * @return Boolean
	 * 
	 */
	checkDate : function(date)
	{
		var b = true;
		var msg = null;
		var now = new Date();
		
		//if date is anterior to current day and date.month is not the current month
		//the last check (current month check)is done so that we don't get an alert when switching to current month
		//in this case an onSelect event is triggered and the date passed is the month previoulsy selected day
		//so this day can be anterior to the current day
		//but we still want to be able to select a day in the current month
		if(date.getTime() < now.getTime() && date.getMonth() != now.getMonth())
		{
			b = false;
			msg = I18N._('calendar',"outOfMinDate"); 
			var min_date = new Date();
			min_date.setTime(now.getTime());
			window.calendar.setDate(min_date);
		}
		//compputes max reservation date (in time format)
		var max_period = now.getTime() + (Date.DAY*((bookingEngineViewBean.hotelMaxPeriod)? bookingEngineViewBean.hotelMaxPeriod : 405));
		//check if date is greater than max reservation date
		if(date.getTime() >= max_period)
		{
				b = false;
				
				var max_period_date = new Date(max_period);
				
				
				msg = 
					I18N._('calendar',"outOfMaxDate") + " " +
					((max_period_date.getDate() < 10)? "0" : "") + max_period_date.getDate() + '/' + 
					((max_period_date.getMonth() < 9)? "0" : "") + (max_period_date.getMonth()+1) + '/' + 
					max_period_date.getFullYear();
				var safe_date = new Date();
				safe_date.setTime(max_period - ((this.nights_select_index+1)*Date.DAY));
				window.calendar.setDate(safe_date);
		}
		if(!b) alert(msg);
		return b;
	},
	
	/**
	 * 
	 * sets the values for hidden dates field
	 * 
	 * @return void
	 * 
	 */
	setDateHiddenFieldsValue : function(date)
		{
			 $("jour_arrivee").value = date.getDate();
			 $("mois_arrivee").value = date.getMonth()+1; // janvier=0
			 $("annee_arrivee").value = date.getFullYear();
		},
	
	
	/**
	 * adds the number of options to the nb_nuit select box based on the json var
	 * also writes the nb of nights where appropriate
	 * 
	 * @return void
	 * 
	 */
	setupMaxStayDropDown: function(id_select_input)
	{
		var select = $(id_select_input);
		var maxStay = bookingEngineViewBean.hotelMaxStay;
		var options_array = select.descendants();
		var count = 0;
		//empty select box if not empty
		if(options_array.length)
		{
			options_array.each(
				function(option)
				{
					$(option).remove();
				}
			)
		}
		//fill select box with bean maxStay value and set default selected value based on bookingEngineViewBean.nightsNumber
		for(var i = 1; i <= maxStay; i++)
		{
			var selected;
			if(bookingEngineViewBean.nightsNumber == i)
			{
				selected = true;
				this.nights_select_index = i-1;
			}
			else
			{
				selected = false;
				this.nights_select_index = 0;
			}
			var option = new Option(i,i, selected);
			//3rd parameter seems to be ignored by ie
			//select.options.add(option);
			try
			{
				select.add(option, null);
			}
			catch(ex)
			{
				select.add(option);
			}
			if(selected) var selected_index = i-1;
			//new Insertion.Top(select, '<option value="' + i + '">' + i + '</option>');//does not work in ie
		}
		//for ie
		if(select.options[selected_index]) select.options[selected_index].selected = true;
		//listens to events and bind appropriate handler
		Event.observe(
			select,
			"change",
			function(e)
			{
				this.maxStayNightsNbSelectAction(select);	
			}.bind(this)
		);
		Event.observe(
			select,
			"keyup",
			function(e)
			{
				this.maxStayNightsNbSelectAction(select);	
			}.bind(this)
		);
	},
	
	/**
	 * 
	 * max stay select box handler
	 * 
	 * @return void
	 * 
	 * 
	 */
	maxStayNightsNbSelectAction: function(select)
	{
		
			
			var date = new Date();
			if(bookingEngineViewBean.freeNight ==  true && select.id == "nb_nuit"){
				var day = $('rooms-dates-stay-dates').select('input')[1].value;
				var month = $('rooms-dates-stay-dates').select('input')[2].value;
				var year = $('rooms-dates-stay-dates').select('input')[3].value;
				this.arrival_date = new Date(year, month-1, day);
			}
			else if (this.arrival_date)
			{
				date.setTime(this.arrival_date.getTime());
			}
			else {
				
				alert("Error : No arrival date set");
				
			}
			date.setTime(date.getTime() + Date.DAY*select.options[select.selectedIndex].value);
			if(!this.checkDate(date))
			{
				select.selectedIndex = this.nights_select_index;
				return false;
			}
			this.nights_select_index = select.selectedIndex;
			this.nights_nb = Number(select.options[select.selectedIndex].value);
			this.updateDepartureDate();
			
			
		},
	
	/**
	 * 
	 * updates departure date and displays it based on arrival date and number of nights
	 * 
	 * @return void
	 * 
	 */
	updateDepartureDate: function()
	{
		
		
		if(this.arrival_date == undefined) {
			alert("Selectionnez une date d'arrivee");
			return false;
		}
		/*var params2update = ['nb_nuit_display', 'nb_nuit', 'nb_nuit_calendar_side'];
		for(var i = params2update.length-1; i >= 0; i--)
		{
			if($(params2update[i]))
			{
				var select = $(params2update[i]);
				//console.log("param départ", params2update[i].replace("nb_nuit", "depart"));
			      var departure_date_display_element = $(params2update[i].replace("nb_nuit", "depart"));
				  
			      //var week_day = departure_date_display_element.down("span.jour");
			      
				  var date = departure_date_display_element.down("span.date");
				  
			      //compute new date
			      var nights_stay_in_days = parseInt(this.nights_nb);
			      var nights_stay_in_ms = nights_stay_in_days * Date.DAY;
			      if(!this.departure_date) this.departure_date  = new Date();
			      this.departure_date.setTime(
			        this.arrival_date.getTime() + 
			        nights_stay_in_ms
			      );
			      //if(week_day) week_day.innerHTML = Calendar._DN[this.departure_date.getDay()];
			      var day_unit_zero = (this.departure_date.getDate() < 10)? "0" : '';
			      var month_unit_zero = ((Number(this.departure_date.getMonth())+1) < 10)? "0" : '';
			      date.innerHTML = this.departure_date.print(Calendar._TT["DEF_DATE_FORMAT"]);
			}
		}*/
		
		if($('nb_nuit_display'))
		{
		      
			  var select = $('nb_nuit_display');
		      var departure_date_display_element = $("depart_display");
		      //var week_day = departure_date_display_element.down("span.jour");
		      var date = departure_date_display_element.down("span.date");
		      //compute new date
		      var nights_stay_in_days = parseInt(this.nights_nb);
		      var nights_stay_in_ms = nights_stay_in_days * Date.DAY;
		      if(!this.departure_date) this.departure_date  = new Date();
		      this.departure_date.setTime(
		        this.arrival_date.getTime() + nights_stay_in_ms + Date.HOUR	// ajout d'une heure pour compenser le cas du passage de l'heure d'été à l'heure d'hiver
		      );
		      //if(week_day) week_day.innerHTML = Calendar._DN[this.departure_date.getDay()];
		      var day_unit_zero = (this.departure_date.getDate() < 10)? "0" : '';
		      var month_unit_zero = ((Number(this.departure_date.getMonth())+1) < 10)? "0" : '';
		      date.innerHTML = this.departure_date.print(Calendar._TT["DEF_DATE_FORMAT"]);
		}
		
		if(document.getElementById('arrivee_calendar_side'))
		{
		      //alert("calendar side");
			  var select = $('nb_nuit_calendar_side');
		      var departure_date_display_element = $("depart_calendar_side");
		      //var week_day = departure_date_display_element.down("span.jour");
		      var date = departure_date_display_element.down("span.date");
		      //compute new date
		      var nights_stay_in_days = parseInt(this.nights_nb);
		      var nights_stay_in_ms = nights_stay_in_days * Date.DAY;
		      if(!this.departure_date) this.departure_date  = new Date();
		      this.departure_date.setTime(
		        this.arrival_date.getTime() + nights_stay_in_ms + Date.HOUR	// ajout d'une heure pour compenser le cas du passage de l'heure d'été à l'heure d'hiver
		      );
		     // if(week_day) week_day.innerHTML = Calendar._DN[this.departure_date.getDay()];
		      var day_unit_zero = (this.departure_date.getDate() < 10)? "0" : '';
		      var month_unit_zero = ((Number(this.departure_date.getMonth())+1) < 10)? "0" : '';
		      date.innerHTML = this.departure_date.print(Calendar._TT["DEF_DATE_FORMAT"]);
		}
		
		if(this.getBookingEngineViewBean().displayDate == true && document.body.id == "dates-et-nb-chambres")
		{
		     
			 var select = $('nb_nuit');
		      var departure_date_display_element = $("depart");
		      var week_day = departure_date_display_element.down("span.jour");
		      var date = departure_date_display_element.down("span.date");
		      //compute new date
		      var nights_stay_in_days = parseInt(this.nights_nb);
		      var nights_stay_in_ms = nights_stay_in_days * Date.DAY;
		      if(!this.departure_date) this.departure_date  = new Date();
		      this.departure_date.setTime(
		        this.arrival_date.getTime() + nights_stay_in_ms + Date.HOUR	// ajout d'une heure pour compenser le cas du passage de l'heure d'été à l'heure d'hiver
		      );
		      if(week_day) week_day.innerHTML = Calendar._DN[this.departure_date.getDay()];
		      var day_unit_zero = (this.departure_date.getDate() < 10)? "0" : '';
		      var month_unit_zero = ((Number(this.departure_date.getMonth())+1) < 10)? "0" : '';
		      date.innerHTML = this.departure_date.print(Calendar._TT["DEF_DATE_FORMAT"]);
		}
		
	},
	
	/**
	 *  displays a link to open the user basket popup
	 * the link is displayed if the basketViewBean.displayBasket ppty is set to true
	 * the url of the popup is retrieved from: basketViewBean.basketUrl
	 * 
	 * @return void
	 * 
	 */
	setupBasketLink: function() {
	
		var basket_link_container = $('basket_link_container');
		if(basket_link_container) {
			
			var basket_link_element = basket_link_container.down('a');
			
		}
		
		var basket_bean = this.getBasketViewBean();
	    
        //do not display the link to view the user basket if we are on these two pages
        if((document.body.id != 'detail-clients') && (document.body.id != 'confirmation')){
        
            if((basket_bean && basket_bean.displayBasket) && basket_link_element) {
                
                
                basket_link_container.setStyle({display: 'block'});
                
                Event.observe(
                        basket_link_element,
                        'click',
                        function(e) {
                            
                            Event.stop(e);
                            
                            if(this.basket_popup) {
                                this.basket_popup.close();
                            }
                            
                            this.basket_popup = window.open(basket_bean.basketUrl,'basket_popup','width=750,height=300');
                            
                        }.bind(this)
                        
                
                );
                
            }
            else if(basket_link_container) {
                
                basket_link_container.hide();
                
            }
        }

	},
	/* mise à jour du titre de la page */
		setTitle: function() {
			var url = location.host;
			var brand = url.split(".");
			brand = brand[1].toLowerCase();
			switch(brand) {
			case "accorhotels": 		var tit = 'AccorHotels.com'; break;
			case "all-seasons-hotels": 		var tit = 'Hôtels all seasons'; break;
			case "etaphotel": 			var tit = 'Etap Hotel'; break;
			case "hotelformule1": 	var tit = 'Hotel Formule 1'; break;
			case "ibishotel": 			var tit = 'Ibis'; break;
			case "mercure": 				var tit = 'Mercure'; break;
			case "novotel": 				var tit = 'Novotel'; break;
			case "sofitel": 				var tit = 'Sofitel Hotels'; break;
			case "suitehotel": 		var tit = 'Suite Hotel'; break;
			case "accorthalassa": 	var tit = 'Accor Thalassa'; break;
			case "pullmanhotels": 	var tit = 'Pullman'; break;
			default : 							var tit = 'AccorHotels.com'; break;
		}
			tit+=": "+I18N._('title-reservation','title'); 
			document.title=tit;
	}
	
	
}

core.push(ReservationSummary);

