<!--

/*
* author: Francis Hoey
* date: 17-Nov-2004
* Desc:
*			Contains validations and general dhtml 
*			functions etc for the Hotel Sourcing pages.
*/

/*
* Validates the Sourcing form
*/
function validateMe(theForm)
{
try {
	var errorArray = new Array();
	var isValid = true;
	
	//create a list of manatory form elements
	var formElements = new Array("country", "city", "from_date_DD", "from_date_MM", "from_date_YYYY", "to_date_DD", "to_date_MM", "to_date_YYYY") ;
	if (theForm.FEcountry) {
		formElements = new Array("country", "city", "from_date_DD1", "from_date_MM1", "from_date_YYYY1", "to_date_DD1", "to_date_MM1", "to_date_YYYY1") ;
	}
	//create a complimentry list of form element names
	var formElementNames = new Array("country", "city", "check in day", "check in month", "check in year", "check out day", "check out month", "check out year") ;
	var tempError ;
	
	//check all for elements in above arrays are correct
	for(i=0;i<formElements.length;i++)
	{
		tempError = checkFieldHotel(formElements[i], formElementNames[i], (errorArray.length == 0)) ;
		if(tempError.length > 0)
		{
			errorArray[errorArray.length] = tempError ;
			isValid = false;
		}
	}
	
	//check the dates are in the correct order and not in the past
	var isDateValid = parseInt(checkDatesHotel(theForm).substring(0,1));
	switch(isDateValid)
	{
		case 1:
		{
			if (errorArray.length == 0)
			{
				theForm.from_date_DD.focus();
			}
			errorArray[errorArray.length] = "The check in date cannot be in the past." ;
			isValid = false;
			break;
		}
		case 2:
		{
			if (errorArray.length == 0)
			{
				theForm.to_date_DD.focus();
			}
			errorArray[errorArray.length] = "The check out date cannot be in the past." ;
			isValid = false;
			break;
		}
		case 3:
		{
			if (errorArray.length == 0)
			{
				theForm.to_date_DD.focus();
			}
			errorArray[errorArray.length] = "The check out date must be after the check in date." ;
			isValid = false;
			break;
		}		
	}
	
	
	var AdultCount = 0 ;
	try {
		var numRooms = 1;
		if (theForm.numRooms) {
			numRooms = parseInt(theForm.numRooms.value);
		}
		var adt, chl, inf;
		
		//loop through as many room details as numRooms selected and ensure at least 1 adult of child is in each room
		for(n=1;n<=numRooms;n++)
		{
			adt = parseInt(eval("theForm.room" + n + "Adults.value")) ;
			chl = parseInt(eval("theForm.room" + n + "Children.value")) ;
			inf = parseInt(eval("theForm.room" + n + "Infants.value")) ;
			
			AdultCount += adt ;
			
			if((adt + chl + inf) == 0)
			{
				if (errorArray.length == 0)
				{
					eval("theForm.room" + n + "Adults.focus()");
				}
				errorArray[errorArray.length] = "There must be at least one adult or child in room " + n + "." ;
				isValid = false;
			}
			else if (adt ==0 && inf > 0)
			{
				if (errorArray.length == 0)
				{
					eval("theForm.room" + n + "Adults.focus()");
				}
				errorArray[errorArray.length] = "There must be at least one adult with the infant(s) in room " + n + "." ;
				isValid = false;
			}
			
			// Check maximum number of guests per room.
			if ((adt + chl + inf) > 6)
			{
				errorArray[errorArray.length] = "Room " + n + " can have a maximum of 6 guests.";
				isValid = false;
			}
		}
	} catch (roomError) {
	//	alert(roomError);
	}
	
	//make sure there is at least one adult per booking
	if((AdultCount == 0) || (String(AdultCount) == "NaN"))
	{
		if (errorArray.length == 0)
		{
			theForm.room1Adults.focus();
		}
		errorArray[errorArray.length] = "There must be at least 1 adult per booking." ;
		isValid = false;
	}
	
	// check email (if populated)...
	if (dGetById('emailName')) {
	      result = validateEmail(dGetById('emailName'), dGetById('emailDomain'));
	      if (result == false) {
	        errorArray[errorArray.length] = "Please enter a valid email address." ;
			isValid = false;
	      }
	}

	if (theForm.starRating) {
		//make sure a star rating has been selected
		if(!(theForm.starRating[0].checked || theForm.starRating[1].checked || theForm.starRating[2].checked))
		{
			if (errorArray.length == 0)
			{
				theForm.starRating[0].focus();
			}
			errorArray[errorArray.length] = "Please select a star rating from the list." ;
			isValid = false;
		}	
	}
	
	var errorMessage, errorRow;
	errorMessage = ""
	//either fail or pass the form
	if( ! isValid ) 
	{
		//if fail build up an error list
		errorMessage = "Please correct the following:<ul>";
		for (n=0;n<errorArray.length;n++)
		{
			errorMessage += "<li>" + errorArray[n] + "</li>";
		}
		errorMessage += "</ul>";
		//display the errors 
		errorRow = dGetById("errorDiv")
		if (errorRow.cells) {
			//clear the cell so ie on the mac will look ok
			errorRow.cells[0].innerHTML = "";
			errorRow.cells[0].innerHTML = errorMessage;
		} else if (errorRow) {
			errorRow.innerHTML = "";
			errorRow.innerHTML = errorMessage;
		}
		errorRow.style.display = (document.all && !window.opera) ? "block" : "table-row";

		 document.body.scrollTop = 0;
	}
	else
	{
		//hide any previous errors 
		dGetById("errorDiv").style.display = "none";
	}

	setCountryName();
	setCityName();

	if (isValid) {
		if (parent) {
			if (parent.window) {
				if (parent.window['formLoad_dyn']) {
					eval(parent.window['formLoad_dyn']);
				}
			}
		}
	}

	return isValid ;
} catch (ex) {
	alert(ex);
	return false;
}
}

