var undefined;
var toDay = new Date();
var tomorrow;
var dayInMilli = 86400000;

function updateOut(checkIn, f)
{
	var checkOut = f.chkOut;
	var nextDay;
	var dtChkOut;
	var totalDays = 1;

	dtChkOut = checkOut.value;
	
	pChkIn = Date.parse(checkIn);
	pChkOut = Date.parse(dtChkOut);
	 
	//totalDays = getTotalDays(f) - 0; // check to see the number of nights selected
	raw_days = (pChkOut.getTime() - pChkIn.getTime())/dayInMilli;
	totalDays = (raw_days < 1)? 1 : raw_days;
	dtChkIn = new Date(pChkIn);
	
	losMS = 1;
	if (f.nights != null) {
		if(f.nights.value > totalDays)
			totalDays = f.nights.value;
	}
	losMS = totalDays*dayInMilli;	

	nextDay = new Date(dtChkIn.getTime() + losMS);

	checkOut.value = (nextDay.getMonth() + 1) + "/" + nextDay.getDate() + "/" + nextDay.getFullYear();
	updateCalendar(f, checkOut);

	if (checkOut.type == "hidden")
		updateDropDowns("Check-Out", checkOut, f);

	setNightsDropDown(f);
}

function updateIn(checkOut, f)
{
	var checkIn = f.chkIn;
	var dtChkIn = checkIn.value;
	var new_dtChkIn;
	var totalDays = 1;
	var prevDay;

	pChkIn = Date.parse(dtChkIn);
	pChkOut = Date.parse(checkOut);

	// check to see the number of nights selected
	//totalDays = getTotalDays(f) - 0;
	raw_days = (pChkOut.getTime() - pChkIn.getTime())/dayInMilli;
	totalDays = (raw_days < 1)? 1 : raw_days;
	losMS = 1;
	if (f.nights != null) {
		if(f.nights.value > totalDays)
			totalDays = f.nights.value;
	}
	losMS = totalDays*dayInMilli;

	if(toDay.getTime() > pChkOut || toDay.getTime() > pChkOut - losMS){
		new_dtChkIn = toDay;
		pChkOut = new Date(new_dtChkIn.getTime() + losMS);
	} else
		new_dtChkIn = new Date(pChkOut - losMS);

	dtChkIn = (new_dtChkIn.getMonth() + 1) + "/" + new_dtChkIn.getDate() + "/" + new_dtChkIn.getFullYear();

	// only change checkIn if it is after chkOut and greater than or equal to minimum required length of stay, if specified
/*	if (pChkOut-pChkIn >= losMS)
	{
		setNightsDropDown(f); 
		return;
	}*/
	if (f.nights != null) {
		
		/*if (pChkOut-pChkIn < dayInMilli) {
	    //alert("Departure Date must be after Arrival Date");

	    updateOut(dtChkIn, f);
			updateCalendar(f, f.chkOut);			
	    return;
		} else if (pChkOut-pChkIn < losMS && pChkOut-pChkIn >= dayInMilli) {
	    //alert("Minimum length of stay required is " + f.nights.value + " nights");

	    updateOut(dtChkIn, f);
			updateCalendar(f, f.chkOut);
	    return;
		}*/
			updateOut(dtChkIn, f);
			checkIn.value = dtChkIn;			
			updateCalendar(f, checkIn, f.chkOut);			
			return;
                }
	dtChkOut = new Date(pChkOut);

	/* This code was causing a problem in webkit browsers so it was converted to use milliseconds to create the date instead of strings
	prevDay = (dtChkOut.getMonth() + 1) + "/" + (dtChkOut.getDate() - totalDays) + "/" + dtChkOut.getFullYear();
	prevDay = Date.parse(prevDay);
	prevDay = new Date(prevDay);
	*/
	//prevDay = new Date(dtChkOut.getTime() - (totalDays * dayInMilli));

	checkIn.value = dtChkIn;
	updateCalendar(f, checkIn, f.chkOut);	

	if (checkIn.type == "hidden")
		updateDropDowns("Check-In", checkIn, f);

	setNightsDropDown(f);
}

