// dateValidator.js


//--------------------------------------------------------------------------------------------
				// I N I T
// -------------------------------------------------------------------------------------------

// set the in & out dates with the hidden fields date values if any
// hidden fields date format is yyyy-mm-dd
function loadDates(fo)
{
   		// check if all fields are here
		// hidden fields
   		if(fo.arrivalDate == null || fo.departureDate == null)
      		    return;
		// form fields
		if( ! datesExist(fo) )
		 		return;

   		// shortcut vars
   		var arv = fo.arrivalDate.value;
   		var dpt = fo.departureDate.value;
		// load the dates from the hidden fields, or if they're empty, default the to today
        //2005.31.03 DJB handled in the JSP, no need to call setDateToToday
		//(arv != '' && dpt != '') ? loadDatesFromFields(fo, arv, dpt) : setDateToToday(fo) ;
		if (fo.lengthOfStay != null && fo.lengthOfStay.type == 'select-one' && fo.lengthOfStay.length == 1) setCheckoutFromStay(fo);
        if(arv != '' && dpt != ''){
            loadDatesFromFields(fo, arv, dpt);
        }
}

//-------------------------------------------------------------

// default the checkin date to today's date
function setDateToToday(fo)
{
		// get the date from server (defined in JSP page) if we can.
		var now;
		// donot use system time for default date
		//(typeof today == 'undefined' || today == null) ? now = new Date() : (now = today);
		now = new Date();
        //-----------changed by Chinmei for promo booking funciton------------------------------
        var myDate=location.search.substring(1);
        var dateArray = myDate.split('&');
        var myYear;
        var myDay;
        var myMon;
        for (i=0;i<dateArray.length;i++){
             	if ((dateArray[i].substring(0,6)=="myYear")||(dateArray[i].substring(0,5)=="myDay")||(dateArray[i].substring(0,5)=="myMon")){
        	    eval(dateArray[i]);
            	}
		}

        if ((myYear!=null)&&(myDay!=null)&&(myMon!=null)) {
          var index_year = myYear;
  		  var index_month = myMon-1;
  		  var index_day = myDay-1;
		  setSelectorSelected( fo.arrivalDateYear, index_year ); //dkersting: added function call to populate appropriate dropdown
		  //fo.arrivalDateYear.options[index_year].selected = true; //dkersting: commented out
        }else{
  		//debug( "Today is " + now.getMonth() + "/" + now.getDate() + "/" + now.getFullYear());
  		var index_year =  getYearIdx( now.getFullYear() );
  		// bsmith - going to bypass this 'index attempt' below:  see comment

  		//debug('setDateToToday::getYearIdx( now.getFullYear() ) = ' + index_year );
  		var index_month = now.getMonth(); // in Javascript, months are zero-based, in HTML, it's also zero-based.
  		// 2005.24.03 DJB removed -1 on index_day to set arrival dates to tommorow as per CQ34930
        var index_day = now.getDate();

  		//debug("indexes :");
  		//debug("year= " + index_year + " month= " + index_month + " day= " + index_day);

  		//fo.arrivalDateYear.options[index_year].selected = true; // bsmith - this seems buggy - assumes year digits map to index numbers of selector options
  		setSelectorSelected( fo.arrivalDateYear, now.getFullYear() );//     - this makes no assumptions about indexes and relationships to year numbers.
  		}
        //------------------end of chinmei's code changes--------------------------------------------------------                                                        //     - also, should not affect the other functionality here as index_year is not an arg to any other function called in this function
  		fo.arrivalDateMonth.options[index_month].selected = true;
  		fo.arrivalDateDay.options[index_day].selected = true;

		// set the other date fields accordingly (i.e + 1 day)
		setStayFromCheckin(fo);
		setCheckoutFromCheckin(fo);

}

//--------------------------------------------------------------

