/*
This file contains javascript functions that are used by the hotel search
include file on bestwestern.com.  This code is copied from the original 
javascript on book.bestwestern.com but there are some modifications.  Please
pay attention to comments when making any changes or prior to overwriting
any code with updated versions from book.bestwestern.com.  It is recommended
that a code merge be done as opposed to overwriting.
*/

function showWindow( m_url, winname, winwidth, winheight, wndparams)
{
	if ((winname == null) || (winname == "")) winname = "lvs";
	
	winleft = (screen.availWidth / 2) - (winwidth / 2);
	wintop = (screen.availHeight / 2) - (winheight / 2);
	
	if (wndparams == null) wndparams = "scrollbars=no,resizable=no";
	oWinInfo=(window.open(m_url, winname,"left=" + winleft + ",top=" + wintop + ",width=" + winwidth + ",height=" + winheight + "," + wndparams));
	//	registerWindow(oWinInfo);
	if (!Browser.ie) {
		if(oWinInfo.self != null)  oWinInfo.focus();
	}
}
/**
 ****************************************************************************
 * the main validation methods
 ****************************************************************************
 */

/**
 * wrapper function that calls all post-submit validation functions
 */
function validatePropertySearchFormAll(form) {

	var passed = true;

	form.searchCty.value = Trim(form.searchCty.value);
	form.city.value = form.searchCty.value;
	//alert(form.city.value);
	
	// the Struts-Validator dynamically generated validation
	passed = validatePropertySearchForm(form);

	switch (form.searchByType.value)
	{
		case "Airport":
		{
			form.referencePoint.value = form.airportCode.value;

			if((form.referencePoint == null || form.referencePoint.value == "") &&
				form.countryCode.options[form.countryCode.selectedIndex].value == "" &&
				form.stateCode.options[form.stateCode.selectedIndex].value == "" ){
				alert("Please provide an Airport Name/Code OR a location.");
				passed = false;
			}
			else if((form.referencePoint == null || form.referencePoint.value == "") &&
				(form.countryCode.options[form.countryCode.selectedIndex].value != "" &&
				Trim(form.searchCty.value) == "" && form.stateCode.options[form.stateCode.selectedIndex].value == "" )){
				alert("Please provide an Airport Name/Code OR a City.");
				passed = false;
			}
			else if((form.referencePoint != null && form.referencePoint.value != "") &&
				(form.countryCode.options[form.countryCode.selectedIndex].value != "" &&
				Trim(form.searchCty.value) == "" && form.stateCode.options[form.stateCode.selectedIndex].value == "" )){
					//Nothing to do if this is the case.
			}
			else if((form.referencePoint != null && form.referencePoint.value != "") &&
				(form.countryCode.options[form.countryCode.selectedIndex].value != "" ||
				Trim(form.searchCty.value) != "" )){
					alert("You cannot enter both an Airport Name/Code AND a location.  Please enter only an Airport Name/Code OR a location.");
					passed = false;
			}
			else if((form.referencePoint == null || form.referencePoint.value == "") &&
				(form.countryCode.options[form.countryCode.selectedIndex].value != "" &&
				form.stateCode.options[form.stateCode.selectedIndex].value != "" && Trim(form.searchCty.value) == "" )){
				alert("Please provide a City name.");
				passed = false;
			}
			else if((form.referencePoint == null || form.referencePoint.value == "") &&
				(form.countryCode.options[form.countryCode.selectedIndex].value != "" ||
				Trim(form.searchCty.value) != "" )){
				passed = validateCountryState(form);
			}
			break;
		}

		case "Address":
		{
			var cCode = form.countryCode.options[form.countryCode.selectedIndex].value;
			if(form.postalCode.value != ""){
				passed = true;
			}
			else if(form.addressLine1.value == "" &&
				form.countryCode.options[form.countryCode.selectedIndex].value == ""){
				alert("Please Provide Zip Code and/or Address with Country Code.");
				passed = false;
			}
			else if(cCode != "AU" && cCode != "AT" && cCode != "BE" && cCode != "BR" && cCode != "CA" &&
					cCode != "DK" && cCode != "FI" && cCode != "FR" && cCode != "DE" && cCode != "GR" &&
					cCode != "IT" && cCode != "LU" && cCode != "NL" && cCode != "NO" && cCode != "PT" &&
					cCode != "ES" && cCode != "SE" && cCode != "CH" && cCode != "GB" && cCode != "US" ){
				alert("Countries available for Address search are:\n\n 	Australia, Austria, Belgium, Brazil, Canada, Denmark, Finland, France,\n 	Germany, Greece, Italy, Luxembourg, Netherlands, Norway, Portugal,\n 	Spain, Sweden, Switzerland, United Kingdom and United States.\n\n Please select a country among these.");
				passed = false;
			}
			else{
				passed = validateCountryState(form);
			}
			break;
		}		
		case "Attraction":
		{
			form.referencePoint.value = form.attractionName.value;
			if(form.referencePoint == null || form.referencePoint.value == ""){
				alert("Please provide an Attraction Name.");
				passed = false;
			}
			break;
		}

		default:
		{
			form.referencePoint.value = "";
		}
	}

	// the 'custom' validations below
	if (passed) 
	{
		passed = validateCapacityRequest(form);
	}
	if (passed && (form.searchByType.value != "Attraction") && (form.searchByType.value != "Address")) 
	{
		passed = validateCountryState(form);
	}
	return passed;
}


