var isError=false;
var baseText = null;
var FormName;
var formHotel;
var hotelForm = new Array("dayOfMonth","month","year");
var inputControlName;
var maxDate = new Date(0);
var selectedDate = new Date(0);
var useSelectedDate = false;
var usedFor = "arrival";
var noAnchor = false;
var calendarTitle = "";
var popUp ;

var monday='M';
var tuesday='T';
var wednesday='W';
var thursday='T';
var friday='F';
var saturday='S';
var sunday='S';
var monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
	// [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var displaceCalOnOccupancy = 'false';

// Setting variables for displacement of check-out calendar	
		//	checkForbrowser()
		var browser=navigator.appName;
		var is_major = parseInt(navigator.appVersion);
		var agt=navigator.userAgent.toLowerCase();
		var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	    var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );   
		var ie6CalTopLoc = '0px';
		if (is_ie6){
			displaceCalOnOccupancy = 'true';
			//alert(displaceCalOnOccupancy);
				ie6CalTopLoc = '-225px';	
		}
	
var calDate = new Date();
var currentDate = new Date();

/*********************************************************************
  Main Calendar pop-up function
  
  divid - object in which calendar displays
  frmName - Form containing check-in and check-out date input fields
  usedFor - 'arrival' or 'departure'
**********************************************************************/

function popupCalendar(divid, frmName, usedFor){

	FormName = frmName;
	popUp = document.getElementById(divid);	
	popUp.style.display = "block";
	popUp.className = "calboxon";
	popUp.innerHTML = ""; //clear any previous content
	
	if (baseText == null)
	baseText = popUp.innerHTML;  
	//	alert("usedFor " + usedFor);
	getDateFromInputField(FormName, usedFor);
	if (displaceCalOnOccupancy == 'true'){
		// This block will execute for occupancy page and IE6 browser
		if(usedFor == "arrival"){			
			calendarTitle = "Check-In";
			popUp.style.top = ie6CalTopLoc; 
			popUp.style.left = "0px";
		}else{
			calendarTitle = "Check-Out";
			popUp.style.top = ie6CalTopLoc; 
			popUp.style.left = "130px";
		}
	}else{
		if(usedFor == "arrival"){			
			calendarTitle = "Check-In";
			popUp.style.top = "0px"; 
			popUp.style.left = "0px";
		}else{
			calendarTitle = "Check-Out";
			popUp.style.top = ""; 
			popUp.style.left = "130px";			
		}
	}
	// create calendar with header (showing usage), close button and function which draws remainder of calendar
	// This first table is the container table for whole calendar
	var calNew = "<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr><td>";
	calNew = calNew+"<table cellpadding='0' cellspacing='0' border='0' class='calendarHeader'><tr><td style='width:100%;padding:0;margin:0;color:#ffffff;font-size:11px;line-height:18px;font-weight:bold;'>&nbsp;" + calendarTitle + "</td><td style='padding:0px 6px 0px 0px;line-height:18px;text-align:right;vertical-align:middle;'><a href='#' onclick=\"hidePopup(\'calPopUp\');\"><img src='images/btn-close-grey.gif' border='0'><a></td></tr></table>" + "<td></tr>"+ DrawCalendarNew();	
	popUp.innerHTML  = calNew;	
}
/*****************************
Function to hide the calendar
*****************************/

function hidePopup(divid){
	var popUp = document.getElementById(divid);   
	popUp.style.display = "none";
	popUp.className = "calboxoff";
}


/******************************************
Function to determine whether a date falls 
within an acceptable pre-defined range
******************************************/

function withInBoundry(inputDate){
	var inDt = new Date(inputDate);
	var chkMaxDt = new Date();
	var currDt = new Date();
	chkMaxDt.setYear(formHotel.elements["maxYear"].value);
	chkMaxDt.setMonth((formHotel.elements["maxMonth"].value) - 1);
	chkMaxDt.setDate(formHotel.elements["maxDayOfMonth"].value);

	//alert(chkMaxDt + "   "  + inputDate + "   "  + inDt + "     " + currDt + 
	//		"     " + dateDiff(chkMaxDt.getDate(),chkMaxDt.getMonth(),chkMaxDt.getYear(),inDt) + 
	//		"     " + dateDiff(currDt.getDate(),currDt.getMonth(),currDt.getYear(),inDt));

	if(dateDiff(chkMaxDt.getDate(),chkMaxDt.getMonth(),chkMaxDt.getFullYear(),inDt) < 0 ||
		dateDiff(currDt.getDate(),currDt.getMonth(),currDt.getFullYear(),inDt) > 0 ){
		return false;
	}

	return true;
}


/*****************************************************************
// This method picks already entered value from check-in/check-out fields
// depending upon the parameter usedFor
// FormName - form having check-in and check-out fields
// field - It can have values 'arrival' or 'departure' depending upon 
// which input field or calendar icon user has clicked.
*******************************************************************/

function getDateFromInputField(FormName, field){
	if(field == "arrival"){
		inputControlName = "arrDate";
		usedFor = 'arrival';
	} else if(field == "departure"){
		inputControlName = "depDate";
		usedFor = 'departure';
	}

	if (Browser.nav4){
		if (document.layers['DivBotHotel']){
			formHotel = document.layers['DivBotHotel'].document.forms[FormName];
		}
	}
	else{
		formHotel = document.forms[FormName];
	}

	var inputDate = formHotel.elements[inputControlName].value;

	if(inputDate!= ''){ 
		if(isValidDate(inputDate)){		
			selectedDate = new Date(inputDate); 
			useSelectedDate = true;
		}else{
			inputDate = '';
			useSelectedDate = false;	
		}
	}
}

	

/*********************************************************
Function to determine whether a year is leap year or not
year - year that need to verify
*********************************************************/

function isLeapYear(year){
	if((year%4)==0){
		if(year%100==0){
			if(year%400==0) 
				return true; 
			else 
				return false;
		}
		else{		 
			return true;
		}
	}
	else	
		return false;
}


/***************************************************************
Function to create row of months and container for calendars
**********************************************************************/

function createCalendar(){

	var monthNum= new Date().getMonth() - 1;

	/*=================================
	Create table of month names & links
	===================================*/
	//	alert("Create Calendar monthNum "+ monthNum);

	var curMonthNum = currentDate.getMonth();

	var monthSeparator = "|";	
	
	var startTable = "<tr><td><table border='0' cellpadding='0' cellspacing='0' width='100%' class='monthTable'><tr>";

	var monthRow = "";	

	var counter =0;

	var monthIndex =0;

	for(var i = curMonthNum; i < monthNames.length ; i++,counter++){

		if(counter >10 ){			

			(i+1)>11 ? monthIndex=1 : monthIndex = i+1;

			if(i==-1) i=11;

			monthRow+= "<td style='vertical-align:middle;' nowrap='nowrap'>&nbsp;<a href='javascript:reDrawCalendar("+i+");' class='monthNames'>" + monthNames[i]+ "</a>&nbsp;</td>";		

			break;

		}else{			

			monthIndex = i+1;

			if(i==-1) i=11;

			monthRow+= "<td style='vertical-align:middle;' nowrap='nowrap'>&nbsp;<a href='javascript:reDrawCalendar("+i+");' class='monthNames'>" + monthNames[i] + "</a>&nbsp;" + monthSeparator + "</td>";

		}

		if(i == 11) 

			i= - 1;			

	}	

	monthRow+= "</tr></table></td></tr>";

	/*===============================
	Create table containing calendars
	=================================*/

	var calRow = "<tr><td>" + "<table border='0' cellpadding='0' cellspacing='0' width='100%' class='monthViewTable'><tr><td style='width:50%;border-right:1px solid #B0D1E3;'>"+ showCalendar(0) +" </td><td width='50%;padding:0px;margin:0px;' style='vertical-align:top'>"+ showCalendar(1) +"</td></tr></table>" + "</td></tr></table>";

	var calTable = startTable + monthRow + calRow ;

	//		alert("calTable" + calTable);

	return calTable;

}



/******************************************************
Function to create actual calendar for a month
index -  can have values 0 or 1.
********************************************************/
function showCalendar(index){	

	var calendarTable="";
	var monthNum=0; 
	var dayOfMonth=0;
	var layerNum=0;

	// alert("FormName " + FormName);
	// get name of form containing date input

	if (Browser.ie || Browser.nav6up){
		if (document.forms[FormName]){
			formHotel = document.forms[FormName];
		}
	}

	if (Browser.nav4){
		if (document.layers['DivBotHotel']){
			formHotel = document.layers['DivBotHotel'].document.forms[FormName];
		}
	}

	// get current value for date input (to be used as currently selected date)

	var inputDate = formHotel.elements[inputControlName].value;

	if (inputDate != ''){
		if(isValidDate(inputDate)){	
			selectedDate = new Date(inputDate); 	
			useSelectedDate = true;	
		}else{
			inputDate = '';
			useSelectedDate = false;	
		}
	}	

	var checkNext = formHotel.elements["maxYear"].value + "" + formHotel.elements["maxMonth"].value;

	maxDate.setYear(formHotel.elements["maxYear"].value);

	maxDate.setMonth(formHotel.elements["maxMonth"].value - 1);// Here months are starting from index 0 that's why we are reducing 1 from the month that we are picking from form.

	maxDate.setDate(formHotel.elements["maxDayOfMonth"].value);

	var set = false;

	dom = (document.getElementById)? true : false;

	ie4 = (document.all)? true : false;

	ns6= (dom && !ie4)? true : false;

	ns4 = (document.layers)? true:false;	

	// start calendar table

	var tableStart = "<table border='0' cellpadding='0' cellspacing='0' width='100%' ><tr><td><table border='0' cellpadding='0' cellspacing='0' width='100%' align='center' class='calendar'>";

	calendarTable+=tableStart; //+afterYear;	

	// add month header row for this calendar	
	
	//	alert("before Setting calDate month/year "+ calDate.getMonth() + "/" + calDate.getYear());

	if (index == '0'){	
		monthNum = calDate.getMonth();		
	}else{		
		if(calDate.getMonth() == 0){		
			 monthNum = index;			 
		}else{
		 	monthNum = calDate.getMonth() + index;		 	
		}
				
		if(monthNum == 12)
			monthNum =0;
			
		var		currMonthIndex = new Date().getMonth();
		var		selMonthIndex = monthNum;
		if (selMonthIndex <= currMonthIndex){
			year = new Date().getFullYear();
			year =  year + 1 ;
			calDate.setYear(year);
		}	
	}
	
	var curYear=calDate.getFullYear();	
	
	var monthRowStart="<tr><td style='width:100%;' class='tablePaddingSecond'><table border='0' cellpadding='0' cellspacing='0' style='width:100%;'><tr><td class='selectedMonth' nowrap='nowrap'>"; 

	var monthRowEnd="</td><td class='selectedMonthLayout'>&nbsp;</td></tr></table></td></tr>";

	calendarTable+=monthRowStart+monthNames[monthNum]+"&nbsp;"+calDate.getFullYear()+monthRowEnd+"</table>";
	
	// added another table for padding purpose	
	calendarTable+="<table border='0' cellpadding='0' cellspacing='0' class='tablePadding' width='100%'><tr><td>";	
	
	// add day of week header row for this calendar
	
	calendarTable+="<table border='0' cellpadding='0' cellspacing='0' class='tablePadding' width='100%'><tr style='text-align: center;'>";
	
	calendarTable+="<td class='weekDays'>"+sunday+"</td><td class='weekDays'>"+monday+"</td><td class='weekDays'>"+tuesday+"</td><td class='weekDays'>"+wednesday+"</td><td class='weekDays'>"+thursday+"</td><td class='weekDays'>"+friday+"</td><td class='weekDays'>"+saturday+"</td></tr>";

	// create rows of days for this calendar
	var daysInMonthes=[31,28,31,30,31,30,31,31,30,31,30,31];

	var tdTagForDay="<td class='dayCellInactive'>";

	var tdTagForCurrentDay="<td class='dayCellCurrent'>";

	var tdTagForActiveDay="<td class='dayCellActive'>";

	var tdTagForInactiveDay="<td class='dayCellInactive'>";

	var aTagForPastFutureDay="<div class='dayBorderInactive'>";

	var aTagForDay="<div class='dayBorderActive' onmouseover='this.className=\"dayBorderActiveHover\"' onmouseout='this.className=\"dayBorderActive\"'><a class='dayLink' href='javascript:divClick(\"";

	var aTagForSelectedDay="<div class='dayBorderSelected'><a class='dayLinkSelected' href='javascript:divClick(\"";

	var aTagForCurrentDay="<div class='dayBorderActive' onmouseover='this.className=\"dayBorderActiveHover\"' onmouseout='this.className=\"dayBorderActive\"'><a class='dayLinkCurrent' href='javascript:divClick(\"";

	var tmpDate = new Date(calDate.getFullYear(), monthNum, 1);	
	
	//	alert("after Setting calDate month/year "+ monthNum + "/" + calDate.getYear());
	var startDay = tmpDate.getDay();

	var daysInMonth=daysInMonthes[monthNum];

	if (monthNum==1 && isLeapYear(curYear)) daysInMonth=29;
		
	for (var j=0; j < 6; j++){

		if(j==0 || j==2 || j==4){
			calendarTable+="<tr align='center'>";
		}else{
			calendarTable+="<tr align='center'>";
		}

		for (var k=0; k < 7; k++){
			//calendarTable+=tdTagForDay;
			if((j==0 && k < startDay) || (dayOfMonth==daysInMonth)){
				
				calendarTable+=tdTagForDay+"&nbsp;</td>";
				
			}else{
				if ((dayOfMonth == (currentDate.getDate() - 1)) && (monthNum == currentDate.getMonth()) && (curYear == currentDate.getFullYear()) ){
					calendarTable+=tdTagForActiveDay+aTagForCurrentDay;
					
				}else if(dateDiff(dayOfMonth+1 ,monthNum,curYear,currentDate)< 0 || dateDiff(dayOfMonth+1,monthNum,curYear,maxDate) > 0){					
					calendarTable+=tdTagForInactiveDay+aTagForPastFutureDay;
					noAnchor = true;
					
				}else if(useSelectedDate == true &&(dayOfMonth == (selectedDate.getDate() - 1)) && (monthNum == selectedDate.getMonth()) && (curYear == selectedDate.getFullYear())){
					calendarTable+=tdTagForCurrentDay+aTagForSelectedDay;

				}else{
					calendarTable+=tdTagForActiveDay+aTagForDay;

				}
				
				if(noAnchor == true){
					calendarTable+=(++dayOfMonth)+"</div>";
					noAnchor = false;
				}else{
					calendarTable+=curYear+"\",\""+(monthNum+1)+"\",\""+(dayOfMonth+1)+"\",\""+FormName+"\",\""+usedFor;
					calendarTable+="\")'>";
					calendarTable+=(++dayOfMonth)+"</a></div>";
				}

				calendarTable+="</td>";
				layerNum++;

			}

		}

		calendarTable+="</tr>";
	}

	// close table for this calendar

	var documentEnd="</table></td></tr></table></td></tr></table>";

	
	

	calendarTable+=documentEnd;			

	return calendarTable;

}