// load the hidden fields dates into the drop-down
function loadDatesFromFields(fo, arv, dpt)
{
	arr = new Array(3);
    offset = parseInt(fo.arrivalDateYear.options[1].value.toString().slice(2),10)-1;
   		// checkin
   		if(arv != '' && (arr = parser(arv)) != null)
   		{
	  	// debug('From parser, arrivalDate : ' + arr[0] + ' ' + arr[1] + ' ' + arr[2]);
                /*commented this next line out because the logic to find the index of the year is faulty*/
	  	    fo.arrivalDateYear.options[ getYearIdx( arr[0] )-offset].selected = true;
      		fo.arrivalDateMonth.options[ arr[1]-1].selected = true;
      		fo.arrivalDateDay.options[ arr[2]-1].selected = true;
	  		var chin = new Date( arr[0], arr[1]-1, arr[2] );
   		}

   		// checkout
   		if(dpt != '' &&  (arr = parser(dpt)) != null)
   		{
      		// debug('From parser, departureDate : ' + arr[0] + ' ' + arr[1] + ' ' + arr[2]);
                /*commented this next line out because the logic to find the index of the year is faulty*/
      		fo.departureDateYear.options[ getYearIdx( arr[0] )-offset].selected = true;
      		fo.departureDateMonth.options[ arr[1]-1].selected = true;
      		fo.departureDateDay.options[ arr[2]-1].selected = true;
	  		var chout = new Date( arr[0], arr[1]-1, arr[2] );
   		}

   		// len of stay
   		if(arv != '' && dpt != '' && fo.lengthOfStay != null)
		{
			var diff = getDiffDaysNumber(chin,chout);
			if(diff > 32 || diff <0)
				diff = 0;

			setStayValue(fo, diff);
			/*(fo.lengthOfStay.options != null) ?
     			(fo.lengthOfStay.options[ diff ].selected = true)
				: (fo.lengthOfStay.value = diff) ;*/

   		}

		//debug('Date fields coming in: ');
	    //debug('---------------');
	  	//debug('arrivalDate= ' + arv);
	  	//debug('departureDate= ' + dpt);
	  	//debug('lengthOfStay= ' + getStayValue(fo));
	  	//debug('---------------');
}

//--------------------------------------------------------------------------------------------
				// E V E N T    H A N D L I N G
// -------------------------------------------------------------------------------------------


// dynamic behavior : populate checkout if loStay is set and vice-versa
function setFormHandlers(){
    var i = 0;
    while(document.forms[i])
    {
        var f = document.forms[i];
        if(	   f.arrivalDateMonth != null
            && f.arrivalDateDay != null
            && f.arrivalDateYear != null
            && f.departureDateMonth != null
            && f.departureDateDay != null
            && f.departureDateYear != null )
        {
              if (f.lengthOfStay != null && f.lengthOfStay.type == 'select-one' && f.lengthOfStay.length == 1)
              {
                f.arrivalDateDay.onchange = function() { setStayFromCheckin(f); }
                f.arrivalDateMonth.onchange = function() { setStayFromCheckin(f); }
                f.arrivalDateYear.onchange = function() { setStayFromCheckin(f); }
              }
              else if (f.lengthOfStay != null && f.lengthOfStay.type == 'select-one')
              {
                f.lengthOfStay.onchange = function(){ setCheckoutFromStay(f); }

                f.departureDateDay.onchange = function() { setStayFromCheckout(f); }
                f.departureDateMonth.onchange = function() { setStayFromCheckout(f); }
                f.departureDateYear.onchange = function() { setStayFromCheckout(f); }

                f.arrivalDateDay.onchange = function() { setStayFromCheckin(f); }
                f.arrivalDateMonth.onchange = function() { setStayFromCheckin(f); }
                f.arrivalDateYear.onchange = function() { setStayFromCheckin(f); }
              }
              else // no length of Stay field in the form
              {
                f.arrivalDateDay.onchange = function() { setCheckoutFromCheckin(f); }
                f.arrivalDateMonth.onchange = function() { setCheckoutFromCheckin(f); }
                f.arrivalDateYear.onchange = function() { setCheckoutFromCheckin(f); }
                f.departureDateDay.onchange = function() { setCheckinFromCheckout(f); } /*##### new */
                f.departureDateMonth.onchange = function() { setCheckinFromCheckout(f); }/*##### new */
                f.departureDateYear.onchange = function() { setCheckinFromCheckout(f); }/*##### new */

              }
            break;
        }

        i++;// next form if any
    }
}
//-------------------------------------
// set the checkout date form the checkin date at start
// to reflect a stay of 1 day by default
/*################## new function */

