//********************************************************************
// Global Variables
//********************************************************************

	dateToday = new Date();


//********************************************************************
// Search
//********************************************************************


	function checkSearch() 
	{ 

		strError = "";

		getArrAndDepDates();
		
		if (document.getElementById('bedMin').value > document.getElementById('bedMax').value) {
			strError = strError + "The minimum number of bedrooms is GREATER than the maximum number of bedrooms\n"; 
		}

		isDateDepGreaterThanDateArr();
		
		if (strError != "") {
			alert("Sorry, but we cannot process your request due to the following errors.\n\n" + strError + "\n\nPlease correct these errors and try again.");
		} else {
			document.getElementById('showVillasButtonClicked').value = 'yes';
			document.forms[0].submit();
		}

	}


//********************************************************************
// MyVillas
//********************************************************************


	//add villa to the cookie and/or search list
	function myVillasAdd(pId) 
	{ 
	
		var increaseCount = false;
		
		//first check the Villas_list cookie exists
		pCookie_list = getCookie("Villas_list");
		
		if (pCookie_list == "") {
			//alert("new");
			setCookie ("Villas_list", pId, 365)
			increaseCount = true;
		} else if ( inStringSpace(pCookie_list, pId) ) {
			//alert("already exits");
			//do nothing
		} else if (pCookie_list.length <=2000) {
			//alert("add");
			setCookie ("Villas_list", pCookie_list + '_' + pId, 365)
			increaseCount = true;
		} else {
			alert("Sorry, but you have reached the maximum number of villas allowed in \'MyVillas\'.\n");
		}
	
		if (increaseCount) {
			pID = document.getElementById(pId);
			pID.innerHTML = "Added to 'My Villas'";
			pID = document.getElementById('myVillasCount');
			villaCount = parseInt(pID.innerHTML) + 1;
			pID.innerHTML = villaCount;
		}

	}



	//remove annonce from the cookie and/or search list
	function myVillasDelete(pId) 
	{ 

		//alert(pId);
	
		var answer = confirm ("Are you sure you want to remove this villa ?")
		if (answer) {

			pCookie_list = getCookie("Villas_list");
			setCookie ("Villas_list", pCookie_list.replace(pId + '_', ''), 365);
			pCookie_list = getCookie("Villas_list");
			setCookie ("Villas_list", pCookie_list.replace('_' + pId, ''), 365);
			pCookie_list = getCookie("Villas_list");
			setCookie ("Villas_list", pCookie_list.replace(pId, ''), 365);
			pCookie_list = getCookie("Villas_list");
			//alert(pCookie_list);
			
			//reduce the count
			pID = document.getElementById('myVillasCount');
			villaCount = parseInt(pID.innerHTML) - 1;
			pID.innerHTML = villaCount;

			location.reload(true);

		}			

	}


//********************************************************************
// Enquiry
//********************************************************************

	function checkEnquiry() {
	
		strError = "";
		strEnquireName = trim(removeMultipleWhiteSpaces(document.getElementById('enquireName').value));
		strEnquireEmail = trim(removeAllWhiteSpaces(document.getElementById('enquireEmail').value));
		strEnquireTel = trim(removeAllWhiteSpaces(document.getElementById('enquireTel').value));
		strEnquireSummary = trim(removeMultipleWhiteSpaces(document.getElementById('enquireSummary').value));		
		iEnquireSource = document.getElementById('enquireSource').value;		
		
		document.getElementById('enquireName').value = strEnquireName;
		document.getElementById('enquireEmail').value = strEnquireEmail;
		document.getElementById('enquireTel').value = strEnquireTel;
		document.getElementById('enquireSummary').value = strEnquireSummary;
		
		if (strEnquireName == "") {
			strError = strError + "Please enter your name\n"; 
		}
		if (strEnquireEmail == "") {
			strError = strError + "Please enter your email address\n"; 
		} else if (isEmailValid(strEnquireEmail) == false) {
			strError = strError + "Please enter a valid email address\n"; 
		}
		if (strEnquireSummary == "") {
			strError = strError + "Please enter your message\n"; 
		}
		if (iEnquireSource == "0") {
			strError = strError + "Please tell us how you heard about us\n"; 
		}

		if (strError == "") {
			getCaptcha();
		}
			
		if (strError != "") {
			alert(strError);
		} else {
			alert("Thank you for submitting your enquiry.\nOne of our representatives will contact you shortly.");
			document.forms[0].submit();
		}
	}