/*
* checks if a selection has been made from a select box or a text field is not empty
*/
function checkFieldHotel(strFieldId, strFieldDesc, setFocus)
{	
	var obj = eval("document.Step1." + strFieldId)
	if (obj) {
		var strValue = obj.value ;
		
		if ((strValue == '') || strValue == null )
		{
			if(setFocus)
			{
				obj.focus();
			}
			return "Please select a " + strFieldDesc + " from the list." ;
		}
	}
	return "";
}

/*
* shows/hides the tbody tags containing the number or people per room
* parameter takes the number of rooms to show
*/
function ShowRoomDetails(numRooms)
{
	var rmDetail ;
	//start on the second tbody as the first is always shown
	var i ;
	for(i = 2;i<=numRooms;i++)
	{
		//display each row upto an including the number of rooms
		rmDetail = dGetById("roomDetail" + i);
		if(rmDetail.style.display == "none")
		{
			eval("document.Step1.room" + i + "Adults").selectedIndex = 2;
		}
		rmDetail.style.display = (document.all && !window.opera) ? "block" : "table-row-group";
	}
	
	//hide and remaining row
	while(dGetById("roomDetail" + i))
	{	
		rmDetail = dGetById("roomDetail" + i);
		rmDetail.style.display = "none";
		//reset the data in the remaining row to avoid it getting posted and confusing people further down the line
		//use selected index incase the minimum ever changes
		eval("document.Step1.room" + i + "Adults").selectedIndex = 0;
		eval("document.Step1.room" + i + "Children").selectedIndex = 0;
		eval("document.Step1.room" + i + "Infants").selectedIndex = 0;
		
		i++;
	}

}

/*
* calculates and displays the number of nights the user is staying
*/
function CalculateNights()
{

	var validDatesArray = checkDatesHotel(document.Step1).split("|");
	var NightBox = dGetById("numberofnights")

	if (NightBox) {

		//clear the cell so ie on the mac will look ok
		NightBox.innerHTML = "";
		switch(parseInt(validDatesArray[0]))
		{
			case 0: //everything ok
			{
				NightBox.innerHTML = validDatesArray[1];
				NightBox.style.fontWeight = "normal";
				NightBox.style.color = "black"
				break;
			}
			case 1: //check in date in the past
			{
				NightBox.innerHTML = "The check in date must not be in the past.";
				NightBox.style.fontWeight = "bold";
				NightBox.style.color = "red"
				break;
			}
			case 2: //check out date in the past
			{
				NightBox.innerHTML = "The check out date must not be in the past.";
				NightBox.style.fontWeight = "bold";
				NightBox.style.color = "red"
				break;
			}
			case 3: //check in date greater than/equal to check out date
			{
				NightBox.innerHTML = "The check out date must be after the check in date."
				NightBox.style.fontWeight = "bold";
				NightBox.style.color = "red"
				break;
			}
		}
			
		document.Step1.numNights.value = validDatesArray[1] ;
	}
}