//-------------------------------------
// set the checkout date form the checkin date at start
// to reflect a stay of 1 day by default
function setCheckinFromCheckout(f)
{
		//alert("setCheckoutFromCheckin");
		// use short names
		// values
  		var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  		var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  		var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

        var checkinFilled = ( inyear != '' && inmonth != '' && inday != '');
			//alert("checkinFilled " + checkinFilled);
		if( !checkinFilled)
			return;
			//alert("passed return checkin");

 	 	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  		var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  		var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

        var checkoutFilled = ( outyear != '' && outmonth != '' && outday != '');
		//alert("checkoutFilled " + checkoutFilled);
		// if chout is filled just return

		/* ############# Changes from checkoutFilled to !checkoutFilled############# */
		if(!checkoutFilled)
			return;
			//alert("passed return checkout");



		// we have checkin but not checkout. set checkout = checkin + 1 day
		var checkin = new Date(inyear, inmonth -1, inday);
		var checkout = new Date(outyear, outmonth -1, outday);

		//alert("Checkin:"+checkin.getTime()+" Checkout:"+checkout.getTime());

		if (checkin.getTime() >= checkout.getTime())	{

		//alert("mew function");

			oneDayInMillis =  24 * 3600 * 1000;
			checkinMillis = checkout.getTime() - oneDayInMillis;
			chin = new Date( checkinMillis );



			f.arrivalDateDay.selectedIndex = parseInt( chin.getDate(), 10 ) - 1;
			f.arrivalDateMonth.selectedIndex = parseInt( chin.getMonth(), 10 );
			offset = parseInt(f.departureDateYear.options[1].value.toString().slice(2),10)-1;
			if(typeof pastDates == 'undefined' || pastDates == null)
				f.arrivalDateYear.selectedIndex = parseInt( chin.getFullYear().toString().slice(2), 10 )-offset;
			else
			{
				// SPG specific.
				// we can have dates in the past in that particular form, e.g when asking for missing
				// credits for a stay in a hotel
				// the problem is that the above code will give us an index of 0 for year 2000 .
				// we'll just do a +1 on the index

				debug('SPG specific');
				f.arrivalDateYear.selectedIndex = parseInt( chin.getFullYear().toString().slice(2), 10 ) - offset;
			}
		}

}




/*############################################# changed Function*/
//-------------------------------------
// set the checkout date form the checkin date at start
// to reflect a stay of 1 day by default
function setCheckoutFromCheckin(f)
{
		//alert("setCheckoutFromCheckin");
		// use short names
		// values
  		var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  		var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  		var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

        var checkinFilled = ( inyear != '' && inmonth != '' && inday != '');
			//alert("checkinFilled " + checkinFilled);
		if( !checkinFilled)
			return;
			//alert("passed return checkin");

 	 	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  		var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  		var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

        var checkoutFilled = ( outyear != '' && outmonth != '' && outday != '');
		//alert("checkoutFilled " + checkoutFilled);
		// if chout is filled just return

		/* ############# Changes from checkoutFilled to !checkoutFilled############# */
		if(!checkoutFilled)
			return;
			//alert("passed return checkout");



		// we have checkin but not checkout. set checkout = checkin + 1 day
		var checkin = new Date(inyear, inmonth -1, inday);
		var checkout = new Date(outyear, outmonth -1, outday);

		//alert("Checkin:"+checkin.getTime()+" Checkout:"+checkout.getTime());

		if (checkin.getTime() >= checkout.getTime())	{

			oneDayInMillis =  24 * 3600 * 1000;
			checkoutMillis = checkin.getTime() + oneDayInMillis;
			chout = new Date( checkoutMillis );

			f.departureDateDay.selectedIndex = parseInt( chout.getDate(), 10 ) - 1;
			f.departureDateMonth.selectedIndex = parseInt( chout.getMonth(), 10 );
             if(typeof pastDates != 'undefined' && pastDates != null)
            {
            f.departureDateMonth.selectedIndex = parseInt( chout.getMonth(), 10 )+1;
            f.departureDateDay.selectedIndex = parseInt( chout.getDate(), 10 );
            }
            offset = parseInt(f.arrivalDateYear.options[1].value.toString().slice(2),10)-1;
			if(typeof pastDates == 'undefined' || pastDates == null)
				f.departureDateYear.selectedIndex = parseInt( chout.getFullYear().toString().slice(2), 10 )-offset;
			else
			{
				// SPG specific.
				// we can have dates in the past in that particular form, e.g when asking for missing
				// credits for a stay in a hotel
				// the problem is that the above code will give us an index of 0 for year 2000 .
				// we'll just do a +1 on the index

				debug('SPG specific');
				f.departureDateYear.selectedIndex = parseInt( chout.getFullYear().toString().slice(2), 10 ) - offset;
			}
		}

}

