var W3CDOM = (document.getElementsByTagName && document.createElement);

window.onload = function () {
    document.forms[0].onsubmit = function () {
        return validate()
    }
}

function validate() {
    validForm = true;
    firstError = null;
    errorstring = '';
    var x = document.forms[0].elements;
    
    var emptyError = ' « 必須';
    var formatError = ' « 半角英数';
    
    if (!x['name'].value.replace(/^\s+/g,""))
        writeError(x['name'],emptyError,'name_label');
    if (!x['email'].value)
        writeError(x['email'],emptyError,'email_label');
    var s = x['email'].value
    if (!/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9-]{2,4}$/.test(s))
        writeError(x['email'],formatError,'email_label');
    if (x['phone'].value.replace(/^\s+/g,""))
    {
        s = x['phone'].value
        s = s.replace(/[\.\-\ ]/g, '');
        if(!s.match(/^[0-9]+$/))
            writeError(x['phone'],formatError,'phone_label');
    }
    if (!x['inquiry'].value.replace(/^\s+/g,""))
        writeError(x['inquiry'],emptyError,'inquiry_label');
    
    if (!W3CDOM)
        alert(errorstring);
    if (firstError)
        firstError.focus();
    return validForm;
}

function writeError(obj,message,parent) {
    validForm = false;
    if (obj.hasError) return;
    if (W3CDOM) {
        obj.className += 'field_error';
        obj.onchange = removeError;
        var sp = document.createElement('span');
        sp.className = 'error';
        sp.appendChild(document.createTextNode(message));
        document.getElementById(parent).appendChild(sp);
        obj.hasError = sp;
    }
    else {
        errorstring += obj.name + ': ' + message + '\n';
        obj.hasError = true;
    }
    if (!firstError)
        firstError = obj;
}

function removeError()
{
    this.className = this.className.substring(0,this.className.lastIndexOf(' '));
    document.getElementById(this.id + '_label').removeChild(this.hasError);
    this.hasError = null;
    this.onchange = null;
}