function getTotalDays(f)
{
	f = $(f);
	var numNights =  f.getElement('select[name=numNights]');

	numNights.disabled = false;
	totalNights = (numNights && numNights.get('value') > 0)? numNights.get('value') : 1;
	numNights.disabled = true;

	return totalNights;
}
/*
function setDefaults()
{
     var nextDate;
     toDay = new Date();
     tomorrow = new Date();
     nextDate = toDay.getDate() + 1;
     tomorrow.setInputDate(nextDate);

     setPeople();
     setInputDates();
}

function setInputDates()
{
     document.room_reservations.chkIn.value = (toDay.getMonth() + 1) + "/" + toDay.getDate() + "/" + toDay.getFullYear();
     document.room_reservations.chkOut.value = (tomorrow.getMonth() + 1) + "/" + tomorrow.getDate() + "/" + tomorrow.getFullYear();
}
*/
function setDropDownDates()
{
	var arrivalMonth = toDay.getMonth() + 1;
	var arrivalDay = toDay.getDate();
	var arrivalYear = toDay.getFullYear();

	var departMonth = tomorrow.getMonth() + 1;
	var departDay = tomorrow.getDate();
	var departYear = tomorrow.getFullYear();
	
	setChkInDate(arrivalMonth, arrivalDay, arrivalYear);
	setChkOutDate(departMonth, departDay, departYear);
}

/*
function setPeople()
{
     document.room_reservations.adult_no.value = 1;
     document.room_reservations.child_no.value = 0;
}
*/

function chkPeople(txtBoxName, txtBox)
{
	var val = txtBox.value;
	var newValue = parseFloat(val);
	if (val == "")
	{
		alert("The number of " + txtBoxName + " staying cannot be blank.");
		txtBox.value = 0;
	}
	else
	{
		if( isNaN(newValue) )
		{
			alert(val + " is not a valid number.\nPlease enter a valid number.");
			txtBox.value = 0;
		}
	}
	txtBox.focus();
}

function setCheckOut(f)
{
	updateOut(f.chkIn.value, f);
}

function openCalendar()
{
	top.newWin = window.open('/hotelsite/reservations/calendar.html','cal','WIDTH=400,HEIGHT=230');
	top.newWin.focus();
}

function validateForm(f)
{
// check that the dates are after today
	if (chkDate('Check-In', f.chkIn) == false)
		return false;
	
	if (chkDate('Check-Out', f.chkOut) == false)
		return false;

	if (Date.parse(f.chkIn.value) >= Date.parse(f.chkOut.value))
	{
		alert ("The Check Out Date needs to be after the Check In Date.");
		updateOut(f.chkIn.value, f);

		if (f.chkOut.type != "hidden");
			f.chkOut.focus();

		return false;
	}
	return true;
}

function setChkInDate(arrivalMonthYear, arrivalDay, f)
{
	var newChkInDate;
	var arrivalMonth;

	var thisDate = new Date();
	var thisMonth = thisDate.getMonth() + 1; // need to increment arrivalMonth and arrivaldate b/c they are arrays
	var thisYear = thisDate.getFullYear();
	var ddMonthYearVal = (arrivalMonthYear.options[arrivalMonthYear.selectedIndex].value - 0) + 1; // need to increment Month and day b/c they are arrays

	arrivalMonth = getActualMonthVal(ddMonthYearVal);
	arrivalYear = thisYear + getMyYear(thisMonth, ddMonthYearVal);
	arrivalDay = arrivalDay + 1;

	if (arrivalMonth < 10)
		arrivalMonth = "0" + arrivalMonth;

	if (arrivalDay < 10)
		arrivalDay = "0" + arrivalDay;

	if (arrivalYear < 10)
		arrivalYear = "0" + arrivalYear ;
	
	newChkInDate = arrivalMonth + "/" + arrivalDay + "/" + arrivalYear;

	setInputDate(f.chkIn, newChkInDate);

	//testing for first load and the presence of the f.nights hidden field
	//this is to insure the correct values are set at page load.
	if($(f).getScrollSize().x == 0 && f.nights)
		updateIn(f.chkOut.value, f);
	else
	updateOut(f.chkIn.value, f);
}

