//function to validate the dates entered into the rental search bar
function validateRentalSearch() {
	if (document.forms) {
		if (document.forms["rentalssearch"].start.value.length == 0) {
			alert("You must enter a 'From' date in the field provided.");
			document.forms["rentalssearch"].start.focus();
			return false;
		} else {
			var startDate = document.forms["rentalssearch"].start.value;
		}
		if (document.forms["rentalssearch"].end.value.length == 0) {
			alert("You must enter a 'To' date in the field provided.");
			document.forms["rentalssearch"].end.focus();
			return false;
		} else {
			var endDate = document.forms["rentalssearch"].end.value;
		}
		
		//Change the format of the 'end' date that will be understood by the Date format
		var tempDate = startDate.split("-");
		startDay = tempDate[0];
		startMonth = tempDate[1];
		startYear = tempDate[2];
		startDate = new Date(startMonth + startDay + ", " + startYear);
		
		//Change the format of the 'end' date that will be understood by the Date format
		var tempDate = endDate.split("-");
		endDay = tempDate[0];
		endMonth = tempDate[1];
		endYear = tempDate[2];
		endDate = new Date(endMonth + endDay + ", " + endYear);

		// The number of milliseconds in one day
		var oneDay = 1000 * 60 * 60 * 24

		// Calculate the difference in milliseconds and convert back to days
		var diffDays = Math.abs((startDate.getTime() - endDate.getTime())/(oneDay));
		
		if (diffDays <= 2) {
			alert("Please reselect your dates - minimum stay is 4 nights");
			return false;
		} else if (diffDays > 29) {
			alert("Please reselect your dates - you can only book a maximum stay of 30 nights online. \r\n\r\nPlease contact us via our'Contact Us' page if you wish to book for more than 30 days.");
			return false;
		}
		if (document.forms["rentalssearch"].noPeople.selectedIndex  == 0) {
			alert("Please choose the number of people staying");
			document.forms["rentalssearch"].noPeople.focus();
			return false;
		}
		return true;
	} 
}

// Function to define language to be used - not sure if this is used anymore - TOS 21.10.10
var sLang;

function Translate(sLang) {
	if (sLang == "en")
	{
		var sPath = "http://www.esteponamarinaproperties.com/newsite/booking.php";
	}
	else
	{
		var sPath = "http://translate.google.com/translate_p?hl=en&ie=UTF-8&oe=UTF-8&langpair=en%7C" + sLang + "&u=http://www.esteponamarinaproperties.com/newsite/booking.php&prev=/language_tools";
	}
	
	top.location = sPath;
}
	
