var startDateObj; 

function setDates() {


	var startDay = document.forms[0].startDay.options[document.forms[0].startDay.selectedIndex].value;
	var startMonthAndYear = document.forms[0].startMonthAndYear.options[document.forms[0].startMonthAndYear.selectedIndex].value;
	var startDateParts = startMonthAndYear.split("|");

	var endDay = document.forms[0].endDay.options[document.forms[0].endDay.selectedIndex].value;
	var endMonthAndYear = document.forms[0].endMonthAndYear.options[document.forms[0].endMonthAndYear.selectedIndex].value;
	var endDateParts = endMonthAndYear.split("|");

	startMonth = startDateParts[0];
	startMonth  = getMonthNumber(startMonth);

	endMonth = endDateParts[0];
	endMonth = getMonthNumber(endMonth);

	var startDate = startDay + "/" + startMonth + "/" + startDateParts[1]
	var endDate = endDay + "/" + endMonth + "/" + endDateParts[1]

	document.forms[0].startDate.value = startDate;
	document.forms[0].endDate.value = endDate;


}

function checkBooking(pID) {
	
	var error = ""

	var startDay = document.forms[0].startDay.options[document.forms[0].startDay.selectedIndex].value;
	var startMonthAndYear = document.forms[0].startMonthAndYear.options[document.forms[0].startMonthAndYear.selectedIndex].value;
	var startDateParts = startMonthAndYear.split("|");

	var endDay = document.forms[0].endDay.options[document.forms[0].endDay.selectedIndex].value;
	var endMonthAndYear = document.forms[0].endMonthAndYear.options[document.forms[0].endMonthAndYear.selectedIndex].value;
	var endDateParts = endMonthAndYear.split("|");

	startMonth = startDateParts[0];
	startMonth  = getMonthNumber(startMonth);

	endMonth = endDateParts[0];
	endMonth = getMonthNumber(endMonth);

	var startDate = startDay + "/" + startMonth + "/" + startDateParts[1]
	var endDate = endDay + "/" + endMonth + "/" + endDateParts[1]
	//alert ("dateTest = " + dateTest);
	
	if ((startDay=='') || (startMonthAndYear=='') || (endDay=='') || (endMonthAndYear=='')) {
		error = error + "Please complete the Start Date and the End Date\n";	
	} else {
		if (validateDate(startDate)==false) {
			error = error + "The Start Date is invalid\n";	
		}
		if (validateDate(endDate)==false) {
			error = error + "The End Date is invalid\n";	
		}
		if (error=="") {
			//alert ("test=" + parseInt(startMonth-1));
			startDateObj = new Date(startDateParts[1] + "/" + parseInt(startMonth) + "/" + startDay);
			endDateObj = new Date(endDateParts[1] + "/" + parseInt(endMonth) + "/" + endDay)
			//alert ("start=" + startDateObj.getTime() + " endTime=" + endDateObj.getTime());
			if (startDateObj.getTime() >= endDateObj.getTime()) {
				error = error + "The Start Date is greater than or equal to the End Date\n";
			}
			today = new Date();
			//alert ("today=" + today + " startTime=" + startDateObj);
			if ( today > startDateObj ) {
				error = error + "The Start Date is before today's date\n";
			}
			if (days_between(startDateObj, endDateObj) < 7) {
				error = error + "The duration of your stay is less than 7 days\n";
			}
		}	
	}
		
	if (error!="") {
		alert(error);
		//document.forms[0].startDate.value = "";
		//document.forms[0].endDate.value = "";
	} else {
	
		//check the dates are available if booked make sure they are not already booked
	    if (!window.ActiveXObject) {
		    //alert("Firefox");
	    	xmlHttpReq = new XMLHttpRequest();  
	   	} else {
		    //alert("Microsoft"); 
	    	xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
		}


		var strURL = "/administration/CheckDupeDate.asp"
		var params = "ID=" + pID + "&startDate=" + startDate + "&endDate=" + endDate
	    xmlHttpReq.open('POST',strURL,true);
	    xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	    xmlHttpReq.onreadystatechange = function() {
	    
	        if (xmlHttpReq.readyState == 4) { //ready state 4 means its complete.
	            answer = xmlHttpReq.responseText;
	    		//alert ("answer = " + answer);
	    		

				//var answer = checkDupeDate(pID, startDate, endDate)
				//alert ("answer=" + answer);
				if (answer != "") {
					error = error + "Some, or all, of these dates are not available\n";
				}
				
				if (error!="") {
					alert(error);
				} else {
				

					//Now check that the start date and end date start and finish on the correct DAY !
					answer = "";
					var strURL = "/administration/CheckBookingDay.asp"
					var params = "ID=" + pID + "&startDate=" + startDate + "&endDate=" + endDate
				    xmlHttpReq.open('POST',strURL,true);
				    xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				    xmlHttpReq.onreadystatechange = function() {
				    
				        if (xmlHttpReq.readyState == 4) { //ready state 4 means its complete.
				            answer = xmlHttpReq.responseText;
							//alert(answer);

							if (answer == "") {
								error = error + "Pricing information has not been set for these dates.\n For more information please contact us directly.\nYou will find all our contact details on our 'Contact Us' page.\n";
							}
							
							if (isNumeric(answer) == false) {
								error = error + "During this period the property rents from " + answer + " to " + answer + ", please ensure your booking starts and finishes on a " + answer + ".\n";
							}
							
							if (error!="") {
								alert(error);
							} else {
							
								pID = document.getElementById("secDep_row");
								pID.style.display = "none";
								pID = document.getElementById("costTotalDisplay_row");
								pID.style.display = "none";
							
								document.forms[0].startDate.value = startDate;
								document.forms[0].endDate.value = endDate;
								pID = document.getElementById("bookingForm");
								pID.style.display = "block";
								
								pID = document.getElementById("arrDateDisplay");
								pID.innerHTML = startDate;
								pID = document.getElementById("arrDate");
								pID.value = startDate;
								pID = document.getElementById("depDateDisplay");
								pID.innerHTML = endDate;
								pID = document.getElementById("depDate");
								pID.value = endDate;
				
								//set the paypal premium if applicable
								var premium = 1.0
								var methodID = document.forms[0].method.options[document.forms[0].method.selectedIndex].value;
								if (methodID == 3) {
									var premium = 1.015
								}
								
								//how many days are there between the dates
								var daysBooked = days_between(endDateObj, startDateObj)
								//alert ("daysBooked=" + daysBooked);
								exRate = document.forms[0].exRate.value;
								totalCostPounds = Math.round( daysBooked * (answer/7) / exRate * premium);
								totalCostEuros = Math.round((daysBooked * (answer/7) * premium));
				
								pID = document.getElementById("rentalPriceDisplay");
								pID.innerHTML = "€" + totalCostEuros;
								pID = document.getElementById("rentalPricePounds");
								pID.value = totalCostPounds;
								pID = document.getElementById("rentalPriceEuros");
								pID.value = totalCostEuros;
				
								
								//is today's date less than 8 weeks (56 days) before departure
								var daysLeft = days_between(startDateObj, new Date())
								//alert ("daysLeft=" + daysLeft);
								if (daysLeft >= 56) {
								
									totalCostPounds_today = Math.round( daysBooked * (answer/7) / exRate * 0.25 * premium);
									totalCostEuros_today = Math.round( daysBooked * (answer/7) * 0.25 * premium);
									totalCostPounds_bal = Math.round( daysBooked * (answer/7) / exRate * 0.75 * premium);
									totalCostEuros_bal = Math.round( daysBooked * (answer/7) * 0.75 * premium);
				
									pID = document.getElementById("secDep_row");
									pID.style.display = "none";
									pID = document.getElementById("secDepPaid");
									pID.value = "";
									pID = document.getElementById("costTotalDisplay_row");
									pID.style.display = "block";
									pID = document.getElementById("costTotalDisplay_bal");
									pID.innerHTML = "€" + totalCostEuros_bal;
									pID = document.getElementById("costTotalPounds_bal");
									pID.value = totalCostPounds_bal
									pID = document.getElementById("costTotalEuros_bal");
									pID.value = totalCostEuros_bal
									
								} else {
									pID = document.getElementById("secDep_row");
									pID.style.display = "block";
									pID = document.getElementById("secDepPaid");
									pID.value = "Y";
									//totalCostPounds_today = Math.round(( parseInt(totalCostPounds) + parseInt(document.forms[0].secDepPounds.value) ) * premium); 
									//totalCostEuros_today = Math.round(( parseInt(totalCostEuros) + parseInt(document.forms[0].secDepEuros.value) ) * premium);
									totalCostPounds_today = Math.round( parseInt(totalCostPounds)); 
									totalCostEuros_today = Math.round( parseInt(totalCostEuros));
								}				

								pID = document.getElementById("costTotalDisplay_today");
								pID.innerHTML = "€" + totalCostEuros_today;
								pID = document.getElementById("costTotalPounds_today");
								pID.value = totalCostPounds_today
								pID = document.getElementById("costTotalEuros_today");
								pID.value = totalCostEuros_today

							}
						}			
					}
	   				xmlHttpReq.send(params);
				}
	        }
		}
	   	xmlHttpReq.send(params);
	}

	return true;

}


