/* Global variable definitions and extended types. */

// We need to know the certain browser versions (or if it's IE) since IE is "special" and requires spoon feeding.
/*@cc_on
	/*@if (@_jscript)
		var gIsIE = (document.all && !window.opera) ? true : false;
	/*@else @*/
		var gIsIE = false;
	/*@end
@*/
var gIsIE7 = (gIsIE && window.XMLHttpRequest);

// Global variable to store the current state of Ajax requests.
var gProcessingRequest = false;

// Extend String class to add trim() and stripHtml() functionality
String.prototype.trim = function () { return this.replace(/^\s*/, '').replace(/\s*$/, ''); }

/*****************************************************************************************************************/
/* FUNCTION: setProcessing(bProcessing, sMessage, sWhich)
/*   PARAMS: bProcessing	- true if processing, false otherwise
/*			 sMessage		- the message to show after processing, or an empty string to clear the processing message
/*			 sWhich			- the "id" where we want to show the processing indicator
/*  PURPOSE: To display a processing indicator when an Ajax call is processing. We also disable all form fields
/*			 and buttons so that no actions can occur while processing is taking place. Note that these fields
/*			 are re-enabled once setProcessing() is called and bProcessing = false.
/*****************************************************************************************************************/
function setProcessing(bProcessing, sMessage, sWhich) {
	// Set our global variable to the correct processing state. We use this to cancel
	// calls to certain functions so we can allow all Ajax requests to properly finish.
	gProcessingRequest = bProcessing;
	
	$(sWhich).innerHTML	= (bProcessing ? ' ' + sMessage : '');
	$(sWhich).style.visibility = (bProcessing ? 'visible' : 'hidden');
	
	// Disable form buttons (try/catch since buttons vary depending on which page/tab we're on.
	try { $('contactButton').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('previousButton').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('nextButton').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	
	// For non-IE browsers, we have to set the button text color so that it appears disabled.
	if (!gIsIE) {
		try { $('contactButton').setAttribute('style', (bProcessing ? 'color: #808097;' : 'color: #333333;')); } catch (e) {}
		try { $('previousButton').setAttribute('style', (bProcessing ? 'color: #808097;' : 'color: #333333;')); } catch (e) {}
		try { $('nextButton').setAttribute('style', (bProcessing ? 'color: #808097;' : 'color: #333333;')); } catch (e) {}
	}
	
	// Disable fields so that they can't be changed while processing.
	try { $('firstName').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('firstName').setAttribute((gIsIE ? 'className' : 'class'), (bProcessing ? 'disabled' : '')); } catch (e) {}
	try { $('lastName').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('lastName').setAttribute((gIsIE ? 'className' : 'class'), (bProcessing ? 'disabled' : '')); } catch (e) {}
	try { $('age').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('age').setAttribute((gIsIE ? 'className' : 'class'), (bProcessing ? 'disabled' : '')); } catch (e) {}
	try { $('email').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('email').setAttribute((gIsIE ? 'className' : 'class'), (bProcessing ? 'disabled' : '')); } catch (e) {}
	try { $('subject').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('subject').setAttribute((gIsIE ? 'className' : 'class'), (bProcessing ? 'disabled' : '')); } catch (e) {}
	try { $('message').disabled = (bProcessing ? 'disabled' : ''); } catch (e) {}
	try { $('message').setAttribute((gIsIE ? 'className' : 'class'), (bProcessing ? 'disabled' : '')); } catch (e) {}
}	

/* Clear any success/error messages */
function clearMessages() {
	try { $('successDetails').innerHTML = ''; $('successDetails').style.display = 'none'; } catch (e) {}
	try { $('errorDetails').innerHTML = ''; $('errorDetails').style.display = 'none'; } catch (e) {}
}

/* Set success/error messages */
function setMessage(sWhich, sMsg) {
	if (sWhich == 'success') {
		try { $('successDetails').innerHTML = sMsg; $('successDetails').style.display = 'block'; } catch (e) {}
	} else if (sWhich == 'error') {
		try { $('errorDetails').innerHTML = sMsg; $('errorDetails').style.display = 'block'; } catch (e) { alert('exception'); }
	}
}

/* Validate form fields */
function validateForm(id) {
	// Set our processing state.
	setProcessing(true, (id == 'contactForm' ? 'Sending inquiry... please wait.' : '&nbsp;'), 'processing');
	
	// Clear out any success/error messages.
	clearMessages();
	
	// Get a handle on the form object and initialize error flag.
	var oFrm = document.getElementById(id);
	var bError = false;
	
	// regular expression for a valid email address
	var reEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	// Validate the form according to which id we are processing.
	if (id == 'contactForm') {
	
		// Get the relevant information from the form.
		var firstName = new String(oFrm.firstName.value);
		var lastName = new String(oFrm.lastName.value);
		var email = new String(oFrm.email.value);
		var subject = new String(oFrm.subject.value);
		var message = new String(oFrm.message.value);
		
		// Strip any HTML tags that the user may have entered.
		firstName = firstName.replace(/(<([^>]+)>)/ig, '');
		lastName = lastName.replace(/(<([^>]+)>)/ig, '');
		email = email.replace(/(<([^>]+)>)/ig, '');
		subject = subject.replace(/(<([^>]+)>)/ig, '');
		message = message.replace(/(<([^>]+)>)/ig, '');
		
		// Replace newlines with linebreaks before handing off to PHP.
		message = message.replace(/\n/g, '<br />');
		
		// Get values from drop downs.
		var age = new String(document.getElementById("age").options[document.getElementById("age").selectedIndex].text);
		age = (age.trim() == 'Select your age' ? '' : age);
		var inquiry = new String(document.getElementById("inquiry").options[document.getElementById("inquiry").selectedIndex].text);
		inquiry = (inquiry.trim() == 'Please select' ? '' : inquiry);
		var country = new String(document.getElementById("country").options[document.getElementById("country").selectedIndex].text);
		country = (country.trim() == 'Choose a country' ? '' : country);
		
		// Now validate the form information.
		if (firstName.trim() == '') {
			bError = true;
			setMessage('error', 'Please enter your <b>first name</b>.');
		} else if (lastName.trim() == '') {
			bError = true;
			setMessage('error', 'Please enter your <b>last name</b>.');
		} else if (country.trim() == '') {
			bError = true;
			setMessage('error', 'Please select your <b>country</b>.');
		} else if (email.trim() == '' || !reEmail.test(email.trim())) {
			bError = true;
			setMessage('error', 'Please enter a valid <b>e-mail address</b>.');
		} else if (message.trim() == '') {
			bError = true;
			setMessage('error', 'Please enter a detailed inquiry in the <b>"Message"</b> input field.');
		}
		
		if (bError) {	// If there was an error, discontinue processing.
			setProcessing(false, '', 'processing');
		} else {		// If all is good, proceed with making an Ajax call to submit the form.
			var options = options ||{};
			options.onComplete = function(r) {
				if (r.responseText != 'success') {
					setMessage('error', 'Your inquiry could not be sent. Please try again.<br /><br />If the problem persists, please send an e-mail directly to <a href="mailto:lovelyguide@hotmail.com?subject=' + subject + '">lovelyguide@hotmail.com</a>');
				} else {
					setMessage('success', 'Your inquiry has been sent. Someone will contact you soon if necessary.<br /><br />Thank you.');
				}
				setProcessing(false, '', 'processing');
			}
			var qs = 'sendmail.php?firstName='+firstName+'&lastName='+lastName+'&country='+country+'&age='+age+'&email='+email+'&inquiry='+inquiry+'&subject='+subject+'&message='+message;
			new Ajax.Request(qs, options);
		}
		
	} else if (id == 'bookingFormStepOne') {
		
		// Get the relevant information from the form.
		var firstName = new String(oFrm.bkFirstName.value);
		var lastName = new String(oFrm.bkLastName.value);
		var email = new String(oFrm.bkEmail.value);
		var startDate = new String(oFrm.bkStartDate.value);
		
		// We're going to use this to test the start date to ensure that it's not in the past.
		var today = new Date();
		var testStartDate = new Date();
		var dateElements = startDate.split('/');
		testStartDate.setFullYear(dateElements[2], dateElements[0]-1, dateElements[1]);
		
		// Get values from drop downs.
		var country = new String(document.getElementById("bkCountry").options[document.getElementById("bkCountry").selectedIndex].text);
		country = (country.indexOf('Choose a country') >= 0 ? '' : country.trim());
		
		// Now validate the form information.
		if (firstName.trim() == '') {
			bError = true;
			setMessage('error', 'Please enter your <b>first name</b>.');
		} else if (lastName.trim() == '') {
			bError = true;
			setMessage('error', 'Please enter your <b>last name</b>.');
		} else if (country.trim() == '') {
			bError = true;
			setMessage('error', 'Please select your <b>country of origin</b>.');
		} else if (email.trim() == '' || !reEmail.test(email.trim())) {
			bError = true;
			setMessage('error', 'Please enter a valid <b>e-mail address</b>.');
		} else if (testStartDate <= today) {
			bError = true;
			setMessage('error', 'Please select the start date when you will be requiring our services. The date must be after today.');
		}
		
		if (bError) {	// If there was an error, discontinue processing.
			setProcessing(false, '', 'processing');			
		} else {		// Otherwise, submit the form.
			// Strip HTML tags before submitting.
			oFrm.bkFirstName.value = firstName.replace(/(<([^>]+)>)/ig, '');
			oFrm.bkLastName.value = lastName.replace(/(<([^>]+)>)/ig, '');
			oFrm.bkPhone.value = oFrm.bkPhone.value.replace(/(<([^>]+)>)/ig, '');
			oFrm.bkComments.value = oFrm.bkComments.value.replace(/(<([^>]+)>)/ig, '');
			oFrm.bkHotel.value = oFrm.bkHotel.value.replace(/(<([^>]+)>)/ig, '');
			
			oFrm.submit();
		}
		
	} else if (id == 'bookingFormStepTwo') {
		
		// Ensure that a minimum of 4 hours is selected before proceeding. If a tour package is selected, then that is enough. Likewise, if
		// no hours or packages are selected then we will assume a full 8 hours.
		var totalDays = $('totalDays').value;
		var bError = true;
		var temp = '';
		var hours = 0;
		
		// We're going to loop and set bError to false as soon as we know we have enough hours to proceed.
		for (var i = 0; i < totalDays; i++) {
			temp = document.getElementById('hours_'+i).options[document.getElementById('hours_'+i).selectedIndex].value;
			hours += (temp == '' ? 8 : parseInt(temp));
			hours += (document.getElementById('package_'+i).options[document.getElementById('package_'+i).selectedIndex].value != '' ? 8 : 0);
			if (hours >= 4) {
				bError = false;
				break;
			}
		}
		
		if (bError) {	// If there was an error, discontinue processing.
			setMessage('error', 'You must select a minimum of 4 hours or one of our tour packages to proceed.');
			setProcessing(false, '', 'processing');
		} else {		// Otherwise, submit the form.
			oFrm.submit();
		}
		
	} else if (id == 'bookingFormStepThree') {
		
		oFrm.submit(); // Just submit.
		
	}
}

/* For tour guide booking */
var gBookingWindow = null;
function launchBookingWindow() {
	if (gBookingWindow != null) closeWindow(gBookingWindow);
	gBookingWindow = window.open('bookUs.php','ezway_booking','width=790,height=530,toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=0');
}
function closeWindow(windowHandle) {
	if (windowHandle != null) {
		if (!windowHandle.closed) {
			windowHandle.close();
		}
	}
}
