/***********************************************************
	Purpose:
	    Ensures that an email address is properly syntaxed and ends with a 
	    valid TLD (top level domain).

	Version History:
	    Email verification in general has had a checkered history at the ASP 
	    Emporium. It took a while but I think we finally came up with something 
	    good... Here's the short version history of all email validation 
	    software from ASP Emporium...

		3/2003  v4.1 (JScript Only)
			- Bug fix: TLD Validation bug fixed - thanks to 
			  jean-philippe.latruffe@libertysurf.fr for spotting 
			  the bug.

		10/2002 v4.0 (JScript & C#)
			- Added new TLD (.int). Thanks to alex.wernhardt@web.de
			- Supports all the rules as detailed here: 
			  http://www.aspemporium.com/aspEmporium/tutorials/emailvalidation.asp
			  and repairs all known issues in version 3.2.
			- backwards compatible with version 3.*
			- adds a class that is capable of parsing the email in addition
			  to validating it

		2/2002 v3.2 (JScript)
			- fixed a problem that allows emails like test@mydomain.......com
			  to pass through. Thanks to g.falcone@mclink.it for letting
			  me know about it.

		11/2001 v3.1 (JScript)
			- added new tlds. thanks to alex.wernhardt@web.de for sending
			  me the list - http://www.icann.org/tlds/
			- new tlds: aero, biz, coop, info, museum, name, pro

		9/2001  v3.0 (JScript)
			- fixed spaced email problem. thanks to mikael@perfoatris.com 
			  for the report.
			- put the length check right in the function rather
			  than relying on a programmer to check length before
			  testing an email. thanks to eduardo.azambuja@uol.com.br for
			  bringing that to my attention.

		7/2001  v2.5 (JScript)
			- forgot the TLD (.gov). added now...
			- fixed @@ problem... thanks to davidchersg@yahoo.com for
			  letting me know that the problem was still there.

		5/2001  v2.0 (JScript)
			- added verification of all known TLDs as of
			  May 2001: http://www.behindtheurl.com/TLD/
			- added line to remove leading and trailing spaces before
			  testing email
			    http://www.aspemporium.com/aspEmporium/feedback/feedbacklib.asp?mail=200105060001
			- regular expression improvements by:
				Bjrn Hansson  -  http://nytek.nu
			  you can view his emails here:
			    http://www.aspemporium.com/aspEmporium/feedback/feedbacklib.asp?mail=200104180005
			    http://www.aspemporium.com/aspEmporium/feedback/feedbacklib.asp?mail=200104090006
			    http://www.aspemporium.com/aspEmporium/feedback/feedbacklib.asp?mail=200104090005
			- this email verification software replaces all other email 
			  verification software at the ASP Emporium. VBScript versions 
			  have been abandoned in favor of this JScript version.

		2/2001  v1.5 (JScript)
			- Regular Expression introduced to validate emails. Basically 
			  a re-hashed version of the VBScript edition of IsEmail, aka 
			  the EmailVerification object 3.0 (next line below)

		12/2000 v3.0 (VBScript)
			- EmailVerification Class released, resolving multiple domain 
			  and user name problems.
			- Abandoned VBScript processing of emails in favor of regular 
			  expressions.
			- New VBScript class structure.

		8/2000  v1.0 (JScript)
			- Initial Release of IsEmail for JScript is a lame function 
			  that uses weak JScript inherent functions like indexOf... 
			  This is essentually a copy of the vbscript edition of the
			  software, version 2, remembered on the next line below...

		8/2000  v2.0 (VBScript)
			- IsEmail function updated to resolve several issues but 
			  multiple domains still pose a problem.

		4/2000  v1.0 (VBScript)
			- IsEmail function introduced
			  (used in the Simple Email Verification example)

		4/2000  v0.1 (VBScript)
			- First email validation code at the ASP Emporium checks only 
			  for an @ and a . (Used in the first version of the 
			  autoresponder example)

	***********************************************************/

var IsValid = false, Domain = "", Account = "", Address = "";

function EmailSyntaxValidator(email, TLDrequired)
{
	var tmpmail = ""+email+"", tmpdomain;
	var mailobj;

	this.Address = tmpmail;

	tmpmail = Trim(RemoveBrackets(tmpmail));

	mailobj = new Object();
	mailobj.acct="";
	mailobj.domain="";

	if (! CrackEmail(tmpmail, mailobj))
	{
		return;
	}

	this.Account = mailobj.acct;
	this.Domain = mailobj.domain;

	if (! DomainValid(TLDrequired, this.Domain) )
	{
		return;
	}

	if (TLDrequired && ! DomainExtensionValid(this.Domain))
	{
		return;
	}

	this.IsValid = true;
}

function CrackEmail(email, mailobj)
{
	var arr, re;

	re = /^(.+?)\@(.+?)$/gi
	if ((arr=re.exec(ReverseString(email))) == null)
	{
		return false;
	}

	mailobj.acct = ReverseString(RegExp.$2);
	mailobj.domain = ReverseString(RegExp.$1);
	return true;
}

function RemoveBrackets(email)
{	
	var re = /^\<*|\>*$/gi	
	return email.replace(re, "");
}

function Trim(email)
{
	var re = /^\s*|\s*$/gi	
	return email.replace(re, "");
}

function ReverseString(str)
{
	var i, outstr = "";

	for(i=str.length-1;i>-1;i--)
	{
		outstr += str.charAt(i);
	}
	return outstr;
}

