function ValidateForm()
{
	Screen.Form_error = false;

	var requestedStayDuration = 0;
	var establishmentId = parseInt(document.getElementById("hidEstablishmentId").value);

	verifyMandatoryField("txtFirstName", "first name");

	verifyMandatoryField("txtSurname", "surname");

	verifyMandatoryEmail("txtEmailAddress", "email address");

	verifyMandatoryField("txtContactNumber", "contact number");

	verifyMandatoryDateField("txtCheckInDate", "check-in date");

	verifyMandatoryDateField("txtCheckOutDate", "check-out date");


	if ( GetElement("txtCheckInDate") && GetElement("txtCheckOutDate")  )
	{
		//check if checkout date > checkin date
		if ( bIsValidDateDMY(GetElement("txtCheckInDate").value) && bIsValidDateDMY(GetElement("txtCheckOutDate").value) )
		{
			var ldtTodaysDate = new Date();
			ldtTodaysDate.setHours(0, 0, 0, 0);
			
			var ldtCheckInDate = new Date();
			ldtCheckInDate = stringToDate(GetElement("txtCheckInDate").value);

			var ldtCheckOutDate = new Date();
			ldtCheckOutDate =  stringToDate(GetElement("txtCheckOutDate").value);

			if (ldtCheckInDate < ldtTodaysDate)
				alertFieldError(GetElement("txtCheckInDate"), "The check in date may not be in the past");


			if (ldtCheckInDate > ldtCheckOutDate)
				alertFieldError(GetElement("txtCheckInDate"), "The check-in date cannot be greater than the check-out date");

			if (ldtCheckInDate.valueOf() == ldtCheckOutDate.valueOf() )
				alertFieldError(GetElement("txtCheckOutDate"), "The check-in and check-out dates may not be the same day");



			var lsCheckInDateMDY = 	ldtCheckInDate.toDateString("MM/dd/yyyy")
			var lsCheckOutDateMDY = ldtCheckOutDate.toDateString("MM/dd/yyyy");
			requestedStayDuration = DateDiff( lsCheckInDateMDY, lsCheckOutDateMDY, "d", false)
		}
	}

	//validate the grid input data
	var tblUnits = document.getElementById("tblEstablishmentUnits");
	if (tblUnits)
	{
		RecalculateTotalCost();

		var gridValidates = true;
		var totalNoAdults = document.getElementById("txtTotalNoAdults");
		var totalNoChildren = document.getElementById("txtTotalNoChildren");

		totalNoAdults.value = totalNoAdults.value.Trim();
		totalNoChildren.value = totalNoChildren.value.Trim();


		//check if the totals have been calculated
		if ( (totalNoAdults.value != "") && (!isNumber(totalNoAdults.value)) )
			gridValidates = false;

		if ( (totalNoChildren.value != "") && (!isNumber(totalNoChildren.value)) )
			gridValidates = false;


		//check row data entered
		var tbodyRows = tblUnits.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
		for (var i=0; i < tbodyRows.length; i++)
		{
			var unitIdField = tbodyRows[i].getElementsByTagName("input")[1];
			var minimumStayDuration = tbodyRows[i].getElementsByTagName("input")[3];
			var noAdultsField = tbodyRows[i].getElementsByTagName("input")[4];
			var noChildrenField = tbodyRows[i].getElementsByTagName("input")[5];
			var agesField = tbodyRows[i].getElementsByTagName("input")[6];
			var noAdults = 0;
			var noChildren  = 0;
			var unitId = parseInt(unitIdField.value);


			if (isInt(noAdultsField.value))
				noAdults = parseInt(noAdultsField.value)

			if (isInt(noChildrenField.value))
				noChildren = parseInt(noChildrenField.value)

			if (noChildren > 0)
			{
				if (!bValidChildAges(noChildren, agesField.value) )
					gridValidates = false;
			}
			else
			{
				if (agesField.value == '0')
				{
					agesField.value = '';
				}

				if (agesField.value != "")
					gridValidates = false;
			}


			var unitMinStay = GetUnitMinimumUnitStayDuration(establishmentId, unitId, GetElement("txtCheckInDate").value, GetElement("txtCheckOutDate").value, noAdults);
			if (requestedStayDuration < unitMinStay)
			{
				gridValidates = false;
				alert("The required minimum stay is " + unitMinStay.toString() + " day(s)");
				return false;
			}

		}


		//total no of guests must be greater than 0
		if (gridValidates)
		{
			var totalNoGuests = 0;
			totalNoGuests += parseInt(totalNoAdults.value);
			totalNoGuests += parseInt(totalNoChildren.value);

			if ( (isNaN(totalNoGuests)) || (totalNoGuests == 0) )
				gridValidates = false;
		}

		if (gridValidates == false)
			alertError("Please allocate guests to the unit(s) you would like to be quoted on. Please separate the ages of children with commas, e.g.  1,6");

	}


	if (GetElement("txtBedConfiguration"))
		verifyString("txtBedConfiguration", "bed configuration", 500);


	if (Screen.Form_error == true)
	{
		alert(Screen.Form_errorString);
		return false;
	}
	else
	{
		if (document.getElementById("tblEstablishmentUnits"))
		{
			var lbGridValidated = ValidateGridUnitInfo();
			if (lbGridValidated == false)
				return false;
		}

		if (GetElement("txtCheckInDate"))
			setCookie("CheckInDate", GetElement("txtCheckInDate").value)

		if (GetElement("txtCheckOutDate"))
			setCookie("CheckOutDate", GetElement("txtCheckOutDate").value)

		$.blockUI({ message: '<h1>Please wait while we are sending your request to this establishment...</h1>' });
		setTimeout($.unblockUI, 15000);

		return true;
	}
}