/*
*checks the check in and out dates and returns a code depending on the error
*		0 - all ok
*		1 - check in date in the past
*		2 - check out date in the past
*		3 - check in date is greater than or equal to the check out date
*
*/
function checkDatesHotel(theForm)
{
	var d = new Date();
	var dteFrom = new Date();
	var dteTo = new Date();
	if (theForm.from_date_YYYY) {
		dteFrom = new Date(theForm.from_date_YYYY.value, (parseInt(theForm.from_date_MM.value, 10)-1), theForm.from_date_DD.value);
		dteTo = new Date(theForm.to_date_YYYY.value, (parseInt(theForm.to_date_MM.value, 10)-1), theForm.to_date_DD.value);
	} else {
		dteFrom = new Date(theForm.from_date_YYYY1.value, (parseInt(theForm.from_date_MM1.value, 10)-1), theForm.from_date_DD1.value);
		dteTo = new Date(theForm.to_date_YYYY1.value, (parseInt(theForm.to_date_MM1.value, 10)-1), theForm.to_date_DD1.value);
	}
	//create a date of today with default time values
	var dteToday = new Date(d.getFullYear(), d.getMonth(), d.getDate());

	var dateDiff;
	
	if( dteToday > dteFrom )
	{
		return "1|0" ;
	}
	else if( dteTo < dteToday )
	{
		return "2|0";
	}
	else
	{
		//get the difference in milliseconds
		dateDiff = (dteTo - dteFrom) 
		//divide diff by number or milliseconds in a day
		dateDiff = Math.round(dateDiff / 86400000) ;
		if(dateDiff > 0) 
		{
			return "0|" + dateDiff ;
		}
		else
		{
			return "3|" + dateDiff ;
		}
	}

}

function CalendarClosed()
{
	CalculateNights();
}

/*
* Clears the contents of a select box
*/
function clearSelectCity(tmpID,tmpDefault)	{
	strMyElement = dGetById(tmpID)
	strMyElement.options.length = 0;

}

/*
* Sets display style attribute to a div
*/
function SelectVisibility(objDIV,strStatus)	{

	objSelPopStatus = dGetById(objDIV);
	objSelPopStatus.style.display = strStatus;

}

/*
* Calls the gofa to populate the city drop down
*/
function GetCities(countryId)
{
	clearSelectCity("city");
	
	SelectVisibility("city","none") ;
	SelectVisibility("citymessage","inline") ;

	var myIFrame = dGetById("Gofa");
	myIFrame.src = '/travel/travelsupermarket/HotelFinderGofa.aspx?CountryID=' + countryId; //'HotelFinderStep1Gofa.asp?CountryID=' + countryId;
}


// WRID 7142 - TISC JS
// 22/12/2004 Matthew Bateman
// Populates the Cities list using the javascript arrays rather than the gofa
function getCitiesDropDown(array, Code, destBox)
{

   if ((eval(FindInArray(Code)) != -1) || (array=="l")) {
		var ddArray = array + Code
		var ArrayLength = eval(ddArray + ".length")
		destBox.length = 1

		for (var i = 0; i < ArrayLength ; i++)
			{	
				
				var ddVal = eval(ddArray + "[" + i + "]")
		
				splitString = ddVal.split("|")
				var ddCode = splitString[0];
				var ddName = splitString[1];

				destBox.length += 1;
				destBox.options[destBox.length - 1] = new Option(ddName);
				destBox.options[destBox.length - 1].value = ddCode;
			}
	} else {
	//clear airport options
		destBox.length = 1
		for (var i = 0; i < destBox.options.length; i++){
			destBox.length += 1;
			destBox.options[destBox.length - 1] = null;
		}
		alert("No cities available for your selected country.");
	} 

}


