//var MinAdult = 1;
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
/////////////////////////////////////////////////////////////		
		function displayEntry(eName, fName)
		{
			
			maxChildren = parseInt(eval(fName +"('max_o_" + eName + "').value")) - parseInt(eval(fName +"('min_a_" + eName + "').value"));
//			alert (maxChildren);
			var max = parseInt(eval(fName + "('c_" + eName + "').value"));
			var roomMax = parseInt(eval(fName +"('max_o_" + eName + "').value"));
//			var adult = parseInt(eval(fName + "('a_" + eName + "').value"));
			var roomID = eval(fName + "('acc_" + eName + "').value");
			
			eval("document.all('span_ac_" + eName + "').style.visibility='hidden';");
			for (var i = 1; i <= maxChildren; i ++)
			{

				if (i <= max)
				{
					
					//eval("document.all('span1_" + i + "_" + eName + "').style.visibility='visible';");
					//eval("document.all('span2_" + i + "_" + eName + "').style.visibility='visible';");
					eval("document.all('span_ac_" + eName + "').style.visibility='visible';");
				}
				else
				{
					//eval("document.all('span1_" + i + "_" + eName + "').style.visibility='hidden';");
					//eval("document.all('span2_" + i + "_" + eName + "').style.visibility='hidden';");
				}
				
			}

			return true;
		}
		////////////////////////////////////////////////////
		function checkConfig(eName, fName)
		{
			var maxDbl = parseInt(eval(fName + "('max_dbl_" + eName + "').value"));
			var maxSngl = parseInt(eval(fName + "('max_sngl_" + eName + "').value"));
			var maxOcc = parseInt(eval(fName + "('max_o_" + eName + "').value"));
			var roomID = eval(fName + "('acc_" + eName + "').value");
			var Dbl =  parseInt(eval(fName + "('dbl_" + eName + "').value"));
			var Sngl =  parseInt(eval(fName + "('s_" + eName + "').value"));
			if (maxDbl < Dbl)
			{
				alert ("Number of required double beds exceeds the number of double beds in this room. \nPlease amend your entry to match available room configuration.\n\n You can check bedding configuration for a room on any of the screens showing room type title by clicking on the room type title.")
				eval('QuoteForm("dbl_' + eName + '").focus()');
				return false;
			}
			if (maxSngl < Sngl)
			{
				alert ("Number of required single beds exceeds the number of single beds in this room. \nPlease amend your entry to match available room configuration.\n\n You can check bedding configuration for a room on any of the screens showing room type title by clicking on the room type title.")
				eval('QuoteForm("s_' + eName + '").focus()');
				return false;
			}
			if (Dbl*2 + Sngl > maxOcc)
			{
				alert ("Number of beds specified in bedding configuration exceeds maximum occupancy for this room type. Please amend your entry to match available room configuration.\n\n You can check room occupancy and bedding configuration for a room on any of the screens showing room type title by clicking on the room type title.")
				eval('QuoteForm("dbl_' + eName + '").focus()');
				return false;
			}
			return true;
		}
	///////////////////////////////////////////////////
		function getChildrenAge(eName, fName)
		{
//			alert("checking children's ages");
			var children = parseInt(eval(fName + "('c_" + eName + "').value"));
			for (var i=1; i<=children; i++)
			{	
				if (trim(eval(fName + "('con_" + i + "_" + eName + "').value"))=="")
				{
					alert("The ages for all children/students must be entered. \n\nPlease enter ages for the specified number of children/students in order to continue.");
					eval(fName + "('con_" + i + "_" + eName + "').focus()");
					return false;
				}
			}
			return true;
		}
		function checkOccupancy(eName, fName)
		{
			var max = parseInt(eval(fName + "('c_" + eName + "').value"));
			var roomMax = parseInt(eval(fName + "('max_o_" + eName + "').value"));
			var roomMin = parseInt(eval(fName + "('min_o_" + eName + "').value"));
			var adult = parseInt(eval(fName + "('a_" + eName + "').value"));
			var roomID = eval(fName + "('acc_" + eName + "').value");
			if (max + adult > roomMax)
			{
				alert("Maximum occupancy for room: " + roomID + " is " + roomMax + " persons.\n\nPlease adjust your entries to adhere to the allowed occupancy.");
				return false;
			}
			/*
			else
			{
				if (max + adult < roomMin)
				{
					alert("Minimum occupancy for room: " + roomID + " is " + roomMin + " persons.\n\nPlease note you will be charged minimum room occupancy price.");
				}
			}
			*/
			return true;
		}

		function getPrice(eName, fName)
		{
			var ClientBrowser = BrowserDetect.browser;
			var ClientOS = BrowserDetect.OS;
			var ClientBVersion = BrowserDetect.version;
			
			if (ClientBrowser != "Explorer")
			{
				alert("You are using: " + ClientBrowser + "(version " + ClientBVersion + ") on " + ClientOS + ".\n\nYou may experience problems with price calculation. If the price does not calculate on this page, please proceed and the next page will display the price for selected rooms.\n\nIf you wish to change your room configuration you can always go back, make corrections and repeat the process.");
			}else
				if (ClientOS != "Windows")
				{
					alert("You are using: " + ClientBrowser + "(version " + ClientBVersion + ") on " + ClientOS + ".\n\nYou may experience problems with price calculation. If the price does not calculate on this page, please proceed and the next page will display the price for selected rooms.\n\nIf you wish to change your room configuration you can always go back make corrections and repeat the process.");
				}
			var total, dailySurcharge;
			var price = parseFloat(eval(fName + "('price_" + eName + "').value"));
			var secondaryPrice = parseFloat(eval(fName + "('secondary_price_" + eName + "').value"));
			var surcharge = parseFloat(eval(fName + "('surcharge_" + eName + "').value"));
			if (eval(fName + "('surcharge_d_" + eName + "').value == 'True'"))
			{
				dailySurcharge = 1
			}
			else
			{
				dailySurcharge  = 0;
			}
//			alert (dailySurcharge);
			var discount = eval(fName + "('discount_" + eName + "').value");
			var concession = eval(fName + "('concession_" + eName + "').value");
			var concessionLimit = eval(fName + "('max_cl_" + eName + "').value");
			var minOcc = parseInt(eval(fName + "('min_o_" + eName + "').value"));
			var maxOcc = parseInt(eval(fName + "('max_o_" + eName + "').value"));
			var minAdult = parseInt(eval(fName + "('min_a_" + eName + "').value"));
			var adults = parseInt(eval(fName + "('a_" + eName + "').value"));
			var children = parseInt(eval(fName + "('c_" + eName + "').value"));
			
			if (isNaN(children))
			{
				children = 0;
			}
			if (isNaN(adults))
			{
				adults = 0;
			}
			var duration = parseInt(eval(fName + "('d_" + eName + "').value"));
			var durationOriginal = parseInt(eval(fName + "('do_" + eName + "').value"));
			var durationType = eval(fName + "('d_" + eName + "').type")
			var pricePerPerson = parseInt(eval(fName + "('per_person_" + eName + "').value"));
			var childPrice, childAge, arrayLength, childCount, childProcessed, adultCount, additionalCharge = 0;

			if (!checkOccupancy(eName, fName))
			{
				eval('QuoteForm("a_' + eName + '").focus()');
				return false;
			}	
			var durationMultiplier = parseFloat(duration)/parseFloat(durationOriginal)
/*
			alert(eName);
			alert('price: ' + price);
			alert('secondaryPrice:' + secondaryPrice);
			alert('surcharge: ' + surcharge);
			alert('discount: ' + discount);
			alert('concession: ' + concession);
			alert('duration: ' + duration);
			alert('price per person ' + pricePerPerson);
*/
			if (concession == '')
			{//no applicable concessions
				if (pricePerPerson == '0')
				{//pricing is per room
					if (adults + children <= minOcc)
					{
						total = price * durationMultiplier;
					}
					else
					{
						total = secondaryPrice * durationMultiplier;
					}
				}//pricing is per person
				else
				{
					if (isNaN(surcharge))
					{
						surcharge = 0.0;
					}
					if (dailySurcharge == 1)
					{
						if (adults+children <= minOcc)
						{
							total = (minOcc * price  + surcharge ) * durationMultiplier;
						}
						else
						{
							total = ((adults + children) * price  + surcharge ) * durationMultiplier;
						}
					}
					else
					{
						if (adults+children <= minOcc)
						{
							total = minOcc * price  * durationMultiplier + surcharge;
						}
						else
						{
							total = (adults + children) * price  * durationMultiplier + surcharge;
						}
					}
			}
				
			}//concessions exist - apply it
			else
			{
				//get concessions into an array
				concession = concession.substring(3, concession.length);
				//alert(concession);
				var concessionArray = concession.split("|||");
				arrayLength = concessionArray.length;

				var concessionArrF = new Array (arrayLength)
				for (var c = 0; c < arrayLength; c++)
				{
				//	alert("hello: " + c);
					concessionArrF[c] = concessionArray[c].split("::");
				}
				if (isNaN(surcharge))
				{
					surcharge = 0.0;
				}
				childPrice = 0;
				//alert (children);
				if (children > 0)
				{//concessions are required
					childProcessed = 0;
					if (adults < minAdult)
					{
						adultCount = minAdult;
						childCount = children - (minAdult - adults);
					}
					else
					{
						adultCount = adults;
						childCount = children;
					}
					
					if (dailySurcharge == 1)
					{
						total = (adultCount * price  + surcharge) * durationMultiplier;
					}
					else
					{
						total = adultCount * price  * durationMultiplier + surcharge;
					}
					

					for (var i = 1; i <= childCount; i++)
					{
						childAge = parseInt(eval(fName + "('con_"+ i + "_" + eName + "').value"));
						if (isNaN(childAge))
						{//child age not specified
								childPrice = childPrice + price * durationMultiplier;
								childProcessed = childProcessed + 1;
						}
						else
						{
							for (var c1 = 0; c1 < concessionArray.length; c1++)
							{
									if (childAge >= parseInt(concessionArrF[c1][1]) && childAge <= parseInt(concessionArrF[c1][2]))
									{
										//check if we exceeded applicable concessions
//										alert (childProcessed + ", " + concessionLimit)
										if (childProcessed < concessionLimit)
										{
											//alert(concessionArrF[c1][0] + " " + concessionArrF[c1][1] + " " + concessionArrF[c1][2] + " " + concessionArrF[c1][3] + " " + concessionArrF[c1][4]);
											childPrice = childPrice + parseFloat(concessionArrF[c1][3]) * durationMultiplier;
										}
										else
										{
											if (parseFloat(concessionArrF[c1][4])> 0)
											{
												//apply secondary concession price
												childPrice = childPrice + parseFloat(concessionArrF[c1][4]) * durationMultiplier;
											}
											else
											{
												//secundary concession is 0 apply adult pricing
												childPrice = childPrice + price * durationMultiplier;
											}
										}
										childProcessed = childProcessed + 1;
									}
							}
						}
					}
					if ((childCount - childProcessed) > 0)
					{
						//add any children noneligable for concession as adult price
						childPrice = childPrice + (childCount - childProcessed) * price * durationMultiplier;					
					}
					total = childPrice + total;
					//check if (adults + children <= minOcc) and adjust as per Sue's choice (min adult * adult price + shildprice + min concession * (minOcc - adults - children)
					if (childCount + adultCount < minOcc)
					{
						additionalCharge = (minOcc - childCount - adultCount) * parseFloat(concessionArrF[0][3]) * durationMultiplier
					}
					total = total + additionalCharge

				}
				else
				{//concessions are not required
					if (pricePerPerson == '0')
					{//pricing is per room
						if (adults + children <= minOcc)
						{
							total = price * durationMultiplier;
						}
						else
						{
							total = secondaryPrice * durationMultiplier;
						}
					}//pricing is per person
					else
					{
						if (isNaN(surcharge))
						{
							surcharge = 0.0;
						}
						if (dailySurcharge == 1)
						{
							if (adults+children <= minOcc)
							{
								total = (minOcc * price  + surcharge ) * durationMultiplier;
							}
							else
							{
								total = ((adults + children) * price  + surcharge ) * durationMultiplier;
							}
						}else
						{
							if (adults+children <= minOcc)
							{
								total = minOcc * price  * durationMultiplier + surcharge;
							}
							else
							{
								total = (adults + children) * price  * durationMultiplier + surcharge;
							}
						}
					}
				}

			}

			if (discount == '')
			{//no applicable discounts
				total = total
			}
			else
			{//discounts exist - apply it
				//get concessions into an array
				discount = discount.substring(3, discount.length);
				//alert(concession);
				var discountArray = discount.split("|||");
				var discountArrF = new Array (discountArray.length)
				for (var c = 0; c < discountArray.length; c++)
				{
					discountArrF[c] = discountArray[c].split("::");

					if (duration == parseInt(discountArrF[c][0]))
					{//apply discount
						//alert(total);
						total = total * (1 - parseFloat(discountArrF[c][1])/100);
					}
				}

			}
//			alert('total: ' + total);
//			alert (currency(total));
			eval(fName + '("span_price_' + eName + '").value="' + currency(total) + '"');
			eval(fName + '("total_' + eName + '").value=' + total);
//			alert(total);
			return total;
		}
		
		function setCart(eName, fName)
		{
			var temp = getPrice(eName, fName)
			if (!temp)
			{
				return false;
			}
/*
			var cart = eval(fName + "('cart_" + eName + "').value");
			var cartFlag = eval(fName + "('cart_f_" + eName + "').value");
//			alert(cart);
//			alert(cartFlag);

			if (cart == 'Add to Cart')
			{
				eval(fName + "('cart_" + eName + "').value = 'Remove from Cart'");
				eval(fName + "('cart_f_" + eName + "').value='true'");
			}
			else
			{
				eval(fName + "('cart_" + eName + "').value = 'Add to Cart'");
				eval(fName + "('cart_f_" + eName + "').value='false'");
			}
*/
		}

		function currency(anynum) {
		   //-- Returns passed number as string in $xxx,xxx.xx format.
		   var workNum = Math.abs((Math.round(anynum*100)/100));
		   var workStr = "" + workNum;
			
			if (workStr.indexOf(".") == -1)
			{
				//alert("add decimal point");
				workStr = workStr + ".00"
			}
			var dStr = workStr.substr(0,workStr.indexOf("."));
			var dNum = parseInt(dStr);
			var pStr = workStr.substr(workStr.indexOf("."));

			while (pStr.length < 3)
			{
				pStr = "" + pStr + "0";
			}

		   //--- Adds comma in thousands place.
			if (dNum >= 1000) 
			{
			  var dLen = dStr.length;
			  var dStr = parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen);
			}

		   //-- Adds comma in millions place.
			if (dNum >= 1000000) 
			{
			  dLen = dStr.length;
			  dStr = parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen);
			}

			var retval = dStr + pStr;
		   //-- Put  - in front of negative numbers
			if (anynum<0) 
			{
				retval = "- $" + retval;
			}
			else
			{
				retval = "$" + retval;
			}

		  //anynum = "$" + anynum;
		   return retval;
		}

	function displayAgeBoxes(f)
	{
		
		//if the user clicks back browser button, display children's ages
		var RoomList = f.RoomList.value;
		var RoomArray = RoomList.split("|||");
		var NoRooms = RoomArray.length - 1

		for (var i=0; i <= NoRooms; i++)
		{
			 if (eval(f.name + "('c_" + RoomArray[i] + "').value") > 0)
			 {
				var step1 = displayEntry(RoomArray[i], f.name);
				if (!step1)
					return false;
			 }
			//deal with cart buttons
/*			var cart = eval(f.name + "('cart_" + RoomArray[i] + "').value");
			var cartFlag = eval(f.name + "('cart_f_" + RoomArray[i] + "').value");
			if (cartFlag == 'true')
			{
				eval(f.name + "('cart_" + RoomArray[i] + "').value = 'Remove from Cart'");
			}
			else
			{
				eval(f.name + "('cart_" + RoomArray[i] + "').value = 'Add to Cart'");
			}
*/		}
		return true;
	}