function DateOnChange()
{
	var loEstablishmentId = document.getElementById("hidEstablishmentId");
	var loCheckInDate = document.getElementById("txtCheckInDate");
	var loCheckOutDate = document.getElementById("txtCheckOutDate");
	var loMinStayDuration = document.getElementById("hidMinimumStayDuration");
	
	var liEstablishmentId = parseInt(loEstablishmentId.value);
	
	if (bIsValidDateDMY(loCheckInDate.value) && bIsValidDateDMY(loCheckOutDate.value) )
	{
		ValidateGridUnitInfo();
	}
}



function bValidChildAges(pNoChildren, pAges)
{
	var arrAges = pAges.split(',');
	if (arrAges.length != parseInt(pNoChildren))
		return false;

	if (pNoChildren > 0)
	{
		//check if each row contains a valid number
		for (var i=0; i < arrAges.length; i++)
		{
			if (!isInt(arrAges[i]))
				return false;	
		}
	}

	return true;
}



function ValidateGridUnitInfo()
{
	var lbResult = new Boolean();
	lbResult = true;
	var loTblEstUnit = document.getElementById("tblEstablishmentUnits");

	if (loTblEstUnit)	//table exists
	{

		$.blockUI({ message: '<h1>Please wait while we are checking rates for your selected rooms...</h1>' });

	
		var loTotalNoAdults = document.getElementById("txtTotalNoAdults");
		var loTotalNoChildren = document.getElementById("txtTotalNoChildren");
		var loTotalPrice = document.getElementById("txtTotalPrice");

		loTotalNoAdults.value = "";
		loTotalNoChildren.value = "";
		loTotalPrice.value = "";

		var tbodyRef = loTblEstUnit.getElementsByTagName("tbody")[0];
		var trCol = tbodyRef.getElementsByTagName("tr");

		for (var i=0; i < trCol.length; i++)
		{
			lbResult = CalcRowUnitPrice(i, trCol[i]);
			if (lbResult == false)	//stop validation if problem is detected
				break;
		}

		if (lbResult == true)
			RecalculateTotalCost();

		$.unblockUI();
	}

	return lbResult;
}


function GetUnitMinimumUnitStayDuration(pEstablishmentId, pUnitId, pCheckInDateDMY, pCheckOutDateDMY, pNoAdults)
{
	var returnValue = 1;
	var minimumStay = 0;


	jQuery.ajax({
		async : false,
		type: "POST",
		url: "Lookups/GetUnitMinimumStayDuration.aspx",
		data: "iEstablishmentId=" + pEstablishmentId + "&iUnitId=" + pUnitId + "&iNoOfAdults=" + pNoAdults + "&dtCheckInDate=" + escape(pCheckInDateDMY) + "&dtCheckOutDate=" + escape(pCheckOutDateDMY),
		success: function(data) {
			if (isInt(data)) {
				minimumStay = data;
			}
		}
	});


	if (minimumStay >= 1)
		returnValue = minimumStay;
	else
		returnValue = 1;
	
	return returnValue;	
}




