/* (c) 2005 - Laurent Houdard <laurent@houdard.net> 
   $Id: formvalid.js 1 2008-06-29 11:21:07Z lh $ */

function formValid(form) {
    var W3CDOM = (document.createElement && document.getElementsByTagName);
    if (!W3CDOM) { return true; }

    var check = new Array();
    var post  = new Array();

    var labels = form.getElementsByTagName('LABEL');
    if (labels) {
	for (var i = 0; i < labels.length; i++) {
	    var label = labels[i];
	    var labelfor = label.getAttribute('FOR');
	    if (!labelfor) { labelfor = label.getAttribute('HTMLFOR'); } // IE
	    var input = document.getElementById(labelfor);
	    var str = '';
	    if (label.firstChild) {
		str = label.firstChild.nodeValue;
	    }
	    if (input.className) {
		var classes = input.className.split(" ");
		for (var j = 0; j < classes.length; j++) {
		    var fcheck = 'formValid_'+classes[j];
		    if (window[fcheck]) {
			check.push({func: fcheck, str: str, input: input});
		    }
		    var fsubmit = 'formValid_'+classes[j]+'_submit';
		    if (window[fsubmit]) {
			post.push({func: fsubmit, input: input});
		    }
		}
	    }
	}
    }

    var error = '';

    while (check.length) {
	var c = check.pop();
	var e = window[c.func](c.str, c.input);
	if (e) { error += e+'\n'; }
    }

    if (error != '') {
	alert(error);
	return false;
    }

    while (post.length) {
	var p = post.pop();
	window[p.func](p.input);
    }

    return true;
}

function formValid_isInt(str, input) {
    var data = input.value;
    return ((data != '' && !data.match(/^([-]?[0-9]+)$/)) ?
	    'Le champ "'+str+'" doit être un entier' : '');
}

function formValid_isFloat(str, input) {
    var data = input.value;
    return ((data != '' && !data.match(/^([-]?\d+(\.\d+)?)$/)) ?
	    'Le champ "'+str+'" doit être un nombre' : '');
}

function formValid_mandatory(str, input) {
    var data = input.value;
    return ((data == '') ? 'Le champ "'+str+'" est obligatoire' : '');
}

function formValid_checkPasswd(str, input) {
    var p1 = document.getElementById(input.id+'_1');
    var p2 = document.getElementById(input.id+'_2');
    if (p1.value != p2.value) {
	p1.value = '';
	p2.value = '';
	return 'Erreur dans la confirmation du mot de passe';
    }
    return '';
}

function formValid_checkPasswd_submit(input) {
    var p1 = document.getElementById(input.id+'_1');
    var p2 = document.getElementById(input.id+'_2');
    if (p1.value != '') {
	input.disabled = false;
	input.value = calcMD5(p1.value);
    }
    p1.disabled = true;
    p2.disabled = true;
}