/*******************************************************************************
Function to create a calendar. Called by DrawCalendarNew() and reDrawCalendar()
*******************************************************************************/
function DrawCalendar(){
	if(Browser.ie || Browser.nav6up || Browser.opera){
		var finalCal=createCalendar();
		return finalCal;
	}
	else{
		var tmp = createCalendar();
		document.layers[0].document.open();
		document.layers[0].document.write(tmp);
		document.layers[0].document.close();
	}	
}


/*******************************************************************************************
Selecting another month when the calendar is already displayed calls reDrawCalendar())
*******************************************************************************************/
function DrawCalendarNew(){

	if(formHotel.elements[inputControlName].value != ''){		
		if(isValidDate(formHotel.elements[inputControlName].value)){	
			if(withInBoundry(formHotel.elements[inputControlName].value)){	
				calDate.setYear(selectedDate.getFullYear());	
				calDate.setMonth(selectedDate.getMonth() );	
				calDate.setDate(selectedDate.getDate() );	
			}	
		}
	}

	return DrawCalendar();
}


/************************************************************************
Function to redraw a new set of months on the calendar control when a user 
selects a different month on the calendar control already being displayed
selMonthIndex - Index of selected month
*************************************************************************/
function reDrawCalendar(selMonthIndex){

	var currMonthIndex = new Date().getMonth();
	var month ;
	var year ;

	//alert("before setting date " + calDate.getYear() + +" "+ calDate.getMonth());
	if (selMonthIndex < currMonthIndex){	
		month =	selMonthIndex ;
		year = new Date().getFullYear();
		year =  year + 1 ;
		calDate.setYear(year);
		calDate.setMonth(month);
	}else if(selMonthIndex >= currMonthIndex){		
		month =	selMonthIndex ;		
		year = new Date().getFullYear();		
		calDate.setYear(year);			
		calDate.setMonth(month);
	}
	
	//alert("After setting date " + calDate.getYear() + +" "+ calDate.getMonth());
	var calNew = "<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr><td>";
	calNew = calNew+"<table cellpadding='0' cellspacing='0' border='0' style='background-color:#012674;border:1px solid #B0D1E3;border-bottom:0px;'><tr><td style='width:100%;padding:0;margin:0;color:#ffffff;font-size:11px;line-height:18px;font-weight:bold;'>&nbsp;" + calendarTitle + "</td><td style='padding:0px 6px 0px 0px;line-height:18px;text-align:right;vertical-align:middle;'><a href='#' onclick=\"hidePopup(\'calPopUp\');\"><img src='/bestwestern/images/btn-close-grey.gif' border='0'><a></td></tr></table>" + "<td></tr>"+ DrawCalendar();	
	popUp.innerHTML  = calNew;
	
}


/******************************************************************
Function to calculate the difference (in milliseconds) of two dates
******************************************************************/
function dateDiff(dayOfMonth,monthNum,curYear, date2){
	 //alert(dayOfMonth + "  " + monthNum + "  " +curYear);
	date1 = new Date(0);
	date1.setDate(dayOfMonth);
	date1.setMonth(monthNum);
	date1.setYear(curYear);
	date1.setHours(23);
	date1.setMinutes(59);
	date1.setSeconds(59);
	date2.setHours(23);
	date2.setMinutes(59);
	date2.setSeconds(59);
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds

    var difference_ms = date1_ms - date2_ms;

    return difference_ms;
}


/**********************************************************************************
Function to set the date control input value to the date selected from the calendar
frmName - form Name
usedFor -  can have values 'arrival' or 'departure'
***********************************************************************************/
function divClick(year,month,day,frmName,usedFor){

	var formHotel = null;
	var strMonthYear;		

	if(month < 11){
		strMonthYear = year + "0" + (parseInt(month) - 1);
	}else{
		strMonthYear = year + (parseInt(month) - 1);
	}	
	if (Browser.ie || Browser.nav6up){
		if (document.forms[frmName]){
			formHotel = document.forms[frmName];
		}
	}
	if (Browser.nav4){
		if (document.layers['DivBotHotel']){
			formHotel = document.layers['DivBotHotel'].document.forms[frmName];			
		}
	}
	if (formHotel != null){
	 // decremented array index since the default of blank is no longer available
      formHotel.elements[inputControlName].value=month+ "/" + day + "/" + year;
      if(usedFor == 'arrival'){      		
	      changeDepDateAuto(formHotel, formHotel.elements['packagesTest'].value);
      }
      // This is done to prevent erroneous condition if the calendar is inviked from the 
      // Hotel Search pages. 
      try{      		
    	  formHotel.elements[hotelForm[0]].onchange();
      }catch(e){}	
	}
	hidePopup('calPopUp');
	return;
}

/***********************************************************************************
Function to validate check-in, check-out dates without the alerts.
dtStr- can be check-in or check-out date
***********************************************************************************/
function isValidDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
	//	alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYr || year>maxYr){
		//alert("Please enter a valid 4 digit year between "+minYr+" and "+maxYr)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
} 






		function openWin(URL)
			{
				window.open(URL);
				return false;
			}
function setupDisplay(rooms)
{
	var number = rooms.value;
	if (!(number > 1))
	{
		number = 1;
	}
	for (i = 1 ; i <= number ; i++)
	{
		setStyle('room' + i + 'a', 'block');
		setStyle('room' + i + 'b', 'block');
		setStyle('room' + i + 'c', 'block');
		setStyle('room' + i + 'd', 'block');
	}
	for (i = 5 ; i > number ; i--)
	{
		setStyle('room' + i + 'a', 'none');
		setStyle('room' + i + 'b', 'none');
		setStyle('room' + i + 'c', 'none');
		setStyle('room' + i + 'd', 'none');
	}
}


function submitSelectOccupancyForm(event){
	try{
		var srcFormName;
		if(event.srcElement){
			srcFormName = event.srcElement.form.name;
		}
		// Netscape and Firefox
		else if (event.target){
			srcFormName = event.target.form.name;
		}
		if(srcFormName == "LogInForm" || srcFormName == "searchBox"){
			return true;
		}
	}catch(e){
		// ignore
	}	
	return goReturn(document.selectOccupancyForm, document.searchBox, event);	
}

	function submitToProductInfo(propertyCode, disablenav)
	{
		document.selectOccupancyForm.action = "productInfo.do?propertyCode=" + propertyCode + "&disablenav=" + disablenav;
		document.selectOccupancyForm.submit();
		return false;
	}

	function formvalidation(thisform)
	{

		test = validatePriceAvailForm(thisform);
		if(test==true){
		thisform.submit();
						}

	}

	function setStyle(objId, style)
	{
		if (navigator.userAgent.indexOf("Opera") != -1)
		{ //Opera
			styleObj = eval('document.all.' + objId);
			styleObj.style.display = style;
		}
		else if (document.getElementById)
		{ //Netscape 6 & IE 5
			myObj = document.getElementById(objId);
			myObj.style.display = style;
		}
		else
		{
			alert('This website uses DHTML. We recommend you upgrade your browser.');
		}
	}
	
	


preload('calendarOff','images/ico-calendar2.gif');
preload('calendarOn','images/ico-calendar2ovr.gif');