function CalcRowUnitPrice(piRowNumber, pRowRef)
{
	var lbResult = true;

	var liEstablishmentId = document.getElementById("hidEstablishmentId").value;

	//get ref to the td collection
	var tdCol = pRowRef.getElementsByTagName("td");

	//get references for all fields in the td collection
	var lsUnitCode = tdCol[0].getElementsByTagName("input")[0].value;
	var liUnitId = tdCol[0].getElementsByTagName("input")[1].value;
	var loUnitPrice = tdCol[6].getElementsByTagName("input")[0];
	var lsCheckInDateDMY = document.getElementById("txtCheckInDate").value;
	var lsCheckOutDateDMY = document.getElementById("txtCheckOutDate").value;
	var loNoAdults = tdCol[3].getElementsByTagName("input")[0];
	var loNoChildren = tdCol[4].getElementsByTagName("input")[0];
	var loAges = tdCol[5].getElementsByTagName("input")[0];

	loNoAdults.value = loNoAdults.value.Trim();
	loNoChildren.value = loNoChildren.value.Trim();
	loAges.value = loAges.value.Trim();

	var liNoAdults = 0;
	if (loNoAdults.value != "")
	{	
		if (isInt(loNoAdults.value))
			liNoAdults = parseInt(loNoAdults.value)
		else
			lbResult = false;
	}

	var liNoChildren = 0;
	if (loNoChildren.value != "")
	{
		if (isInt(loNoChildren.value))
			liNoChildren = parseInt(loNoChildren.value);
		else
			lbResult = false;
	}


	loUnitPrice.value = "";


	//no data entry errors occurred
	if (lbResult)
	{
		//valid data entered
		var liTotalNoPeople = liNoAdults + liNoChildren;

		if (lbResult && (liTotalNoPeople > 0) )
		{
			jQuery.ajax({
				async : false, 
				type : "POST",
				url: "Lookups/CalculateUnitPrice.aspx",
				data: "iEstablishmentId=" + liEstablishmentId + "&iUnitId=" + liUnitId + "&iNoOfAdults=" + liNoAdults + "&iNoOfChildren=" + liNoChildren + "&vcChildrenAges=" + escape(loAges.value) + "&dtCheckInDate=" + escape(lsCheckInDateDMY) + "&dtCheckOutDate=" + escape(lsCheckOutDateDMY),
				success: function(data) 
				{
					if (data != "0.00") 
					{
						loUnitPrice.value = data;
					}
					else 
					{
						loUnitPrice.value = "On request";
					}
				}
			});
			
		}
	}

	return lbResult;
}


function RecalculateTotalCost()
{
	var liTotalNoAdults = 0;
	var liTotalNoChidlren = 0;
	var lfTotalPrice = 0
	var lbPoeExists = false;

	var tblRef = document.getElementById("tblEstablishmentUnits");
	var tbodyRef = tblRef.getElementsByTagName("tbody")[0];

	//get references to total fields
	var loTotalNoAdults = document.getElementById("txtTotalNoAdults");
	var loTotalNoChildren = document.getElementById("txtTotalNoChildren");
	var loTotalPrice = document.getElementById("txtTotalPrice");

	var trCol = tbodyRef.getElementsByTagName("tr");

	for (var i=0; i < trCol.length; i++)
	{
		var tdCol = trCol[i].getElementsByTagName("td");
		var loNoAdults = tdCol[3].getElementsByTagName("input")[0];
		var loNoChildren = tdCol[4].getElementsByTagName("input")[0];
		var loUnitPrice = tdCol[6].getElementsByTagName("input")[0];

		if (loNoAdults.value != "")
			liTotalNoAdults += parseInt(loNoAdults.value);

		if (loNoChildren.value != "")
			liTotalNoChidlren += parseInt(loNoChildren.value);

		if (loUnitPrice.value == "On request")
		{
			lbPoeExists = true;
		}
		else
		{
			var unitPrice = loUnitPrice.value;
			unitPrice = unitPrice.replace('R', '');
			unitPrice = unitPrice.replace(' ', '');
			if (unitPrice != "")
				lfTotalPrice += parseFloat(unitPrice);
		}
	}

	loTotalNoAdults.value = liTotalNoAdults;
	loTotalNoChildren.value = liTotalNoChidlren;

	if (lbPoeExists)
		loTotalPrice.value = "On request";
	else
		loTotalPrice.value = lfTotalPrice.toFixed(2);
}