//------------------------
function setStayFromCheckin(f)
{
      // debug('setStayFromCheckout called');
 	// use short names
		// values
  		var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  		var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  		var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

        var checkinFilled = ( inyear != '' && inmonth != '' && inday != '');
		if( !checkinFilled)
			return;

 	 	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  		var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  		var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

        var checkoutFilled = ( outyear != '' && outmonth != '' && outday != '');
		// if chout is filled set the stay from there
		if(checkoutFilled && ((f.lengthOfStay != null && f.lengthOfStay.options.length > 1) || f.lengthOfStay == null))
		{
			setStayFromCheckout(f);
			return;
		}
		// if stay is already filled, it will be set from checkout
		if(getStayValue(f) != '')
		{
			setCheckoutFromStay(f);
			return;
		}
		// otherwise, we are entering a checkin date for the first time
		// set a default stay of 1 day and the corresponding checkout date
		setStayValue(f,1);
		setCheckoutFromStay(f);

}

//------------------------
function setStayFromCheckout(f)
{
	// debug('setStayFromCheckout called');
 	// use short names
	var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
	var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
	var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

	var checkinFilled = ( inyear != '' && inmonth != '' && inday != '');
	if( !checkinFilled)	return;

	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
	var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
	var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

	var checkoutFilled = ( outyear != '' && outmonth != '' && outday != '');
	if( !checkoutFilled) return;

	//var stay = getStayValue(f);

	var checkin = new Date(inyear, inmonth -1, inday);
	var checkout = new Date(outyear, outmonth -1, outday);

	var diff = getDiffDaysNumber(checkin,checkout);
	// this happens when user selects a checkout date so that the lofStay is more than the
	// drop-down allows, or even negative if checkout is mistakenly before checkin.
	// This is possible, since the user has not clicked on 'submit' yet
	// to get the max lofStay of 30 days error...
	/* BEGIN MODIFY
		12/09/2003 by Randy Knight for CQ 23637 */

	if (diff > 31) diff = 31;
	if (diff <= 0)	diff = 1;

	setStayValue(f, diff);
        if(typeof pastDates == 'undefined' || pastDates == null)
        {
        setCheckoutFromStay(f);
         }

    /* END MODIFY */
}
//-------------------------
function setCheckoutFromStay(f)
{
    //debug('setCheckoutFromStay called');

      // use short names
         // values
           var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
           var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
           var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

         var checkinFilled = ( inyear != '' && inmonth != '' && inday != '');
         if( !checkinFilled)
             return;

         var stay = getStayValue(f);
         if( stay == '')
             return;

           var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
           var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
           var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;
         var checkin = new Date(inyear, inmonth-1, inday);


         // a stay=1 corresponds to options[1] in the drop-down.
         idx = parseInt( stripZero(stay), 10 );
         stayInMillis = idx * 24 * 3600 * 1000;
         addMillis = checkin.getTime() + stayInMillis;
         chout = new Date( addMillis + 3600*1000 );

                 //fix for strange October 28,2001 bug - BEGIN
                 var oneDayInMillisAdjusted = (24 * 3600 * 1000) + (3600 * 1000);
                 if(chout.getDate() == checkin.getDate() && idx == 1) {
                     while(chout.getDate() == checkin.getDate()) {
                         chout = new Date(checkin.getTime() + oneDayInMillisAdjusted);
                         oneDayInMillisAdjusted += 3600;
                     }
                 }
             //fix for strange October 28,2001 bug - END

         f.departureDateDay.selectedIndex = parseInt( chout.getDate(), 10 ) - 1;
         f.departureDateMonth.selectedIndex = parseInt( chout.getMonth(), 10 );
        if(typeof pastDates != 'undefined' && pastDates != null)
        {
         f.departureDateMonth.selectedIndex = parseInt( chout.getMonth(), 10 )+1;
         }
          /*if(typeof pastDates != 'undefined' && pastDates != null)
          {
              // SPG Missing Credits Specific
             // we can have dates in the past in that particular form,  when asking for missing
             // credits for a stay in a hotel
          f.departureDateDay.selectedIndex = parseInt( chout.getDate(), 10 );
           }*/
         offset = parseInt(f.arrivalDateYear.options[1].value.toString().slice(2),10)-1;
         if(typeof pastDates == 'undefined' || pastDates == null)
         {
             f.departureDateYear.selectedIndex = parseInt( chout.getFullYear().toString().slice(2), 10 )-offset;
             //debug('f.departureDateYear.selectedIndex = ' + f.departureDateYear.selectedIndex);
         }
         else
         {
             // SPG specific.
             // we can have dates in the past in that particular form, e.g when asking for missing
             // credits for a stay in a hotel
             // the problem is that the above code will give us an index of 0 for year 2000 .
             // we'll just do a +1 on the index

             debug('SPG specific');
             f.departureDateYear.selectedIndex = parseInt( chout.getFullYear().toString().slice(2), 10 ) - offset;
         }



}