//********************************************************************
// Cookies
//********************************************************************

	function getCookie(c_name)
	{
		if (document.cookie.length>0)
		{
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		return "";
	}


	function setCookie(c_name,value,expiredays)
	{
		//alert("Set Cookie = "+ value);
		document.cookie='Villas_list=' + value + '; expires=Mon 31-Jan-2021 13:46:00 GMT; path=/;'
	}


//********************************************************************
// CAPTCHA
//********************************************************************

	function setCaptchaImage(valImageId) {
		var objImage = document.images[valImageId];
		if (objImage == undefined) {
			return;
		}
		var now = new Date();
		objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
	}
	
	function getCaptcha() {
		strCaptchaCode = trim(removeAllWhiteSpaces(document.getElementById('captchaCode').value));
		document.getElementById('captchaCode').value = strCaptchaCode;
				
		if (strCaptchaCode == "") { 
			strError = strError + "Please enter characters for the image\n";
		} else {	
			//alert(strCaptchaCode);
			doHttpRequest("/HttpCaptcha.asp", "captcha=" + strCaptchaCode + '&session=ASPCAPTCHA');
		}	
		if (strError != "") {
			document.getElementById('captchaCode').value = "";
			setCaptchaImage('imgCaptcha');
		}
	}


//********************************************************************
// BOOKING
//********************************************************************

	function getTodayPrice() {

		iToday = Math.round(iRental * 0.25);
		if (checkDateInterval(dateToday, dateArr, 0) < 56) {
			iToday = iRental;
		}
	
	}	

	function setTodayPrice() {
	
		iRental = removeAllWhiteSpaces(document.getElementById('rentalPrice').value);
		document.getElementById('rentalPrice').value = iRental;

		pTodayPriceDisplay = document.getElementById('todayPriceDisplay');
		pTodayPrice = document.getElementById('todayPrice');

		//alert(iToday);
		if (isNumeric(iRental)) {
			getTodayPrice();
			pTodayPriceDisplay.innerHTML = addCommas(iToday) + " Euros";
		} else {
			pTodayPriceDisplay.innerHTML = "Cannot calculate value, rental price is not a number";
		}

		pTodayPrice.value = iToday;

	}	

	function setRentalDisplay(pAction) {
	
		pRentalPriceDisplay = document.getElementById('rentalPriceDisplay');
		pTodayPriceDisplay = document.getElementById('todayPriceDisplay');

		if (isNumeric(strError)) {			
			
			if ( pAction == "Add" ) {
				pRentalPriceDisplay.innerHTML = "";
			} else {
				pRentalPriceDisplay.innerHTML = addCommas(iRental) + " Euros";
		}
			
			pRentalPrice = document.getElementById('rentalPrice');
			pRentalPrice.value = iRental;
			
			pTodayPriceDisplay.innerHTML = addCommas(iToday) + " Euros";
			pTodayPrice = document.getElementById('todayPrice');
			pTodayPrice.value = iToday;
		
		} else {

			pRentalPriceDisplay.innerHTML = strError;
			pTodayPriceDisplay.innerHTML = "-";
		
		}
	
	}


//********************************************************************
// Misc
//********************************************************************


	//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;
	}

	function isNumeric(pNumber)
	{
		if (pNumber.match(/\D+/g)) {
       		return false;
       	} else {
       		return true;
       	}
	}

	function isNumericWithOptionalDecimals(pNumber)
	{
		//match to any number of decimal places
		if ( pNumber.match(/^(\d*)(\.?)(\d*)$/) ) {
       		return true;
       	} else {
       		return false;
       	}
	}
	
	//is the email address valid
	function isEmailValid(vText)
	{
		if (vText.match(/[A-Z0-9._%-]+@[A-Z0-9._%-]+/gi)) {
	   		return true;
	   	} else {
			return false;
	   	}
	}

	function inStringSpace(vBigText, vSmallText)
	{
	
		if (vSmallText.length != 0) {
			var i=0;
			var bigTextArray  = vBigText.split("_")
			var nameExists = false
			
			if (bigTextArray.length > 0)
			{
			   for (i = 0; i < bigTextArray.length; i++) 
			   { 
			      if (bigTextArray[i].toUpperCase() == vSmallText.toUpperCase()) 
			         {
			         	nameExists = true;
			         }
			   }
			}
		
			if (nameExists) {
		   		return true;
		   	} else {
		   		return false;
		   	}

		} else {
			return false;
		}
	}		
	
	function showImageStatic(id) { 
		imgUrl = 'http://www.cotedazurvillarentals.com/' + id + '.jpg'
		document.getElementById('imageContainer').style.display = "none";
		document.getElementById('imageContainerStatic').style.display = "block";
		document.getElementById('imageStatic').src = 'http://www.cotedazurvillarentals.com/' + id + '.jpg'
	}	

	function hideImageStatic() { 
		document.getElementById('imageContainerStatic').style.display = "none";
		document.getElementById('imageContainer').style.display = "block";
	}	

	//if the user enters an invlid date eg 30 Feb 2011 it will be reset to the last day of the month ie 28 Feb 2011
	function resetDate(pDay, pMonthAndYear) {
		for (i = 1; i < 4; i++) {
			//alert(pDay + " " + pMonthAndYear);
			dateToCheck = new Date(pDay + " " + pMonthAndYear.replace("/", " "));
			if (dateToCheck.getDate() != pDay) {
				pDay = pDay - i;
			}
		} 
		return pDay
	}
	
	function getArrAndDepDates() {
	
		iArrDay = document.getElementById('arrDay').value;
		strArrMonthAndYear = document.getElementById('arrMonthAndYear').value;
		if ( (iArrDay != 0) && (strArrMonthAndYear != 0) ) {
			iArrDay = resetDate(iArrDay, strArrMonthAndYear);
			document.getElementById('arrDay').value = iArrDay;
			arrayArrMonthAndYear = strArrMonthAndYear.split("/");
			dateArr = new Date(arrayArrMonthAndYear[1], getMonthNumber(arrayArrMonthAndYear[0]), iArrDay);
		}
				
		iDepDay = document.getElementById('depDay').value;
		strDepMonthAndYear = document.getElementById('depMonthAndYear').value;
		if ( (iDepDay != 0) && (strDepMonthAndYear != 0) ) {
			iDepDay = resetDate(iDepDay, strDepMonthAndYear);
			document.getElementById('depDay').value = iDepDay;
			arrayDepMonthAndYear = strDepMonthAndYear.split("/");
			dateDep = new Date(arrayDepMonthAndYear[1], getMonthNumber(arrayDepMonthAndYear[0]), iDepDay);
		}

		//dates used in function checkBooking()
		strDateArr = iArrDay + "-" + strArrMonthAndYear.replace("/", "-");
		strDateDep = iDepDay + "-" + strDepMonthAndYear.replace("/", "-");;
		
	}


	function getArrDate() {
	
		iArrDay = document.getElementById('arrDay').value;
		strArrMonthAndYear = document.getElementById('arrMonthAndYear').value;
		iArrDay = resetDate(iArrDay, strArrMonthAndYear);
		document.getElementById('arrDay').value = iArrDay;
		arrayArrMonthAndYear = strArrMonthAndYear.split("/");
		dateArr = new Date(arrayArrMonthAndYear[1], getMonthNumber(arrayArrMonthAndYear[0]), iArrDay);
				
		//dates used in function checkBooking()
		strDateArr = iArrDay + "-" + strArrMonthAndYear.replace("/", "-");

	}
	
	function getMonthNumber(pMonth) {
	
		//this function ensures international date compatibility
		if (pMonth == "Jan") {
			monthNumber = 0;
		} else if (pMonth == "Feb") {
			monthNumber = 1;
		} else if (pMonth == "Mar") {
			monthNumber = 2;
		} else if (pMonth == "Apr") {
			monthNumber = 3;
		} else if (pMonth == "May") {
			monthNumber = 4;
		} else if (pMonth == "Jun") {
			monthNumber = 5;
		} else if (pMonth == "Jul") {
			monthNumber = 6;
		} else if (pMonth == "Aug") {
			monthNumber = 7;
		} else if (pMonth == "Sep") {
			monthNumber = 8;
		} else if (pMonth == "Oct") {
			monthNumber = 9;
		} else if (pMonth == "Nov") {
			monthNumber = 10;
		} else if (pMonth == "Dec") {
			monthNumber = 11;
		}
		return monthNumber;
	}
	
	function isDateArrBeforeToday() {
		today = new Date();
		today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
		//alert(dateArr);
		if (dateArr < today) {
			strError = strError + "The arrival date is before today\'s date\n"; 
		}	
	}	
	
	function isDateDepGreaterThanDateArr() {
		if ( (iArrDay != 0) && (strArrMonthAndYear != 0) && (iDepDay != 0) && (strDepMonthAndYear != 0) ) {
			if (dateArr >= dateDep) {
				strError = strError + "The first arrival date is GREATER than or equal to the departure date\n"; 
			}
		}
	}


	function checkDateInterval(pDate1, pDate2, pIntervalAllowed) {
	
	    // The number of milliseconds in one day
	    var ONE_DAY = 1000 * 60 * 60 * 24
	
	    // Convert both dates to milliseconds
	    var date1_ms = pDate1.getTime();
	    var date2_ms = pDate2.getTime();
	
	    // Calculate the difference in milliseconds
	    var difference_ms = Math.abs(date1_ms - date2_ms);
	    
	    // Convert back to days and return
	    iIntervalActual = Math.round(difference_ms/ONE_DAY);
	    
	    if ( (pIntervalAllowed > 0) && (iIntervalActual < pIntervalAllowed) ) {
			strError = strError + "The duration of your stay must be a minimum of " + pIntervalAllowed + " nights\n"; 
	    } 
	
		return iIntervalActual;
	}		
	

	function doHttpRequest(pUrl, pParams) {

		var strURL = pUrl;
		var params = pParams;
		//alert(params);
		
		if (window.XMLHttpRequest) {
			//alert("IE7+, Firefox, Chrome, Opera, Safari");
		  	xmlHttpReq = new XMLHttpRequest();
		} else {
			//alert("IE6, IE5");
		 	xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		 }

	    xmlHttpReq.open('POST',strURL,false);
	    xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	   	xmlHttpReq.send(params);
	   	//alert(params);

		if (xmlHttpReq.readyState == 4) {
			if (xmlHttpReq.status == 200) {
		        strError = strError + xmlHttpReq.responseText;
		        strError = strError.replace(/<BR>/g, "\n");
		        //alert(strError);
			}
		}	   	
	}	  

	function doHttpRequestSync(pUrl, pParams) {

		//same as above expcept set to true instead of false;

		var strURL = pUrl;
		var params = pParams;
		//alert(params);
		
		if (window.XMLHttpRequest) {
			//alert("IE7+, Firefox, Chrome, Opera, Safari");
		  	xmlHttpReq = new XMLHttpRequest();
		} else {
			//alert("IE6, IE5");
		 	xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		 }

	    xmlHttpReq.open('POST',strURL,true);
	    xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	   	xmlHttpReq.send(params);
	   	//alert(params);

		if (xmlHttpReq.readyState == 4) {
			if (xmlHttpReq.status == 200) {
		        strError = strError + xmlHttpReq.responseText;
		        strError = strError.replace(/<BR>/g, "\n");
		        //alert(strError);
			}
		}	   	
	}	  
	  

	function addCommas(nStr) {
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}


	  
