
String.prototype.startswith = function(str) {
    return this.substr(0,str.length) == str
}
String.prototype.endswith = function(str) {
    return this.substr(this.length-str.length) == str
}

String.prototype.trim = function() {
    // Strip leading and trailing whitespace
    match = this.match(String.prototype.trim.trimRe);
    return match[1]; // Return first submatch
}
String.prototype.trim.trimRe = /^\s*(.*?)\s*$/;

Array.prototype.indexOf = function(value) {
    // Find value in array, return index or -1 if not found.
    for (var i=0; i<this.length; i++)
        if (this[i] == value) return i;
    return -1;
}

function $(id) {
    return document.getElementById(id);
}

function check_form() {
    var form = $("contact-form");
 
    // Determine required fields: 
    // look at the input named "required", comma-separated names
    var required_fields = [];
    var inputs = form.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
        if (inputs[i].name=="required") {
            required_fields = inputs[i].value.split(",");
            break;
        }
    }

    if (!required_fields.length) {
        return true; // No fields to check, so form is ok.
    }

    // Find the required field elements, look among inputs and textareas
    fields = [];
    for (tagname in {"input":1, "textarea":2}) { 
        var elements = form.getElementsByTagName(tagname);
        for (var i=0; i<elements.length; i++) {
            if (required_fields.indexOf(elements[i].name) != -1) {
                fields.push(elements[i]);
            }
        }
    }
    
    // Check the required fields for empty values
    var errors = [];
    for (var i=0; i<fields.length; i++) {
        if (!fields[i].value.trim()) {
            errors.push(fields[i]);
        }
    }

    // Handle errors: display message
    if (errors.length) {
        alert("Please fill all the required fields (" + required_fields.join(", ") + ")!");
    }
    
    return (errors.length == 0);
}

function toggle(el) {
    el.style.display = (el.style.display == "none") ? "block" : "none";
}

function toggle_optional() {
    toggle($("optional-fields"));
}

function onload() {
    contact_form = $("contact-form");
    if (contact_form) {
        contact_form.onsubmit = check_form;
    }
}

window.onload=onload;
