// general utilities [includes code by cyc on may 3, 2001]

// formatting
// ----------

function format(field,unify) {
    field.value = unify ? trimunify(field.value) : trim(field.value);
}

var whitespace = " \t\r\n";

function trim(s) {
// removes leading and trailing spaces
    if (s == "") return "";
    while (s.length && whitespace.indexOf(s.charAt(0)) > -1)
        s = s.substring(1);
    while (s.length && whitespace.indexOf(s.charAt(s.length-1)) > -1)
        s = s.substring(0,s.length-1);
    return s;
}

function trimunify(s) {
// trims and removes multiple spaces
    s = trim(s);
    if (s == "") return "";
    var r = "";
    var ignore = true;
    for (var i=0; i< s.length; i++) {
        c = s.charAt(i);
        w = (c == ' ' || c == '\t')
        if (!w || !ignore)
            r += c;
        ignore = w;
    }
    return r
}

// validation
// ----------

function isBlank(s) {
// returns true if null or whitespace
    if (s == null || s == "") return true;
    for (var i=0; i < s.length; i++) {
        var c = s.charAt(i);
        if ( (c != ' ') && ( c != '\n') && ( c != '\t')) return false;
    }
    return true;
}

function Error(field, msg) {
// usage: if (errorCondition) return Error(field,msg);
    field.focus();
    alert(msg);
    return false; // do not submit form
}

function isMissing(field, label) {
// usage: if (isMissing(field,label)) return false;
    if (!isBlank(field.value)) return false;
    Error(field, label + " is required");
    return true;
}

function isNum(s) {
// check if s contains only 0,1,...,9

    if (isBlank(s)) {
        return false;
    }
    for (var i=0; i<s.length; i++) {
        var c = s.charAt(i);
        if (c < '0' || c > '9') {
            return false;
        }
    }
    return true;
}

function isEmail(s) {
// rudimentary check for most elementary errors. from Negriono and Smith (1999)

    invalidChars = " /:,;";

    if (s == '') { 
        return false;
    }

    for (i=0; i<invalidChars.length; i++) {

        badChar = invalidChars.charAt(i);

        if (s.indexOf(badChar,0) > -1) { 
            return false; 
        }
    }
    
    atPos = s.indexOf("@",1);
    if (atPos == -1) {
       return false;
    }
    if (s.indexOf("@", atPos+1) > -1) {
        return false;
    }

    periodPos = s.indexOf(".", atPos);
    if (periodPos == -1) {
        return false;
    }

    if (periodPos + 3 > s.length) {
        return false;
    }

    return true;  
}