/**
* 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 Check-In date\n  - Your Check-Out date\n\nIf you do not wish to check Room Availability and are just searching for a hotel,\nplease leave these fields blank.";

	        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;
}

/**
* 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;
   }

	/**
    * 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();
		
		form.depDate.value = tempDMY;
   }

	
function getDay(day,month,year)
{
	var days = new Array(12);
	var retVal = 0;
	days[0] = 31;
	days[1] = 28;
	days[2] = 31;
	days[3] = 30;
	days[4] = 31;
	days[5] = 30;
	days[6] = 31;
	days[7] = 31;
	days[8] = 30;
	days[9] = 31;
	days[10] = 30;
	days[11] = 31;
	for (var i = 0 ; i < (month) ; i++)
	{
		retVal += days[i];
	}
	if (month > 1 && isLeapYear(year))
	{
		retVal++;
	}
	retVal = retVal + day;
	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)
{
	if (year1 != year2)
	{
		day2 += (year2 - year1) * 365;
		if (day1 < 59 && isLeapYear(year1))
		{
			day2++;
		}
	}
	return day2 - day1;
}

/**
 * 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 && form.searchCty.value == "")
		{
			window.alert("For Canada, the United States and Australia,\n please select a City or 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;
		}
	}
	return true;
}

/**
 * If the Guest wishes to reserve 6-9 rooms (US/Canada) or 4-9 rooms (non US/Canada),
 * or 10+ rooms, this method causes a popup window to open providing a link and/or
 * instructions for reserving rooms under such situations, as these types of 
 * reservations cannot be booked online
 */
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("You must select a country before choosing the number of rooms");
		aSelect.selectedIndex = 0;
		return false;
	}
	if (numRooms == 9) {
		aSelect.selectedIndex=0;
		aSelect.focus();
		
/* JDW EDIT START - added form.base_url_book.value */
		var url = form.base_url_book.value + "message.do?msgKey=search.group_request_msg&arg1=http%3A%2F%2Fwww.bestwestern.com";
/* JDW EDIT END */
		url += "&arg0=" + numRoomsLabel;		
		popupMessage(url,"msgWindow", 300,200);
		return false;
	}

	if (numRooms == 10) {
		aSelect.selectedIndex=0;
		aSelect.focus();
/* JDW EDIT START - added form.base_url_book.value */
		var url = form.base_url_book.value + "message.do?msgKey=search.group_online_msg&arg0=http%3A%2F%2Fwww.bestwestern.com";
/* JDW EDIT END */
		popupMessage(url,"msgWindow", 300,200);
		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 City or 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.searchCty != null) {
			form.searchCty.value = aTextbox.value;
		}
		if (form.nearCity != null) {
			form.nearCity.value = aTextbox.value;
		}
		return true;
   }

   
   /**
    * called to set the city field, state select and country select
	* when quick city option selected
    */
   function setCity(aOption) 
   {
		var idx = 0;
		var form = aOption.form;
		var arrayValue = aOption.value.split(";")
		// set city
		form.searchCty.value = arrayValue[0]; //aOption.value;
		// set state
		idx = getIndex(form.stateCode, arrayValue[1]); //aOption.value2); 
		form.stateCode.selectedIndex = idx;
		// set country
		idx = getIndexCountry(form.countryCode, arrayValue[2], arrayValue[3]); //aOption.value3);
		form.countryCode.selectedIndex = idx;
		return true;
   }
   


