/*********
toggle the text inside a form on/off
*********/
function toggleFormText(thisId, thisText) {
	//alert(document.getElementById(thisId).value + ',' + thisText);
	if (document.getElementById(thisId).value == thisText)
	{
		document.getElementById(thisId).value='';
	}
	else if (document.getElementById(thisId).value == '')
	{
		document.getElementById(thisId).value=thisText;
	}
}


/*********
validates an email address
*********/
function validateEmail(thisEmail) {
	//initiate returnMessage variable
	var returnMessage="";

	if(thisEmail == '')
	{
		// alert the user
		returnMessage = "Please type in a valid email address.";
	}
	else
	{
		// function to check email address vilidity
		function emailCheck(emailStr)
		{
			/* The following pattern is used to check if the entered e-mail address
			   fits the user@domain format.  It also is used to separate the username
			   from the domain. */
			var emailPat=/^(.+)@(.+)$/
			/* The following string represents the pattern for matching all special
			   characters.  We don't want to allow special characters in the address.
			   These characters include ( ) < > @ , ; : \ " . [ ]    */
			var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
			/* The following string represents the range of characters allowed in a
			   username or domainname.  It really states which chars aren't allowed. */
			var validChars="\[^\\s" + specialChars + "\]"
			/* The following pattern applies if the "user" is a quoted string (in
			   which case, there are no rules about which characters are allowed
			   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
			   is a legal e-mail address. */
			var quotedUser="(\"[^\"]*\")"
			/* The following pattern applies for domains that are IP addresses,
			   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
			   e-mail address. NOTE: The square brackets are required. */
			var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
			/* The following string represents an atom (basically a series of
			   non-special characters.) */
			var atom=validChars + '+'
			/* The following string represents one word in the typical username.
			   For example, in john.doe@somewhere.com, john and doe are words.
			   Basically, a word is either an atom or quoted string. */
			var word="(" + atom + "|" + quotedUser + ")"
			// The following pattern describes the structure of the user
			var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
			/* The following pattern describes the structure of a normal symbolic
			   domain, as opposed to ipDomainPat, shown above. */
			var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


			/* Finally, let's start trying to figure out if the supplied address is
			   valid. */

			/* Begin with the coarse pattern to simply break up user@domain into
			   different pieces that are easy to analyze. */
			var matchArray=emailStr.match(emailPat);
			//alert(emailStr);
			var checkMatch='-' + matchArray + '-';
			if (checkMatch == "-null-")
			{
			  /* Too many/few @'s or something; basically, this address doesn't
				 even fit the general mould of a valid e-mail address. */
				returnMessage = "The email address seems incorrect (check @ and .'s).";
			}
			else
			{
				var user=matchArray[1];
				var domain=matchArray[2];

				// See if "user" is valid
				if (user.match(userPat)==null)
				{
					// user is not valid
					returnMessage = "The email's username doesn't seem to be valid (before the @).";
				}

				/* if the e-mail address is at an IP address (as opposed to a symbolic
				   host name) make sure the IP address is valid. */
				var IPArray=domain.match(ipDomainPat)
				if (IPArray!=null) {
					// this is an IP address
					  for (var i=1;i<=4;i++) {
						if (IPArray[i]>255) {
							returnMessage = "The email's destination IP address is invalid.";
						}
					}
				}

				// Domain is symbolic name
				var domainArray=domain.match(domainPat)
				if (domainArray==null) {
					returnMessage = "The email's domain name doesn't seem to be valid (after the @).";
				}

				/* domain name seems valid, but now make sure that it ends in a
				   three-letter word (like com, edu, gov) or a two-letter word,
				   representing country (uk, nl), and that there's a hostname preceding
				   the domain or country. */

				/* Now we need to break up the domain to get a count of how many atoms
				   it consists of. */
				var atomPat=new RegExp(atom,"g")
				var domArr=domain.match(atomPat)
				var len=domArr.length
				if (domArr[domArr.length-1].length<2 ||
					domArr[domArr.length-1].length>4) {
				   // the address must end in a two letter or three letter word.
				   returnMessage = "The email must end in a four-letter domain, three-letter domain, or two letter country.";
				}

				// Make sure there's a host name preceding the domain.
				if (len < 2) {
				   returnMessage="This email is missing a hostname!";
				}
			}
		}
		// call the validation function and return its result
		val=emailCheck(thisEmail);
		// if it returns val=no_submit, stop form
	}
	return returnMessage;
}

