﻿var searchClicked=false;

var nullNameError="Please insert your name";
var nullEmailError="Please insert your email";
var nullQuestionError="Please insert your question";
var invalidEmailError="Please insert a valid email address";

var urlToPhp = "http://yourdomain/sendEmail.php";

var valid=true;

$(function(){
setSearchInputClickHandler();
validateSendEmailForm();
});

/**
 *	Removes the text in the search text box when clicked on it.
 */
function setSearchInputClickHandler(){
	$("#emailTextBox").click(function(){
		if(searchClicked==false){
			this.value='';
			searchClicked=true;
		}
	});
}

/**
 *	Validates the send email form.
 */
function validateSendEmailForm(){
    $("#button a").click(function(){
	valid=true;
		
		$("#emailError").text("");  
		$("#message").text("");  
		
		//verify whether the inserted email address is valid
		var email = document.getElementById("emailTextBox").value;
		
			var dotIndex = email.indexOf(".");
			var atIndex = email.indexOf("@");
			var beforeAt = email.substring(0,atIndex);
			var between = email.substring(atIndex+1,dotIndex);
			var afterDot = email.substring(dotIndex+1);
			

	if(beforeAt.length<2 || afterDot.length<2 || between.length<2 || !(email.indexOf(".") > 2) || !(email.indexOf("@") > 0)){
		$("#emailError").text(invalidEmailError); 
		valid=false;
	}
		
		//verify whether the email text box is empty
		if(document.getElementById("emailTextBox").value=="" || document.getElementById("emailTextBox").value==null){
			$("#emailError").text(nullEmailError);
			valid=false;
		}
	

		//if the inserted data is valid, then sumbit the form
		if(valid==true){
			urlToPhp="sendEmail.php";
			
			var dataString = '&email=' + email;  

			$.ajax({  
				type: "POST",  
				url: urlToPhp,  
				data: dataString,  
				success: function() {  
				$("label#message").html("Thank you!");
				$("#submitForm").each(function(){
					this.reset();
				});
				}
			}); 
		}
    });
}


