//  Fichier Javascript contenant les fonctions nécessaires au bon fonctionnement de Netbooker 4  
//  Relais & Chateaux, version 1.1
// version 1.2 : correction du bug lié au changement d'heure d'hiber (dernier weekend d'octobre)
// version 1.3 : correction d'un bug sur les listes déroulantes sous IE 
// version 1.5 : correction d'un bug sur le calcul du nombre de mois pour afficher le calendrier de dispo (03/08/2007)
//  Pour plus d'infos sur ce fichier => webmaster@relaischateaux.com

         //************************************************************************      
	// tells older browsers to treat the script as comments
	// Find out if browser is capable of running the javascript properly
	browserAcceptable = false;
	if ((navigator.appVersion.charAt(1) == '.')) browserVersion = navigator.appVersion.charAt(0);
	else browserVersion = 10; // we know that it must be at least 10;
	if (((navigator.appName == 'Netscape') && (browserVersion > 2)) || ((navigator.appName == 'Microsoft Internet Explorer') && (browserVersion > 3)))
	browserAcceptable = true;
	

      //************************************************************************
      // Function:  inidate
      // Purpose:   itinialise les dates en fonction des choix faits dans le HTML
      //************************************************************************

	function inidate(formStr, Day, nb_nuits)
	{
		if (nb_nuits ==0)
		{nb_nuits =2;}
		Today = new Date;
		Jour = Today.getDate();
		Mois = (Today.getMonth())+1;
		Annee = Today.getFullYear();
		Jourarr = Jour + Day;
		if (Jourarr > getDaysInMonth(Mois, Annee)) {
			Jourarr = Jourarr - getDaysInMonth(Mois, Annee);
			Mois = Mois + 1;
			if (Mois>12) {
				Mois = 1;
				Annee = Annee+1;
			}
		}
		Jourdept = Jourarr + nb_nuits;
		

		document.forms[formStr].DATERANGESTART_MONTH.value= Mois;
		document.forms[formStr].DATERANGESTART_YEAR.value= Annee;
		document.forms[formStr].DATERANGESTART_DAY.value= Jourarr;
		
		document.forms[formStr].DATERANGEEND_MONTH.value= Mois ;
		document.forms[formStr].DATERANGEEND_YEAR.value= Annee;
		document.forms[formStr].DATERANGEEND_DAY.value= Jourdept;

		
		document.forms[formStr].NUMBER_OF_NIGHTS.value =nb_nuits;
		
		validateDay(formStr,'DATERANGEEND_YEAR', 'DATERANGEEND_MONTH', 'DATERANGEEND_DAY');
		
		updateSTART_DATE(formStr,'','');
		
		
	}

      //************************************************************************
      // Function:  changeYear
      // Purpose:   Updates the year if incrementing or decrementing into the
      //            previous or following year.
      // Input:     direction - incrementing or decrementing
      //            month - month that is being updated.
      //            year - current year value.
      // Output:    Updated year.
      //************************************************************************
         function changeYear (direction, month, year)
         {
            // increments or decrements month when it goes past Jan or Dec
            var theYear = year
            if (direction=='next')
            {
               if (month == 12)
               {
                  theYear = (year + 1)
               }
            }
            if (direction=='prev')
            {
               if (month == 1)
               {
                  theYear = (year - 1)
               }
            }
            return theYear
         }

      //************************************************************************
      // Function:  isLeapYear
      // Purpose:   Determine if a year is a leap year.
      // Input:     yrStr - year to determine leapness..
      // Output:    true - if the year is a leap year.
      //            false - otherwise.
      //************************************************************************
      function isLeapYear(yrStr)
      {
        var leapYear=false;
        // every fourth year is a leap year
        if ((parseInt(yrStr, 10)%4) == 0)
        {
          leapYear=true;
        }
        return leapYear;
      }
      //************************************************************************
      // Function:  getDaysInMonth
      // Purpose:   Determine the number of days in a month.
      // Input:     mthIdx - month
      //            yrStr - year
      // Output:    true - if the year is a leap year.
      //            false - otherwise.
      //************************************************************************
      function getDaysInMonth(mthIdx, YrStr)
      {
        // all the rest have 31
        var maxDays = 31
        // expect Feb. (of course)
        if (mthIdx==2)
        {
          if (isLeapYear(YrStr))
          {
            maxDays=29;
          }
          else
          {
            maxDays=28;
          }
        }
        // thirty days hath...
        if (mthIdx==4 || mthIdx==6 || mthIdx==9 || mthIdx==11)
        {
          maxDays=30;
        }
        return maxDays;
      }

      //************************************************************************
      // Fonction addDays (addition de jours)
      //************************************************************************
       function addDays(myDate,days)
       {
          return new Date(myDate.getTime() + days*25*60*60*1000);
       }
      //************************************************************************
      // Function:  updateDATES
      // Purpose:   Update the Departure Date to the Arrival Date + 1.
      // Input:     language - language used by the WEB page.
      //            locale - locale used by the WEB page.
      // Output:    None
      //************************************************************************
      function updateDATES(formStr, language, locale, days)
      {    
        // Get the current arrival date.
        var startYear = parseInt (document.forms[formStr].DATERANGESTART_YEAR.value, 10);
        var startMonth = parseInt (document.forms[formStr].DATERANGESTART_MONTH.value, 10);
        var startDay = parseInt (document.forms[formStr].DATERANGESTART_DAY.value, 10);
        var startDate = new Date (startYear, startMonth - 1, startDay);
        // Get the current departure date.
        var endYear = document.forms[formStr].DATERANGEEND_YEAR.value;
        var endMonth = document.forms[formStr].DATERANGEEND_MONTH.value;
        var endDay = document.forms[formStr].DATERANGEEND_DAY.value;
        var endDate = new Date (endYear, endMonth - 1, endDay);
       // If the arrival date is greater than the departure date then update the departure date.
       
	   
	 
	   
		var done = true;
        var daydiff = DateDiff( startDate,endDate,'d');
		
        var nights=0;
        if (days != -1)
        {		 
		
          endDate = addDays(startDate,days);
		  
          endYear = endDate.getFullYear() ;
          endMonth = endDate.getMonth() + 1;		  
          endDay = endDate.getDate() ;	  
          
          updateDateCombos(formStr,language, locale,endYear,endMonth,endDay,'DATERANGEEND_YEAR', 'DATERANGEEND_MONTH', 'DATERANGEEND_DAY', 'DATERANGEEND_DOW');
		   		
		document.forms[formStr].DATERANGEEND_YEAR.value= endYear;
		document.forms[formStr].DATERANGEEND_MONTH.value= endMonth;
		document.forms[formStr].DATERANGEEND_DAY.value= endDay;
        }
        else
        {
			
          if(daydiff > 0)
          {
            nights = daydiff;
          }
          else
          {
            nights = document.forms[formStr].NUMBER_OF_NIGHTS.value;
            }

          if (document.forms[formStr].NUMBER_OF_NIGHTS.value !=null)
          {
            document.forms[formStr].NUMBER_OF_NIGHTS.value = nights;
          }
        }
		
	}
	
	
	//************************************************************************	

      function updateDateCombos(formStr,language, locale,endYear,endMonth,endDay,yearID,monthID,dayID,wkID)
      {
      
	  
      
        var objYear = eval("document.forms[formStr]."+yearID);
	    var objMonth = eval("document.forms[formStr]."+monthID);
        var objDay = eval("document.forms[formStr]."+dayID);
		
          // Update departure year.
	          
		if (objYear.options) {
			  for (index = 0; (index < objYear.length) && (objYear.options[index].value != endYear);index++);				   
			  if (objYear.options) {
			  	objYear.options[index].selected = true;
			  }
			  else {
				objYear.value=index;
			  }
		}
		else {
			objYear.value=endYear;
		}
		
		if (objMonth.options) {
          // Update departure month.
          for (index = 0; (index < objMonth.length) &&
                          (objMonth.options[index].value != endMonth);
               index++);
		  if (objMonth.options) {
		  	objMonth.options[index].selected = true;
		  }
		  else {
			objMonth.value=index;
		  }
		 }
		 else {
		 
		 objMonth.value=endMonth;
		 }
		 

          // Update departure day.
		 if (objDay.options) { 
          for (index = 0; (index < objDay.length) &&
                          (objDay.options[index].value != endDay);
               index++);
			if (objDay.options) {
			  objDay.options[index].selected = true;
			}
			else {
			objDay.value=index;
			}
        }
		else {
		objDay.value=endDay;
		}
        return true;
      }
      //************************************************************************
      // Function:  updateNUMBER_OF_NIGHTS
      // Purpose:   Update the nights as per the arrival and departure date diff.
      // Input:     nights - number of nights.
      // Output:    none.
      //************************************************************************
      function updateNUMBER_OF_NIGHTS(formStr,language,locale)
      {
      	var nights = 0;
		
 		if (document.forms[formStr].DATERANGESTART_MONTH.value != null)
        {
            nights = document.forms[formStr].NUMBER_OF_NIGHTS.value;
        }
		
        if (nights.substring(0,1) != '-')
        {
             updateDATES(formStr, language, locale, nights);
        }
		
		
	}
      
      //*****************************************************
      function updateSTART_DATE(formStr, language, locale)
      {
     
          updateNUMBER_OF_NIGHTS(formStr, language, locale);
      }

      //************************************************************************
      // Function:  DateDiff
      // Purpose:   Diff of two dates.
      // Input:     startDate, endDate, interval (m-month, d-day, y-year)
      // Output:    difference in interval.
      //************************************************************************
      function DateDiff( start, end, interval )
      {
        var iOut = 0;
        var rounding =0;

        // Create 2 error messages, 1 for each argument.
        var startMsg = "Check the Start Date and End Date\n"
            startMsg += "must be a valid date format.\n\n"
            startMsg += "Please try again." ;

        var intervalMsg = "Sorry the dateAdd function only accepts\n"
            intervalMsg += "d, h, m OR s intervals.\n\n"
            intervalMsg += "Please try again." ;

        var bufferA = Date.parse( start ) ;
        var bufferB = Date.parse( end ) ;

        // check that the start parameter is a valid Date.
        if ( isNaN (bufferA) || isNaN (bufferB) ) {
            alert( startMsg ) ;
            return null ;
        }
        // check that an interval parameter was not numeric.
        if ( interval.charAt == 'undefined' ) {
            // the user specified an incorrect interval, handle the error.
            alert( intervalMsg ) ;
            return null ;
        }
        var number = bufferB-bufferA ;
        // what kind of add to do?

        switch (interval.charAt(0))
        {
            case 'd': case 'D':
                iOut = parseInt(number / 86400000) ;
                if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
                break ;
            case 'h': case 'H':
                iOut = parseInt(number / 3600000 ) ;
                if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
                break ;
            case 'm': case 'M':
                iOut = parseInt(number / 60000 ) ;
                if(rounding) iOut += parseInt((number % 60000)/30001) ;
                break ;
            case 's': case 'S':
                iOut = parseInt(number / 1000 ) ;
                if(rounding) iOut += parseInt((number % 1000)/501) ;
                break ;
            default:
            // If we get to here then the interval parameter
            // didn't meet the d,h,m,s criteria.  Handle
            // the error.
            alert(intervalMsg) ;
            return null ;
        }
        return iOut ;
    }
      //************************************************************************
      // Function:  validateDay
      // Purpose:   Ensure that a selected day is valid. Example 2/31 is an
      //            invalid day. If an invalid date is selected, select the
      //            previous valid day.
      // Input:     yearCtrl - Year dropdown.
      //            monthCtrl - Month dropdown.
      //            dayCtrl - Day dropdown.
      // Output:    None
      //************************************************************************
      function validateDay (formStr, yearCtrl, monthCtrl, dayCtrl)
      {
		
        eval ("var year = parseInt (document.forms['"+formStr+"'].DATERANGESTART_YEAR.options[document.forms['"+formStr+"'].DATERANGESTART_YEAR.selectedIndex].value, 10)");
        eval ("var month = parseInt (document.forms['"+formStr+"'].DATERANGESTART_MONTH.options[document.forms['"+formStr+"'].DATERANGESTART_MONTH.selectedIndex].value, 10)");
        eval ("var day = parseInt (document.forms['"+formStr+"'].DATERANGESTART_DAY.options[document.forms['"+formStr+"'].DATERANGESTART_DAY.selectedIndex].value, 10)");
		
        if (day > (maxDay = getDaysInMonth (month, year)))
        {
         for (index = 0; (index < eval ("document.forms[formStr].DATERANGESTART_DAY.length")) &&
		(eval ("document.forms[formStr].DATERANGESTART_DAY[" + index +"].value != " + maxDay));index++);
          eval ("document.forms[formStr].DATERANGESTART_DAY[" + index +"].selected = true");
	    }
      }


      //************************************************************************
      // Function to see the planning with soft date search
      //************************************************************************

	function check_date_end_range(monform, delai_mini, nb_month){
		if (Number(monform.arriveMonth.value)+nb_month>12) {
			mois_cible = nb_month-1;
			annee_cible = Number(monform.arriveYear.value)+1;			
		}
		else {
			mois_cible = Number(monform.arriveMonth.value)+nb_month-1;
			annee_cible = monform.arriveYear.value;			
		}
		//window.alert("TEST 2 " + mois_cible);
		
		monform.arriveDateEnd.value = getDaysInMonth(mois_cible, annee_cible);
		monform.arriveMonthEnd.value = mois_cible;
		monform.arriveYearEnd.value =  annee_cible;
		return true;
	}
