var interval;
var tries = 1;
var delay = 8000;

function checkConfirmation(id) {
	clearInterval(interval);
	var xmlhttp = InstanceXMLHttpRequest();
	xmlhttp.open('POST', '/confirmation.php?id=' + id + "&tries=" + tries, true);

	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	xmlhttp.onreadystatechange = function() {		
		if (xmlhttp.readyState == 4) {
			//alert(xmlhttp.responseText);
			var result = xmlhttp.responseText;
			if (result != "") {
				var values = result.split("&");
				if (values.length == 4) {
					var booking_id = values[0].split("=");
					var assigned_room = values[1].split("=");
					var accepted = values[2].split("=");
					var reason = values[3].split("=");
					
					booking_id = booking_id[1];
					assigned_room = assigned_room[1];
					accepted = accepted[1];
					reason = reason[1];
					
					if (accepted == "A") {
						var message = "You booking has been confirmed:<br /><br />";
						message += "<strong>Booking reference:</strong> " + booking_id + "<br />";
						message += "<strong>Room assigned:</strong> " + assigned_room + "<br />";
						
					} else {
						var message = "You booking has been rejected:<br /><br />";
						message += "<strong>Booking reference:</strong> " + booking_id + "<br />";
						message += "<strong>Reason:</strong> " + reason + "<br />";
					}
					
					writeLayer("message_booking", message);
					
				} else {
					writeLayer("message_booking", "<span id='message_booking'>There was a problem with your booking, please contact the hotel using the phone numbers you will find on the 'How to find us' page.</span>");

				}
				
			} else {
				tries++;
				if (tries > 5) {
					writeLayer("message_booking", "<span id='message_booking'>There was a problem with your booking, please contact the hotel using the phone numbers you will find on the 'How to find us' page.</span>");
					
				} else {
					writeLayer("message_booking", "<span id='message_booking'>Please wait until we confirm the booking... (" + tries + ")<br /><img src='support/img/global/loading.gif' alt='wait...' /><script>delayConfirmation(" + id + ");</script></span>");
					interval = setInterval("checkConfirmation(" + id + ")",delay);
				}
			}			
		}
	}
	xmlhttp.send(null);
}

function delayConfirmation(id) {
	interval = setInterval("checkConfirmation(" + id + ")",delay);
}