//--------------------------------------------------------------------------------------------
				// E R R O R    H A N D L I N G
// -------------------------------------------------------------------------------------------
// button e.g : search or continue or...
//
//var button ; //document.searchBrand ? 'Search' : 'Continue';

//-------------------------------------------------
// this function is called first
// sets the msgs
// calls the err hdler
function checkDates(fo,btn)
{
  //button = btn;
   return okDates(fo) ? true : false;
}

//--------------------------------------------------------
// check the dates
// if called with a second arg, dates are required, otherwise dates can be empty.
// Error : incomplete or invalid dates
// Error : checkin date after checkout date
// Error : checkin date = checkout date
// Error : checkin date before today
// Error : too far out in the future
// Error : stay too long
function okDates(f)
{
		  if( arguments[1] == null && fieldsEmpty(f) )
		     return true;

		  if(arguments[1] != null && fieldsEmpty(f) && ! okDatesReq(f))
			 return false;

		  if( ! okCheckin(f) )
		     return false;

		  if( ! okCheckout(f) )
		     return false;

		  if( ! okCheckinAndCheckout(f) )
		     return false;


		  // fill in date hidden fields if any
		  fillInDates(f);

   	  	  return true;
}

//------------------------------------------------------
// ADDED: if no date field is filled at all, just return true without doing any checking,
// since user should be able to do a global search without a date
function fieldsEmpty(f)
{
   		// all fields must exist, otherwise the check is not needed
   		if( ! datesExist(f) )
		 		return true;

  		// use short names
  		var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  		var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  		var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

 	 	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  		var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  		var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;
		var stay = getStayValue(f);

  		// If no date field is filled at all, just return true without doing any checking,
  		// since user should be able to do a global search without a date
  		if( inyear == '' && inmonth == '' && inyear == ''
      		&& outyear == '' && outmonth == '' &&  outday == '' )
		{
		        // reset the dates hidden fields
				if(f.arrivalDate != null && f.departureDate != null)
				{
						f.arrivalDate.value = '';
			    		f.departureDate.value = '';
			    		// debug('Dates reset');
				}

		   		if(stay == '')
		      		return true;
		}

		return false;
}
//-----------------------------------------------------
// case where the dates are required
 function okDatesReq(f)
{
	error('datesRequired');
	return false;
}
//------------------------------------------------------
function getOpeningDate(){
    var openDateString=propertyOpenInfo.openDate;
    if (openDateString && openDateString.length>0){
        var openDateArray = openDateString.split("/");
        var openDate = new Date();
        openDate.setFullYear(openDateArray[2],openDateArray[0]-1,openDateArray[1]);
        var openDateObj = {openDate:openDate,openDateDisplay:propertyOpenInfo.openDateDisplay};
        return openDateObj;
    }
}
function outputOpenDateError_preDecider(displayDate){
    var checkinDateBeforeOpendateContainer = document.getElementById("topMsgDiv");
    var dateField = yuiDom.getElementsByClassName('openDateDisplay','span',checkinDateBeforeOpendateContainer)[0];
    dateField.innerHTML=displayDate;

    if (document.getElementById("errorHandlerContainer")){
        document.getElementById("errorHandlerContainer").style.display="none";    
    }
    return true;
}

