// Customizable variables
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 3; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var ImageURL = 'http://www.clickhoteles.com.mx/images/customers/mx/img_calendar.gif';
var NextURL = 'next.gif';
var PrevURL = 'prev.gif';
var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightgrey';


// Global variables
var ZCounter = 100;
var Today = new Date();
var WeekDays = new Array('D','L','M','M','J','V','S');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');

// Write out the stylesheet definition for the calendar
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('</style>');
}

// Only allows certain keys to be used in the date field
function NumOnly(e) {
   var KeyCode = (e.keyCode) ? e.keyCode : e.which;
   return ((KeyCode == 8) // backspace
        || (KeyCode == 9) // tab
        || (KeyCode == 37) // left arrow
        || (KeyCode == 39) // right arrow
        || (KeyCode == 46) // delete
        || ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
   );
}

// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

// Is the specified select-list behind the calendar?
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY) {
   var ListLeftX = GetTagPixels(SelectList, 'LEFT');
   var ListRightX = ListLeftX + SelectList.offsetWidth;
   var ListBottomY = ListTopY + SelectList.offsetHeight;
   return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}

// For IE, hides any select-lists that are behind the calendar
function FixSelectLists(Over) {
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var CalDiv = this.getCalendar();
      var CalLeftX = CalDiv.offsetLeft;
      var CalRightX = CalLeftX + CalDiv.offsetWidth;
      var CalTopY = CalDiv.offsetTop;
      var CalBottomY = CalTopY + (CellHeight * 9);
      var FoundCalInput = false;
      formLoop :
      for (var j=this.formNumber;j < document.forms.length;j++) {
         for (var i=0;i < document.forms[j].elements.length;i++) {
            if (typeof document.forms[j].elements[i].type == 'string') {
               if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName)) {
                  FoundCalInput = true;
                  i += 3; // 3 elements between the 1st hidden field and the last year input field
               }
               if (FoundCalInput) {
                  if (document.forms[j].elements[i].type.substr(0,6) == 'select') {
                     ListTopY = GetTagPixels(document.forms[j].elements[i], 'TOP');
                     if (ListTopY < CalBottomY) {
                        if (BehindCal(document.forms[j].elements[i], CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY)) {
                           document.forms[j].elements[i].style.visibility = (Over) ? 'hidden' : 'visible';
                        }
                     }
                     else break formLoop;
                  }
               }
            }
         }
      }
   }
}

// Displays a message in the status bar when hovering over the calendar days
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   if (Over) {
      if ((this.yearValue == Today.getFullYear()) && (this.monthIndex == Today.getMonth()) && (HoveredDay == Today.getDate())) self.status = 'Click to select today';
      else {
         var Suffix = HoveredDay.toString();
         switch (Suffix.substr(Suffix.length - 1, 1)) {
            case '1' : Suffix += (HoveredDay == 11) ? 'th' : 'st'; break;
            case '2' : Suffix += (HoveredDay == 12) ? 'th' : 'nd'; break;
            case '3' : Suffix += (HoveredDay == 13) ? 'th' : 'rd'; break;
            default : Suffix += 'th'; break;
         }
         self.status = 'Click to select ' + this.monthName + ' ' + Suffix;
      }
   }
   else self.status = '';
   return true;
}

// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) {
   this.show();
   var MonthList = this.getMonthList();
   var DayList = this.getDayList();
   var YearField = this.getYearField();
   FixDayList(DayList, GetDayCount(this.displayed.yearValue, this.displayed.monthIndex));
   // Select the month and day in the lists
   for (var i=0;i < MonthList.length;i++) {
      if (MonthList.options[i].value == this.displayed.monthIndex) MonthList.options[i].selected = true;
   }
   for (var j=1;j<=DayList.length;j++) {
      if (j == ClickedDay) DayList.options[j-1].selected = true;
   }
   this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
   // Change the year, if necessary
   YearField.value = this.picked.yearPad;
   YearField.defaultValue = YearField.value;

   var oFuncionClose;
   var sNombreFuncionClose;
   var sFuncionClose;
   sNombreFuncionClose = this.hiddenFieldName+"_OnClose";

   sFuncionClose = ""
   sFuncionClose = sFuncionClose + "if (typeof(" + sNombreFuncionClose + ") == 'undefined') { \n";
   sFuncionClose = sFuncionClose + "	return;\n";
   sFuncionClose = sFuncionClose + "} else { \n";
   sFuncionClose = sFuncionClose + "	return " + sNombreFuncionClose + "();\n";
   sFuncionClose = sFuncionClose + "};\n";

   oFuncionClose = new Function("",sFuncionClose);
   oFuncionClose()

}

// Builds the HTML for the calendar days
function BuildCalendarDays() {
   var Rows = 5;
   var dFechaActualShow;

   dFechaActualShow = new Date();
   dFechaActualShow.setFullYear(this.displayed.yearValue);
   dFechaActualShow.setMonth(this.displayed.monthIndex);

   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:default">';
   for (var j=0;j < Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               TextStyle = 'color:white;font-weight:bold;'
               BackColor = DayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) {
              TextStyle += 'border:1px solid darkred;padding:0px;';
            };
			dFechaActualShow.setDate(Day);

			if (dFechaActualShow - Today >= 0) {
				HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
			} else {
				HTML += '<td align="center" background="images/baddate.gif" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
			}
         } else {
            HTML += '<td class="calendarDateInput" style="height:' + CellHeight + '">&nbsp;</td>';
         };
      };
      HTML += '</tr>';
   };
   return HTML += '</table>';
}

// Determines which century to use (20th or 21st) when dealing with 2-digit years
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}

// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}

// Highlights the buttons
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}