function setChkOutDate(departMonthYear, departDay, f)
{
	var newChkOutDate;
	var departMonth;

	var thisDate = new Date();
	var thisMonth = thisDate.getMonth() + 1;
	var thisYear = thisDate.getFullYear();
	var ddMonthYearVal = (departMonthYear.options[departMonthYear.selectedIndex].value - 0) + 1; // need to increment Month and day b/c they are arrays

	departMonth = getActualMonthVal(ddMonthYearVal);
	departYear = thisYear + getMyYear(thisMonth, ddMonthYearVal);
	departDay = departDay + 1;

	if (departMonth < 10)
		departMonth = "0" + departMonth;

	if (departDay < 10)
		departDay = "0" + departDay;

	if (departYear < 10)
		departYear = "0" + departYear ;
	
	newChkOutDate = departMonth + "/" + departDay + "/" + departYear;

	setInputDate(f.chkOut, newChkOutDate);
	updateIn(newChkOutDate, f);
}

function getMyMonth_old(startMonth, dateIndex)
{
// this function gets the month from the 12 mo drop down
	var myMonth = startMonth + dateIndex;
	
	if (myMonth > 12)
		myMonth = myMonth - 12;

	return myMonth;
}

function getMyYear_old(startMonth, dateIndex)
{
	// this function gets the year from the 12 mo drop down
	var myMonth = startMonth + dateIndex;
	var myYear = 0;
	
	//alert ("startMonth = " + startMonth);
	//alert ("dateIndex = " + dateIndex);
	//alert ("myMonth  = " + myMonth);
	
	if (myMonth > 12)
		myYear = myYear + 1;

	//alert ("myYear = " + myYear);
	return myYear;
}

function getMonthIndex(todayMonth, selMonth, yearsOut)
{
	var myIndex;
	var monthsOut;
	
	//if (selMonth < startMonth)
	//{
	//	selMonth = selMonth + 12;
	//}
	//selMonth = selMonth + yearDif *12;
	
	if (yearsOut == 0) // calculate the drop down selection
		monthsOut = selMonth - todayMonth;
	else
		monthsOut = 12 - todayMonth + selMonth + (yearsOut - 1) * 12; // months to the end of the year and then the months in the new year -- if a new year subtract 1 b/c need only 12 new months

	myIndex = monthsOut;
	return myIndex;
}

function setInputDate(hdDate, value)
{
	hdDate.value = value;
}

function setNightsDropDown(f)
{
	var arrivalDate = f.chkIn.value; // get the arrival date
	var departDate = f.chkOut.value; // get the depart date
	var dateArrival = new Date(arrivalDate);
	var dateDepart = new Date(departDate);
	var daysBetween = getDateDifference(dateArrival, dateDepart);

	f.numNights.selectedIndex = daysBetween - 1
}

function getDateDifference(startDate, endDate)
{
	var dateDif;

	dateDif = endDate.getTime() - startDate.getTime();
	dateDif = Math.round(dateDif/(1000 * 60 * 60 * 24));
	return dateDif;
}

function updateDropDowns(txtBoxName, txtBox, f)
{
	var myDate = new Date(txtBox.value);
	var thisDate = new Date();
	
	var ddMonth;
	var ddDay;
	var ddYear;
	var yearDif;

	if (txtBox.type != "hidden")
		return;
	
	if (txtBoxName == "Check-In")
	{
		ddDay = f.chkInDay;
		ddMonthYear = f.chkInMonthYear;
	}
	else
	{
		ddDay = f.chkOutDay;
		ddMonthYear = f.chkOutMonthYear;	
	}
	
	// update month
	var startMonth = thisDate.getMonth() + 1;
	var valMonth = myDate.getMonth() + 1;
	var startYear = thisDate.getYear();
	var valYear = myDate.getYear();
	
	yearDif = valYear - startYear;
	ddMonthYear.selectedIndex = getMonthIndex(startMonth, valMonth, yearDif);

	setDaysDropDown (ddMonthYear, ddDay, 1); // set # days for the month
	ddDay.selectedIndex = (myDate.getDate() -1) // decrement day b/c day is not 0 based
}