// Error : incomplete or invalid checkin date
// Error : checkin date before today  (not with a partial check, i.e second arg supplied)
function okCheckin(f)
{
    	if( ! datesExist(f) )
		 		return true;

  		// use short names
  		var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  		var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  		var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;

		if ( ! dateValid(inyear,inmonth,inday) )
		{
		  	error('dateInvalid',f.arrivalDateMonth, f.arrivalDateDay, f.arrivalDateYear );
		  	return false;
		}

		// if a second arg is supplied here, it means that we 're done. (partialCheck)
		if(arguments[1] != null)
			return true;

		// Error : checkin date before today
                if (typeof(today)=='undefined') {
		    today = new Date();
		}
		// Note: in Javascript, months are zero-based (i.e Jan is 0 and Dec is 11),
   		var checkin = new Date(inyear, inmonth -1, inday);
	  	if(getDiffDaysNumber(today,checkin) <-1)
	  	{
	      	error('checkinBeforeToday',f.arrivalDateMonth, f.arrivalDateDay, f.arrivalDateYear );
		  	return false;
	  	}
        var openingDateObj = getOpeningDate();
        if (openingDateObj!=null){
           var openDelta = getDiffDaysFloor(checkin,openingDateObj.openDate);
            if (openDelta>0){
                error('checkinDateBeforeOpendate', f.arrivalDateMonth, f.arrivalDateDay, f.arrivalDateYear);
                outputOpenDateError_preDecider(openingDateObj.openDateDisplay);
                return false;
                
            }
        }
		return true;
}
//--------------------------------------------------------
// Error : incomplete or invalid checkout date
function okCheckout(f)
{
        if( ! datesExist(f) )
		 		return true;

  		// use short names
 	 	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  		var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  		var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

		if ( ! dateValid(outyear,outmonth,outday) )
	    {
	  	  	     error('dateInvalid',f.departureDateMonth, f.departureDateYear,
			                         f.departureDateDay );
	      	     return false;
	    }

		return true;
}