/************
verify Contact Form
************/
function verifyContactForm() {
	//form variables
	submitBtnMessage='Saving... Please Wait';
	formName='ContactForm';

	//initialize submitForm value
	submitForm=true;
	warningMessage="";
	formFocus="";

	//check name
	if (submitForm)
	{
		formElement="First_Name";
		thisDOM=eval('document.' + formName + '.' + formElement);
		if (thisDOM.value == "" || thisDOM.value == 'First Name*')
		{
			warningMessage='Please type in your first name.';
			formFocus=formElement;
			submitForm=false;
		}
	}

	//check name
	if (submitForm)
	{
		formElement="Last_Name";
		thisDOM=eval('document.' + formName + '.' + formElement);
		if (thisDOM.value == "" || thisDOM.value == 'Last Name*')
		{
			warningMessage='Please type in your last name.';
			formFocus=formElement;
			submitForm=false;
		}
	}

	//check the email
	if (submitForm)
	{
		formElement="Email_Address";
		thisDOM=eval('document.' + formName + '.' + formElement);
		//check the email address
		thisMessage=validateEmail(thisDOM.value);
		//if there is no message sent back, set the alert.
		if (thisMessage.length != 0)
		{
			warningMessage=thisMessage;
			formFocus=formElement;
			submitForm=false;
		}
	}
	// Phone
	if (submitForm)
	{
		formElement="Phone";
		thisDOM=eval('document.' + formName + '.' + formElement);
		if (thisDOM.value == "" || thisDOM.value == 'Phone Number*')
		{
			warningMessage='Please type in your phone number.';
			formFocus=formElement;
			submitForm=false;
		}
	}

	// Subject
	if (submitForm)
	{
		formElement="Subject";
		thisDOM=eval('document.' + formName + '.' + formElement);
		if (thisDOM.value == "" || thisDOM.value == 'Subject Line*')
		{
			warningMessage='Please type in a subject for your contact request.';
			formFocus=formElement;
			submitForm=false;
		}
	}
	
	//check comment
	if (submitForm)
	{
		formElement="Message";
		thisDOM=eval('document.' + formName + '.' + formElement);
		if (thisDOM.value == "" || thisDOM.value == 'Message Here*')
		{
			warningMessage='Please type in your message.';
			formFocus=formElement;
			submitForm=false;
		}
	}

	//disable the form if the form checks out
	if (!submitForm)
	{
		alert(warningMessage);
	}

	//focus the form if necessary
	if (formFocus.length > 0)
	{
		thisDOM=eval('document.' + formName + '.' + formFocus);
		thisDOM.focus();
	}

	//return the boolean value whether or not we should submit this form
	return submitForm;
}

/*********
returns true if the phone number is valid, false otherwise
Valid:
(343) 234-3432
2342342342
234-242-2342
*********/
function isPhoneValid(phone_number) {
	valid = true;

	if (thisDOM.value.search(/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/) == -1)
	{
		valid = false;
	}

	return valid;
}

//function to clear form 
$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			 this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

function errorMessage(Subject,Field,Required){
	if((Field == "" || Field == "Subject Line*" || Field == "Phone" || Field == "Your Message*" || Field == "First Name*" || Field == "Last Name*" || Field == "Email Address*" || Field == "Phone*"
	) && Required=='required'){
		return Subject+" is required<br/>";
	}
	else{
		return "";
	}
}

// JQUERY BEGINS HERE
$(document).ready(function() {
	// USA MAP 
	$(".usaMapSwitcher li a").hover (
		function () {
			var usaMapYOffset = "0 " + $(this).attr("y_offset");
			$(".usaMapSwitcher").css("background-position",usaMapYOffset);
		},
		function () {
			var usaMapYOffset = "0 0";
			$(".usaMapSwitcher").css("background-position",usaMapYOffset);
		}
	);

	// AMENITIES (Hover over icons and returns text based on their "amenity" attribute

	$(".amenitiesIcons li a").hover (
		function () {
			var amenityVar = $(this).attr("amenity");
			$(".amenitiesDesc").text(amenityVar);
		},
		function () {
			var amenityVar = "";
			$(".amenitiesDesc").text(amenityVar);
		}
	);
	
	// show the overlay
	$('.btnShowOverlay').click(function(){
		$('html, body').animate({ scrollTop: 0 }, 'slow');
		var openThisWindow = $(this).attr("rel");
		$('.overlayBG').fadeIn('slow');
		$(openThisWindow).fadeIn('slow');
		$("#ovSiError").hide();
		return false;
	});
	// hide the overlay
	$('.closeBox').live('click',function(){
		$('.overlayBG').fadeOut('slow');
		$(this).parents('div.overlayBox').fadeOut('slow');
		$("#ovSiError").hide();
	});
	
	$("#ovSiSubmit").live('click',function(){
		var error = "";		
		var email = $("#ovSiEmail").val();
		var firstname = $("#ovSiFirstName").val();
		var lastname = $("#ovSiLastName").val();
		var phone = $("#ovSiPhone").val();
		var subject = $("#ovSiSubject").val();
		var message =  $("textarea#ovSiMessage").val();
		var community_name =  $("#ovSiCommunityName").val();
		var contact_email =  $("#ovSiContactEmail").val();
		//error +=errorMessage('Email',email,'required');
		error +=errorMessage('First Name',firstname,'required');
		error +=errorMessage('Last Name',lastname,'required');
		email_error = validateEmail(email);
		if (email_error.length > 0) {
			error += email_error + '<br/>';
		}
		error +=errorMessage('Phone',phone,'required');
		error +=errorMessage('Subject',subject,'required');
		error +=errorMessage('Message',message,'required');
		if(error!=""){
			$("#ovSiError").html(error);
			$("#ovSiError").slideDown();
			error = "";
			return false;
		}
		else{
			var parameter = "Contact_Email="+contact_email+"&Email_Address="+email+"&First_Name="+firstname+"&Last_Name="+lastname+"&Subject="+subject+"&Message="+message+"&Phone="+phone+"&Community_Name="+community_name;
			$.ajax({
				type: "POST",
				url: "/landing-page/send-form/",
				data: parameter,
				async: false,
				dataType: "json",
				beforeSend:function(){
					$("#ovSiForm").hide();
				},
				success: function(data){
					if(data.error == 0){
						$('.overlayBG').fadeOut('slow');
						$(this).parents('div.overlayBox').fadeOut('slow');
						$("#ovSiResponse").show();
						$("#ovSiResponse").html('<label for="signUpMessage">'+data.message+'<label/>');
					}else{						
						$("#ovSiError").html("");
						$("#ovSiError").html(data.message);
						$("#ovSiError").slideDown();
					}
				}
			});			
		}
		return false;
	});
	
});