/////////////////////////////////////////////////////
function trim(s) 
{
	while (s.substring(0,1) == ' ') 
	{
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') 
	{
		s = s.substring(0,s.length-1);
	}
	return s;
}
//////////////////////////
function checkForm(f)
{
//	alert("checking form");
	if (trim(f.QEmail.value) == '')
	{
		alert("Contact Email must be entered prior to saving the cart.\n\nPlease ensure this field is entered and entered correctly in order to continue.");
		f.FormType.value='quoteDetails'
		f.QEmail.focus();
		return false;
	}else
	{
		if (!checkEmail(f.QEmail.value))
		{
			alert (f.QEmail.value + " is not a valid email address.\n\nPlease correct the email address entry and try again.");
			f.FormType.value='quoteDetails'
			f.QEmail.focus();
			return false;
		}
		else
			return true;
	}
	if (trim(f.QPhone.value) == '')
	{
		alert("Contact Phone is a compulsory field. \n\nPlease ensure this field is entered and entered correctly in order to continue.");
		f.QPhone.focus();
		return false;
	}
	if (trim(f.QName.value) == '')
	{
		alert("First name of the person requesting the quote must be entered prior to saving the quote. \n\nPlease ensure this field is entered and entered correctly in order to continue.");
		f.QName.focus();
		f.FormType.value='quoteDetails'
		return false;
	}
	if (trim(f.QSurname.value) == '')
	{
		alert("Surname must be entered in order to save the cart. \n\nPlease ensure this field is entered and entered correctly in order to continue.");
		f.QSurname.focus();
		f.FormType.value='quoteDetails'
		return false;
	}
	
	//checking staying at
	/*
	if (f.StayingAt.value != "NA")
	{
		if (trim(f.StayingAt.value) == '')
		{
			alert('Please specify accommodation house you will be staying at prior to saving the quote.');
			f.selStayingAt.focus();
			return false;
		}
	}
	*/
	return true;
}
//////////////////////////////
function checkEmail(myString) 
		{
			var newString = myString.match(/\b(^(\S+@\S+)+((.com)|(.net)|(.edu)|(.mil)|(.gov)|(.org)|(\..{2,2}))$)\b/gi);
			if (!newString) 
				return false;
			else 
			{
				return true;
			}
		}

///////////////////////////
function checkCancel(QID)
{
	var temp = confirm("Are you sure you wish to cancel cart: " + QID + "?\n\nOnce a cart is canceled you will have no further access to it.");
	if (temp)
	{
		document.location="quote.asp?v=c&qid=" + QID
	}
}////////////////////////////////////
function checkPriceForm(f)
{
//	alert ("checking form");
	var RoomList = f.RoomList.value;
	if (RoomList.lastIndexOf('|||') == (RoomList.length - 3))
	{	
		RoomList = RoomList.substring(0, RoomList.length - 3)
	}
	var RoomArray = RoomList.split("|||");
	var NoRooms = RoomArray.length;

	var noneSelected = true

	for (var i=0; i < NoRooms; i++)
	{
		  if (eval(f.name + "('cart_" + RoomArray[i] + "').checked"))
		 {
			noneSelected = false;

			var step1 = displayEntry(RoomArray[i], f.name);
			if (!step1)
				return false;
			var step2 = checkConfig(RoomArray[i], f.name);
			if (!step2)
				return false;
			var step3 = getPrice(RoomArray[i], f.name);
			if (!step3)
				return false;
			if (isNaN(step3))
				return false;
			var step4 = getChildrenAge(RoomArray[i], f.name);
			if (!step4)
				return false;
		 }
	}
	if (noneSelected) 
	{
		alert("There are no rooms in your shopping cart.\n\nPlease add at least one room to your shopping cart in order to continue.")
		return false;
	}
	return true;

}
//////////////////////////////////////////
function updateStayingAt(f)
{
		//alert (f.selStayingAt.selectedIndex);

		if (f.selStayingAt(f.selStayingAt.selectedIndex).value == 'other')
		{
				f.StayingAt.value = '';
				document.all("s_StayingAt").style.visibility = 'visible';
		}
		else
		{
				f.StayingAt.value = f.selStayingAt(f.selStayingAt.selectedIndex).value;
				document.all("s_StayingAt").style.visibility = 'hidden';
		}
}