//------------------------------------------------------
// Error : checkin date after checkout date
// Error : checkin date = checkout date
// Error : too far out in the future  (not with a partial check, i.e second arg supplied)
// Error : stay too long  (not with a partial check, i.e second arg supplied)
function okCheckinAndCheckout(f)
{
      if( ! datesExist(f) )
		 		return true;

  		// use short names
  		var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  		var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  		var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;
 	 	var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  		var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  		var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

		var checkin = new Date(inyear, inmonth -1, inday);
   		checkoutFilled = ( outyear != '' && outmonth != '' && outday != '');
   		if(checkoutFilled)
     		var checkout = new Date(outyear, outmonth -1, outday);

		// Error : checkin date after checkout date
		if( checkoutFilled && getDiffDaysNumber(checkin,checkout) <0 )
		{
	      		error('checkinAfterCheckout',f.arrivalDateMonth, f.arrivalDateDay,
											 f.arrivalDateYear, f.departureDateMonth,
				                             f.departureDateYear, f.departureDateDay );
		  		return false;
	   	}

        // Error : checkin date = checkout date
	    if( checkoutFilled && inyear == outyear && inmonth == outmonth && inday == outday )
		{
	      		error('checkinEqualsCheckout',f.arrivalDateMonth, f.arrivalDateDay,
											  f.arrivalDateYear, f.departureDateMonth,
				                              f.departureDateYear, f.departureDateDay );
		  		return false;
	   	}

		// if a second arg is supplied here, it means that we 're done (partialCheck)
		if(arguments[1] != null)
			return true;

		if(checkoutFilled)
	  	{
   			// Error : too far out in the future (> 550 days or 18 months)
		    if (typeof(today)=='undefined') {
			today = new Date();
		    }
                    var isCashAndPointsRes = (f.promoType != null && f.promoType.value == 'CP');
		    var limit = isCashAndPointsRes ? new Date("January 3, 2004") : new Date(550 * 24 * 60 * 60 * 1000);
		    var excess = isCashAndPointsRes? (((checkout.getTime()-limit.getTime()) > 0) ? true : false) : ((checkout.getTime() - today.getTime() > limit.getTime())? true : false);


		    if (excess)
	      	{
                    if(isCashAndPointsRes) {
                        error('checkoutTooFarForCashAndPoints',f.arrivalDateMonth,f.arrivalDateDay,
                              f.arrivalDateYear,f.departureDateMonth, f.departureDateYear, f.departureDateDay );
                    } else {
		        error('checkoutTooFar',f.arrivalDateMonth, f.arrivalDateDay, f.arrivalDateYear,
			      f.departureDateMonth, f.departureDateYear, f.departureDateDay );
                    }
                    return false;
	      	}


   		  	// Error : stay too long (> 30 days or 1 month)
		  	limit = new Date(31 * 24 * 60 * 60 * 1000);
		  	excess = (checkout.getTime() - checkin.getTime() > limit.getTime())
		                   ? true : false ;
		  	if (excess)
	   	  	{
	        		error('stayTooLong',f.arrivalDateMonth, f.arrivalDateDay, f.arrivalDateYear,
			                    f.departureDateMonth, f.departureDateYear, f.departureDateDay );
		    		return false;
	      	}

	   	}


		return true;
}
//----------------------------------------------------
// update if necessary the date hidden fields
function fillInDates(f)
{
         if(f.arrivalDate == null || f.departureDate == null)
				return;

		  if( ! datesExist(f) )
		 		return;

		   // use short names
  			var inyear = f.arrivalDateYear.options[f.arrivalDateYear.selectedIndex].value;
  			var inmonth = f.arrivalDateMonth.options[f.arrivalDateMonth.selectedIndex].value;
  			var inday = f.arrivalDateDay.options[f.arrivalDateDay.selectedIndex].value;
 	 		var outyear = f.departureDateYear.options[f.departureDateYear.selectedIndex].value;
  			var outmonth = f.departureDateMonth.options[f.departureDateMonth.selectedIndex].value;
  			var outday = f.departureDateDay.options[f.departureDateDay.selectedIndex].value;

		  // 'arrivalDate' --> format : yyyy-mm-dd
          arvDate = inyear + '-' + paddZero(inmonth) + '-' + paddZero(inday) ;
		  f.arrivalDate.value = arvDate;
		  // 'departureDate' --> format : yyyy-mm-dd
		  depDate = outyear + '-' + paddZero(outmonth) + '-' + paddZero(outday) ;
		  f.departureDate.value = depDate;
	      // just in case the user has blanked the lOfstay..
		  if(getStayValue(f) == '')
		  	setStayValue(f, getDiffDaysNumber(new Date(inyear, inmonth -1, inday),
											  new Date(outyear, outmonth -1, outday)) );

		  debug('Date fields going out: ');
	  	  debug('---------------');
	      debug('arrivalDate= ' + arvDate);
	      debug('departureDate= ' + depDate);
		  debug('length of stay= ' + getStayValue(f));
	      debug('---------------');


}