function setDaysDropDown_old(selectBoxMonthYear)
{
	var f = selectBoxMonthYear.form;
	var thisDate = new Date();
	var thisMonth = thisDate.getMonth() + 1;
	var thisYear = thisDate.getFullYear();

	var myMonth;
	var myYear;
	var totalDays;
	var selectDay;
	var curDays;
	var myNewOpt; 
		

	myMonth = getMyMonth(thisMonth, selectBoxMonthYear.selectedIndex);
	myYear = thisYear + getMyYear(thisMonth, selectBoxMonthYear.selectedIndex);
	totalDays = getTotalDaysInMonth(myMonth, myYear);
	
	if (selectBoxMonthYear.name == "chkInMonthYear")
		selectDay = f.chkInDay;		
	else
		selectDay = f.chkOutDay;

	curDays = selectDay.options.length; // find out how many days currently

	if (curDays	> totalDays)
	{
		selectDay.options.length = totalDays;
	}
	else if (curDays < totalDays)
	{
		for (i=curDays+1; i<=totalDays; i++)
		{
			myNewOpt = new Option(i, i);
			selectDay.options[selectDay.options.length] = myNewOpt;
		}
	}
}

// GET NUMBER OF DAYS IN MONTH
function getTotalDaysInMonth(month,year)  
{
    var days = 0;
    if (month==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12)  days=31;
    else if (month==4 || month==6 || month==9 || month==11) 
	{
		days=30;
	}
    else if (month==2)  
    {
        if (isALeapYear(year)) 
            days=29;
        else 
            days=28;
    }
    return (days);
}

// CHECK TO SEE IF YEAR IS A LEAP YEAR
function isALeapYear (Year) 
{
    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) 
        return (true);
    else 
        return (false);
}

function callMe()
{
	alert("on the line");
}

var exit = true;
var externalLink = false;

function loadRatesMessage(URL) {
    ihit = 420;
    iwid = 500;
    ttl = (screen.availHeight/2)-(ihit/2);
    lll = (screen.availWidth/2)-(iwid/2);
    if (exit || externalLink) {
        open(URL,'NoBookedReservation','toolbar=1,scrollbars=1,resizable=1,width=' + iwid + ',height=' + ihit + ',top=' + ttl + ',left=' + lll);
//		alert(window.location.href)
    }
}

function updateCalendar(form, date_field, dept_date_field) {
	var form_id_parts = form.id.split("_");
	var counter = (form_id_parts.length > 3)? form_id_parts[form_id_parts.length - 2] : form_id_parts[form_id_parts.length - 1] ;

	var cal = (date_field.id == "chkIn")? eval('a_calendar_' + counter) : eval('d_calendar_' + counter);
		
	if (cal)
		cal.setDate(new Date(date_field.value));
		
	if (dept_date_field && eval('d_calendar_' + counter))
		eval('d_calendar_' + counter).setDate(new Date(dept_date_field.value));
}