// Function to process the submit function within the booking page - TOS 21.10.10
function Submit(stageID, param) {
	with (document.forms['booking'])
	{
		switch (stageID)
		{
			case 0:
				action = "booking.php";
				newSearch.value = "true";
				action += "#content";
				break;
			case 1:
				action = "booking.php?bookingStage=" + stageID;
				if (param == "")
				{
					newSearch.value = "true";
					action += "#content";
				}
				else if (parseInt(param) > 0)
				{
					newSearch.value = "false";
					searchPage.value = param;
					action += "#search";
				}
				else if (parseInt(param) == 0)
				{
					endDay.value = "";
					endMonth.value = "";
					endYear.value = "";
					propertyType.value = "%";
					noPeople.value = 1;
					newSearch.value = "true";
					action += "#search";
				}
				else
				{
					newSearch.value = "true";
					sortBy.value = param;
					action += "#search";
				}
				break;
			case 2:
				action = "booking.php?bookingStage=" + stageID;
				if (param == -1) {
					displayMonth.value = parseFloat(displayMonth.value) - 1;
					action += "#calendar";
				} else if (param == 1) {
					displayMonth.value = parseFloat(displayMonth.value) + 1;
					action += "#calendar";
				}
				else if (parseFloat(today.value) <=  param)
				{
					//alert ('1. the param is ' + param + ' today is ' + today.value+ ' '); // TOS debug code
					//SELECT A DATE
					if (startDate.value == "" || endDate.value == "") {
						var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
						if (startDate.value == "") {
							// Get the number of milliseconds from 01.01.70 to 01.01.2000
							// Add the number of milliseconds from 01.01.2000 to now
							var dd = (946684800 * 1000) + ((param - 1) * 1000 * 86400) ;
							var d = new Date(dd);
							var curr_date = d.getDate();
							if (curr_date < 10) {
								var curr_date = "0" + curr_date;
							}
							var curr_month = d.getMonth();
							var curr_year = d.getFullYear();
							start.value = curr_date + "-" + m_names[curr_month] + "-" + curr_year;
							startDate.value = param;
							startDay.value = curr_date;
							startMonth.value = curr_month + 1;
							startYear.value = curr_year;
						} else if (endDate.value == "") {
							// Get the number of milliseconds from 01.01.70 to 01.01.2000
							// Add the number of milliseconds from 01.01.2000 to now
							var dd = (946684800 * 1000) + ((param - 1) * 1000 * 86400) ;
							var d = new Date(dd);
							var curr_date = d.getDate();
							if (curr_date < 10) {
								var curr_date = "0" + curr_date;
							}
							var curr_month = d.getMonth();
							var curr_year = d.getFullYear();
							end.value = curr_date + "-" + m_names[curr_month] + "-" + curr_year;
							endDate.value = param;
							endDay.value = curr_date;
							endMonth.value = curr_month + 1;
							endYear.value = curr_year;
							nights.value = endDate.value - startDate.value + 1;
						 if (endDate.value - startDate.value < 3)
							{
								alert("Please reselect your dates - minimum stay is 4 nights");
								endDate.value = "";
								return;
							}
							else if (endDate.value - startDate.value > 29)
							{
								alert("Please reselect your dates - you can only book a maximum stay of 30 nights online. \r\n\r\nPlease contact us via our'Contact Us' page if you wish to book for more than 30 days.");
								endDate.value = "";
								return;
							}
						}
						action += "#calendar";
					} 
				} 
				else if (param == "r")
				{
					//SELECT A DATE
					start.value = "";
					startDay.value = 0;
					startMonth.value = 0;
					startYear.value = 0;
					startDate.value = "";
					end.value = "";
					endDay.value = 0;
					endMonth.value = 0;
					endYear.value = 0;
					endDate.value = "";
					nights.value = "";
					action += "#calendar";
				}
				else if (param > parseFloat(today.value) && param != "x" )
				{
					displayMonth.value = displayMonth.value - 0 + param;
					action += "#";
				} 
				else 
				{
					propID.value = param;
				}
				break;
			case 3:
				action = "booking.php?bookingStage=" + stageID;
				if (param == 1)
				{
					action += "#summary";
				}
				break;
			case 4:
				action = "booking.php?bookingStage=" + stageID;
				break;
			case 5:
				action = "booking.php?bookingStage=" + stageID;
				break;
		}
		submit();
	}
}

// Function to process the submit function within the sale page - TOS 25.01.11
function SalesSubmit(stageID, param)
	{
		with (document.forms["sales"])
		{
			switch (stageID)
			{
				case 0:
					action = "sales.php";
					newSearch.value = "true";
					//action += "#content";
					break;
				case 1:
					action = "sales.php?searchStage=" + stageID;
					if (param == "")
					{
						newSearch.value = "true";
						//action += "#content";
					}
					else if (parseInt(param) > 0)
					{
						newSearch.value = "false";
						searchPage.value = param;
						//action += "#search";
					}
					else if (parseInt(param) == 0)
					{
						propertyType.value = "%";
						priceRange.value = "%";
						newSearch.value = "true";
					}
					else
					{
						newSearch.value = "true";
						sortBy.value = param;
						//action += "#search";
					}
					break;
				case 2:
					action = "sales.php?searchStage=" + stageID;
					propID.value = param;
					break;
				case 3: // Window display
					action = "sales.php?searchStage=" + stageID;
					propID.value = param;
					break;
			}
			submit();
		}
	}
	