//------------------------------------------------
// utility function to get a year's index
function getYearIdx(y)
{
  		// if(y == 2001) return 1;
  		// else if (y == 2012) return 12;
  		year = y.toString();

        return parseInt( stripZero(year.slice(2)) ,10) ;
}

//-------------------------------------------------
// utility function to validate dates
function dateValid(year, month, day)
{
  		// check for all fields
		if (year == '' || month == '' || day == '')
          		return false;

	   // work with ints
		var y = (year);
		var m = stripZero(month);
		var d = stripZero(day);

	    // debug('Inside dateValid()  y= ' + y + ' m= ' + m + 'd= ' +d );

		if(isNaN(y) || isNaN(m) || isNaN(d))
	  		return false;

		// check for compatibility month-day i.e avoid things like Feb 31

		//  Jan is 1 and Dec is 12
		// Feb(2) cannot have values 29 (except leap year),30,31
		if (m==2)
		{
	   		var isleap = false;
	   		// A year is a leap year if it is evenly divisible by 4 but not evenly divisible by 100
	   		// unless it is also evenly divisible by 400 ...
	   		if (y % 4 ==0)
	   		{
	     		if( !(y % 100 == 0) || ((y % 100 == 0) && (y % 400 == 0)) )
		 			isleap = true;
	   		}

	   		if(d==30 || d==31)
	     		return false;

	   		if(!isleap && d==29)
	     		return false;

		}
		// all 30 - days months should not get 31 : April(4),June(6),Sept(9),Nov(11)
		if (m==4 || m==6 || m==9 || m==11)
		{
	   		if(d==31)
	     		return false;
		}


   		return true;
}

//--------------------------------------------------------
// diff in days between two dates
function getDiffDays(indate,outdate)
{
  		// convert to string
  		return  getDiffDaysNumber(indate,outdate).toString(10);
}

//--------------------------------------------------------
// diff in days between two dates
function getDiffDaysNumber(indate,outdate)
{
  		// this will give us a float i.e something like 7.9583333.. for 8 days
  		var df =  ( outdate.getTime()-indate.getTime() ) / (1000 * 60 * 60 * 24);

  		// convert to a whole number
  		return Math.round(df);

}
function getDiffDaysFloor(indate,outdate)
{
  		// this will give us a float i.e something like 7.9583333.. for 8 days
  		var df =  ( outdate.getTime()-indate.getTime() ) / (1000 * 60 * 60 * 24);

  		// convert to a whole number
  		return Math.floor(df);

}
//--------------------------------------------------------
// check if date fields exist
// use this at the beginning of every function that operates on date fields
function datesExist(f)
{
		  if(
		    f.arrivalDateMonth == null || f.arrivalDateDay == null || f.arrivalDateYear == null
			|| f.departureDateMonth == null || f.departureDateDay == null
			|| f.departureDateYear == null
		    )
		 		return false;

			return true;
}

//-----------------------------------------------------------
// get the lofStay val, if exists
function getStayValue(f)
{
	if(f.lengthOfStay == null)
		return '';

    var stay = '';
	(f.lengthOfStay.options != null) ?
		 ( stay = f.lengthOfStay.options[f.lengthOfStay.selectedIndex].value )
		: ( stay = f.lengthOfStay.value ) ;

	return stay;
}
//------------------------------------------------------------
// set the lOfStay val, if exists
function setStayValue(f,val)
{
	//commented out to avoid displaying blank LOS
	//if(f.lengthOfStay == null)
	//	return ;
   if(val>0)
   {
    (f.lengthOfStay.options != null) ?
     			(f.lengthOfStay.options[ parseInt(val,10) ].selected = true)
				: (f.lengthOfStay.value = val) ;
       }

}

function setSelectorSelected( selector, selectedValue ) {
  if( selector && selector.options && selectedValue ) {
    ix = 0;
    while( ix <selector.length ) {
      if( selector.options[ ix ].value == selectedValue ) {
        selector.selectedIndex = ix;
        break;
      }
      ix++;
    }
  }
}