function selectNextDate(aSelect){
	var day	  = aSelect.form.arrivalDay.value;
	var month = (aSelect.form.arrivalMonthYear.value).substring(4,6);
	var year  = (aSelect.form.arrivalMonthYear.value).substring(0,4);
	var curDate		=new Date(year,month,day)
	var nextDate	=new Date(curDate)
	nextDate.setDate(nextDate.getDate()+1);
	var nextmonthyear = nextDate.getFullYear() +'' + 
						(nextDate.getMonth() <10 ? '0'+ nextDate.getMonth() :nextDate.getMonth())
	if(	aSelect.form.departureDay.selectedIndex==0 && 
		aSelect.form.departureMonthYear.selectedIndex==0 ){
		aSelect.form.departureDay.value=nextDate.getDate();
		aSelect.form.departureMonthYear.value=nextmonthyear;
	}
}

/**
 ****************************************************************************
 * 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);
	}
}

/* JDW - Displays the proper state drop-downs based on a country */
function resetStates(aSelect) {
	var form = aSelect.form;
   	removeAllData(aSelect);
	// have to use setTimeout to avoid bug in Opera
	setTimeout("form.stateCode[form.stateCode.length] = new Option('Select State', '')", 5);
	setTimeout("appendSelectOptionGroup(form.stateCode, 'United States', US_states)", 5);
	setTimeout("appendSelectOptionGroup(form.stateCode, 'Canada', CA_states)", 5);
	setTimeout("appendSelectOptionGroup(form.stateCode, 'Australia', AU_states)", 5);
	aSelect.selectedIndex = 0;
}

/* JDW - adds option group to a select dropdown using pre-defined option array values */
function appendSelectOptionGroup(aSelect, optGroupLabel, aryOptions) {
	// create new option group 
   	var oGroup = document.createElement('optgroup'); 
   	//document.forms['form1'].elements['select1']; 
   	oGroup.label = optGroupLabel; 
	oGroup.style.fontSize = "8pt";
	// for each array item
	for (var i=0; i < aryOptions.length; i++) {
		if (aryOptions[i].text != 'All') { // don't inlcude "All" option
		    // create option
			var oOption = document.createElement('option'); 
    	 	oOption.value = aryOptions[i].value; 
			oOption.innerHTML = aryOptions[i].text; 
		    //append the option to the option group 
    		oGroup.appendChild(oOption); 
		}
	}
	// append option group to select
	aSelect.appendChild(oGroup);
}


/** 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) {
		idx = getIndex(form.countryCode, "US");
	} 
	else if (val.indexOf("CA_") == 0) {
		idx = getIndex(form.countryCode, "CA");
	}
	else if (val.indexOf("AU_") == 0) {
		idx = getIndex(form.countryCode, "AU");
	}

	if (idx > 0) 
	{
		form.countryCode.selectedIndex = idx;
		if (form.nearCountry != null) { 
			form.nearCountry.selectedIndex = idx;
		}
	}
}


/** 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 if (val == "CA")
		{
			removeAllData(numRoomsSelect);
			numRoomsSelect.options[numRoomsSelect.length] = new Option("", "0");
			 
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("1", "1");
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("2", "2");
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("3", "3");
				 
				numRoomsSelect[numRoomsSelect.length] = new Option("4-9", "9");
				numRoomsSelect[numRoomsSelect.length] = new Option("10+", "10");				
			
		}
		
		else if (val == "IT")
		{
			removeAllData(numRoomsSelect);
			numRoomsSelect.options[numRoomsSelect.length] = new Option("", "0");
			 
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("1", "1");
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("2", "2");
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("3", "3");
				 
				numRoomsSelect[numRoomsSelect.length] = new Option("4-9", "9");
				numRoomsSelect[numRoomsSelect.length] = new Option("10+", "10");				
			
		}
		
		else if (val == "US")
		{
			removeAllData(numRoomsSelect);
			numRoomsSelect.options[numRoomsSelect.length] = new Option("", "0");
			 
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("1", "1");
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("2", "2");
				
					numRoomsSelect.options[numRoomsSelect.length] = new Option("3", "3");
				 
				numRoomsSelect[numRoomsSelect.length] = new Option("4-9", "9");
				numRoomsSelect[numRoomsSelect.length] = new Option("10+", "10");				
			
		}
		
		else if (val == "policy")
		{
			removeAllData(numRoomsSelect);
			numRoomsSelect.options[numRoomsSelect.length] = new Option("", "0");
			 
				
		}
		
		else 
		{
			setOptions(form.numRooms, numRooms_max3);
		}
		if (form.numRooms.length > (currentSelect + 2) && !(val == "" || val == "none"))
		{				
			form.numRooms.selectedIndex = currentSelect;
		}
	}
}

/**
* 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 a select value, return index of occurance specified 
 * within the country select element; 
 * if not found return the first element in the select.  
 */