function checkBookingForm() {
	
	error = ""

	var clientName = trim(removeMultipleWhiteSpaces(document.forms[0].clientName.value));
	var clientEmail = trim(removeAllWhiteSpaces(document.forms[0].clientEmail.value));
	var clientAddress = trim(document.forms[0].clientAddress.value);
	var clientPostCode = trim(removeAllWhiteSpaces(document.forms[0].clientPostCode.value));
	var clientTel = trim(removeAllWhiteSpaces(document.forms[0].clientTel.value));
	var clientMob = trim(removeAllWhiteSpaces(document.forms[0].clientMob.value));
	var peopleName1 = document.forms[0].peopleName1.value;
	
	//var curr = document.forms[0].curr.options[document.forms[0].curr.selectedIndex].value;
	var curr = 2;
	var method = document.forms[0].method.options[document.forms[0].method.selectedIndex].value;
	
	document.forms[0].clientName.value = clientName;
	document.forms[0].clientEmail.value = clientEmail;
	document.forms[0].clientAddress.value = clientAddress;
	document.forms[0].clientPostCode.value = clientPostCode;
	document.forms[0].clientTel.value = clientTel;
	document.forms[0].clientMob.value = clientMob;

	if (clientName == "") {
		error = error + "Please enter you name\n";
	}
	if (clientEmail == "") {
		error = error + "Please enter you email\n";
	} else if (isEmailValid(clientEmail) == false) {
		error = error + "Pleas enter a real email address\n";
	}
	if (clientAddress == "") {
		error = error + "Please enter your address\n";
	}
	if (clientPostCode == "") {
		error = error + "Please enter your postcode\n";
	}
	if (clientTel == "") {
		error = error + "Please enter your telephone number\n";
	}
	if (clientMob == "") {
		error = error + "Please enter your mobile number\n";
	}
	if (peopleName1 == "") {
		error = error + "Please enter the people in your booking\n";
	}
	if (curr == "") {
		error = error + "Please choose a payment currency\n";
	}
	if (method == "") {
		error = error + "Please choose a payment method\n";
	}

	if (document.forms[0].terms.checked == false) {
		error = error + "Please confirm you have read and agree to the Terms & Conditions\n";
	}
	if (error != "") {
		alert(error)
	} else {
		restOfPage.style.display='none';
		progressBar.style.display='block';
		document.forms[0].submit();
	}

}