function sendSubscribe() {
	var errors = "";
		
	if (document.forms["subscribeform"]["name"].value == "") {
		errors += "Name\n";
	}
	if (!isValidEmail(document.forms["subscribeform"]["email"].value)) {
		errors += "Email\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["subscribeform"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
}

function sendBooking(use_live) {
	var errors = "";
		
	if (document.forms["bookingform"]["firstname"].value == "") {
		errors += "First Name\n";
	}
	if (document.forms["bookingform"]["surname"].value == "") {
		errors += "Surname\n";
	}
	if (document.forms["bookingform"]["address1"].value == "") {
		errors += "Address 1\n";
	}
	if (document.forms["bookingform"]["address2"].value == "") {
		errors += "Address 2\n";
	}
	if (document.forms["bookingform"]["town"].value == "") {
		errors += "Town\n";
	}
	if (document.forms["bookingform"]["postcode"].value == "") {
		errors += "Post Code\n";
	}
	if ((document.forms["bookingform"]["phone"].value == "") && (document.forms["bookingform"]["mobile"].value == "")) {
		errors += "Phone or Mobile\n";
	}
	if (!isValidEmail(document.forms["bookingform"]["email"].value)) {
		errors += "Email\n";
	}
	
	if (use_live) {
		if (!document.forms["bookingform"]["samedetails"].checked) {
			if (document.forms["bookingform"]["firstname_card"].value == "") {
				errors += "Card Holder First Name\n";
			}
			if (document.forms["bookingform"]["surname_card"].value == "") {
				errors += "Card Holder Surname\n";
			}
			if (document.forms["bookingform"]["address1_card"].value == "") {
				errors += "Card Holder Address 1\n";
			}
			if (document.forms["bookingform"]["address2_card"].value == "") {
				errors += "Card Holder Address 2\n";
			}
			if (document.forms["bookingform"]["town_card"].value == "") {
				errors += "Card Holder Town\n";
			}
			if (document.forms["bookingform"]["postcode_card"].value == "") {
				errors += "Card Holder Post Code\n";
			}
			if ((document.forms["bookingform"]["phone_card"].value == "") && (document.forms["bookingform"]["mobile"].value == "")) {
				errors += "Card Holder Phone or Mobile\n";
			}
			if (!isValidEmail(document.forms["bookingform"]["email_card"].value)) {
				errors += "Card Holder Email\n";
			}
		}
	
		if (document.forms["bookingform"]["cardnumber"].value == "") {
			errors += "Card Number\n";
		}
		if (document.forms["bookingform"]["securitynumber"].value == "") {
			errors += "Security Number\n";
		}
	}
	
	if (errors == "") {
		if (use_live) {
			var cardnumber = document.forms["bookingform"]["cardnumber"].value;
			var cardtype = document.forms["bookingform"]["cardtype"].value;
			var validto_month = document.forms["bookingform"]["validto_month"].options[document.forms["bookingform"]["validto_month"].selectedIndex].value;
			var validto_year = document.forms["bookingform"]["validto_year"].options[document.forms["bookingform"]["validto_year"].selectedIndex].value;
			
			if (checkCreditCard (cardnumber,cardtype)) {
				//alert ("Credit Card has a valid format");
				document.forms["bookingform"].submit();
			} else {
				alert(ccErrors[ccErrorNo]);
			}
		} else {
			document.forms["bookingform"].submit();
		}
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
	
}

function sameDetails(checked)
{
	if (checked) {
		displayLayer("cardholderpanel", false);
	} else {
		displayLayer("cardholderpanel", true);
	}
}


function bookRoom()
{
	document.forms["availabilityform"].submit();
}

function checkAvailability()
{
	var errors = "";
		
	if (document.forms["availabilityform"]["hotel"].selectedIndex == 0) {
		errors += "Select hotel\n";
	}
	if (!isValidDate(document.forms["availabilityform"]["date"].value,'DMY')) {
		errors += "Arrival date\n";
	}
	if (document.forms["availabilityform"]["nights"].selectedIndex == 0) {
		errors += "Number of nights\n";
	}
	if (document.forms["availabilityform"]["people"].selectedIndex == 0) {
		errors += "Number of people\n";
	}
	
	if (errors == "") {
		//return true;
		document.forms["availabilityform"].submit();
	} else {
		alert("Please review the following information:\n\n" + errors);
		//return false;
	}
	
}

function isValidEmail(email) {
	var re = /^ *([a-z0-9_-]+\.)*[a-z0-9_-]+@(([a-z0-9-]+\.)+(com|net|org|mil|edu|gov|arpa|info|biz|inc|name|[a-z]{2})|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) *$/;
	return (re.test(email.toLowerCase()));
}

function isValidUsernamePassword(value) {
	re = /^\w+$/;
	return (re.test(value.toLowerCase()));
}

String.prototype.trim = function (){
	return this.replace(/(^\s+)/g, "").replace(/(\s+$)/g, "");
}

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{4}(\-)\d{1,2}\1\d{1,2}$/

   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-)\d{4}\1\d{1,2}$/

   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-)\d{1,2}\1\d{4}$/

   }
   if ( reg1.test(dateStr) == false ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else 
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

function popup(w,h,t,l,url,winName,status,toolBar,scrollBars,resizable) {
	if (scrollBars == undefined) scrollBars = "auto";
	if (resizable == undefined) resizable = "no";
  	var sWid = screen.width;
  	var sHi = screen.height;
	var wid = w;
	var hi = h;
	if ((t == 0) && (l == 0)) {
		var tp = (sHi/2)-(hi/2);
		var lft = (sWid/2)-(wid/2);
	} else {
		var tp = t;
		var lft = l;	
	}
	if (scroll && document.all && (navigator.userAgent.indexOf("Mac") > -1)) wid = wid+17;
	newwin=window.open(url,winName,"width=" + wid + ",height=" + hi + ",status=" + status + ",scrollbars=" + scrollBars + ",toolbar=" + toolBar + ",resizable=" + resizable + ", top = "+ tp +", left ="+ lft + ", screenX=" + lft +", screenY= "+tp);
	newwin.focus();
}

function changeClassName(name, className){
	var obj = document.getElementById(name);
	obj.className = className;
}


function writeLayer(name, txt){
	var layer = document.getElementById(name);
	layer.innerHTML = txt;
}

function displayLayer(name, visible){
	var foc = document.getElementById(name);
	if (foc) {
		if (visible) {
			foc.style.display='block';
		} else {
			foc.style.display='none';
		}
	}
}

function setStyle(name, property, value){
	var foc = document.getElementById(name);
	if (foc) {
		foc.style[property] = value;
	}
}

function InstanceXMLHttpRequest() {
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	return req;
}