//preload added for update btn 
preload('updateOff','images/btn-update.gif');
preload('updateOn','images/btn-updateon.gif');
function validatePriceAvailForm(form)
	{
		if (form.numRooms.value == "")
		{
		
			//alert('Please specify the Number of <x:choose><x:when select="$Product/AttributeType[@AttributeTypeCode='UNIT CAPTION PLURAL']"><x:out select="$Product/AttributeType[@AttributeTypeCode='UNIT CAPTION PLURAL']/AttributeValue/AttributeValueText/@Text" /></x:when><x:otherwise>Rooms</x:otherwise></x:choose>');
			return false;
		}

		if ( form.numRooms.value != 1 )
		{
			var sameOccupancy = 'true';

			for (var i = 1 ; i <= 5 ; i++)
			{
				if (document.getElementById('room' + i + 'b').style.display == 'block')
				{
					if( i > 1 )
					{
						var numAdults = document.getElementById('numAdults' + i).selectedIndex;
						var lastRoomNumAdults = document.getElementById('numAdults' + (i-1)).selectedIndex;

						if( numAdults != lastRoomNumAdults )
						{
							sameOccupancy = 'false';
						}
					}
				}

				if (document.getElementById('room' + i + 'c').style.display == 'block')
				{

					if( i > 1 )
					{
						var numChildren = 0;
						var numChildrenBox = document.getElementById('numChildren' + i);
						if (numChildrenBox != null)
						{
							numChildren = numChildrenBox.selectedIndex;
						}
						var lastRoomNumChildren = 0;
						numChildrenBox = document.getElementById('numChildren' + (i-1));
						if (numChildrenBox != null)
						{
							lastRoomNumChildren = numChildrenBox.selectedIndex;
						}

						if( numChildren != lastRoomNumChildren )
						{
							sameOccupancy = 'false';
						}
					}
				}
				if (document.getElementById('room' + i + 'd').style.display == 'block')
				{

					if(i > 1)
					{
						var ratePlan = null;
						var ratePlanBox = document.getElementById('ratePlanForm' + i);
						if (ratePlanBox != null)
						{
							ratePlan = ratePlanBox.selectedIndex;

						}

						var lastRatePlan= null ;
						ratePlanBox = document.getElementById('ratePlanForm' + (i-1));

						if (ratePlanBox != null)
						{
							lastRatePlan = ratePlanBox.selectedIndex;

						}


						if( ratePlan != lastRatePlan )
						{
							sameOccupancy = 'false';
						}

					}
				}

			}

		}

		for (var i = 1 ; i <= 5 ; i++)
		{
			if (document.getElementById('room' + i + 'b').style.display == 'block')
			{
				if (document.getElementById('numAdults' + i).selectedIndex < 0)
				{
					//alert('Please Enter Your Guest <x:choose><x:when select="$Product/AttributeType[@AttributeTypeCode='UNIT CAPTION SINGULAR']"><x:out select="$Product/AttributeType[@AttributeTypeCode='UNIT CAPTION SINGULAR']/AttributeValue/AttributeValueText/@Text" /></x:when><x:otherwise>Room</x:otherwise></x:choose> Occupancy');
					return false;
				}
			}
		}

		if(!isDate(form.arrDate.value) || !isDate(form.depDate.value)){

			return false;
		}

		//new validation for date
		
		arrDate = new Date(Date.parse(form.arrDate.value));
		depDate = new Date(Date.parse(form.depDate.value));
		if(days_between(depDate, arrDate)< 0){

			//alert('Your Check-out date must occur after your Check-in date.  Please revise your dates and try again.');
			changeDep(form);
			depDate = new Date(Date.parse(form.depDate.value));
			//return false;
		}
		if(days_between(depDate, arrDate)== 0){

			//alert('Check-in date is equal to the Check-out date. Please enter a valid date.');
			changeDep(form);
			depDate = new Date(Date.parse(form.depDate.value));
			//return false;
		}
		var nights = Math.abs(days_between(arrDate, depDate));
		if( nights > 30)
		{
			alert('Bestwestern.com cannot process a hotel reservation that exceeds 30 days in length. Please revise your reservation Check In or Check Out dates.');
			return false;
		}
		var istooFar = Math.abs(days_between(arrDate, new Date()));
		if( istooFar > 350)
		{
			alert('The Arrival Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}

		var istooFarCheckOutDate = Math.abs(days_between(depDate, new Date()));
		if( istooFarCheckOutDate > 350)
		{
			alert('The Departure Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}
		//end validation


		if (validateAscii(form.corporateId) == false){
			return false;
		}

		if (validateAscii(form.promotionalCode) == false){
			return false;
		}


		if (preventDoubleClick())
		{
			if( sameOccupancy == 'true' )
			{
				form.allRoomsSame.value = confirm('Would you like all the Room/rates to be the same? Click OK if all the same and Cancel if you wish to select different Rooms/rates for each Room.');
			}
			/*AR0755B:TR7534:- Added else block for setting the flag for checking room occupancy. Now the flag will set to false if all the rooms are not having same occupancy */
			else
			{ 
				form.allRoomsSame.value = false;  
			}
		}
		else
		{
			return false;
		}
		 return true;
	}


	function validDate(form) {

		var arrMY = form.arrivalMonthYear.value;
		var depMY = form.departureMonthYear.value;
		var arrDY = form.arrivalDay.value;
		var depDY = form.departureDay.value;
		arrMonthTemp = arrMY.substring(6,4);
		arrYearTemp = arrMY.substring(0,4);
		depMonthTemp = depMY.substring(6,4);
		depYearTemp = depMY.substring(0,4);
		arrDate = new Date(0);
		depDate = new Date(0);
		arrDate.setYear(arrMY.substring(0,4));
		arrDate.setDate(arrDY);
		arrDate.setMonth(arrMY.substring(6,4));
		
		depDate.setYear(depMY.substring(0,4));
		depDate.setDate(depDY);
		depDate.setMonth(depMY.substring(6,4));
		
	        if ((arrDate.getMonth() < 0 || arrDate.getMonth() > 11)||(depDate.getMonth() < 0 || depDate.getMonth() > 11)) {
                    alert('Please Enter a Valid Date');
					return false;
                }
                if ((arrDate.getDate() < 1 || arrDate.getDate() > 31)||(depDate.getDate() < 1 || depDate.getDate() > 31)) {
                    alert('Please Enter a Valid Date');
					return false;
                }
                if ((arrMonthTemp == 3 || arrMonthTemp == 5 || arrMonthTemp == 8 || arrMonthTemp == 10) &&
                    (arrDY == 31)) {
                    alert('Please Enter a Valid Date');
					return false;
                }
                if ((depMonthTemp == 3 || depMonthTemp == 5 || depMonthTemp == 8 || depMonthTemp == 10) &&
                    (depDY == 31)) {
                    alert('Please Enter a Valid Date');
					return false;
                }
                if (arrMonthTemp == 1) {
                    var leap = (arrYearTemp % 4 == 0 &&
                               (arrYearTemp % 100 != 0 || arrYearTemp % 400 == 0));
                    if (arrDY >29 || (arrDY == 29 && !leap)) {
                        alert('Please Enter a Valid Date');
						return false;
                    }
				}
                if (depMonthTemp == 1) {
                    var leap = (depYearTemp % 4 == 0 &&
                               (depYearTemp % 100 != 0 || depYearTemp % 400 == 0));
                    if (depDY >29 || (depDY == 29 && !leap)) {
                        alert('Please Enter a Valid Date');
						return false;
                    }
               }
               compDate = new Date();
               compDate.setHours(0,0,0,0);
				if (arrDate < (compDate)|| depDate < (compDate) ){
					alert('The arrival or departure date you have provided has already passed, please provide valid dates.');
					return false;
				}
                return true;
            }

	function days_between(date1, date2)
	 {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = date1_ms - date2_ms;


    //return Math.round(difference_ms/ONE_DAY)
    diff=Math.round(difference_ms/ONE_DAY);

    return diff;
   }
   
   function changeDep(form)
   {
   		arrDate = new Date(Date.parse(form.arrDate.value));				
		temp_date = new Date(arrDate.getTime() +(24*60*60*1000)); //Incrementing the arrival date to one day.			
		tempDMY= (temp_date.getMonth() +1) + "/" + temp_date.getDate() + "/" + temp_date.getYear();		
		form.depDate.value = tempDMY;
   }
   
   // function to open help window
	function MM_openBrWindow(theURL,winName,features) {


			if(ie4){
			xMousePos = window.event.x+document.body.scrollLeft;
			yMousePos = window.event.y+document.body.scrollTop - 100;
			}else {
			
			}
		features=features+",left="+xMousePos+",top="+yMousePos;
		helpPopup=window.open(theURL,winName,features);
		//helpPopup.moveTo(xMousePos,yMousePos);
	}
	
	function setNights() {
	   var date1 = new Date(document.selectOccupancyForm.arrDate.value);
	   var date2 = new Date(document.selectOccupancyForm.depDate.value);
	   var days=days_between(date2, date1);
	  
	   if(document.selectOccupancyForm.nights != null) {
	    if(days<=30){
	   	document.selectOccupancyForm.nights.selectedIndex=days-1;
	   	}
	    else {
	    //set the index to 30 if the difference is more than 30 days
	 	document.selectOccupancyForm.nights.selectedIndex=29;
	 	}
	  }		   
	}
	
	function setCheckOutDate() {
	   	var date1 = new Date(Date.parse(document.selectOccupancyForm.arrDate.value));
	   //	alert("setchkoutdate");
	   	var numOfNights = document.selectOccupancyForm.nights.value;
	   
	   	var d1= new Number (date1.getDate());
	   	var d2= new Number (numOfNights);
	   
	   	date1.setDate(d1+d2);
	   	date1 = (date1.getMonth()+1) + "/" + date1.getDate() + "/" + date1.getFullYear();		
		document.selectOccupancyForm.depDate.value=date1;	   
	}
		
	function checkdate(){	
		var arrDate = new Date(Date.parse(document.selectOccupancyForm.arrDate.value));
	 	var depDate = new Date(Date.parse(document.selectOccupancyForm.depDate.value));
	 	var nights = document.selectOccupancyForm.nights.value;
	   	var compDate = new Date();
      	compDate.setHours(0,0,0,0);
		if (arrDate < (compDate)|| depDate < (compDate) ){
			alert('The arrival or departure date you have provided has already passed, please provide valid dates.');
			return false;
		}	 
		//new if checkout less than checkin
		if(days_between(depDate,arrDate)<=0){
			changeDep(document.selectOccupancyForm);
		}

		if(Math.abs(days_between(arrDate, new Date())) > 350) {
			alert('The Arrival Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}
		
		//alert("days betn arrdate and today "+days_between(arrDate, new Date()));	
		//to show alert if checkindate+nights > 350
		 /*var date1 = new Date(document.selectOccupancyForm.arrDate.value);
		 var d1= new Number (arrDate.getDate());
		 var d2= new Number (nights);
		 date1.setDate(d1+d2);
		 
		 if(Math.abs(days_between(date1,new Date())) > 350) {
		    alert('The Departure Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		 }*/	
	 
		var istooFarCheckOutDate = Math.abs(days_between(depDate, new Date()));
	 	//alert("depDate "+depDate+" daysbetn "+istooFarCheckOutDate);
		if( istooFarCheckOutDate > 351){
			alert('The Departure Date that you entered is too far in the future. Please enter a valid Date or choose valid Nights.');
			return false;
		}	 
		if(isDate(document.selectOccupancyForm.arrDate.value) && isDate(document.selectOccupancyForm.depDate.value)){
			return true;
		}
		else{
			return false;
		}
	}
	
	function checkdateOnPrevious(){
	    var depDate = new Date(document.selectOccupancyForm.depDate.value);
		var istooFarCheckOutDate = Math.abs(days_between(depDate, new Date()));
	    
		if( (istooFarCheckOutDate > 351 && document.selectOccupancyForm.nights.selectedIndex != 0) ||
			(istooFarCheckOutDate == 351 && document.selectOccupancyForm.nights.selectedIndex == 1))
		{  
		    //alert("setting nights to 1");
		    alert('The Departure Date that you entered is too far in the future. Please enter a valid Date or choose valid Nights.');
		    return false;
			//document.selectOccupancyForm.nights.selectedIndex=0;
		}
		
	}
	
	
function setArrDateFromParam(form){
		
		
		//alert("we are here in setArrDateFromParam");
		if(!isError){
		var arrMY = '200911';
		var arrDY = '27';
		arrMonthTemp = arrMY.substring(4,6);
		arrYearTemp = arrMY.substring(0,4);
		arrDate = new Date(0);
		//alert(arrMY + "  " + arrDY + "   " + arrMonthTemp +  arrYearTemp);
		arrDate.setDate(arrDY);
		arrDate.setMonth(arrMY.substring(4,6));
		arrDate.setYear(arrMY.substring(0,4));
		//alert(arrDate);
			form.arrDate.value= (arrDate.getMonth() + 1) + "/" + arrDate.getDate() + "/" + arrDate.getFullYear(); 
		}
		
}
function setDepDateFromParam(form){
		
		if(!isError){
		var depMY = '200911';
		var depDY = '29';		
		
		depMonthTemp = depMY.substring(4,6);
		depYearTemp = depMY.substring(0,4);		
		depDate = new Date(0);	
		//alert(depMY + "  " + depDY + "   " + depMonthTemp +  depYearTemp);
		depDate.setDate(depDY);	
		depDate.setMonth(depMY.substring(4,6));
		depDate.setYear(depMY.substring(0,4));
		//alert(depDate);
			form.depDate.value= (depDate.getMonth() + 1) + "/" + depDate.getDate() + "/" + depDate.getFullYear(); 	
		}
		
}

	



var currentDate = new Date();

var arrivalDate=null;
var celldate = null;
var updatedCellDate = null;
var nights = 0; 
var checkindate=null;
var prevflag="false";


var prevnextFlag="false";
var chkoutDate=null;
var sessionTimeout=false;


//This is called on clicking of show calendar link
function showCal() {
     
      //This is to show only the calendar and not to show the hide calendar link till the 
      //calendar UI is displayed
      if(viewCal == true)
      	setCalendarVisibility();
      
   	  prevnextFlag="false";
	  celldate = document.selectOccupancyForm.arrDate.value;
	  
	  //NEW TO SET CHKOUTDATE and nights
	  var thisForm = document.selectOccupancyForm;
	  nights = thisForm.nights[thisForm.nights.selectedIndex].value;
	  setCheckOutDate();
	  getCalendarDetails();
	  
	 
	 
	  if(sessionTimeout==true) {
	   //alert("sessiontimeout true");
	   return false;
	  } 
	 
	 
	  if(viewCal == false) {
	 	 setHideLinkVisibility();	 	  
	  }  	 
	
}

function setCalendarVisibility() {
	 document.getElementById('calendar').style.visibility="visible";
	 document.getElementById('cal').style.visibility="visible";
	 document.getElementById('calendar').style.display='';
	 document.getElementById('cal').style.display='';
}

function setHideLinkVisibility(){
	 
	  document.getElementById('show').style.visibility="hidden";
	  document.getElementById('hide').style.visibility="visible";
	  
	  document.getElementById('hide').style.display='inline';
	  document.getElementById('show').style.display='none';
	  
	 
}


function hideCal() {
 
   document.getElementById('cal').style.visibility="hidden";
   document.getElementById('cal').innerHTML="";
   document.getElementById('calendar').style.visibility="hidden";
   document.getElementById('hide').style.visibility="hidden";
   document.getElementById('show').style.visibility="visible";
   
   document.getElementById('show').style.display='inline';
   document.getElementById('hide').style.display='none';
   document.getElementById('dek').style.visibility="hidden";
   document.getElementById('dek').style.display='none';
}
//Called on click of updatebutton
function onUpdateClick(thisForm){
	  
         nights = thisForm.nights[thisForm.nights.selectedIndex].value;
         //arrivalDate = thisForm.arrDate.value;
         
         //Calendar cell is not clicked,but since same ajax call is needed
         //we can make the arrivaldate as cell date
         celldate=document.selectOccupancyForm.arrDate.value;
         prevnextFlag="false";
         setCheckOutDate();
         getCalendarDetails();
     
}

function previous(mon,year) {
	
	   
    var mons=0;
	if(mon != 0) {
		 mons = mon-1;
		 currentDate.setYear(year);
	}	 
	else if(mon == 0) {
	    var mons=11;	
	    var year=year-1;
	    currentDate.setYear(year);
	    
    }
    
    //var mons=mon-1;
             			
	//alert("get month before setting "+currentDate.getMonth() +" mons "+mons);
	
	currentDate.setMonth(mons);
	
	
	arrivalDate=currentDate;
	//new
	checkindate= document.selectOccupancyForm.arrDate.value;
	prevflag="true";	
	
	prevnextFlag="true";
	celldate=null;
	getCalendarDetails();
	
	

}

function next(mon,year) {
	
	var mons = mon+1;
	currentDate.setMonth(mon);
	
	//set current year as year passed 
	currentDate.setYear(year);
	arrivalDate=currentDate;
	prevflag="false";
	checkindate= document.selectOccupancyForm.arrDate.value;
	
	prevnextFlag="true";
	celldate=null;
	getCalendarDetails();
  

}


//called on cliking a cell in the calendar
//caldate1 is in mm/dd/yy format
function popCal(caldate,caldate1){
prevnextFlag="false";
document.selectOccupancyForm.arrDate.value=caldate1;
nights =document.selectOccupancyForm.nights[document.selectOccupancyForm.nights.selectedIndex].value;

//Apr 10
setCheckOutDate();
if(checkdate() == false){
	return false;
}

if(caldate != null){
	
	//new to set checkout date
	setCheckOutDate();
	
	celldate = caldate1;
	var datePassed = new Date(caldate1);
	var curdate = new Date();
	curdate.setHours(0);curdate.setMinutes(0);curdate.setSeconds(0);
	if(datePassed > curdate)
		getCalendarDetails();
	else if(datePassed.getDate() == curdate.getDate())
	 getCalendarDetails();			
	else
		alert("date passed is less than currentdate");   		
}
}

var xmlHttp;
function getCalendarDetails()
  { 
	
	  
	  
  try
    {    // Firefox, Opera 8.0+, Safari    
		xmlHttp=new XMLHttpRequest(); 
  }
  catch (e)
    {    // Internet Explorer    
  try
    {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");     
	}
    catch (e)
    { 
		try 
        {   
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");       
		}
      catch (e)
        {   
		  alert("Your browser does not support AJAX!");        return false;    
		} 
	} 
   }

    xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {
        
        	if(xmlHttp.status  == 200){
        	
			  //alert("ready to display calendar ");
			  var cal = document.getElementById('cal');
			  
			  
			  //NEW FOR CHECKING IF THE TEXT HAS WHOLE HTML
			  var respHtml=xmlHttp.responseText;
			  if(prevnextFlag == "true") {
			 	//alert("response has div only");
			  	 //alert("Responsetext  "+xmlHttp.responseText);
			 	cal.innerHTML=xmlHttp.responseText;
			 	
			 	
			 	showdate('range');
			 	showdate('rangenew');
			  }
			  else {
			  	// alert("Responsetext has entire HTML "+xmlHttp.responseText);
			     var divElements=splitTextIntoDiv(respHtml);  
			     //alert("after splittext divelems "+divElements);
			     replaceExistingWithNewHtml(divElements);
		
			  }
			  
			  //NEW
			  
			  if(prevnextFlag=="true") 
			     checkdateOnPrevious();
			   highlight();
			  
			  
			   //new for restriction  - ajax call Apr 9
			   if(prevnextFlag=="false")
			   	getRestrictionDetails();
			   //End new for restriction  - ajax call Apr 9
			   
			   //Apr 12
        	  
        	    if(viewCal==true) {
        		 setHideLinkVisibility();
        		 viewCal=false;		
        	   }
        	  //APR 12
			   
	        }
	        else if(xmlHttp.status  == 404)
	       {
	       		alert('Unable to contact server. Please try again later.');
	       		viewCal=true;
	       }
	       else{
		       	alert('An error occurred while connecting to server.\nPlease try again later.');
		       	viewCal=true;
	       }
      }
    }
    
    if(celldate != null) {
    	//alert("CELLDATE NOT NULL BEFORE CALLING AJAX "+document.selectOccupancyForm.nights.value);
    	xmlHttp.open("GET","priceAvail.do?cellDate="+celldate+"&nights="+nights+"&chkoutdate="+document.selectOccupancyForm.depDate.value+"&" + (new Date()).getTime(),true);    
    }
    /*else if(updatedCellDate != null) {
    	xmlHttp.open("GET","priceAvail.do?updatedCellDate="+updatedCellDate
    }*/
   
    else if(arrivalDate != null) {
    	xmlHttp.open("GET","Calendar.do?Monthstart="+toBWIDateString(arrivalDate)+"&checkindate="+checkindate+"&prevflag="+prevflag+"&chkoutdate="+document.selectOccupancyForm.depDate.value+"&" + (new Date()).getTime(),true);
    } 	
    else {
    	xmlHttp.open("GET","Calendar.do?Monthstart="+toBWIDateString(currentDate),true);
    }
    xmlHttp.send(null); 
}

/*
 * custom date to string conversion function
 */
function toBWIDateString(date){
	month = date.getMonth() + 1;
	day = date.getDate() ;
	year = date.getFullYear();

	str = month + " - " + day + " - " + year;
	return str;
}

function splitTextIntoDiv(textToSplit){
 
  //Split the document
  var returnElements=textToSplit. 
            split("</div>")
        
  //Process each of the elements        
  for(var i=returnElements.length-1;i>=0;--i){
                
    //Remove everything before the 1st span
    var divPos = returnElements[i]. 
             indexOf("<div");               
                
    //if we find a match, take out 
    //everything before the span
    if(divPos>0){
          subString=returnElements[i].substring(divPos);
          returnElements[i]=subString;
    } 
  }
  return returnElements;
}

function replaceExistingWithNewHtml 
        (newTextElements){
 var elementFound = false;
  //loop through newTextElements
  for(var i=newTextElements.length-1;i>=0;--i){
  	
  	
    //check that this begins with span
    if(newTextElements[i].indexOf("<div")>-1){
                        
          //get the div name - sits
      // between the 1st and 2nd quote mark
      //Make sure your spans are in the format 
      var startNamePos=newTextElements[i].indexOf('"')+1;
      var endNamePos=newTextElements[i].indexOf('"',startNamePos);
      var name=newTextElements[i].substring(startNamePos,endNamePos);
                        
      //get the content - everything 
      // after the first > mark
      var startContentPos=newTextElements[i].indexOf('>')+1; 
      var content=newTextElements[i].substring(startContentPos);
      //alert("ID OF DIV ELEMENT "+name);                  
     //Now update the existing Document 
     // with this element, checking that 
     // this element exists in the document
     if(name == "cal") {
     if(document.getElementById(name)){
         //alert("CONTENT "+content);
         document.getElementById(name).innerHTML = content;
         elementFound = true;
         
      }
     }
    }
    
  }//end of fn
  if(elementFound == false ){
  	 	alert('Your session has timed out.');
    	sessionTimeout=true;
    	viewCal=false;
    }
    else{
    	// success
    	
    }
  }
  
  function getRestrictionDetails() {
  
  var xmlHttp1;
  try
    {    // Firefox, Opera 8.0+, Safari    
		xmlHttp1=new XMLHttpRequest(); 
  }
  catch (e)
  {    // Internet Explorer    
  try
    {      xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");     
	}
  catch (e)
    { 
		try 
        {   
			xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");       
			 
		}
      catch (e)
        {   
		  alert("Your browser does not support AJAX!");        return false;    
		} 
	} 
   }
  		xmlHttp1.open("GET","restriction.do?chkoutdate="+document.selectOccupancyForm.depDate.value+"&" + (new Date()).getTime(),true);    
        xmlHttp1.send(null); 
        
        
   xmlHttp1.onreadystatechange=function()
   {
      if(xmlHttp1.readyState==4)
      {
        var responsetxt=xmlHttp1.responseText;
       
        if(responsetxt !=  null) {
	        var msg=responsetxt.substring(0,responsetxt.indexOf('*'));
	        
	        var caldate=responsetxt.substring(responsetxt.indexOf('*')+1,responsetxt.indexOf('#'));
	        var availFlag=responsetxt.substring(responsetxt.indexOf('#')+1,responsetxt.indexOf('$'));
	        var losUnits = responsetxt.substring(responsetxt.indexOf('$')+1);
	        
	        //hide unavailable error msg in case of user clicking on available cell
	        if(availFlag != null && trim(availFlag) == "true" && document.getElementById('unAvailableText')!=null){
          		document.getElementById('unAvailableText').style.visibility='hidden'; 	
       			document.getElementById('unAvailableText').style.display='none';
       			if(document.getElementById('errorMsg') != null) {
       				document.getElementById('errorMsg').style.visibility='hidden'; 
       				document.getElementById('errorMsg').style.display='none';
       			}
	        }
	        else if(availFlag != null && trim(availFlag) == "false" && document.getElementById('unAvailableText')!=null){
	        	document.getElementById('unAvailableText').style.visibility='visible'; 
	        	document.getElementById('unAvailableText').style.display='';
	        }
	        
	        popup(msg,'blue',caldate,losUnits); 
        }
        
      }
      else {
           //alert("inside call "+xmlHttp.readyState);
      }  
  	}
  
}//end of fn

//Apr 12

var doubleClick=false;
var viewCal=false;
function viewCalendar() {

viewCal=true;
showCal();

}



function preventdoubleClick()
{
	
 	 var temp_date = new Date().getTime();
 	
     if (doubleClick){
        
         return false;
      }
      else{
         doubleClick = true;
         return true;
      }

}

// AR0755B: SJ: Added los to display losUnits in Restriction message whereever applicable.	
function popup(msg,bak,caldate,los){
skn=document.getElementById("dek").style;
if(trim(msg) == "AVAILABLE" || trim(msg) =="CLOSE" || trim(msg)=="null" || (msg != null && msg.length==0) || (trim(caldate)=="null")) {
 kill();
 return false;
} 
else {
msg=msg.substring(msg.indexOf(':')+1);

if (ns4) {

skn=document.getElementById("dek").style;
}
else if (ns6)

skn=document.getElementById("dek").style;

else if (ie4)

skn=document.getElementById("dek").style;;

if(ns4)document.captureEvents(Event.MOUSEMOVE);

else{

skn=document.getElementById("dek").style;
skn.visibility="visible";

skn.display='';

}

var content="<TABLE BORDER='1px' BORDERCOLOR=#73A6CE BGCOLOR=#ffffff height='192px'CELLPADDING='6px' CELLSPACING='0px'"+

"BGCOLOR="+bak+"><tr><td><table ALIGN=CENTER BORDER=0 BGCOLOR=#EFF7FF height='100%'CELLPADDING=4 CELLSPACING=0><tr><td class='title'>Available With&nbsp;"+
						"Restrictions</td></tr><tr><td><img src='images/1px_new.gif' height='1px' width='210px'></td></tr>"+
"<tr><TD class='line1'>Availability on <strong>"+caldate+"</strong>is based on following restrictions:</tr>"+
"<tr><TD class='line1'>"+showMessage(msg, '1', los)+"</tr>"+
"<tr><td class='line2'>"+showMessage(msg, '2', los)+"</td></tr></TD><tr><td class='close'><img src='images/close.gif' onClick=kill('skn')>&nbsp;<a href='#null' onClick=kill('skn')><u>Close</u></a></td></tr></TD></table></td></tr></TABLE>";

var dek1 = document.getElementById("dek");
dek1.style.display='block';
//dek1.style.left=findPos(document.getElementById("update"))[0]+15;
//dek1.style.top=findPos(document.getElementById("update"))[1]+70;

	var posiX = findPos(document.getElementById("update"))[0]+15;

	var posiY = findPos(document.getElementById("update"))[1]+70;

	dek1.style.display='block';
	dek1.style.left=posiX + 'px';
	dek1.style.top=posiY + 'px'; 

 if(ns4){skn.document.write(content);skn.document.close();skn.visibility="hidden"}

 if(ns6){document.getElementById("dek").innerHTML=content;skn.display=''}

 if(ie4){document.getElementById("dek").innerHTML=content;skn.display=''}
 
 if(moz){
  document.getElementById("dek").innerHTML=content;skn.display='';
 }
 
 }//END ELSE

}

// AR0755B: SJ: called from popup() to set relevant Restriction Message on Restriction Pop-Up, with internationalization.
function showMessage(msg, line, los) {
	var CTAmsg = "This date is not available for check in.";
	var LOSmsg;
	var LOSmsg1 = "A minimum stay of";
	var LOSmsg2 = "days is required.";
	var restMsg3 = "You must adjust your travel dates to book on this night.  ";
	var restMsg3MLOSMET = "Early departure fees may apply.";
	var restMsg3CTA = "You must adjust your travel dates to book this night.";
	
	if(line == '1') {
		if(trim(msg) == 'CTA') {
			return CTAmsg;
		} else {
			LOSmsg = (LOSmsg1 + " " +los + " " +LOSmsg2);
			return LOSmsg;
		}
	} else {
		if(trim(msg) == 'MLOSMET') {
			return restMsg3MLOSMET;
		} else if(trim(msg) == 'CTA') {
			return restMsg3CTA;
		} else {
			return restMsg3;
		}
	}
}

	       document.getElementById("calendar").style.visibility="hidden"; 
	       document.getElementById("cal").style.visibility="hidden"; 
	   	   document.getElementById("cal").innerHTML="";
	   	   document.getElementById("show").style.visibility="visible"; 
	       document.getElementById("hide").style.visibility="hidden"; 
	       document.getElementById("show").style.display="inline";
	       document.getElementById("hide").style.display="none";
	       //MAY 7 -- NOT TO SHOW UNAVAILBALE TEXT 
	      if(document.getElementById("unAvailableText") != null) 
		      document.getElementById("unAvailableText").style.display="none";


   var doubleClick;

   /**
    ****************************************************************************
    * the main validation methods
    ****************************************************************************
    */

   /**
    * wrapper function that calls all post-submit validation functions
    */
   function validateSelectHotelFormAll(form) {
      var passed = true;
      
		

		
		
		
		
      // the 'custom' validations below
     if (passed)
      {
         passed = validateCapacityRequest(form);
      }
      
	      if (passed)
    	  {
        	 passed = validateCountryState(form);
	      }
	  
      if (passed)
      {
         passed = validateAddressSearch(form);
      }
      if (passed)
      {
         passed = validateReferencePointSearch(form);
      }
      if (passed)
      {
         passed = preventDoubleClick();
      }
      return passed;
   }

   /**
    * Called on form submit to ensure that asian users only enter valid
    * ascii (includes extended). DANSHAW
   */
   function validateAscii(item){
      
      return true;
   }

   /**
    * Called on form submit to ensure that the telephone number only contains valid
    * characters (dec ascii 32-64 and 91-96). WT593
    */
   function validateTelephoneNumber(telephoneNumber)
   {
      for (i = 0; i < telephoneNumber.length; i++)
      {
         if (telephoneNumber.charCodeAt(i) > 96)
         {
            return false;
         }
         if (telephoneNumber.charCodeAt(i) < 32)
         {
            return false;
         }
         if (telephoneNumber.charCodeAt(i) > 64 && telephoneNumber.charCodeAt(i) < 91)
         {
            return false;
         }
      }
      return true;
   }

   /**
    * Called on form submit to ensure that either none or all of the input elements that would
    * trigger an availability have been selected (arrival date, departure date)
    */
   function validateCapacityRequest(form) {
      if (hasAStayElement(form) && !hasAllStayElements(form)) {
     	if(isDate(form.arrDate.value) &&
     			form.depDate.value == ""){
     		changeDep(form);
     		return true;
     	}
     	else {
        	 var msg = "If you would like to check Room Availability for a Stay, you must provide:\n  - Your Arrival Date and Month-Year\n  - Your Departure Date and Month-Year\n\nIf you do not wish to check Room Availability and are just searching for a hotel,\nplease deselect all of these fields.";

	         window.alert(msg);

    	     try
        	 {
            	if (form.arrDate.value == "") {
	               form.arrDate.focus();
    	           return false;
        	    }
            	else if (!isDate(form.depDate.value)) {
	               form.depDate.focus();
    	           return false;
        	    }
            	return false;
	         }

        	 catch (e)
	         {
    	        //Must've come from a page that doesn't have this property.
        	 }
        }
      }
      else if (hasAllStayElements(form)) {
         return validateArrivalAndDepDate(form);
      }

      return true;
   }


   function validateReferencePointSearch(form)
   {
      if ((form.referencePoint != null) && (form.referencePointType != null))
      {
         if ((form.referencePoint.value == "") && (form.referencePointType.value != ""))
         {
            window.alert("Please enter a reference point.");
            return false;
         }

         if ((form.referencePointType.value == "") && (form.referencePoint.value != ""))
         {
            window.alert("Please select a reference point type from the drop down list.");
            return false;
         }
         return true;
      }
      return true;
   }

   /**
    * this method ensures that the Stay Date provided occurs in the future; this
    * is called inside validateCapacityRequest
    */
   function validateArrivalAndDepDate(form)
   {
	  try {


		if(form.arrDate.value == "" && form.depDate.value == ""){
			return true;
		}
		
		if(!isDate(form.arrDate.value)){
			form.arrDate.focus();
			form.arrDate.select();
			return false;
		}
		if(!isDate(form.depDate.value)){
			form.depDate.focus();
			form.depDate.select();
			return false;
		}
		//new validation for date
		var arrDMY = form.arrDate.value;
		var depDMY = form.depDate.value;
		

		arrDate = new Date(Date.parse(arrDMY));
		depDate = new Date(Date.parse(depDMY));
		
	
		if(days_between(depDate, arrDate)< 0){
			
			//alert('Your Check-out date must occur after your Check-in date.  Please revise your dates and try again.');
			changeDep(form);
				depDate = new Date(Date.parse(form.depDate.value));				
			//return false;			
		}
		if(days_between(depDate, arrDate)== 0){			
			//alert('Check-in date is equal to the Check-out date. Please enter a valid date.');
			changeDep(form);			
				depDate = new Date(Date.parse(form.depDate.value));			
			//return false;
		}
		var nights = Math.abs(days_between(arrDate, depDate));
		if( nights > 30)
		{
			alert('Bestwestern.com cannot process a hotel reservation that exceeds 30 days in length. Please revise your reservation Check In or Check Out dates.');
			return false;
		}

		var istooFar = Math.abs(days_between(arrDate, new Date()));
		if( istooFar > 350)
		{
			alert('The Arrival Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}

		var istooFarCheckOutDate = Math.abs(days_between(depDate, new Date()));
		if( istooFarCheckOutDate > 350)
		{
			alert('The Departure Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}


		//end validation
	  }
      catch (e)
      {
         alert(e);
         return false;
      }
      return true;
   }

   /**
    * this method ensures that the Stay Date provided is valid; this
    * is called inside validateArrivalAndDepDate
    */
	function validDate(form) {
		var arrMY = form.arrivalMonthYear.value;
		var depMY = form.departureMonthYear.value;
		var arrDY = form.arrivalDay.value;
		var depDY = form.departureDay.value;
		//when user blank out all the dates
		if(arrDY == "" && arrMY == "" && depDY == "" && depMY == ""){
			return true;
		}


		arrMonthTemp = arrMY.substring(6,4);
		arrYearTemp = arrMY.substring(0,4);
		depMonthTemp = depMY.substring(6,4);
		depYearTemp = depMY.substring(0,4);

		arrDate = new Date(0);
		depDate = new Date(0);
		
		arrDate.setYear(arrMY.substring(0,4));
		arrDate.setDate(arrDY);
		arrDate.setMonth(arrMY.substring(6,4));
		

		depDate.setYear(depMY.substring(0,4));
		depDate.setDate(depDY);
		depDate.setMonth(depMY.substring(6,4));
		

		if ((arrDate.getMonth() < 0 || arrDate.getMonth() > 11)||(depDate.getMonth() < 0 || depDate.getMonth() > 11)) {
		    alert('Please Enter a Valid Date');
				return false;
		}
		if ((arrDate.getDate() < 1 || arrDate.getDate() > 31)||(depDate.getDate() < 1 || depDate.getDate() > 31)) {
		    alert('Please Enter a Valid Date');
				return false;
		}
		if ((arrMonthTemp == 3 || arrMonthTemp == 5 || arrMonthTemp == 8 || arrMonthTemp == 10) &&
		    (arrDY == 31)) {
		    alert('Please Enter a Valid Date');
				return false;
		}
		if ((depMonthTemp == 3 || depMonthTemp == 5 || depMonthTemp == 8 || depMonthTemp == 10) &&
		    (depDY == 31)) {
		    alert('Please Enter a Valid Date');
				return false;
		}
		if (arrMonthTemp == 1) {
		    if (arrDY > 29 || (arrDY == 29 && !isLeapYear(arrYearTemp))) {
				alert('Please Enter a Valid Date');
					return false;
		    }
		}
		if (depMonthTemp == 1) {
		    if (depDY > 29 || (depDY == 29 && !isLeapYear(arrYearTemp))) {
				alert('Please Enter a Valid Date');
					return false;
			}
		}
        compDate = new Date();
        compDate.setHours(0,0,0,0);
		if (arrDate < (compDate)|| depDate < (compDate) ){
			alert('The arrival or departure date you have provided has already passed, please provide valid dates.');
				return false;
		}

		return true;
	}


	/**
    * Returns the difference between two dates.
    */
	function days_between(date1, date2)
	{
    	// The number of milliseconds in one day
	    var ONE_DAY = 1000 * 60 * 60 * 24;

    	// Convert both dates to milliseconds
	    var date1_ms = date1.getTime();
    	var date2_ms = date2.getTime();

	    // Calculate the difference in milliseconds
    	var difference_ms = date1_ms - date2_ms;

	    diff=Math.round(difference_ms/ONE_DAY);

    	return diff;
   }

   /**
    * Changes the departure date equal to increment of
    * arrival date to one day.
    */
   function changeDep(form)
   {
   		
		arrDate = new Date(Date.parse(form.arrDate.value));

				
		temp_date = new Date(arrDate.getTime() +(24*60*60*1000)); //Incrementing the arrival date to one day	
		
		tempDMY= (temp_date.getMonth() +1) + "/" + temp_date.getDate() + "/" + temp_date.getFullYear(); //The function getYear is repalced with getFullYear as it is not supported by Mozilla and Safari.
		
		form.depDate.value = tempDMY;
   }
   /* END - Changes for HotelSearchForm */

   function getDay(day,month,year)
   {
      var days = new Array(12);
      var retVal = 0;
      days[0] = 0;   // place holder
      days[1] = 31;  // January
      days[2] = 28;  // February
      days[3] = 31;  // March
      days[4] = 30;  // April
      days[5] = 31;  // May
      days[6] = 30;  // June
      days[7] = 31;  // July
      days[8] = 31;  // August
      days[9] = 30;  // September
      days[10] = 31; // October
      days[11] = 30; // November
      days[12] = 31; // December

      for (var i = 0 ; i < month; i++)
      {
         retVal += days[i];
      }

      if (month > 1 && isLeapYear(year))
      {
         retVal++;
      }

      retVal = retVal + day;
      //alert("getDay::retVal: " + retVal);
      return retVal;
   }

   function isLeapYear(year)
   {
      if ((year % 100 != 0 && year % 4 == 0) || (year % 400 == 0))
      {
         return true;
      }
      else
      {
         return false;
      }
   }

   function compare(day1, day2, year1, year2)
   {
      //alert ("compare::day1: " + day1 + " compare::day2: " + day2 + " compare::year1: " + year1 + " compare::year2: " + year2);
      if (year1 != year2)
      {
         day2 += (year2 - year1) * 365;
         //alert ("compare::(new)day2: " + day2);
         if (day1 < 59 && isLeapYear(year1))
         {
            day2++;
         }
      }

      var ret = day2 - day1;
      //alert("compare::returning: " + ret);

      return ret;
   }

   /**
    * Called on form submit to ensure that the Guest has selected a state in the event
    * that they selected the US, Canada, or Australia as the country, and did not select
    * a city
    */
   function validateCountryState(form)
   {
      if ((form.referencePoint == null || form.referencePoint.value == "") &&
         (form.hotelName == null || form.hotelName.value == "") )
      {
         var country = form.countryCode.options[form.countryCode.selectedIndex].value;
         if (country == "")
         {
            window.alert("Please select a country.");
            if ( (form.nearStreetAddress != null && form.nearStreetAddress.value != "") ||
                (form.nearPostalCode != null && form.nearPostalCode.value != ""))
            {
               form.nearCountry.focus();
            }
            else
            {
               form.countryCode.focus();
            }
            return false;
         }
         var state    = form.stateCode.options[form.stateCode.selectedIndex].value;
         /*
         if ((country == "US" || country == "CA" || country == "AU") && form.stateCode.selectedIndex == 0)
         */
         if ((country == "US" || country == "CA" || country == "AU") && form.stateCode.selectedIndex == 0 && Trim(form.city.value) == "")
         {
            window.alert("For Canada, the United States and Australia,\n please select a State");
            // if the Guest is doing a 'near address' search, bring the focus there
            if ( (form.nearStreetAddress != null && form.nearStreetAddress.value != "") ||
                (form.nearPostalCode != null && form.nearPostalCode.value != "") )
            {
               form.nearState.focus();
            }
            else
            {
               form.stateCode.focus();
            }
            return false;
         }
         result = validateAscii(form.city);
         if(result == false){
            return false;
         }
      }
      return true;
   }

   /**
    * If the Guest has input a Street Address in attempting to perform a Street Address Search,
    * this method ensures that at least a City or Postal Code has been specified in addition
    * to the basic Country or Country/State requirement
    */
   function validateAddressSearch(form) {
      if (form.nearStreetAddress != null && form.nearStreetAddress.value != "") {
         if (form.nearCity.value == "" && form.nearPostalCode.value == "") {
            window.alert("When performing a Street Address search,\n you must provide either a City or a Postal Code");
            form.nearCity.focus();
            return false;
         }
      }
      return true;
   }



   /**
    * When a guest selects a state, we synch the other state box, if any, we change
    * the country to the appropriate country, and we changed the number of rooms
    * drop-down according to the country
    */
   function changeOfState(aSelect) {
      var val = new String(aSelect.options[aSelect.selectedIndex].value);
      var form = aSelect.form;

      // synch any existing state dropdown
      if (form.stateCode != null) {
         form.stateCode.selectedIndex = aSelect.selectedIndex;
      }

      if (form.nearState!= null) {
         form.nearState.selectedIndex = aSelect.selectedIndex;
      }

      // change the country dropdown(s) to the proper value
      displayCountry(aSelect);

      // refresh the number of rooms dropdown based on country
      //refreshNumRoomsDropdown(form.countryCode);

      // if the Guest selected one of the country headers in the state drop-down, complain
      if (val == "US" || val == "CA" || val == "AU") {
         window.alert("For Canada, the United States and Australia,\n please select a State");
         aSelect.focus();
      }
      return;
   }

   /**
    * When a guest selects a country, we synch the other state box, if any,
    * we display the appropriate list of states, and we display the
    * number of rooms drop-down appropriate to the country.
    * Commenting out code for synching Number of Rooms drop down. It looks to be obsolete. Will remove later.
    */
   function changeOfCountry(aSelect) {
      refreshStates(aSelect);
      //refreshNumRoomsDropdown(aSelect);
      var form = aSelect.form;

      // synch any existing country dropdowns
      if (form.countryCode != null) {
         form.countryCode.selectedIndex = aSelect.selectedIndex;
      }

      if (form.nearCountry != null) {
         form.nearCountry.selectedIndex = aSelect.selectedIndex;
      }
   }

   /**
    * When a Guest selects a month, refresh the ArrivalDay drop-down;
    * also called when a year changes, to account for the possibility
    * that a leap year was selecte/unselected
    */
   function changeOfMonth(aSelect) {
      var month = aSelect.value;
      var day   = aSelect.form.arrivalDay.value;
      var year  = aSelect.form.arrivalYear.value;
      var numDays = getNumDaysInMonth(month,year);
      var aryDays = new Array();
      
   
   
      day --;
   
     

      for (var i=1; i <= numDays; i++) {
         aryDays[i] = new Option(i,i);
      }

      setOptions(aSelect.form.arrivalDay, aryDays);
      // restore the date, if one was selected and is valid
      if (day > 0 && day < numDays) {
         aSelect.form.arrivalDay.options[day].selected = true;
      }
   }


   /**
    ****************************************************************************
    * functions supporting the main validation methods above
    ****************************************************************************
    */

   /* Displays the proper state drop-downs based on a country */
   function refreshStates(aSelect) {
      var stateCodes = new Array();
      var val = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;

      if (val == "US") {
         stateCodes = US_states;
      }
      else if (val == "CA") {
         stateCodes = CA_states;
      }
      else if (val == "AU") {
         stateCodes = AU_states;
      }
      else if (val != ""){
         stateCodes = new Array(new Option("All",""));
      }

      setOptions(form.stateCode, stateCodes);

      if (form.nearState != null) {
         setOptions(form.nearState, stateCodes);
      }
   }

   /** Displays the proper country depending on a state */
   function displayCountry(aSelect) {
      var val  = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;
      var idx = 0;

      if (val.indexOf("US_") == 0) {
      //if (isValueInOptionArray(val, US_states)) {
         idx = getIndex(form.countryCode, "US");
      }
      else if (val.indexOf("CA_") == 0) {
      // else if (isValueInOptionArray(val, CA_states)) {
         idx = getIndex(form.countryCode, "CA");
      }
      else if (val.indexOf("AU_") == 0) {
      //else if (isValueInOptionArray(val, AU_states)) {
         idx = getIndex(form.countryCode, "AU");
      }

      if (idx > 0)
      {
         form.countryCode.selectedIndex = idx;
         if (form.nearCountry != null) {
            form.nearCountry.selectedIndex = idx;
         }
      }
   }
   /**
    * This method returns true if any one of the input elements
    * that would trigger an availability (arrival date, numNights or numRooms)
    * has been selected - used by validateCapacityRequest to display the proper
    * alert if not all needed elements have been input
    */
   function hasAStayElement(form) {
      try
      {
         return (
            form.arrDate.value != "" ||
         	form.depDate.value != "" );
      }
      catch (e)
      {
         return false;
      }
   }

   /**
    * This method returns true if all one of the input elements
    * that would trigger an availability (arrival date, numNights or numRooms)
    * has been selected - used by validateCapacityRequest to display the proper
    * alert if not all needed elements have been input
    */
   function hasAllStayElements(form) {
      try
      {

      return (
         	form.arrDate.value != "" &&
         	form.depDate.value != "");
      }
      catch (e)
      {
         return false;
      }
   }


   /**
    ****************************************************************************
    * Generic helper functions not specific to the validation that we are performing
    ****************************************************************************
    */

   /**
    * given a select value, return its index within the select element;
    * if not found return the first element in the select
    */
   function getIndex(aSelect, aValue) {
      for (var i=0; i < aSelect.length; i++) {
         if (aSelect.options[i].value == aValue) {
            return i;
         }
      }
      return 0;
   }

   /**
    * given an array of Select Option objects, this function returns
    * true if the passed value is contained in the array; this function
    * is used to determine the Country to which a selected state belongs
    */
   function isValueInOptionArray(aValue, aryOption) {
      if (aryOption.length > 0) {
         for (var i=0; i < aryOption.length; i++) {
            if (aryOption[i].value == aValue) {
               return true;
            }
         }
      }
      return false;
   }

   function removeAllData(options)
   {
      var element = options.firstChild;
      while (element != null)
      {
         var nextChild = element.nextSibling;
         options.removeChild(element);
         element = nextChild;
      }
      options.length = 0;
   }

   /**
    * given a select input and an array of Options,
    * set the options of the select to the Options provided
    */
   function setOptions(aSelect, aryOptions) {
      if (aryOptions.length > 0) {
         removeAllData(aSelect);
         for (var i=0; i < aryOptions.length; i++) {
            // if we do not assign a new Option, running this method twice
            // over the same array will yield a pointer error
            if(aryOptions[i] != null)
               aSelect.options[aSelect.length] = new Option(aryOptions[i].text, aryOptions[i].value);
         }
         /**
          * AR0755B: Profile GCCI Sign-Up:: To remove first element i.e. "Please Select" if we have only one 
          * language in language preference drop down for our selected country.
          */
         if(aSelect.name == 'languageCode'){
         	if(aryOptions.length == 2){
         		var element = aSelect.firstChild;
         		if(element != null){
         			aSelect.removeChild(element);
         		}	
         	}
         }		
      }
   }

   /**
    * checks validity of date, copied from validator-rules.xml;
    * but modified to use a 0-based month index (i.e. jan=0)
    */
   function isDateValid(day, month, year) {
      if (month < 0 || month > 11) {
         return false;
      }
      if (day < 1 || day > 31) {
         return false;
      }
      if ((month == 3 || month == 5 || month == 8 || month == 10) &&
         (day == 31)) {
         return false;
      }
      if (month == 1) {
         var leap = (year % 4 == 0 &&
               (year % 100 != 0 || year % 400 == 0));
         if (day>29 || (day == 29 && !leap)) {
            return false;
         }
      }
      return true;
   }


   /**
    * Given a month represented by an integer (jan=0) and a year,
    * return the number of days in that month; if the year is null,
    * return 29 days for February
    */
   function getNumDaysInMonth(month,year) {
      if (month == 3 || month == 5 || month == 8 || month == 10) {
         return 30;
      }
      else if (month == 1) {
         var leapOrNull = (year < 0) || (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
         if (leapOrNull)
            return 29;
         else
            return 28;
      }
      else {
         return 31;
      }
   }


   /**
    * wrapper around window.open used for opening a non-resizable no-thrills popup message windows
    */
   function validationPopupMessage(url, winName, aWidth, aHeight, X, Y)
   {
      // if Height and Width are passed, but no X and Y coordinates passed,
      // center the window on the screen
      if ( aHeight != null && aWidth != null && X == null && Y == null ) {
         X = Math.round((window.screen.availWidth - aWidth) / 2);
         Y = Math.round((window.screen.availHeight - aHeight) / 2);
      }

      var features= "height="+aHeight +", width="+aWidth +
            ", screenX="+X +", screenY="+Y +", left="+X +", top="+Y
            +", location=no, menubar=no, resizable=no, scrollbars=no, status=no, toolbar=no";

      var popup = window.open(url,winName, features);
      popup.focus();
   }

   function preventDoubleClick()
   {
      if (doubleClick)
      {
         alert('Your request is being processed, please wait.');
         return false;
      }
      else
      {
         doubleClick = true;
         return true;
      }
   }
   
function pressEscapeKey()
{
	if (window.event.keyCode == 27)
		doubleClick = false;
}

function getDoubleClickValue(val)
{
	doubleClick= val;
}


function checkCheckOutDate(form)
{

  try {
//alert(form.arrivalMonthYear.selectedIndex);





  
	if(form.arrivalMonthYear.selectedIndex >= 0 && form.arrivalDay.selectedIndex >= 0 )  {
  
  
	 
		
	if(! validDate(form))
	{
	   return false;
	}
	
	//new validation for date
	var arrMY = form.arrivalMonthYear.value;
	var depMY = form.departureMonthYear.value;
	var arrDY = form.arrivalDay.value;
	var depDY = form.departureDay.value;

	arrDate = new Date(0);
	depDate = new Date(0);

	arrDate.setYear(arrMY.substring(0,4));
	arrDate.setDate(arrDY);
	arrDate.setMonth(arrMY.substring(6,4));
	

	depDate.setYear(depMY.substring(0,4));
	depDate.setDate(depDY);
	depDate.setMonth(depMY.substring(6,4));
	

		var istooFarCheckInDate = Math.abs(days_between(arrDate, new Date()));
		if( istooFarCheckInDate > 350)
		{
			alert('The Arrival Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}
//		if(days_between(depDate, arrDate)< 0){

			changeDep(form);
				depMY = form.departureMonthYear.value;
				depDY = form.departureDay.value;
				depDate.setYear(depMY.substring(0,4));
				depDate.setDate(depDY);
				depDate.setMonth(depMY.substring(6,4));
			
//		}
		if(days_between(depDate, arrDate)== 0){
			changeDep(form);
				depMY = form.departureMonthYear.value;
				depDY = form.departureDay.value;
				depDate.setYear(depMY.substring(0,4));
				depDate.setDate(depDY);
				depDate.setMonth(depMY.substring(6,4));
				
		}

		var istooFarCheckOutDate = Math.abs(days_between(depDate, new Date()));
		if( istooFarCheckOutDate > 350)
		{
			alert('The Departure Date that you entered is too far in the future. Please enter a valid Date.');
			return false;
		}
	 
	 }
  }
 catch (e)
     {
		 alert(e);
         return false;
     }
return true;

}

var dtCh= "/";
var minYr=1900;
var maxYr=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}




   /**
    * wrapper function that calls all post-submit validation functions
    */
function validateReservationRetrieveFormAll(form)
   {

      var passed = true;

      // the Struts-Validator dynamically generated validation
      //passed = validateReservationRetrieveForm(form);

      if (form.number.value == "")
      {
         window.alert("Please enter your reservation Confirmation Number");
         form.number.focus();
         return false;
      }

      if (form.firstName.value == "")
      {
         window.alert("Please enter your First Name");

         form.firstName.focus();
         return false;
      }

      if (form.lastName.value == "")
      {
         window.alert("Please enter your Last Name");
         form.lastName.focus();
         return false;
      }

      if (passed)
      {
         passed = preventDoubleClick();
      }


      return passed;
   }
   
   function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Date format should be mm/dd/yyyy.")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please check month and correct.")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please check your arrival and departure dates.")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYr || year>maxYr){
		alert("Please check year and correct to yyyy.")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Date provide is invalid.")
		return false
	}
return true
}


function validateOtherEmail(form)
   {
   	  var passed;
   	  if (form.emailAddress.value == "")
      {
         window.alert("Please enter a valid email address.");
         form.emailAddress.focus();
         passed = false;
      }
      else if(!validateAscii(form.emailAddress)){
         form.emailAddress.focus();
         passed = false;
      }
      else
      {
      	 passed = validateEmail(form);
      }
      return passed;
   }


/**
 * called to keep the city fields the same
 */
function synchCity(aTextbox)
{ 
	var form = aTextbox.form;
    if (form.city != null) {
    	form.city.value = aTextbox.value;
    }
    if (form.nearCity != null) {
    	form.nearCity.value = aTextbox.value;
    }
    return true;
}

 function validateNumRooms(aSelect) {
      var form = aSelect.form;
      var countryCode;
      try
      {
         countryCode = form.countryCode[form.countryCode.selectedIndex].value;
      }
      catch (e)
      {
         countryCode = "XX";
      }
      var numRooms = aSelect.options[aSelect.selectedIndex].value;
      var numRoomsLabel = aSelect.options[aSelect.selectedIndex].text;
      if (countryCode == "" || countryCode == "none")
      {
         alert("???numRooms.selectCountryFirst???");
         aSelect.selectedIndex = 0;
         return false;
      }
      
         
            if (numRooms == 9) {
               aSelect.selectedIndex=0;
               aSelect.focus();
               
               var url = "messageGroup.do;jsessionid=7ommN6M9Vy8i-DyC6cXwfg**.h55ab?msgKey=search.group_request_msg&arg1=http%3a%2f%2fwww.bestwestern.com";
               
               url += "&arg0=" + numRoomsLabel;
               validationPopupMessage(url,"msgWindow", 300,200);
               return false;
            }
            if (numRooms == 10) {
               aSelect.selectedIndex=0;
               aSelect.focus();
               var url = "messageGroup.do;jsessionid=7ommN6M9Vy8i-DyC6cXwfg**.h55ab?msgKey=search.group_online_msg&arg0=http%3a%2f%2fwww.bestwestern.com";
               validationPopupMessage(url,"msgWindow", 300,200);
               return false;
            }
         
         
      
      return true;
   }
   function setupDisplay(rooms)
{
	var number = rooms.value;
	if (!(number > 1))
	{
		number = 1;
	}
	for (i = 1 ; i <= number ; i++)
	{
		setStyle('room' + i + 'a', 'block');
		setStyle('room' + i + 'b', 'block');
		setStyle('room' + i + 'c', 'block');
		setStyle('room' + i + 'd', 'block');
	}
	for (i = 5 ; i > number ; i--)
	{
		setStyle('room' + i + 'a', 'none');
		setStyle('room' + i + 'b', 'none');
		setStyle('room' + i + 'c', 'none');
		setStyle('room' + i + 'd', 'none');
	}
}

	/**
    * wrapper function that calls all post-submit validation functions
    */
function validateCreateReservationFormAll(form){
	var passed = true;
	var validateMemberIdFields = document.getElementById('validateMemberIdFields').value ;

	/* AR0755B: if both fields are filled and "sign in to Profile" section is not expended, then don't do anything. Do Normal processing.
	* if "sign in to Profile" section is not expended and if any one of the field is filled then assign blank string to both fields
	* if "sign in to Profile" section is expended then don't do anything. Do Normal processing. 
	*/
	if (!(form.memberId.value != "" && form.webPassword.value != "")){
		if(validateMemberIdFields != "" && validateMemberIdFields == 'false'){
			if(form.memberId.value != "" ^ form.webPassword.value != ""){
				form.memberId.value = "";
				form.webPassword.value = "";
			}	
		}
	}
	
	if(form.memberId.value != "" ^ form.webPassword.value != ""){
		window.alert("Both Username and Password fields are mandatory to login as a Rewards customer");
		return false;
	}else if(form.memberId.value == "" && form.webPassword.value == ""){
		if(form.newUserPassword.value != "" || form.newUserConfirmPassword.value != ""){
			if(form.newUserPassword.value == "" || form.newUserConfirmPassword.value == ""){
				window.alert("???reviewreserve.enterBothPasswords???");
				return false;
			}
			else if((form.newUserPassword.value.length < 6 || form.newUserPassword.value.length >8) ||
				(form.newUserConfirmPassword.value.length < 6 || form.newUserConfirmPassword.value.length >8)){
				window.alert("Both the password fields should have 6 - 8 characters.");
				return false;
			}
			else if(form.newUserPassword.value != form.newUserConfirmPassword.value){
				window.alert("???reviewreserve.enterSamePasswords???");
				return false;
			}
		}

		// the Struts-Validator dynamically generated validation
		passed = validateCreateReservationForm(form);
		
		// Go validate the customer information
		if (passed){
			passed = validateCustomerInfo(form);
		}		
		if (passed){
			passed = validateBillingGuestAddress(form);
		}		
		/*if (passed){
			if(!form.useGuestAddress[0].checked){
				passed = validateBillingAddress(form);
			}
		}*/
		// the 'custom' validations below
		if (passed){
			passed = validateEmailAddresses(form);
		}
		/*
		if (passed){
			passed = validateCreditCardExpiryDate(form);
		}
		*/
		if (passed){
			passed = validateResSummary(form);
		}
		if (passed){
			passed = preventDoubleClick();
		}

	}
	
	if (form.iataNumber.value == "Enter IATA/ARC/TIDS #"){
		form.iataNumber.value = "";
	}
		
	return passed;
}


	/**
    * function to validate comments entered by user on ReviewAndReserve page
    */
	function validateResSummary(form)
	{
		// ok, could have more than one comment here,
		// loop over all the comment i's and check em
		var elements = form.elements;
		var str = '';
		str += elements.length + '<BR>';
		for (var i=0;i<elements.length;i++){
			if(elements[i].name.indexOf('comment') != -1){
				if (validateAscii(elements[i]) == false){
					return false;
				}
			}
		}
		return true;
	}



   function validateEmailAddresses(form)
   {
      var email1 = form.email.value;
      var email2 = form.confirmEmail.value;

      if (email1 != email2)
      {
         window.alert("Email and confirm email addresses do not match. Please correct and submit again.");
         return false;
      }
      return true;
   }

   function validateBillingGuestAddress(form)
   {
      if ((form.country.value == "US" || form.country.value == "CA" || form.country.value == "AU"))
      {
         if (form.state.value == "")
         {
            window.alert("Please enter a state for guest address.");
            form.state.focus();
            return false;
         }
      }
      if ((form.country.value == "US" || form.country.value == "CA"))
      {
         if(Trim(form.postalCode.value) == "" || Trim(form.postalCode.value).length<=0)
         {
            window.alert("Please enter a postal code for guest address.");
            form.postalCode.focus();
            return false;
         }
      }
      return true;
   }

   function validateCustomerInfo(form)
   {
      if (form.firstName.value == "")
      {
         window.alert("Please enter the guest first name.");
         form.firstName.focus();
         return false;
      }
      else if(!validateAscii(form.firstName)){
         return false;
      }
      if (form.lastName.value == "")
      {
         window.alert("Please enter the guest last name.");
         form.lastName.focus();
         return false;
      }
      else if(!validateAscii(form.lastName)){
         return false;
      }
      if (form.address1.value == "")
      {
         window.alert("Please enter address line 1 for guest address.");
         form.address1.focus();
         return false;
      }
      else if(!validateAscii(form.address1)){
         return false;
      }
      if (Trim(form.city.value) == "")
      {
         window.alert("Please enter a city for guest address.");
         form.city.focus();
         return false;
      }
      else if(!validateAscii(form.city)){
         return false;
      }

      if (form.country.value == "")
      {
         window.alert("Please enter a country for guest address.");
         form.country.focus();
         return false;
      }

      if (form.email.value == "")
      {
         window.alert("Please enter a valid email address.");
         form.email.focus();
         return false;
      }
      else if(!validateAscii(form.email)){
         return false;
      }

      if (form.confirmEmail.value == "")
      {
         window.alert("Please enter a valid confirmation email address.");
         form.confirmEmail.focus();
         return false;
      }
      else if(!validateAscii(form.confirmEmail)){
         return false;
      }

      if (form.telephone.value == "")
      {
         window.alert("Please enter a valid telephone number for guest.");
         form.telephone.focus();
         return false;
      }
      else
      {
         result = validateTelephoneNumber(form.telephone.value);
         if(result == false)
         {
            window.alert("Please enter a valid telephone number for guest.");
            form.telephone.focus();
            return false;
         }
      }

	  if(form.newCard.value == "true"){
	  	
		  if(form.creditCardType){
		      if (form.creditCardType.value == "")
		      {
		         window.alert("Please enter a credit card type.");
		         form.creditCardType.focus();
		         return false;
		      }
		  }
		  
		  if(form.creditCardNumber){
		      if (form.creditCardNumber.value == "")
		      {
		         window.alert("Please enter your credit card number");
		         form.creditCardNumber.focus();
		         return false;
		      }
		  }
	  
	  
	      if (form.creditCardExpMonth.value == "")
	      {
	         window.alert("Please enter a credit card expiry month.");
	         form.creditCardExpMonth.focus();
	         return false;
	      }
	
	      if (form.creditCardExpYear.value == "-1")
	      {
	         window.alert("Please enter a credit card expiry year.");
	         form.creditCardExpYear.focus();
	         return false;
	      }
	  }
	  else{
	  	
	      if (form.creditCardOldExpMonth.value == "")
	      {
	         window.alert("Please enter a credit card expiry month.");
	         form.creditCardOldExpMonth.focus();
	         return false;
	      }
	
	      if (form.creditCardOldExpYear.value == "-1")
	      {
	         window.alert("Please enter a credit card expiry year.");
	         form.creditCardOldExpYear.focus();
	         return false;
	      }
	  }
      return true;
   
   }

   function validateBillingAddress(form)
   {
      if (form.billingFirstName.value == "")
      {
         window.alert("Please enter the credit card holders first name.");
         form.billingFirstName.focus();
         return false;
      }
      else if(!validateAscii(form.billingFirstName)){
         return false;
      }
      if (form.billingLastName.value == "")
      {
         window.alert("Please enter the credit card holders last name.");
         form.billingLastName.focus();
         return false;
      }
      else if(!validateAscii(form.billingLastName)){
         return false;
      }
      if (form.billingAddress1.value == "")
      {
         window.alert("Please enter address line 1 for billing address.");
         form.billingAddress1.focus();
         return false;
      }
      else if(!validateAscii(form.billingAddress1)){
         return false;
      }
      if (form.billingCity.value == "")
      {
         window.alert("Please enter a city for billing address.");
         form.billingCity.focus();
         return false;
      }
      else if(!validateAscii(form.billingFirstName)){
         return false;
      }

      if ((form.billingCountry.value == "US" || form.billingCountry.value == "CA" || form.billingCountry.value == "AU"))
      {
         if (form.billingState.value == "")
         {
            window.alert("Please enter a state for billing address.");
            form.billingState.focus();
            return false;
         }
      }
      if ((form.billingCountry.value == "US" || form.billingCountry.value == "CA"))
      {
         if (form.billingPostalCode.value == "")
         {
            window.alert("Please enter a postal code for billing address.");
            form.billingPostalCode.focus();
            return false;
         }
      }
      if (form.billingCountry.value == "")
      {
         window.alert("Please enter a country for billing address.");
         form.billingCountry.focus();
         return false;
      }
      return true;
   }
/**
* function for check password for gcci membership on review and reservation page
*/

function validatePassword(form)
{
	if(form.newUserPassword.value.length==0)
		{
			alert("Please enter 6 - 8 characters in Password field");
			form.newUserPassword.focus();
			return false;
		}

		if(form.newUserPassword.value.length<6 || form.newUserPassword.value.length>8 )
		{
			alert("Both the password fields should have 6 - 8 characters.");
			form.newUserPassword.focus();
			return false;
		}

		if(form.newUserConfirmPassword.value.length==0)
		{
			alert("You did not validate password. Please re-enter");
			form.newUserConfirmPassword.focus();
			return false;
		}

		if (form.newUserPassword.value != form.newUserConfirmPassword.value)
		{
			alert("The Passwords you Entered Do Not Match. Please re-enter them");
			form.newUserPassword.focus();
			return false;
		}
		return true;
}

   function changeOfBillingState(aSelect, fieldName)
   {
      var val = new String(aSelect.options[aSelect.selectedIndex].value);
      var form = aSelect.form;

      // synch any existing state dropdown
      if (fieldName == "state")
      {
         form.state.selectedIndex = aSelect.selectedIndex;
      }

      else if (fieldName == "billingState")
      {
         form.billingState.selectedIndex = aSelect.selectedIndex;
      }

      // change the country dropdown(s) to the proper value
      displayBillingCountry(aSelect, fieldName);

      // if the Guest selected one of the country headers in the state drop-down, complain
      if (val == "US" || val == "CA" || val == "AU")
      {
         window.alert("For Canada, the United States and Australia,\n please select a State");
         aSelect.focus();
      }
      return;
   }

   function changeOfBillingCountry(aSelect, fieldName)
   {
      refreshBillingStates(aSelect, fieldName);
      var form = aSelect.form;

      // synch any existing country dropdowns
      if (fieldName == "country")
      {
         form.country.selectedIndex = aSelect.selectedIndex;
      }
      else if (fieldName == "")
      {
         form.billingCountry.selectedIndex = aSelect.selectedIndex;
      }
   }

  /** Displays the proper country depending on a state */
   function displayBillingCountry(aSelect, fieldName)
   {
      var val  = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;
      var idx = 0;

      if (val.indexOf("US_") == 0)
      {
         idx = getIndex(form.billingCountry, "US");
      }
      else if (val.indexOf("CA_") == 0)
      {
         idx = getIndex(form.billingCountry, "CA");
      }
      else if (val.indexOf("AU_") == 0)
      {
         idx = getIndex(form.billingCountry, "AU");
      }

      if (idx > 0)
      {
         if (fieldName == "state")
         {
            form.country.selectedIndex = idx;
         }
         else if (fieldName == "billingState")
         {
            form.billingCountry.selectedIndex = idx;
         }
      }
   }

   function refreshBillingStates(aSelect, fieldName)
   {
      var stateCodes = new Array();
      var val = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;

	
      if (val == "US")
      {
         stateCodes = US_states_withoutAll;
      }
      else if (val == "CA")
      {
         stateCodes = CA_states_withoutAll;
      }
      else if (val == "AU")
      {
         stateCodes = AU_states_withoutAll;
      }
      else if (val != "")
      {
         stateCodes = new Array(new Option("",""));
      }

      if (fieldName == "country")
      {
         setOptions(form.state, stateCodes);
      }
      else if (fieldName == "billingCountry")
      {
         setOptions(form.billingState, stateCodes);
      }
   }

   /**
    * When a guest selects a state, we synch the other state box, if any, we change
    * the country to the appropriate country, and we changed the number of rooms
    * drop-down according to the country
    */
   function changeOfState(aSelect) {
      var val = new String(aSelect.options[aSelect.selectedIndex].value);
      var form = aSelect.form;

      // synch any existing state dropdown
      if (form.stateCode != null) {
         form.stateCode.selectedIndex = aSelect.selectedIndex;
      }

      if (form.nearState!= null) {
         form.nearState.selectedIndex = aSelect.selectedIndex;
      }

      // change the country dropdown(s) to the proper value
      displayCountry(aSelect);

      // refresh the number of rooms dropdown based on country
      refreshNumRoomsDropdown(form.countryCode);

      // if the Guest selected one of the country headers in the state drop-down, complain
      if (val == "US" || val == "CA" || val == "AU") {
         window.alert("For Canada, the United States and Australia,\n please select a State");
         aSelect.focus();
      }
      return;
   }

   /**
    * When a guest selects a country, we synch the other state box, if any,
    * we display the appropriate list of states, and we display the
    * number of rooms drop-down appropriate to the country
    */
   function changeOfCountry(aSelect) {
      refreshStates(aSelect);
      refreshNumRoomsDropdown(aSelect);
      var form = aSelect.form;

      // synch any existing country dropdowns
      if (form.countryCode != null) {
         form.countryCode.selectedIndex = aSelect.selectedIndex;
      }

      if (form.nearCountry != null) {
         form.nearCountry.selectedIndex = aSelect.selectedIndex;
      }
   }

    /**
     * called to keep the city fields the same
     */
    function synchCity(aTextbox)
    {
         var form = aTextbox.form;
         if (form.city != null) {
            form.city.value = aTextbox.value;
         }
         if (form.nearCity != null) {
            form.nearCity.value = aTextbox.value;
         }
         return true;
    }

   /**
    * When a Guest selects a month, refresh the ArrivalDay drop-down;
    * also called when a year changes, to account for the possibility
    * that a leap year was selecte/unselected
    */
   function changeOfMonth(aSelect) {
      var month = aSelect.value;
      var day   = aSelect.form.arrivalDay.value;
      var year  = aSelect.form.arrivalYear.value;
      var numDays = getNumDaysInMonth(month,year);
      var aryDays = new Array();
      
   
   
      day --;
   
     

      for (var i=1; i <= numDays; i++) {
         aryDays[i] = new Option(i,i);
      }

      setOptions(aSelect.form.arrivalDay, aryDays);
      // restore the date, if one was selected and is valid
      if (day > 0 && day < numDays) {
         aSelect.form.arrivalDay.options[day].selected = true;
      }
   }


   /**
    ****************************************************************************
    * functions supporting the main validation methods above
    ****************************************************************************
    */

   /* Displays the proper state drop-downs based on a country */
   function refreshStates(aSelect) {
      var stateCodes = new Array();
      var val = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;

      if (val == "US") {
         stateCodes = US_states;
      }
      else if (val == "CA") {
         stateCodes = CA_states;
      }
      else if (val == "AU") {
         stateCodes = AU_states;
      }
      else if (val != ""){
         stateCodes = new Array(new Option("All",""));
      }

      setOptions(form.stateCode, stateCodes);

      if (form.nearState != null) {
         setOptions(form.nearState, stateCodes);
      }
   }

   /** Displays the proper country depending on a state */
   function displayCountry(aSelect) {
      var val  = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;
      var idx = 0;

      if (val.indexOf("US_") == 0) {
      //if (isValueInOptionArray(val, US_states)) {
         idx = getIndex(form.countryCode, "US");
      }
      else if (val.indexOf("CA_") == 0) {
      // else if (isValueInOptionArray(val, CA_states)) {
         idx = getIndex(form.countryCode, "CA");
      }
      else if (val.indexOf("AU_") == 0) {
      //else if (isValueInOptionArray(val, AU_states)) {
         idx = getIndex(form.countryCode, "AU");
      }

      if (idx > 0)
      {
         form.countryCode.selectedIndex = idx;
         if (form.nearCountry != null) {
            form.nearCountry.selectedIndex = idx;
         }
      }
   }

	  function validateReservationChangeFormAll(form)
   {
      var cancel = "";
      var modifyRoom = "";
      var modifyBestExtra = "";
      var found = false;
      var comp_id = "";

      if (document.forms['reservationChangeForm'].elements["changesSelected"] != null)
      {
         // if you only have a one hotel reservation, we must assign the comp id value into the form as an array so we can access the other elements
         if(document.forms['reservationChangeForm'].elements['COMP_ID'].value != null && !document.forms['reservationChangeForm'].elements['COMP_ID'].length){


            comp_id = document.forms['reservationChangeForm'].elements['COMP_ID'].value;
           for (var i=1; i<20; i++)
            {
               cancel = "CANCEL_ROOM" + i + "_" + comp_id;
               modifyRoom = "MODIFY_ROOM" + i + "_" + comp_id;
               modifyBestExtra = "MODIFY_BEST_EXTRA" + i + "_" + comp_id;

               if ( (document.forms['reservationChangeForm'].elements[cancel] != null && document.forms['reservationChangeForm'].elements[cancel].checked) ||
                   (document.forms['reservationChangeForm'].elements[modifyRoom] != null && document.forms['reservationChangeForm'].elements[modifyRoom].checked) ||
                       (document.forms['reservationChangeForm'].elements[modifyBestExtra] != null && document.forms['reservationChangeForm'].elements[modifyBestExtra].checked) )
               {
                  found = true;
               }
	}



         }else{

	// start logic to handle muliple room
	for(var j=0; j < document.forms['reservationChangeForm'].elements['COMP_ID'].length; j++){
            comp_id = document.forms['reservationChangeForm'].elements['COMP_ID'][j].value;
            for (var i=1; i<20; i++)
            {
               cancel = "CANCEL_ROOM" + i + "_" + comp_id;
               modifyRoom = "MODIFY_ROOM" + i + "_" + comp_id;
               modifyBestExtra = "MODIFY_BEST_EXTRA" + i + "_" + comp_id;

               if ( (document.forms['reservationChangeForm'].elements[cancel] != null && document.forms['reservationChangeForm'].elements[cancel].checked) ||
                   (document.forms['reservationChangeForm'].elements[modifyRoom] != null && document.forms['reservationChangeForm'].elements[modifyRoom].checked) ||
                       (document.forms['reservationChangeForm'].elements[modifyBestExtra] != null && document.forms['reservationChangeForm'].elements[modifyBestExtra].checked) )
               {
                  found = true;
                  break;
               }
            }
         }
	// end logic to handle muliple room

	}

         if (found == false)
         {
           window.alert("There are no modify options selected, please reselect.");

            return false;
         }
         for(var j=0; j < document.forms['reservationChangeForm'].elements['COMP_ID'].length; j++){
            comp_id = document.forms['reservationChangeForm'].elements['COMP_ID'][j].value;

            for (var i=1; i<20; i++)
            {
               cancel = "CANCEL_ROOM" + i + "_" + comp_id;
               modifyRoom = "MODIFY_ROOM" + i + "_" + comp_id;
               modifyBestExtra = "MODIFY_BEST_EXTRA" + i + "_" + comp_id;

               if (document.forms['reservationChangeForm'].elements[cancel] != null && document.forms['reservationChangeForm'].elements[cancel].checked)
               {
                  if ( (document.forms['reservationChangeForm'].elements[modifyRoom] != null && document.forms['reservationChangeForm'].elements[modifyRoom].checked) ||
                      (document.forms['reservationChangeForm'].elements[modifyBestExtra] != null && document.forms['reservationChangeForm'].elements[modifyBestExtra].checked))
                  {
                      window.alert("Cancel Room cannot be combined with the other modify options, please reselect.");

                     return false;
                  }
               }
            }
         }
      }
      return true;
   }
	
	function changeOfShortenStay(aSelect, bSelectName)
   {
      document.forms['reservationChangeForm'].elements[bSelectName].selectedIndex = aSelect.selectedIndex;
      return;
   }

   /** refreshes the numRooms dropdown according to the country selected */
   function refreshNumRoomsDropdown(aSelect) {
      var form = aSelect.form;
      if (form.numRooms != null) {
         var opt = new Array();
         var val = aSelect.options[aSelect.selectedIndex].value;
         var numRoomsSelect = form.numRooms;
         var currentSelect = form.numRooms.selectedIndex;
         if (val == "" || val == "none")
         {
            setOptions(form.numRooms, numRooms_noCountry);
            form.numRooms.selectedIndex = 0;
         }
         
         else
         {
            setOptions(form.numRooms, numRooms_max3);
         }
         if (form.numRooms.length > (currentSelect + 2) && !(val == "" || val == "none"))
         {
            form.numRooms.selectedIndex = currentSelect;
         }
      }
   }
   
      
      function changeOfProfileState(aSelect, fieldName)
   {
      var val = new String(aSelect.options[aSelect.selectedIndex].value);
      var form = aSelect.form;

      // synch any existing state dropdown
      if (fieldName == "state")
      {
         form.state.selectedIndex = aSelect.selectedIndex;
      }

      // change the country dropdown(s) to the proper value
      displayProfileCountry(aSelect, fieldName);

      // if the Guest selected one of the country headers in the state drop-down, complain
      if (val == "US" || val == "CA" || val == "AU")
      {
         window.alert("For Canada, the United States and Australia,\n please select a City or a State");
         aSelect.focus();
      }
      return;
   }

  /** Displays the proper country depending on a state */
   function displayProfileCountry(aSelect, fieldName)
   {
      var val  = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;
      var idx = 0;

      if (val.indexOf("US_") == 0)
      {
         idx = getIndex(form.country, "US");
      }
      else if (val.indexOf("CA_") == 0)
      {
         idx = getIndex(form.country, "CA");
      }
      else if (val.indexOf("AU_") == 0)
      {
         idx = getIndex(form.country, "AU");
      }

      if (idx > 0)
      {
         if (fieldName == "state")
         {
            form.country.selectedIndex = idx;
         }
      }
   }

	/** 
	 * AR0755B: Profile GCCI Sign-Up:: As we have removed second country drop down on the register for a profile page,
	 * we are taking the country value from first country drop down i.e. native country.
	 */
   function refreshProfileStates(aSelect, fieldName)
   {
      var stateCodes = new Array();
      var val = aSelect.options[aSelect.selectedIndex].value;
      var form = aSelect.form;

      if (val == "US")
      {
         stateCodes = US_states_withoutAll;
      }
      else if (val == "CA")
      {
         stateCodes = CA_states_withoutAll;
      }
      else if (val == "AU")
      {
         stateCodes = AU_states_withoutAll;
      }
      else if (val != "")
      {
         stateCodes = new Array(new Option("",""));
      }
      
         setOptions(form.state, stateCodes);
         
   }
   