function isspace(c)
{      
   // what other chars should count as whitespace?
   if (c == ' ' || c == '\t' || c == '\xA0' || c == '\r' || c == '\n')
     return true;

   return false;
}
  
function trim(s) 
{
    for (var i = 0; i < s.length && isspace(s.charAt(i)); i++)
      ;

    for (var j = s.length - 1; j >= i && isspace(s.charAt(j)); j--)
      ;

    return s.substring(i, ++j);
}

// see http://javascript.internet.com/forms/email-address-validation.html
// for what a really good test would look like (except the lack of < 0x20 test)
function validate_email(str)
{
    var atpos = -1;
    var dotpos = -1;
    var specialchars = "()[]><:;,\\\"";

    for (var i = 0; i < str.length; i++)
    {
	var c = str.charAt(i);
	var cc = str.charCodeAt(i);

	// disallow invalid chars (screw quoted usernames and such)
	if (cc <= 0x20 || cc >= 0x7f || specialchars.indexOf(c) >= 0)
	    return false;

	if (c == '@')   
	{
	    if (atpos >= 0)     // do not allow more than 1 @
		return false;

	    atpos = i;          // remember @ position
	}
	else if (c == '.')
	{
	    dotpos = i;         // remember last . position
	}

    }

    if (atpos <= 0                   // no @ found or starts with @
	|| dotpos < atpos + 2        // no . or before @ and string
	|| dotpos >= str.length - 1) // ends with a .
	return false;

    return true; // this has been a lame and incomplete test, of course.
}

function bad_email_alert() 
{
    document.emailform.email.value = trim(document.emailform.email.value);

    if (!validate_email(document.emailform.email.value))
    {
	if (document.emailform.email.value.length < 1)
	    window.alert("Please enter your email address to register "
			 + "for our newsletter.");
	else
	    window.alert("'" + document.emailform.email.value
			 + "' does not look like a valid email address. "
			 + "Did you perhaps type your search string in the "
			 + "wrong field?");

	return false;
    }

    return true;
}
