
var EmailChecker = {

	url:	'contact.php',

	dnsLookup: function (domain, callback) {
		var opt = {
			method:		'post',
			postBody:	'dns-lookup=' + encodeURIComponent (domain),
			onSuccess: function (rq) {
				var rsp = {} ;
				eval ('rsp = ' + rq.responseText + ' ;') ;
				callback (rsp, rq) ;
			},
			onFailure: function (rq) {
				callback ({status:'error', message:'API request failed'}, rq) ;
			}
		} ;
		new Ajax.Request (EmailChecker.url, opt) ;
	},

	test: function (email, callback) {
		//
		// Split the address into local and domain parts. Include a
		// length check while we're at it.
		//
		if (!/^(.{1,64}?)@([^@]{1,255})$/.test (email)) {
			callback (false) ;
			return ;
		}
		var local = RegExp.$1 ;
		var domain = RegExp.$2 ;

		//
		// Check local part
		//
		if (!/^([a-z0-9!#$%&'*+/=?^_`{|}~-][a-z0-9!#$%&'*+/=?^_`{|}~\.-]*|"[^(\|")]*")$/i.test (local)) {
			callback (false) ;
			return ;
		}

		//
		// Check for valid IP address, if it looks good, accept it.
		//
		if (!/^\[[0-9]+(\.[0-9]+){3}\]$/.test (domain)) {
			if (/^[0-9]+(\.[0-9]+){3}$/.test (domain)) {
				callback (true) ;
				return ;
			}
		}

		//
		// Check domain name. This will reject some legal domains and accept
		// some illegal domains, but will yield the desired result for 99.99999%
		// of real-world email addresses.
		//
		if (!/^([a-z0-9]+|([a-z0-9][a-z0-9-]*[a-z0-9]))(\.([a-z0-9]+|([a-z0-9][a-z0-9-]*[a-z0-9])))+$/i.test (domain)) {
			callback (false) ;
			return ;
		}

		//
		// If the domain looks good, do a DNS lookup. If the Ajax request fails,
		// accept it. Only reject on a successful request that returns a failed
		// DNS lookup.
		//
		EmailChecker.dnsLookup (
			domain,
			function (rsp) {
				if (rsp.status == 'ok') {
					callback (rsp.ip ? true : false) ;
				} else {
					callback (true) ;
				}
			}
		) ;
	}
}