// JavaScript Document
// check email format
function validEmail(email)
{
   invalidChars = " /:,;"

   if (email == "")
      return false

   for (i=0; i<invalidChars.length; i++)
   {
      badChar = invalidChars.charAt(i)

      if (email.indexOf(badChar,0)>-1)
         return false
   }

   atPos = email.indexOf("@",1)

   if (atPos == -1)
      return false

   if (email.indexOf("@",atPos+1) != -1)
      return false

   periodPos = email.indexOf(".",atPos)

   if (periodPos == -1)
      return false

   if (periodPos+3 > email.length)
      return false

   return true
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 8;

function isInteger(s)
{
   var i;
   for (i = 0; i < s.length; i++)
   {   
      // Check that current character is number.
      var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) return false;
   }
   // All characters are numbers.
   return true;
}

function stripCharsInBag(s, bag)
{
   var i;
   var returnString = "";
   // Search through string's characters one by one.
   // If character is not in bag, append to returnString.
   for (i = 0; i < s.length; i++)
   {   
      // Check that current character isn't whitespace.
      var c = s.charAt(i);
      if (bag.indexOf(c) == -1) returnString += c;
   }
   return returnString;
}

function checkInternationalPhone(strPhone)
{
   s=stripCharsInBag(strPhone,validWorldPhoneChars);
   return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function submitIt(lighthouse)
{
   if (lighthouse.firstname.value == "")
   {
      alert ("You must enter your first name.");
      return false;
   }

   if (lighthouse.surname.value == "")
   {
      alert ("You must enter your surname.");
      return false;
   }

   if (lighthouse.email.value == "")
   {
      alert ("You must enter your email address.");
      return false;
   }
   
   if (lighthouse.email.value != "")
   {
      if (!validEmail(lighthouse.email.value))
      {
         alert("The email address that you have entered is not valid. Please re-enter the email address.");
         return false;
      }
   }

   if (lighthouse.telephone.value == "")
   {
      alert ("You must enter your telephone number.");
      return false;
   }

   if (lighthouse.telephone.value != "")
   {
      if (!checkInternationalPhone(lighthouse.telephone.value))
      {
         alert("The phone number that you have entered is not valid. Please re-enter the phone number.");
         return false;
      }
   }
   
   return true;
}