/*
* Adds option value and text to a selectbox.
*/
function populateCities(strTxt,strOpt,strThisElement)	{
	strMyElement = dGetById(strThisElement);
	strMyElement.options[strMyElement.options.length] = new Option(strOpt,strTxt);
	if(strTxt == CityId.toString()) {
		strMyElement.options[strMyElement.options.length - 1].selected = true;
	}
}

/*
* Sets the selected value for a drop down box (mozilla safe)
*/
function setSelected(theList, theValue)
{
	if (theValue> 0)
	{
		for(i=1;i<theList.options.length;i++)
		{
			if(theList.options[i].value == theValue)
			{
				theList.selectedIndex = i;
				break;
			}
		}		
	}
}

/*
* checks the number of guests per room to alert the user if it is over a specified value
*/
function checkGuestNumber(RoomNumber)
{

	var numAdults = parseInt(eval("document.Step1.room" + RoomNumber + "Adults").value)
	var numChildren = parseInt(eval("document.Step1.room" + RoomNumber + "Children").value)
	var numInfants = parseInt(eval("document.Step1.room" + RoomNumber + "Infants").value)

	var rmError = dGetById("room" + RoomNumber + "ErrorMsg");

	if ((numAdults + numChildren + numInfants) > parseInt(WarningGuestThreshold))
	{
		rmError.cells[0].innerHTML = "By selecting more than " + WarningGuestThreshold + " guests per room, you may be limiting your choice of available hotels."
		rmError.style.display = (document.all && !window.opera) ? "block" : "table-row";
	}
	else
	{
		rmError.style.display = "none";
	}
	
}

function initialisePage()
{
	//if there is a country id set that to be selected and populate/select the city
	if(parseInt(CountryId) > 0)
	{
		setSelected(document.Step1.country, CountryId);
		GetCities(CountryId);
	}
	//calculate the number of nights the user is staying
	CalculateNights();
	//show/hide the room detail rows
	if (document.Step1.numRooms) {
		ShowRoomDetails(document.Step1.numRooms.value);
		//check the number of guests is below the threashold of the warning
		for(i=1;i<=parseInt(document.Step1.numRooms.value);i++)
		{
			checkGuestNumber(i);
		}
	}
}

function setCountryName()
{
	var oCountry = dGetById("country");
	dGetById('countryname').value = oCountry.options[oCountry.selectedIndex].text;
}

function setCityName()
{
	var oCity = dGetById("city");
	dGetById('cityname').value = oCity.options[oCity.selectedIndex].text;
}

function resetCity()
{
	clearSelectCity('city');

	arrTmpArray = new Array();
	arrTmpArray[0] = new Array("","--- select city ---");
	populateCities(arrTmpArray[0][0],arrTmpArray[0][1],"city");
}