function toggleCalendar(arrive, active_check, counter) {
	var a_ids = new Array('chkIn_picker_' + counter, 'arri_cal', 'arri_cal_title');
	var d_ids = new Array('chkOut_picker_' + counter, 'dept_cal', 'dept_cal_title');
	var switch_check = true;
	
	if (active_check !== undefined)	
		switch_check = ((arrive && $(a_ids[0]).hasClass('highlight')) || (!arrive && $(d_ids[0]).hasClass('highlight')))? true : false;
		
	if (switch_check){
		$(a_ids[0]).toggleClass('highlight');
		$(d_ids[0]).toggleClass('highlight');
	
		if(arrive){
			$(d_ids[1]).setStyle('z-index', 1);
			$(a_ids[1]).setStyle('z-index', 0);
		} else {
			$(a_ids[1]).setStyle('z-index', 1);
			$(d_ids[1]).setStyle('z-index', 0);
		}
		
		$(a_ids[2]).toggleClass('hide');
		$(d_ids[2]).toggleClass('hide');
	}
}
function buildCalendar(date_element, counter, max_date) {
    var res_form = $('room_reservations_' + counter + '_') || $('room_reservations_' + counter);
    var min_date = Date.parse(res_form.chkIn.value);
    var cal_today = new Date();
    min_date = (min_date >= cal_today)? min_date : cal_today;
    var cal_tomorrow = (res_form.nights)? new Date(min_date.getTime() + (dayInMilli * res_form.nights.value)) : min_date.clone().increment();    
    var cal_month = min_date.getMonth() + 1;
    var cal_year = min_date.getFullYear();
    var d_offset = res_form.getElement('#chkOut_picker_' + counter).getCoordinates();
    var a_offset = res_form.getElement('#chkIn_picker_' + counter).getCoordinates();
    var a_cal = eval('a_calendar_' + counter);
    var d_cal = eval('d_calendar_' + counter);

    var cal_offsetX = 0; //this is the current width of the calendar, corrected for proper placement.

    d_cal = new CalendarEightysix(res_form.getElement('input[name=chkOut]'), 	{
        'linkWithInput': false, 'format': '%m/%d/%Y', 'minDate': cal_tomorrow, 'defaultDate': cal_tomorrow,
        'maxDate': max_date, 'toggler': 'chkOut_picker_' + counter, 'prefill': true,
        'offsetX': d_offset.left, 'offsetY': d_offset.top
    });
    d_cal.addEvent('change', function(date) {
	var d_month_year = $("Select3_" + counter + '_') || $("Select3_" + counter);
	var dept_day = $("chkOutDay_" + counter + '_') || $("chkOutDay_" + counter);
        var sel_month_year = parseInt(d_month_year.get('value')) + 1;
        var form_chk_out = new Date(res_form.chkOut.value);
        
        var sel_month = getActualMonthVal(sel_month_year);
        var sel_year = getMyYear(cal_month, sel_month_year);
        
        if ((form_chk_out.getFullYear() != date.getFullYear() && date.getFullYear() != cal_year) || sel_month != date.getMonth()+1 || dept_day.get('value') != date.getDate())
        {			
            var offset_month = (date.getFullYear() > cal_year)? date.getMonth() + 12 : date.getMonth();
	

            d_month_year.set( 'value', offset_month);
            dept_day.set( 'value', date.getDate());

            setDaysDropDown(d_month_year, dept_day, 1);
            setChkOutDate(d_month_year, dept_day.selectedIndex, res_form);
            updateCalendar(res_form, res_form.chkIn);
            //toggleCalendar(false);
        }
    });
    
    a_cal = new CalendarEightysix(res_form.getElement('input[name=chkIn]'), 	{
        'linkWithInput': false, 'format': '%m/%d/%Y', 'minDate': min_date,
        'maxDate': max_date, 'toggler': 'chkIn_picker_' + counter, 'prefill': true,
        'offsetX': a_offset.left, 'offsetY': a_offset.top
    });
    
    a_cal.addEvent('change', function(date) {	
	var a_month_year = $("chkInMonthYear_" + counter + '_') || $("chkInMonthYear_" + counter);
	var a_day = $("Select2_" + counter + "_") || $("Select2_" + counter);
        var sel_month_year = parseInt(a_month_year.get('value')) + 1;
        var form_chk_in = new Date(res_form.chkIn.value);	
    
        var sel_month = getActualMonthVal(sel_month_year);
        var sel_year = getMyYear(cal_month, sel_month_year);	
    
        if ((form_chk_in.getFullYear() != date.getFullYear() && date.getFullYear() != cal_year) || sel_month != date.getMonth()+1 || a_day.get('value') != date.getDate())
        {
            var offset_month = (date.getFullYear() > cal_year)? date.getMonth() + 12 : date.getMonth();

            a_month_year.set('value', offset_month);
            a_day.set('value', date.getDate());
            
            setDaysDropDown(a_month_year, a_day, 1);
            setChkInDate(a_month_year, a_day.selectedIndex, res_form);
            //update depature calendar with new default date
            updateCalendar(res_form, res_form.chkOut);
            //toggleCalendar(true);
        }
    });

    res_form.getElement('#chkOut_picker_' + counter).addEvent('mouseover', function(){
        var coords = this.getCoordinates();

        d_cal.options.offsetX = coords.left;
        d_cal.options.offsetY = coords.top;
    });

    res_form.getElement('#chkIn_picker_' + counter).addEvent('mouseover', function(){
        var coords = this.getCoordinates();

        a_cal.options.offsetX = coords.left;
        a_cal.options.offsetY = coords.top;
    });    

    eval('a_calendar_' + counter + ' = a_cal');
    eval('d_calendar_' + counter + ' = d_cal');
}
