//********************************************************************************
//********************************************************************************
// Version 01.00 - 28/04/2006
//
// This file contains some general email handling routines
//********************************************************************************
// VerifyEmailFormat : Verifies that an email address is in the correct format
//********************************************************************************
//********************************************************************************


//********************************************************************************
//    Author: Steve Betts
//      Date: Oct 2005
//      Desc: VerifyEmailFormat
//            Verifies that an email address is in the correct format
//   Returns:  0 = valid format
//            !0 = inavlid format, value indicates where problem is
//            
// Amendment: Apr 2006 SJB
//            Extended to include domain check and multiple return codes rather
//            than just true or false. 
//********************************************************************************
function VerifyEmailFormat(p_sEmail) {
 var sDomainChar="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.";
 var sAt="@";
 var sDot=".";

 var nEmailLen=p_sEmail.length;
 var nFirstAt=p_sEmail.indexOf(sAt);
 var nFirstDot=p_sEmail.indexOf(sDot);
 var sDomain=p_sEmail.substring(nFirstAt+1);
 var nDomainLen=sDomain.length;

 // Check that there is only a single @. It must not be the first or
 // last character and must not be prefixed or suffixed by a dot (.).
 // -----------------------------------------------------------------
 if (nFirstAt==-1) return 1;
 if (p_sEmail.charAt(0)==sAt || p_sEmail.charAt(nEmailLen-1)==sAt) return 2;
 if (p_sEmail.indexOf(sAt,(nFirstAt+1))!=-1) return 3;
 if (p_sEmail.substring(nFirstAt-1,nFirstAt)==sDot || p_sEmail.substring(nFirstAt+1,nFirstAt+2)==sDot) return 4;

 // Check that there is at least one dot (.). It cannot be the first 
 // or last character and there must be at least one dot after the @.
 // Do not allow consecutive dots
 // -----------------------------------------------------------------
 if (nFirstDot==-1) return 10;
 if (p_sEmail.charAt(0)==sDot || p_sEmail.charAt(nEmailLen-1)==sDot) return 11;
 if (p_sEmail.indexOf(sDot,(nFirstAt+2))==-1) return 12;
 if (p_sEmail.indexOf("..")!=-1) return 13;

 // Do not allow spaces
 // -------------------
 if (p_sEmail.indexOf(" ")!=-1) return 20;

 // Domain names (after @) must only contain specific characters
 // ------------------------------------------------------------
 for (i=0;i<nDomainLen;i++) {
   if (sDomainChar.indexOf(sDomain.charAt(i))==-1) return 30;
 };

 return 0;
}