function DomainValid(TLDrequired, tmpdomain)
{
	var re;

	if (TLDrequired)
	{
		re = /^((([a-z0-9-]+)\.)+)[a-z]{2,6}$/gi
	}
	else
	{
		re = /^((([a-z0-9-]+)\.)+)$/gi
		tmpdomain += ".";
	}

	return re.test(tmpdomain);
}

function DomainExtensionValid(tmpdomain)
{
	var domainvalidatorpattern = "", re;

	domainvalidatorpattern+="^(";
	domainvalidatorpattern+="a[c-gil-oq-uwz]|";     //ac,ad,ae,af,ag,ai,al,am,an,ao,aq,ar,as,at,au,aw,az
	domainvalidatorpattern+="b[a-bd-jm-or-tvwyz]|"; //ba,bb,bd,be,bf,bg,bh,bi,bj,bm,bn,bo,br,bs,bt,bv,bw,by,bz
	domainvalidatorpattern+="c[acdf-ik-orsuvx-z]|"; //ca,cc,cd,cf,cg,ch,ci,ck,cl,cm,cn,co,cr,cs,cu,cv,cz,cy,cz
	domainvalidatorpattern+="d[ejkmoz]|";           //de,dj,dk,dm,do,dz
	domainvalidatorpattern+="e[ceghr-u]|";          //ec,ee,eg,eh,er,es,et,eu
	domainvalidatorpattern+="f[i-kmorx]|";          //fi,fj,fk,fm,fo,fr,fx
	domainvalidatorpattern+="g[abd-ilmnp-uwy]|";    //ga,gb,gd,ge,gf,gg,gh,gi,gl,gm,gn,gp,gq,gr,gs,gt,gu,gw,gy
	domainvalidatorpattern+="h[kmnrtu]|";           //hk,hm,hn,hr,ht,hu
	domainvalidatorpattern+="i[delm-oq-t]|";        //id,ie,il,im,in,io,iq,ir,is,it
	domainvalidatorpattern+="j[emop]|";             //je,jm,jo,jp
	domainvalidatorpattern+="k[eg-imnprwyz]|";      //ke,kg,kh,ki,km,kn,kp,kr,kw,ky,kz
	domainvalidatorpattern+="l[a-cikr-vy]|";        //la,lb,lc,li,lk,lr,ls,lt,lu,lv,ly
	domainvalidatorpattern+="m[acdghk-z]|";         //ma,mc,md,mg,mh,mk,ml,mm,mn,mo,mp,mq,mr,ms,mt,mu,mv,mw,mx,my,mz
	domainvalidatorpattern+="n[ace-giloprtuz]|";    //na,nc,ne,nf,ng,ni,nl,no,np,nr,nt,nu,nz
	domainvalidatorpattern+="om|";                  //om
	domainvalidatorpattern+="p[ae-hk-nrtwy]|";      //pa,pe,pf,pg,ph,pk,pl,pm,pn,pr,pt,pw,py
	domainvalidatorpattern+="qa|";                  //qa
	domainvalidatorpattern+="r[eouw]|";             //re,ro,ru,rw
	domainvalidatorpattern+="s[a-eg-ort-vyz]|";     //sa,sb,sc,sd,se,sg,sh,si,sj,sk,sl,sm,sn,so,sr,st,su,sv,sy,sz
	domainvalidatorpattern+="t[cdf-hjkm-prtvwz]|";  //tc,td,tf,tg,th,tj,tk,tm,tn,to,tp,tr,tt,tv,tx,tz
	domainvalidatorpattern+="u[agkmsyz]|";          //ua,ug,uk,um,us,uy,uz
	domainvalidatorpattern+="v[aceginu]|";          //va,vc,ve,vg,vy,vn,vu
	domainvalidatorpattern+="w[fs]|";               //wf,ws
	domainvalidatorpattern+="y[etu]|";              //ye,yt,yu
	domainvalidatorpattern+="z[admrw]|";            //za,zd,zm,zr,zw
	domainvalidatorpattern+="com|";                 //com
	domainvalidatorpattern+="edu|";                 //edu
	domainvalidatorpattern+="net|";                 //net
	domainvalidatorpattern+="org|";                 //org
	domainvalidatorpattern+="mil|";                 //mil
	domainvalidatorpattern+="gov|";                 //gov
	domainvalidatorpattern+="biz|";                 //biz
	domainvalidatorpattern+="pro|";                 //pro
	domainvalidatorpattern+="aero|";                //aero
	domainvalidatorpattern+="coop|";                //coop
	domainvalidatorpattern+="info|";                //info
	domainvalidatorpattern+="name|";                //name
	domainvalidatorpattern+="int|";                 //int
	domainvalidatorpattern+="museum";               //museum
	domainvalidatorpattern+=")$";

	var idx = tmpdomain.lastIndexOf(".");
	re = new RegExp(domainvalidatorpattern, "i");
	return re.test(tmpdomain.substring(idx+1));
}

EmailSyntaxValidator.prototype.Address=Address;
EmailSyntaxValidator.prototype.Account=Account;
EmailSyntaxValidator.prototype.Domain=Domain;
EmailSyntaxValidator.prototype.IsValid=IsValid;





//this function provides backwards compatibility with version 3.2 
//jscript edition of the software
function IsEmailAddress()
{
	var validator, valid = false;

	//call syntax validator, specifying that the TLD is required
	validator = new EmailSyntaxValidator(this, true);

	//determine validity
	valid = validator.IsValid;

	//cleanup
	validator = null;

	//return validity indicator
	return valid;
}

//add IsEmail to the available methods of the String object
String.prototype.IsEmail = IsEmailAddress;