function getIndexCountry(aSelect, aValue, aOccurrance) {
	var iOccurrance = 0;
	for (var i=0; i < aSelect.length; i++) {
		if (aSelect.options[i].value == aValue) {
			iOccurrance++;
			if (iOccurrance == aOccurrance)
			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
			aSelect.options[aSelect.length] = new Option(aryOptions[i].text, aryOptions[i].value);
		}
	}
}

/** 
 * wrapper around window.open used for opening a non-resizable no-thrills popup message windows
 */
function popupMessage(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 switchToAdvanced()
{
	document.propertySearchForm.action = form.base_url_book.value + "advSearch.do";
	document.propertySearchForm.submit();
	return false;
}


/**
 ****************************************************************************
 * Dynamically created arrays needed to change State/Country/NumRooms
 * dropdowns in the search forms
 ****************************************************************************
 */

// create an array containing all US states
var US_states = new Array ();
US_states[0] = new Option("All","");
	US_states[US_states.length] = new Option("Alabama", "US_" + "AL");
	US_states[US_states.length] = new Option("Alaska", "US_" + "AK");
	US_states[US_states.length] = new Option("Arizona", "US_" + "AZ");
	US_states[US_states.length] = new Option("Arkansas", "US_" + "AR");
	US_states[US_states.length] = new Option("California", "US_" + "CA");
	US_states[US_states.length] = new Option("Colorado", "US_" + "CO");
	US_states[US_states.length] = new Option("Connecticut", "US_" + "CT");
	US_states[US_states.length] = new Option("Delaware", "US_" + "DE");
	US_states[US_states.length] = new Option("District of Columbia", "US_" + "DC");
	US_states[US_states.length] = new Option("Florida", "US_" + "FL");
	US_states[US_states.length] = new Option("Georgia", "US_" + "GA");
	US_states[US_states.length] = new Option("Hawaii", "US_" + "HI");
	US_states[US_states.length] = new Option("Idaho", "US_" + "ID");
	US_states[US_states.length] = new Option("Illinois", "US_" + "IL");
	US_states[US_states.length] = new Option("Indiana", "US_" + "IN");
	US_states[US_states.length] = new Option("Iowa", "US_" + "IA");
	US_states[US_states.length] = new Option("Kansas", "US_" + "KS");
	US_states[US_states.length] = new Option("Kentucky", "US_" + "KY");
	US_states[US_states.length] = new Option("Louisiana", "US_" + "LA");
	US_states[US_states.length] = new Option("Maine", "US_" + "ME");
	US_states[US_states.length] = new Option("Maryland", "US_" + "MD");
	US_states[US_states.length] = new Option("Massachusetts", "US_" + "MA");
	US_states[US_states.length] = new Option("Michigan", "US_" + "MI");
	US_states[US_states.length] = new Option("Minnesota", "US_" + "MN");
	US_states[US_states.length] = new Option("Mississippi", "US_" + "MS");
	US_states[US_states.length] = new Option("Missouri", "US_" + "MO");
	US_states[US_states.length] = new Option("Montana", "US_" + "MT");
	US_states[US_states.length] = new Option("Nebraska", "US_" + "NE");
	US_states[US_states.length] = new Option("Nevada", "US_" + "NV");
	US_states[US_states.length] = new Option("New Hampshire", "US_" + "NH");
	US_states[US_states.length] = new Option("New Jersey", "US_" + "NJ");
	US_states[US_states.length] = new Option("New Mexico", "US_" + "NM");
	US_states[US_states.length] = new Option("New York", "US_" + "NY");
	US_states[US_states.length] = new Option("North Carolina", "US_" + "NC");
	US_states[US_states.length] = new Option("North Dakota", "US_" + "ND");
	US_states[US_states.length] = new Option("Ohio", "US_" + "OH");
	US_states[US_states.length] = new Option("Oklahoma", "US_" + "OK");
	US_states[US_states.length] = new Option("Oregon", "US_" + "OR");
	US_states[US_states.length] = new Option("Pennsylvania", "US_" + "PA");
	US_states[US_states.length] = new Option("Rhode Island", "US_" + "RI");
	US_states[US_states.length] = new Option("South Carolina", "US_" + "SC");
	US_states[US_states.length] = new Option("South Dakota", "US_" + "SD");
	US_states[US_states.length] = new Option("Tennessee", "US_" + "TN");
	US_states[US_states.length] = new Option("Texas", "US_" + "TX");
	US_states[US_states.length] = new Option("Utah", "US_" + "UT");
	US_states[US_states.length] = new Option("Vermont", "US_" + "VT");
	US_states[US_states.length] = new Option("Virginia", "US_" + "VA");
	US_states[US_states.length] = new Option("Washington", "US_" + "WA");
	US_states[US_states.length] = new Option("West Virginia", "US_" + "WV");
	US_states[US_states.length] = new Option("Wisconsin", "US_" + "WI");
	US_states[US_states.length] = new Option("Wyoming", "US_" + "WY");
// create an array containing all Canadian states
var CA_states = new Array ();
CA_states[0] = new Option("All","");
	CA_states[CA_states.length] = new Option("Alberta", "CA_" + "AB");
	CA_states[CA_states.length] = new Option("British Columbia", "CA_" + "BC");
	CA_states[CA_states.length] = new Option("Manitoba", "CA_" + "MB");
	CA_states[CA_states.length] = new Option("New Brunswick", "CA_" + "NB");
	CA_states[CA_states.length] = new Option("Newfoundland", "CA_" + "NL");
	CA_states[CA_states.length] = new Option("Nova Scotia", "CA_" + "NS");
	CA_states[CA_states.length] = new Option("Ontario", "CA_" + "ON");
	CA_states[CA_states.length] = new Option("Prince Edward Island", "CA_" + "PE");
	CA_states[CA_states.length] = new Option("Quebec", "CA_" + "QC");
	CA_states[CA_states.length] = new Option("Saskatchewan", "CA_" + "SK");
	CA_states[CA_states.length] = new Option("Yukon Territory", "CA_" + "YT");
// create an array containing all Australian states
var AU_states = new Array ();
AU_states[0] = new Option("All","");
	AU_states[AU_states.length] = new Option("Australian Capital Territory", "AU_" + "ACT");
	AU_states[AU_states.length] = new Option("New South Wales", "AU_" + "NSW");
	AU_states[AU_states.length] = new Option("Northern Territory", "AU_" + "NT");
	AU_states[AU_states.length] = new Option("Queensland", "AU_" + "QLD");
	AU_states[AU_states.length] = new Option("South Australia", "AU_" + "SA");
	AU_states[AU_states.length] = new Option("Tasmania", "AU_" + "TAS");
	AU_states[AU_states.length] = new Option("Victoria", "AU_" + "VIC");
	AU_states[AU_states.length] = new Option("Western Australia", "AU_" + "WA");
// create the default number of Rooms dropdown
var numRooms_max3 = new Array(
		new Option("","0"),
		new Option("1","1"),
		new Option("2","2"),
		new Option("3","3"),
		new Option("4-9","9"),
		new Option("10+","10")
		);

// create the number of Rooms dropdown for US and CA
var numRooms_max5 = new Array(
		new Option("","0"),
		new Option("1","1"),
		new Option("2","2"),
		new Option("3","3"),
		new Option("4","4"),
		new Option("5","5"),
		new Option("6-9","9"),
		new Option("10+","10")
		);
// create the number of Rooms dropdown for no country selected.
var numRooms_noCountry = new Array(
	   new Option("", "-1"),
	   new Option("1", "1"),
	   new Option("2", "2"),
	   new Option("3", "3"),
	   new Option("4-9", "9"),
	   new Option("10+", "10"));

   var bCancel = false; 

   function validatePropertySearchForm(form) {                                                                   
       if (bCancel) 
     return true; 
       else 
      return true; 
  } 

function validateMaxLength(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oMaxLength = new maxlength();
                for (x in oMaxLength) {
                    if (form[oMaxLength[x][0]].type == 'text' ||
                        form[oMaxLength[x][0]].type == 'textarea') {
                        var iMax = parseInt(oMaxLength[x][2]("maxlength"));
                        if (form[oMaxLength[x][0]].value.length > iMax) {
                            if (i == 0) {
                                focusField = form[oMaxLength[x][0]];
                            }
                            fields[i++] = oMaxLength[x][1];
                            bValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('\n'));
                }
                return bValid;
            }
			
function validateRequired(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oRequired = new required();
                for (x in oRequired) {
                	var field = form[oRequired[x][0]];
                	
                    if (field.type == 'text' ||
                        field.type == 'textarea' ||
                        field.type == 'file' ||
                        field.type == 'select-one' ||
                        field.type == 'radio' ||
                        field.type == 'password') {
                        
                        var value = '';
						// get field's value
						if (field.type == "select-one") {
							var si = field.selectedIndex;
							if (si >= 0) {
								value = field.options[si].value;
							}
						} else {
							value = field.value;
						}
                        
                        if (value == '') {
                        
	                        if (i == 0) {
	                            focusField = field;
	                        }
	                        fields[i++] = oRequired[x][1];
	                        bValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('\n'));
                }
                return bValid;
            }

			
var Browser = new Object();
with (Browser) {
	Browser.b = Browser;
	b.a = navigator.userAgent.toLowerCase();
	b.v = navigator.appVersion;
	b.version = parseFloat(v);
	b.major = parseInt(v);
	b.opera = (a.indexOf('opera') != -1)?true:false;
	b.hotjava = (a.indexOf('hotjava') != -1)?true:false;
	b.webtv = (a.indexOf('webtv') != -1)?true:false;
	b.nav = (a.indexOf('mozilla') != -1 && a.indexOf('spoofer') == -1 && 
		a.indexOf('compatible') == -1 && !opera && !webtv && !hotjava)?true:false;
	b.nav4 = (nav && major == 4)?true:false;
	b.nav6 = (nav && major == 5)?true:false;
	b.nav6up = (nav && major >= 5)?true:false;
	b.aol = (a.indexOf('aol') != -1)?true:false;
	b.ie = (!opera && a.indexOf('msie') != -1)?true:false;
	b.ie4 = (ie && major == 4 && a.indexOf('msie 4') != -1)?true:false;
	b.ie4up = (ie && major >= 4)?true:false;
	b.ie5 = (ie4up && a.indexOf('msie 5.0') != -1)?true:false;
	b.ie5up = (ie4up && !ie4)?true:false;
	b.macie5=(ie4 && v.indexOf("macintosh")!=-1)?true:false;
	b.ie55 = (ie5up && a.indexOf('msie 5.5') != -1)?true:false;
	b.ie55up = (ie5up && !ie5)?true:false;
	b.ie6 = (ie4up && a.indexOf('msie 6.') != -1)?true:false;
	b.ie6up = (ie55up && !ie55)?true:false;
	b.win95 = (a.indexOf('win95') != -1 || a.indexOf('windows 95') != -1)?true:false;
	b.win98 = (a.indexOf('win98') != -1 || a.indexOf('windows 98') != -1)?true:false;
	b.mac = (a.indexOf('macintosh') != -1)?true:false;
	b.win9x = (win95 || win98)?true:false;
	b.sun = (a.indexOf('sunos') != -1)?true:false;
}