function validateDate(fld) {
	//alert ("Field=" + fld);
    var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
    //var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 30/2/2000 would not be accepted.\nFormay dd/mm/yyyy.';
    if (fld.match(RegExPattern)) {
        return true; 
    } else {
    	return false;
        //alert(errorMessage);
    } 
}

function getMonthNumber(strMonth) {

	if (strMonth == "Jan") {
		strMonth = 1
	} else if (strMonth == "Feb") {
		strMonth = 2
	} else if (strMonth == "Mar") {
		strMonth = 3
	} else if (strMonth == "Apr") {
		strMonth = 4
	} else if (strMonth == "May") {
		strMonth = 5
	} else if (strMonth == "Jun") {
		strMonth = 6
	} else if (strMonth == "Jul") {
		strMonth = 7
	} else if (strMonth == "Aug") {
		strMonth = 8
	} else if (strMonth == "Sep") {
		strMonth = 9
	} else if (strMonth == "Oct") {
		strMonth = 10
	} else if (strMonth == "Nov") {
		strMonth = 11
	} else if (strMonth == "Dec") {
		strMonth = 12
	}
	return strMonth;
}


function buildPayOptions() {

		var payOptions = document.getElementById("method");
		payOptions.options.length = 0;

		payOptions.options[payOptions.options.length] = new Option("", "");

		//if there are less than 8 weeks left before arrival then only show the credit card option
		var daysLeft = days_between(startDateObj, new Date())
		//alert ("daysLeft=" + daysLeft);
		if (daysLeft > 56) {
			payOptions.options[payOptions.options.length] = new Option("Cheque", "2");
		}
		
		payOptions.options[payOptions.options.length] = new Option("Bank Transfer", "1");
		payOptions.options[payOptions.options.length] = new Option("Credit Card (+1.5%)", "3");

}


//Are there ONLY numbers in the text string
function isNumeric(vText)
{
	if (vText.match(/\D+/gim)) {
   		return false;
   	} else {
   		return true;
   	}
}


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 = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}


//********************************************************************************************************************************
//  COMMON FUNCTIONS
//********************************************************************************************************************************


//trim
function trim(vText)
{
	vText = vText.replace(/^\s+/g, '').replace(/\s+$/g, '');
	return vText;
}

//remove all white space
function removeAllWhiteSpaces(vText)
{
	vText = vText.replace(/\s+/g, '');
	return vText;
}

//set multiple white spaces as a single white space
function removeMultipleWhiteSpaces(vText)
{
	vText = vText.replace(/\s+/g, ' ');
	return vText;
}


//is the email address valid
function isEmailValid(vText)
{
	if (vText.match(/[A-Z0-9._%-]+@[A-Z0-9._%-]+/gi)) {
   		return true;
   	} else {
		return false;
   	}
}

//diable the backspace except in a text area or input box
document.onkeydown = keyCatcher;
function keyCatcher() {
	var e = event.srcElement.tagName;
	
	if (event.keyCode == 8 && e != "INPUT" && e != "TEXTAREA") {
		event.cancelBubble = true;
		event.returnValue = false;
	}
}