// Ensures the checkin date is valid and sets the checkout date to be the day after checkin.
function validateDates(strFor)
{
	if (strFor == "from")
	{
		var from_date_DD = parseInt(dGetById("from_date_DD").value, 10);
		var from_date_MM = parseInt(dGetById("from_date_MM").value, 10) - 1;
		var from_date_YYYY = parseInt(dGetById("from_date_YYYY").value);
	
		if (!(isNaN(from_date_DD) || isNaN(from_date_MM) || isNaN(from_date_YYYY)))
		{
			var dteCheckIn = new Date(from_date_YYYY, from_date_MM, from_date_DD);
	
			// Reset date to the last day of the month if it's not valid.
			if (from_date_DD != dteCheckIn.getDate())
			{
				from_date_DD = from_date_DD - dteCheckIn.getDate();
				dGetById("from_date_DD").value = from_date_DD;
			}
	
			// Set checkout date.
			var dteCheckOut = new Date(from_date_YYYY, from_date_MM, from_date_DD + 7);
			var to_date_DD = dteCheckOut.getDate(); if (to_date_DD < 10) to_date_DD = "0" + to_date_DD;
			var to_date_MM = dteCheckOut.getMonth() + 1; if (to_date_MM < 10) to_date_MM = "0" + to_date_MM;
			
			dGetById("to_date_DD").value = to_date_DD;
			dGetById("to_date_MM").value = to_date_MM;
			dGetById("to_date_YYYY").value = dteCheckOut.getFullYear();
		}
	} else {
		var to_date_DD = parseInt(dGetById("to_date_DD").value, 10);
		var to_date_MM = parseInt(dGetById("to_date_MM").value, 10) - 1;
		var to_date_YYYY = parseInt(dGetById("to_date_YYYY").value);

		if (!(isNaN(to_date_DD) || isNaN(to_date_MM) || isNaN(to_date_YYYY)))
		{
			var dteCheckOut = new Date(to_date_YYYY, to_date_MM, to_date_DD);

			// Reset date to the last day of the month if it's not valid.
			if (to_date_DD != dteCheckOut.getDate())
			{
				to_date_DD = to_date_DD - dteCheckOut.getDate();
				dGetById("to_date_DD").value = to_date_DD;
			}		
		}	
	}
}
function validateDatesHotel(strFor)
{
	if (strFor == "from")
	{
		var from_date_DD = parseInt(dGetById("from_date_DD1").value, 10);
		var from_date_MM = parseInt(dGetById("from_date_MM1").value, 10) - 1;
		var from_date_YYYY = parseInt(dGetById("from_date_YYYY1").value);
	
		if (!(isNaN(from_date_DD) || isNaN(from_date_MM) || isNaN(from_date_YYYY)))
		{
			var dteCheckIn = new Date(from_date_YYYY, from_date_MM, from_date_DD);
	
			// Reset date to the last day of the month if it's not valid.
			if (from_date_DD != dteCheckIn.getDate())
			{
				from_date_DD = from_date_DD - dteCheckIn.getDate();
				dGetById("from_date_DD1").value = from_date_DD;
			}
	
			// Set checkout date.
			var dteCheckOut = new Date(from_date_YYYY, from_date_MM, from_date_DD + 7);
			var to_date_DD = dteCheckOut.getDate(); if (to_date_DD < 10) to_date_DD = "0" + to_date_DD;
			var to_date_MM = dteCheckOut.getMonth() + 1; if (to_date_MM < 10) to_date_MM = "0" + to_date_MM;
			
			dGetById("to_date_DD1").value = to_date_DD;
			dGetById("to_date_MM1").value = to_date_MM;
			dGetById("to_date_YYYY1").value = dteCheckOut.getFullYear();
		}
	} else {
		var to_date_DD = parseInt(dGetById("to_date_DD1").value, 10);
		var to_date_MM = parseInt(dGetById("to_date_MM1").value, 10) - 1;
		var to_date_YYYY = parseInt(dGetById("to_date_YYYY1").value);

		if (!(isNaN(to_date_DD) || isNaN(to_date_MM) || isNaN(to_date_YYYY)))
		{
			var dteCheckOut = new Date(to_date_YYYY, to_date_MM, to_date_DD);

			// Reset date to the last day of the month if it's not valid.
			if (to_date_DD != dteCheckOut.getDate())
			{
				to_date_DD = to_date_DD - dteCheckOut.getDate();
				dGetById("to_date_DD").value = to_date_DD;
			}		
		}	
	}
}

//*******************************************************
// FUNCTION: validateEmail
//*******************************************************
// DESC:		Validates the user's email address
// PARAMS:		objEmailField - the form field id
// RETURNS:		true = email is valid, false = email not valid
//*******************************************************
function validateEmail(objEmailName, objEmailDomain)
{
	var reEmailName = /^([\w\'\"-])+((([a-zA-Z\-0-9])|\.)+)$/
	var reEmailDomain = /^([a-zA-Z0-9_-])+((([a-zA-Z\-0-9]{1,})+\.)+([a-zA-Z]{2,})+)$/
	
	if (objEmailName) {
	
	    var strEmailName = objEmailName.value;
	    var strEmailDomain = objEmailDomain.value;
	    if ((strEmailName.length > 0) || (strEmailDomain.length > 0))
	    {		
		   blnExpEmailName = reEmailName.test(strEmailName);
		   blnExpEmailDomain = reEmailDomain.test(strEmailDomain);
		   if (blnExpEmailName == false || blnExpEmailDomain == false)
		   {
		    	//showErrorMessage("Please enter a valid email address.");
			    return false;
		   }
	    }
	    return true;
	}
}
//*******************************************************

//-->