// Mouse-over for the previous/next month buttons
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
      self.status = 'Click to view ' + DateObj.fullName;
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
      self.status = '';
   }
   return true;
}

// Adds/removes days from the day list, depending on the month/year
function FixDayList(DayList, NewDays) {
   var DayPick = DayList.selectedIndex + 1;
   if (NewDays != DayList.length) {
      var OldSize = DayList.length;
      for (var k=Math.min(NewDays,OldSize);k < Math.max(NewDays,OldSize);k++) {
         (k >= NewDays) ? DayList.options[NewDays] = null : DayList.options[k] = new Option(k+1, k+1);
      }
      DayPick = Math.min(DayPick, NewDays);
      DayList.options[DayPick-1].selected = true;
   }
   return DayPick;
}

// Resets the year to its previous valid value when something invalid is entered
function FixYearInput(YearField) {
   var YearRE = new RegExp('\\d{' + YearField.defaultValue.length + '}');
   if (!YearRE.test(YearField.value)) YearField.value = YearField.defaultValue;
}

// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isShowing()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}

// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.timerID + ')');
   eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}

// The timer for the calendar
function DoTimer(CancelTimer) {
   if (CancelTimer) eval('clearTimeout(' + this.timerID + ')');
   else {
      eval(this.timerID + '=null');
      this.resetTimer();
   }
}

// Show or hide the calendar
function ShowCalendar() {
   if (this.isShowing()) {
      var StopTimer = true;
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
      this.fixSelects(false);
   }
   else {
      var StopTimer = false;
      this.fixSelects(true);
      this.getCalendar().style.zIndex = ++ZCounter;
      this.getCalendar().style.visibility = 'visible';
   }
   this.handleTimer(StopTimer);
   self.status = '';
}

// Hides the input elements when the "blank" month is selected
function SetElementStatus(Hide) {
   this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}

// Sets the date, based on the month selected
function CheckMonthChange(MonthList) {
   var DayList = this.getDayList();
   if (MonthList.options[MonthList.selectedIndex].value == '') {
      DayList.selectedIndex = 0;
      this.hideElements(true);
      this.setHidden('');
   }
   else {
      this.hideElements(false);
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-selected month
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var DayPick = FixDayList(DayList, GetDayCount(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value));
      this.setPicked(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value, DayPick);
   }
}

// Sets the date, based on the day selected
function CheckDayChange(DayList) {
   if (this.isShowing()) this.show();
   this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
}

// Changes the date when a valid year has been entered
function CheckYearInput(YearField) {
   if ((YearField.value.length == YearField.defaultValue.length) && (YearField.defaultValue != YearField.value)) {
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-entered year
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var NewYear = GetGoodYear(YearField.value);
      var MonthList = this.getMonthList();
      var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
      this.setPicked(NewYear, this.picked.monthIndex, NewDay);
      YearField.defaultValue = YearField.value;
   }
}

// Holds characteristics about a date
function dateObject() {
   this.date = (arguments.length == 1) ? new Date(arguments[0]) : new Date(arguments[0], arguments[1], arguments[2]);
   this.yearValue = this.date.getFullYear();
   this.monthIndex = this.date.getMonth();
   this.monthName = MonthNames[this.monthIndex];
   this.fullName = this.monthName + ' ' + this.yearValue;
   this.day = this.date.getDate();
   this.dayCount = GetDayCount(this.yearValue, this.monthIndex);
   var FirstDate = new Date(this.yearValue, this.monthIndex, 1);
   this.firstDay = FirstDate.getDay();

}

// Keeps track of the date that goes into the hidden field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   dateObject.call(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year value
   if (DateFormat != 'YYYYMMDD') {
      DateFormat.match(/(Y{2,4})$/);
      if (RegExp.$1.length == 2) this.yearPad = this.yearPad.substr(2);
   }
   // Formats the date
   if (/YYYYMMDD/.test(DateFormat)) this.formatted = this.yearPad + this.monthPad + this.dayPad;
   else {
      if (/MM?\/DD?\/Y{2,4}/.test(DateFormat)) var FirstPart = this.monthPad + '/' + this.dayPad + '/';
      else if (/DD?\/MM?\/Y{2,4}/.test(DateFormat)) var FirstPart = this.dayPad + '/' + this.monthPad + '/';
      else if (/DD?-((MON)|(MMM))-Y{2,4}/.test(DateFormat)) var FirstPart = this.dayPad + '-' + this.monthShort + '-';
      else if (/((MON)|(MMM))-DD?-Y{2,4}/.test(DateFormat)) var FirstPart = this.monthShort + '-' + this.dayPad + '-';
      this.formatted = FirstPart + this.yearPad;
   }
}

// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   dateObject.call(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}

// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
   dateObject.call(this, DateMS);
   this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
}

// Sets the currently-displayed month object
function SetDisplayedMonth(DispYear, DispMonth) {
   this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
   // Creates the previous and next month objects
   this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
   this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   // Creates the HTML for the calendar
   if (this.formNumber >= 0) this.getDayTable().innerHTML = this.buildCalendar();
}

// Sets the current selected date
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
   this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
   this.setHidden(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}

// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate) {

   /* Properties */
   this.hiddenFieldName = DateName;
   this.monthListName = DateName + '_Month';
   this.dayListID = DateName + '_Day_ID';
   this.yearFieldID = DateName + '_Year_ID';
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;

   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.checkYear = CheckYearInput;
   this.fixYear = FixYearInput;
   this.changeMonth = CheckMonthChange;
   this.changeDay = CheckDayChange;
   this.resetTimer = CalTimerReset;
   this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   this.handleTimer = DoTimer;
   this.iconHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.fixSelects = FixSelectLists;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   this.getMonthList = new Function('return document.forms[this.formNumber].elements[this.monthListName]');
   this.getDayList = new Function('return document.getElementById(this.dayListID)');
   this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');


   /* Constructor */
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos < MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
      if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
   }
   // Main part of the constructor
   if (DefaultDate == 'undefined') SetGoodDate(this, false);
   else {
      if (this.format == 'YYYYMMDD') {
         (/^\d{8}$/.test(DefaultDate)) ? this.setPicked(DefaultDate.substr(0,4), parseInt(DefaultDate.substr(4,2),10)-1, DefaultDate.substr(6,2)) : SetGoodDate(this, true);
      }
      else {
         if (/\//.test(this.format)) {
            if (/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'M') {
                  var MonPart = RegExp.$1;
                  var DayPart = RegExp.$2;
               }
               else {
                  var MonPart = RegExp.$2;
                  var DayPart = RegExp.$1;
               }
               this.setPicked(GetGoodYear(RegExp.$3), parseInt(MonPart,10)-1, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/-/.test(this.format)) {
            var REMonths = '';
            for (var j=0;j<MonthNames.length;j++) {
               if (j > 0) REMonths += '|';
               REMonths += MonthNames[j].substr(0,3).toUpperCase();
            }
            if (this.format.substr(0,1) == 'D') {
               var DateRE = new RegExp('^(\\d{1,2})-(' + REMonths + ')-(\\d{2,4})$', 'i');
               (DateRE.test(DefaultDate)) ? this.setPicked(GetGoodYear(RegExp.$3), getMonthIndex(RegExp.$2), RegExp.$1) : SetGoodDate(this, true);
            }
            else {
               var DateRE = new RegExp('^(' + REMonths + ')-(\\d{1,2})-(\\d{2,4})$', 'i');
               (DateRE.test(DefaultDate)) ? this.setPicked(GetGoodYear(RegExp.$3), getMonthIndex(RegExp.$1), RegExp.$2) : SetGoodDate(this, true);
            }
         }
      }
   }
}

