(function($){
    var validate = function(event) {
        $("errors").innerHTML = "";
        var errors = [];

        if( nowtools.invalid($("from").value, true, nowtools.emailPattern) )
            errors.push("Your Email Address must be a valid email");

        if( nowtools.invalid($("subject").value, true) )
            errors.push("The Subject cannot be blank");

        $("to").value = nowtools.normalizeEmails($("to").value);
        if( nowtools.invalid($("to").value, true) )
            errors.push("You must specify at least 1 email address in the To field");

        if( nowtools.invalid($("to").value, false, nowtools.emailsPattern) )
            errors.push("The list of To addresses contains an invalid email");

        if( $("message").value && $("message").value.length > 300 )
            errors.push("Your message may not be longer than 300 characters.");

        if( errors.length > 0 ) {
            nowtools.showErrors("errors", errors);
            var html = "";
            nowtools.each(errors, function(error) { html += "<li>" + error + "</li>"; });
            $("errors").innerHTML = "<ul>" + html + "</ul>";
            nowtools.stop(event);
        }
        return errors.length == 0;
    };

    nowtools.event(window, "load", function() {
        nowtools.event($("spread"), "submit", validate);
        nowtools.externalizeLinks();
    });
})(nowtools.$);