// Functions to process the search by reference number utility
// See http://forums.devshed.com/javascript-development-115/help-needed-running-php-mysql-script-asynchronously-and-taking-action-799985.html
// Trigger this function when your form is submitted
function on_submit_action() {
	// Get the values of the SALES or RENTAL radio buttons
	for (var i=0; i < 2; i++)
	   {
	   if (document.idsearch.propertyChoice[i].checked)
		  {
		  var rad_val = document.idsearch.propertyChoice[i].value;
		  }
	   }
	
	// Load the values you want to send to PHP into an object
	var to_send = {
		'ajaxIdRefNo': ''+ document.forms["idsearch"].idRefNo.value +'',
		'ajaxPropertyChoice': ''+ rad_val +''
	};
	
	var idRefNo = document.forms["idsearch"].idRefNo.value;
		
		// Issue the AJAX request
		$.ajax({
			url: 'includes/idsearch-response.php', // the PHP file you want to execute (this is a URL, it may be relative)
			data: to_send, // the JS object containing the data you want to send
			success: task_finished, // the JS function that will be called when the task finishes
			// error: function(xhr, status, error) {
				// Display a generic error for now.
			// alert("AJAX Error!");
			//},
			type: 'POST', // You can also change this to GET if you want to pass the to_send data in the URL
			cache: false, // probably don't want to change this
			dataType: 'json' // probably don't want to change this either
		});
		
		// Note that there are other parameters you can pass to $.ajax too, like a failure handler.  Read the jQuery documentation for details
}
// This function is executed when your PHP script finishes running
function task_finished(data) {
	// data contains the values that are returned by your PHP script
	if (data.searchResponseReturn == 'RENT') {
		window.location='booking.php?bookingStage=2&propID='+ data.searchIdResponseReturn +'';
	} else if (data.searchResponseReturn == 'SALE') {
		window.location='sales.php?searchStage=2&propID='+ data.searchIdResponseReturn +'';
	} else {
		alert(data.searchResponseReturn);
		document.forms["idsearch"].idRefNo.value = data.searchIdRefNO;
	}
}

// define functions to  SHOW/HIDE  Content
function HideContent(d) {
	document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
	document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
	if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
	else { document.getElementById(d).style.display = "none"; }
}

// Define "Request a callback" function
$(function() {
	// See http://nettuts.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
	// See http://jqueryui.com/demos/dialog/#modal-form
	
	// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
	// Set variables from the form input
	var name = $( "#name" ),
		telephoneNo = $( "#telephoneNo" ),
		timeToCall = $( "#timeToCall" ),
		allFields = $( [] ).add( name ).add( telephoneNo ).add( timeToCall ),
		tips = $( ".validateTips" );

	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}
	
	function checkExists( o, n ) {
		if ( o.val().length == 0 ) {
			o.addClass( "ui-state-error" );
			updateTips( "You must specify " + n + "." );
			return false;
		} else {
			return true;
		}
	}
	
	// Specify a "Request a callback" button and modal to open when it is clicked
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		height: 350,
		width: 350,
		modal: true,
		// See http://stackoverflow.com/questions/4929394/assign-id-to-jquery-dialog-button
		// Create buttons and actions to take when clicked
		buttons: [{
			// Define "Send Request" button
			id:"sendRequest",
			text:"Send Request",
			click: function() {
			
			//Validate form
			var bValid = true;
			allFields.removeClass( "ui-state-error" );
			bValid = bValid && checkExists( name, "your name" );
			bValid = bValid && checkExists( telephoneNo, "your telephone number" );
			bValid = bValid && checkExists( timeToCall, "the best time to call" );

			if ( bValid ) {
				// Get variable values to pass to request-callback.php
				var nameVal = $( "input#name" ).val();
				var telephoneNoVal = $( "input#telephoneNo" ).val();
				var timeToCallVal = $( "input#timeToCall" ).val();
				var dataString = 'name='+ nameVal + '&telephoneNo=' + telephoneNoVal + '&timeToCall=' + timeToCallVal;
				// alert (telephoneNoVal);return false;
				// Use AJAX to call request-callback.php
				$.ajax({
					type: "POST",
					url: "includes/request-callback.php",
					data: dataString,
					success: function() {
					//$( this ).dialog( "close" );
						$("#sendRequest").hide();
						$("#dialogFormFields").hide();
						$('#dialogFormMessage').html("<div id='message'></div>");
						$('#message').html("<h2>Callback Form Submitted!</h2>")
						.append("<p>We will be in touch soon.</p>")
					}
				});
				return false;	
			}
			}},
			{
			// Define "Close" button
			id:"closeRequest",
			text:"Close",
			click: function() {
				$( this ).dialog( "close" );
			}
		}],
		 
		// Define actions to take when modal is closed
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
			$("#sendRequest").show();
			$("#dialogFormFields").show();
			$("#dialogFormMessage").empty();
		}
	});

	// Define "Request a callback button
	$( "#callMeButton" )
		.button()
		.click(function() {
			$( "#dialog-form" ).dialog( "open" );
	});
});