// Main function that creates the form elements
function DateInput(DateName, Required, DateFormat, PorcentajePantallaLeft, Evento, DefaultDate) {
	//FABIAN COLLADO 2005-02-16: Esto esta pensado para que reubique el calendario
	//en una posicion left arbitraria que viene como parametro
	var sLeft;
	sLeft="";

   if (DateName == undefined) document.writeln('<span style="color:red;font-size:' + FontSize + 'px;font-family:' + FontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      if (Required == undefined) Required = false;
      if (DateFormat == undefined) DateFormat = DefaultDateFormat;
      else if ((/^YYYYMMDD$/i.test(DateFormat)) || (/^((MM?)|(DD?))\/((MM?)|(DD?))\/Y{2,4}$/i.test(DateFormat)) || (/^((DD?)|((MON)|(MMM)))-((DD?)|((MON)|(MMM)))-Y{2,4}$/i.test(DateFormat))) DateFormat = DateFormat.toUpperCase();
      else {
         var AlertMessage = 'WARNING: The supplied date format for the \'' + DateName + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         var CurrentDate = new storedMonthObject(DefaultDateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
         if (DefaultDate != undefined) AlertMessage += '\n\nThe supplied date cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
         DateFormat = DefaultDateFormat;
         DefaultDate = CurrentDate.formatted;
         alert(AlertMessage);
      }
      // Creates the calendar object!
      eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
      if ((!Required) && (DefaultDate == undefined)) {
         var InitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
      }
      else {
         var InitialStatus = '';
         var InitialDate = eval(DateName + '_Object.picked.formatted');
      }
      if ((Required) && (DefaultDate == undefined)) DefaultDate = eval(DateName + '_Object.picked.formatted');
      // Create the form elements
      with (document) {
         writeln('<input type="hidden" name="' + DateName + '" value="' + InitialDate + '">');
         // Find this form number
         for (var f=0;f < forms.length;f++) {
            for (var e=0;e < forms[f].elements.length;e++) {
               if (typeof forms[f].elements[e].type == 'string') {
                  if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
                     eval(DateName + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
         writeln('<table cellpadding="0" cellspacing="2"><tr>' + String.fromCharCode(13) + '<td valign="middle">');

         //////////////////////////////////////////////////////////////////////////////
         // Dia ///////////////////////////////////////////////////////////////////////
         //////////////////////////////////////////////////////////////////////////////
         writeln('<select' + InitialStatus + ' class="Click_txtFechaCheckIn" id="' + DateName + '_Day_ID" onChange="' + DateName + '_Object.changeDay(this);' + DateName + '_OnClick();">');
         for (var j=1;j<=eval(DateName + '_Object.picked.dayCount');j++) {
            DaySelected = ((DefaultDate != undefined) && eval(DateName + '_Object.picked.day=='+j)) ? ' selected' : '';
            writeln('<option' + DaySelected + ' value = \'' + j + '\'>' + j + '</option>');
         }
         writeln('</select>')
         //////////////////////////////////////////////////////////////////////////////


         writeln(String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle">');

         //////////////////////////////////////////////////////////////////////////////
         // Mes ///////////////////////////////////////////////////////////////////////
         //////////////////////////////////////////////////////////////////////////////
         writeln('<select name="' + DateName + '_Month" class="Click_txtFechaCheckIn" onChange="' + DateName + '_Object.changeMonth(this);' + DateName + '_OnClick();"">');
         if (!Required) {
            var NoneSelected = (DefaultDate == undefined) ? ' selected' : '';
            writeln('<option value=""' + NoneSelected + '></option>');
         }
         for (var i=0;i<12;i++) {
            MonthSelected = ((DefaultDate != undefined) && (eval(DateName + '_Object.picked.monthIndex=='+i))) ? ' selected' : '';
            writeln('<option value="' + i + '"' + MonthSelected + '>' + MonthNames[i].substr(0,3) + '</option>');
         }
         writeln('</select>')
         //////////////////////////////////////////////////////////////////////////////




         writeln(String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle">');

         //////////////////////////////////////////////////////////////////////////////
         // Ano ///////////////////////////////////////////////////////////////////////
         //////////////////////////////////////////////////////////////////////////////
         writeln('<input' + InitialStatus + ' class="Click_txtFechaCheckIn" type="text" id="' + DateName + '_Year_ID" size="' + eval(DateName + '_Object.picked.yearPad.length') + '" maxlength="' + eval(DateName + '_Object.picked.yearPad.length') + '" title="Year" value="' + eval(DateName + '_Object.picked.yearPad') + '" onKeyPress="return NumOnly(event)" onKeyUp="' + DateName + '_Object.checkYear(this)" onBlur="' + DateName + '_Object.fixYear(this);' + DateName + '_OnClick();">');
         //////////////////////////////////////////////////////////////////////////////

	     write('<td valign="middle">' + String.fromCharCode(13) + '<a' + InitialStatus + ' id="' + DateName + '_ID_Link" href="javascript:' + DateName + '_OnOpen();' + DateName + '_Object.show()" onMouseOver="return ' + DateName + '_Object.iconHover(true)" onMouseOut="return ' + DateName + '_Object.iconHover(false)"><img src="' + ImageURL + '" align="baseline" title="Calendar" width="20" height="17" border="0"></a>&nbsp;');

		 if ((PorcentajePantallaLeft != "") && (PorcentajePantallaLeft != null) && (PorcentajePantallaLeft != undefined)) {
		 		 sLeft = "left=" + PorcentajePantallaLeft + ";";
		 }

         writeln('<br><span id="' + DateName + '_ID" style="' + sLeft + 'z-index:2;position:absolute;visibility:hidden;width:' + (CellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid dimgray;" onMouseOver="' + DateName + '_Object.handleTimer(true)" onMouseOut="' + DateName + '_Object.handleTimer(false)">');
         writeln('<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">');
         writeln('<td id="' + DateName + '_Previous_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.previous.hover(this,true)" onMouseOut="return ' + DateName + '_Object.previous.hover(this,false)" title="' + eval(DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '" width="5" height="9"></td>');
         writeln('<td id="' + DateName + '_Current_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + '" colspan="5" onClick="' + DateName + '_Object.displayed.goCurrent()" onMouseOver="self.status=\'Click to view ' + eval(DateName + '_Object.displayed.fullName') + '\';return true;" onMouseOut="self.status=\'\';return true;" title="Show Current Month">' + eval(DateName + '_Object.displayed.fullName') + '</td>');
         writeln('<td id="' + DateName + '_Next_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.next.hover(this,true)" onMouseOut="return ' + DateName + '_Object.next.hover(this,false)" title="' + eval(DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '" width="5" height="9"></td></tr>' + String.fromCharCode(13) + '<tr>');
         for (var w=0;w<7;w++) writeln('<td width="18" align="center" class="calendarDateInput" style="height:' + CellHeight + ';width:' + CellWidth + ';font-weight:bold;border-top:1px solid dimgray;border-bottom:1px solid dimgray;">' + WeekDays[w] + '</td>');
         writeln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + DateName + '_DayTable_ID">' + eval(DateName + '_Object.buildCalendar()') + '</span>' + String.fromCharCode(13) + '</span>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '</tr>' + String.fromCharCode(13) + '</table>');
      }
   }
}

function saveSearchCookies() {
	var exp = new Date();
	var frm = document.getElementById('form1');
	exp.setTime(exp.getTime() + (1*24*60*60*1000));
	setCookie("CityCode", frm.ID_Localidad.value, exp, "/", "", false);
	setCookie("CountryCode", frm.ID_PaisWeb.value, exp, "/", "", false);
	setCookie("CheckInDate_Day", frm.FechaCheckIn_Day_ID.value, exp, "/", "", false);
	setCookie("CheckInDate_Month", parseInt(frm.FechaCheckIn_Month.value) + 1, exp, "/", "", false);
	setCookie("CheckInDate_Year", frm.FechaCheckIn_Year_ID.value, exp, "/", "", false);
	setCookie("CheckOutDate_Day", frm.FechaCheckOut_Day_ID.value, exp, "/", "", false);
	setCookie("CheckOutDate_Month", parseInt(form1.FechaCheckOut_Month.value) + 1, exp, "/", "", false);
	setCookie("CheckOutDate_Year", frm.FechaCheckOut_Year_ID.value, exp, "/", "", false);
	setCookie("RoomType5", frm.CantHabi5.value, exp, "/", "", false);
	setCookie("RoomType6", frm.CantHabi6.value, exp, "/", "", false);
	setCookie("RoomType7", frm.CantHabi7.value, exp, "/", "", false);
	setCookie("RoomType8", frm.CantHabi8.value, exp, "/", "", false);

}

function loadSearchCookies() {
	var frm = document.getElementById('form1');
	var ckCityCode = getCookie("CityCode");
	var ckCountryCode = getCookie("CountryCode");
	var ckCheckInDate_Day = getCookie("CheckInDate_Day");
	var ckCheckInDate_Month = getCookie("CheckInDate_Month");
	var ckCheckInDate_Year = getCookie("CheckInDate_Year");
	var ckCheckOutDate_Day = getCookie("CheckOutDate_Day");
	var ckCheckOutDate_Month = getCookie("CheckOutDate_Month");
	var ckCheckOutDate_Year = getCookie("CheckOutDate_Year");
	var ckRoomType5 = getCookie("RoomType5");
	var ckRoomType6 = getCookie("RoomType6");
	var ckRoomType7 = getCookie("RoomType7");

	if ((ckCountryCode !== "") && (ckCountryCode !== null)) {
		frm.ID_PaisWeb.value = ckCountryCode;
		completar(frm.ID_PaisWeb);
	}
	if ((ckCityCode !== "") && (ckCityCode !== null)) {
		frm.ID_Localidad.value = ckCityCode;
	}

	if ((ckCheckInDate_Day !== "") && (ckCheckInDate_Day !== null)) {
		frm.FechaCheckIn_Day_ID.value = ckCheckInDate_Day;
		FechaCheckIn_Object.changeDay(frm.FechaCheckIn_Day_ID);
	}
	if ((ckCheckInDate_Month !== "") && (ckCheckInDate_Month !== null)) {
		frm.FechaCheckIn_Month.value = parseInt(ckCheckInDate_Month) - 1;
		FechaCheckIn_Object.changeMonth(frm.FechaCheckIn_Month);
	}
	if ((ckCheckInDate_Year !== "") && (ckCheckInDate_Year !== null)) {
		frm.FechaCheckIn_Year_ID.value = ckCheckInDate_Year;
		FechaCheckIn_Object.fixYear(frm.FechaCheckIn_Year_ID);
	}

	if ((ckCheckOutDate_Day !== "") && (ckCheckOutDate_Day !== null)) {
		frm.FechaCheckOut_Day_ID.value = ckCheckOutDate_Day;
		FechaCheckOut_Object.changeDay(frm.FechaCheckOut_Day_ID);
	}
	if ((ckCheckOutDate_Month !== "") && (ckCheckOutDate_Month !== null)) {
		frm.FechaCheckOut_Month.value = parseInt(ckCheckOutDate_Month) - 1;
		FechaCheckOut_Object.changeMonth(frm.FechaCheckOut_Month);
	}
	if ((ckCheckOutDate_Year !== "") && (ckCheckOutDate_Year !== null)) {
		frm.FechaCheckOut_Year_ID.value = ckCheckOutDate_Year;
		FechaCheckOut_Object.fixYear(frm.FechaCheckOut_Year_ID);
	}

	if ((ckRoomType5 !== "") && (ckRoomType5 !== null)) {
		frm.CantHabi5.value = ckRoomType5;
	}
	if ((ckRoomType6 !== "") && (ckRoomType6 !== null)) {
		frm.CantHabi6.value = ckRoomType6;
	}
	if ((ckRoomType7 !== "") && (ckRoomType7 !== null)) {
		frm.CantHabi7.value = ckRoomType7;
	}
	if ((ckRoomType8 !== "") && (ckRoomType8 !== null)) {
		frm.CantHabi8.value = ckRoomType8;
	}

}

function deleteSearchCookies() {
	deleteCookie("CityCode", "", "");
	deleteCookie("CountryCode", "", "");
	deleteCookie("CheckInDate_Day", "", "");
	deleteCookie("CheckInDate_Month", "", "");
	deleteCookie("CheckInDate_Year", "", "");
	deleteCookie("CheckOutDate_Day", "", "");
	deleteCookie("CheckOutDate_Month", "", "");
	deleteCookie("CheckOutDate_Year", "", "");
	deleteCookie("RoomType5", "", "");
	deleteCookie("RoomType6", "", "");
	deleteCookie("RoomType7", "", "");
}

function ProcesoPreBusqueda() {
	if (!ChequeaCampos()) {
		return false;
	};

	var frmProv = document.getElementById('frmProvisorio');
	var frm1 = document.getElementById('form1');


	saveSearchCookies();

	form1.Ano.value = form1.Fecha.value.substring(6,10);
	form1.Mes.value = form1.Fecha.value.substring(3,5);
	form1.Dia.value = form1.Fecha.value.substring(0,2);

	frmProv.txtFechaCheckIn.value = GenerarFechaString(GenerarDate (frm1.FechaCheckIn_Day_ID, frm1.FechaCheckIn_Month, frm1.FechaCheckIn_Year_ID));
	frmProv.txtFechaCheckOut.value = GenerarFechaString(GenerarDate (frm1.FechaCheckOut_Day_ID, frm1.FechaCheckOut_Month, frm1.FechaCheckOut_Year_ID));
	frmProv.txtCityCode.value = frm1.ID_Localidad.value;
	frmProv.cboRoomType5.value = frm1.CantHabi5.value;
	frmProv.cboRoomType6.value = frm1.CantHabi6.value;
	frmProv.cboRoomType7.value = frm1.CantHabi7.value;
	frmProv.cboRoomType8.value = frm1.CantHabi8.value;;
	frmProv.submit();

	return(true);
}

function GenerarDate (campodia, campomes, campoano) {
    return new Date(campoano.value * 1, campomes.value * 1, campodia.value * 1);
}

function GenerarFechaString (dFecha) {
    //Convierto un string a numero para sumarle 1
    //Le sumo 1 porque el calendario considera 0 a Enero
    var nMes = dFecha.getMonth() + 1;
    if (nMes < 10) {
		sMes = "0" + nMes;
    } else {
		sMes = "" + nMes;
    };

    var nDia = dFecha.getDate() * 1;
    if (nDia < 10) {
		sDia = "0" + nDia;
    } else {
		sDia = "" + nDia;
    };

    var nAno = dFecha.getFullYear() * 1;
    var sAno = "" + nAno;

    return sDia+"/"+sMes+"/"+sAno;
}


function ChequeaCampos() {
	var dFechaIn, dFechaOut, sFechaOut;
	var frm = document.getElementById('form1');

	if (frm.ID_Localidad.value == "0") {
	     alert('Por favor complete el campo Ciudad.');
	     frm.ID_Localidad.focus();
	     return (false);
    }


	if ((frm.CantHabi5.value == "0") && (frm.CantHabi6.value == "0") && (frm.CantHabi7.value == "0") && (frm.CantHabi8.value == "0")) {
	     alert('Por favor complete los campos de habitaciones');
	     frm.CantHabi5.focus();
	     return (false);
	}

    dFechaIn = GenerarDate (frm.FechaCheckIn_Day_ID, frm.FechaCheckIn_Month, frm.FechaCheckIn_Year_ID);
 	frm.Fecha.value = GenerarFechaString(dFechaIn);
    dFechaOut = GenerarDate (frm.FechaCheckOut_Day_ID, frm.FechaCheckOut_Month, frm.FechaCheckOut_Year_ID);
    sFechaOut = GenerarFechaString(dFechaOut);
    ChequearFecha (frm.Fecha.value);
    ChequearFecha (sFechaOut);

	var dNow = new Date();
	var dToday = new Date(dNow.getFullYear(), dNow.getMonth() - 1, dNow.getDate());

	if (dFechaIn < dToday) {
		alert('Verifique el campo fecha.');
		frm.FechaCheckIn_Day_ID.focus();
		return(false);
	};
	if (dFechaOut < dToday) {
		alert('Verifique el campo fecha.');
		frm.FechaCheckOut_Day_ID.focus();
		return(false);
	};



    //Calculo la cantidad de noches de la reservacion a partir
    //de la fecha de llegada y de partida
    frm.CantNoches.value = parseInt((dFechaOut - dFechaIn) / 86400000);

	if (form1.CantNoches.value == 0) {
		alert('La fecha de llegada y de salida no deben coincidir');
		return(false);
	}

	if (form1.CantNoches.value < 0) {
		alert('La fecha de llegada debe ser anterior a la fecha de salida');
		return(false);
	}

	return(true);
}

function ChequearFecha (dFecha) {
	var checkOK = "0123456789/";
	var checkStr = dFecha + "";
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++) {
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++) {
			if (ch == checkOK.charAt(j)) {
				break;
			}
		};
		if (j == checkOK.length) {
			allValid = false;
			break;
		}
		allNum += ch;
	}
	if (!allValid) {
		alert('La Fecha ingresada es invalida.');
		sCampoFecha.focus();
		return (false);
	}

	if (!IsDate(dFecha)) {
		alert('{word(7)}');
		sCampoFecha.focus();
		return(false);
	}
}

//-------------------------------------------------------------------------------
//Este chequeo se hace al cambiar la fecha de salida
//Esta funcion se llama de esta manera porque es llamada por una funcion
//generada dinamicamente por la funcion de javascript de 'PickDisplayDay'
// de Calendario.asp. Si no llegara a definirse esta funcion, no dará error
function FechaCheckIn_OnClose () {
	//Se controla que la fecha de salida sea superior a la de llegada,
	//sino se coloca la fecha de salida como el dia siguiente que el de llegada

	var dFechaIn, dFechaOut, sFechaOut, nCantidadNoches, dFechaActual;
	dFechaActual = new Date();
	dFechaIn = GenerarDate (document.form1.FechaCheckIn_Day_ID, document.form1.FechaCheckIn_Month, document.form1.FechaCheckIn_Year_ID);
	dFechaOut = GenerarDate (document.form1.FechaCheckOut_Day_ID, document.form1.FechaCheckOut_Month, document.form1.FechaCheckOut_Year_ID);

    if (dFechaIn < dFechaActual) {
		alert('Debe ingresar como mínimo la fecha de hoy.');
		FechaCheckIn_Object.show();
    } else {
		//Calculo la cantidad de noches de la reservacion a partir
		//de la fecha de llegada y de partida
		nCantidadNoches = parseInt((dFechaOut - dFechaIn) / 86400000);

		if (nCantidadNoches <= 0) {
			//Entonces coloco la fecha de salida como el dia siguiente que el de llegada
			dFechaOut = dFechaIn;
 			dFechaOut.setDate(dFechaOut.getDate() + 1);

			//Cargo el resultado

			//Se le resta uno porque el indice comienza de 0 y los dias del 1
 			document.form1.FechaCheckOut_Day_ID.selectedIndex = dFechaOut.getDate() - 1;
			document.form1.FechaCheckOut_Day_ID.value = document.form1.FechaCheckOut_Day_ID.options(document.form1.FechaCheckOut_Day_ID.selectedIndex).value;
			FechaCheckOut_Object.changeDay(document.form1.FechaCheckOut_Day_ID.options);
 			document.form1.FechaCheckOut_Month.selectedIndex = dFechaOut.getMonth();
			document.form1.FechaCheckOut_Month.value = document.form1.FechaCheckOut_Month.options(document.form1.FechaCheckOut_Month.selectedIndex).value;
			FechaCheckOut_Object.changeMonth(document.form1.FechaCheckOut_Month.options);
 			document.form1.FechaCheckOut_Year_ID.value = dFechaOut.getFullYear();
			FechaCheckOut_Object.fixYear(document.form1.FechaCheckOut_Year_ID);
		}

		FechaCheckOut_Object.show();
    };

}
//-------------------------------------------------------------------------------
//Esta funcion permite inicializar la fecha de salida como el dia siguiente
//del dia de
function Inicializar_FechaCheckOut () {
	//Calculo el día siguiente al dia de llegada
	dFechaOut = GenerarDate (document.form1.FechaCheckIn_Day_ID, document.form1.FechaCheckIn_Month, document.form1.FechaCheckIn_Year_ID);
 	dFechaOut.setDate(dFechaOut.getDate() + 1);

	//Actualizo el combo de fecha de llegada
	document.form1.FechaCheckOut_Day_ID.selectedIndex = dFechaOut.getDate() - 1;
	document.form1.FechaCheckOut_Day_ID.value = document.form1.FechaCheckOut_Day_ID.options(document.form1.FechaCheckOut_Day_ID.selectedIndex).value;
	FechaCheckOut_Object.changeDay(document.form1.FechaCheckOut_Day_ID.options);
 	document.form1.FechaCheckOut_Month.selectedIndex = dFechaOut.getMonth();
	document.form1.FechaCheckOut_Month.value = document.form1.FechaCheckOut_Month.options(document.form1.FechaCheckOut_Month.selectedIndex).value;
	FechaCheckOut_Object.changeMonth(document.form1.FechaCheckOut_Month.options);
 	document.form1.FechaCheckOut_Year_ID.value = dFechaOut.getFullYear();
	FechaCheckOut_Object.fixYear(document.form1.FechaCheckOut_Year_ID);
}
//-------------------------------------------------------------------------------
//Este chequeo se hace al cambiar la fecha de llegada
//Esta funcion se llama de esta manera porque es llamada por una funcion
//generada dinamicamente por la funcion de javascript de 'PickDisplayDay'
// de Calendario.asp. Si no llegara a definirse esta funcion, no dará error

function FechaCheckOut_OnClose () {
	//Se controla que la fecha de llegada sea inferior a la de partida,
	//sino se coloca la fecha de llegada como el dia anterior que el de salida

	var dFechaIn, dFechaOut, sFechaOut, nCantidadNoches, dFechaActual;
	dFechaActual = new Date();
	dFechaIn = GenerarDate (document.form1.FechaCheckIn_Day_ID, document.form1.FechaCheckIn_Month, document.form1.FechaCheckIn_Year_ID);
	dFechaOut = GenerarDate (document.form1.FechaCheckOut_Day_ID, document.form1.FechaCheckOut_Month, document.form1.FechaCheckOut_Year_ID);

	if (dFechaOut < dFechaActual) {
    	alert('Debe ingresar como mínimo la fecha de hoy.');
		FechaCheckOut_Object.show();
	} else {
		//Calculo la cantidad de noches de la reservacion a partir
		//de la fecha de llegada y de partida
		nCantidadNoches = parseInt((dFechaOut - dFechaIn) / 86400000);

		if (nCantidadNoches <= 0) {
			//Entonces coloco la fecha de salida como el dia siguiente que el de llegada
			dFechaIn = dFechaOut;
 			dFechaIn.setDate(dFechaIn.getDate() - 1);

			//Cargo el resultado
			//Se le resta uno porque el indice comienza de 0 y los dias del 1
 			document.form1.FechaCheckIn_Day_ID.selectedIndex = dFechaIn.getDate() - 1;
			document.form1.FechaCheckIn_Day_ID.value = document.form1.FechaCheckIn_Day_ID.options(document.form1.FechaCheckIn_Day_ID.selectedIndex).value;
			FechaCheckIn_Object.changeDay(document.form1.FechaCheckIn_Day_ID.options);
 			document.form1.FechaCheckIn_Month.selectedIndex = dFechaIn.getMonth();
			document.form1.FechaCheckIn_Month.value = document.form1.FechaCheckIn_Month.options(document.form1.FechaCheckIn_Month.selectedIndex).value;
			FechaCheckIn_Object.changeMonth(document.form1.FechaCheckIn_Month.options);
 			document.form1.FechaCheckIn_Year_ID.value = dFechaIn.getFullYear();
			FechaCheckIn_Object.fixYear(document.form1.FechaCheckIn_Year_ID);
		}
	}
}
//-------------------------------------------------------------------------------
//Esta funcion es similar a FechaCheckIn_OnClose. La diferencia es que esta no muestra
//el calendario de fecha de salida. Usada para cuando cambia la fecha manualmente.
function FechaCheckIn_OnClick () {
	//Se controla que la fecha de salida sea superior a la de llegada,
	//sino se coloca la fecha de salida como el dia siguiente que el de llegada

	var dFechaIn, dFechaOut, sFechaOut, nCantidadNoches, dFechaActual;
	dFechaActual = new Date();
	dFechaIn = GenerarDate (document.form1.FechaCheckIn_Day_ID, document.form1.FechaCheckIn_Month, document.form1.FechaCheckIn_Year_ID);
	dFechaOut = GenerarDate (document.form1.FechaCheckOut_Day_ID, document.form1.FechaCheckOut_Month, document.form1.FechaCheckOut_Year_ID);


    if (dFechaIn < dFechaActual) {
		alert('Debe ingresar como mínimo la fecha de hoy.');
		FechaCheckIn_Object.show();
    } else {
		//Calculo la cantidad de noches de la reservacion a partir
		//de la fecha de llegada y de partida
		nCantidadNoches = parseInt((dFechaOut - dFechaIn) / 86400000);

		if (nCantidadNoches <= 0) {
			//Entonces coloco la fecha de salida como el dia siguiente que el de llegada
			dFechaOut = dFechaIn;
 			dFechaOut.setDate(dFechaOut.getDate() + 1);

			//Cargo el resultado

			//Se le resta uno porque el indice comienza de 0 y los dias del 1
 			document.form1.FechaCheckOut_Day_ID.selectedIndex = dFechaOut.getDate() - 1;
			document.form1.FechaCheckOut_Day_ID.value = document.form1.FechaCheckOut_Day_ID.options(document.form1.FechaCheckOut_Day_ID.selectedIndex).value;
			FechaCheckOut_Object.changeDay(document.form1.FechaCheckOut_Day_ID.options);
 			document.form1.FechaCheckOut_Month.selectedIndex = dFechaOut.getMonth();
			document.form1.FechaCheckOut_Month.value = document.form1.FechaCheckOut_Month.options(document.form1.FechaCheckOut_Month.selectedIndex).value;
			FechaCheckOut_Object.changeMonth(document.form1.FechaCheckOut_Month.options);
 			document.form1.FechaCheckOut_Year_ID.value = dFechaOut.getFullYear();
			FechaCheckOut_Object.fixYear(document.form1.FechaCheckOut_Year_ID);
		}

    };

}
//-------------------------------------------------------------------------------
//Esta funcion es similar a FechaCheckOut_OnClose usada para cuando cambia
//la fecha manualmente.
function FechaCheckOut_OnClick () {
	//Se controla que la fecha de llegada sea inferior a la de partida,
	//sino se coloca la fecha de llegada como el dia anterior que el de salida

	var dFechaIn, dFechaOut, sFechaOut, nCantidadNoches, dFechaActual;
	dFechaActual = new Date();
	dFechaIn = GenerarDate (document.form1.FechaCheckIn_Day_ID, document.form1.FechaCheckIn_Month, document.form1.FechaCheckIn_Year_ID);
	dFechaOut = GenerarDate (document.form1.FechaCheckOut_Day_ID, document.form1.FechaCheckOut_Month, document.form1.FechaCheckOut_Year_ID);


    if (dFechaOut < dFechaActual) {
		alert('Debe ingresar como mínimo la fecha de hoy.');
		FechaCheckOut_Object.show();
	} else {
		//Calculo la cantidad de noches de la reservacion a partir
		//de la fecha de llegada y de partida
		nCantidadNoches = parseInt((dFechaOut - dFechaIn) / 86400000);

		if (nCantidadNoches <= 0) {
			//Entonces coloco la fecha de salida como el dia siguiente que el de llegada
			dFechaIn = dFechaOut;
 			dFechaIn.setDate(dFechaIn.getDate() - 1);

			//Cargo el resultado
			//Se le resta uno porque el indice comienza de 0 y los dias del 1
 			document.form1.FechaCheckIn_Day_ID.selectedIndex = dFechaIn.getDate() - 1;
			document.form1.FechaCheckIn_Day_ID.value = document.form1.FechaCheckIn_Day_ID.options(document.form1.FechaCheckIn_Day_ID.selectedIndex).value;
			FechaCheckIn_Object.changeDay(document.form1.FechaCheckIn_Day_ID.options);
 			document.form1.FechaCheckIn_Month.selectedIndex = dFechaIn.getMonth();
			document.form1.FechaCheckIn_Month.value = document.form1.FechaCheckIn_Month.options(document.form1.FechaCheckIn_Month.selectedIndex).value;
			FechaCheckIn_Object.changeMonth(document.form1.FechaCheckIn_Month.options);
 			document.form1.FechaCheckIn_Year_ID.value = dFechaIn.getFullYear();
			FechaCheckIn_Object.fixYear(document.form1.FechaCheckIn_Year_ID);
		}
	}
}

//-------------------------------------------------------------------------------
//FABIAN COLLADO 2005-02-17: Esta funcion esta pensada para hacer una accion antes de abrir el calendario
function FechaCheckIn_OnOpen() {
	//FABIAN COLLADO 2005-02-17: Cuando se abre el calendario de checkin se cierra el de checkout
	if (FechaCheckOut_Object.isShowing()) {
		//Si está mostrandose, al mostrarlo denuevo, lo esconde.
		FechaCheckOut_Object.show();
	};
}

//-------------------------------------------------------------------------------
//FABIAN COLLADO 2005-02-17: Esta funcion esta pensada para hacer una accion antes de abrir el calendario
function FechaCheckOut_OnOpen() {
	//FABIAN COLLADO 2005-02-17: Cuando se abre el calendario de checkout se cierra el de checkin
	if (FechaCheckIn_Object.isShowing) {
		//Si está mostrandose, al mostrarlo denuevo, lo esconde.
		FechaCheckIn_Object.show();
	};
}

//-------------------------------------------------------------------------------
// armo un string con ID_HabitacionTipoCustom=Cantidad cargada en tabla
function ArmarCantidades() {
	var i,sep="";
	var disForm1 = AsignaObjetoForm('form1');
	var disForm1Habit = AsignaObjetoForm('form1','Habitaciones');
	var disForm1Cant = AsignaObjetoForm('form1','Cantidades');
	disForm1Habit.value = "";
	disForm1Cant.value = "";
	for (i=0; i < disForm1.length; i++) {
		disForm1Var = AsignaObjetoForm('form1', i);
		if (disForm1Var.name.substr(0,8) == "CantHabi") {
			disForm1Habit.value = disForm1Habit.value + sep + disForm1Var.name.substr(8);
			//vector de Cantidades
			disForm1Cant.value = disForm1Cant.value + sep + disForm1Var[disForm1Var.selectedIndex].value;
			sep = ",";
	    }
	}
}

function AsignaObjetoForm(nombreForm, nombreObj) {
	var nombreCorrecto;
    if (nombreObj == null) {
		nombreCorrecto = document[nombreForm].elements;
	}
	else {
		nombreCorrecto = document[nombreForm].elements[nombreObj];
	}
	return nombreCorrecto;

} //-- end function --//

