// JavaScript Document

// Validates entered information.
function validateForm(form){
   var selectedTopic = form.topic.selectedIndex;
   
   if (!isTopicSelected(form)) {
      alert("Please select a topic.");
	  return false; 
   } else if (!hasName(form)) {
      alert("Please enter a name.");
	  return false;  
   } else if (!isValidEmail(form)){
      alert("Please enter a valid email address.");
	  form.email.focus();
	  form.email.select();
	  return false;
   } else if (!hasMessage(form)) {
      alert("Please enter a message.");
	  form.message.focus();
	  form.message.select();
	  return false;
   } else if(isValidEmail(form)&&isTopicSelected(form)&&hasMessage(form)){
		return true;
   }
   
}

// Checks whether a topic has been selected. 
function isTopicSelected(form){
   var selectedTopic = form.topic.selectedIndex;
   if (form.topic.options[selectedTopic].value == "") {
	  return false;
   } else {
	  return true;
   }
}

// Checks whether the sender has included his name.
function hasName(form){
   if (form.sname.value == "") {
	  return false;
   } else {
	  return true;
   }
}

// Checks whether a message has been written. 
function hasMessage(form){
   if (form.message.value == "") {
	  return false;
   } else {
	  return true;
   }
}

// Validates the email entered.
function isValidEmail(form){
   // The invalid characters that should not be used in an email address
   var invalidChars = " /:,;"; 
   var emailAddress = form.email.value;
   var atPosition = emailAddress.indexOf("@",1);
   var periodPosition = emailAddress.indexOf(".",atPosition);
   
   if (emailAddress == ""){
      return false;
   }
   // Checks for the invalid characters listed above.
   for (var i=0; i<invalidChars.length; i++){
      badChar = invalidChars.charAt(i);
	  if (emailAddress.indexOf(badChar,0) > -1){
	     return false;
	  }
   }

   if (atPosition == -1){ // Checks for the @
      return false;
   }
   if (emailAddress.indexOf("@",atPosition + 1) > -1){ // Makes sure there is one @
      return false;
   }
   if (periodPosition == -1){ // Makes sure there is a period after the @ 
      return false;
   }
   // Makes sure there is at least 2 characters after the period
   if ((periodPosition + 3) > emailAddress.length){ 
      return false;
   }
   
   return true;
}