function formValidate(form, func)
{
    var i
    var fields = form.elements
    var l = fields.length
    var valid = false

    for (i = 0; i < l; i++)
    {
    	valid = fieldValidate(fields[i])

        if (!valid)
        {
    		return false
    	}
    }

    if (func != null)
    {
    	return eval(func)
    } else
    {
    	return true
    }
}

function fieldValidate(field, func)
{

    //ddv-required
    if (field.attributes["ddv-required"] != null) {
    	if ((field.attributes["ddv-required"].value) && (isBlank(field.value))) {
    		alert("L'inserimento di un valore nel campo è obbligatorio!")
    		field.focus()
    		return false
    	}
    }

    //ddv-regexp
    if (field.attributes["ddv-regexp"] != null) {
    	var re = new RegExp("^" + field.attributes["ddv-regexp"].value + "$")

    	if (field.value.match(re) == null) {
    		alert("Il valore inserito non rispetta il formato previsto!")
    		field.focus()
    		return false
    	}
    }

    if (func != null)
    {
    	return eval(func)
    } else
    {
    	return true
    }
}

function setConstraint(element, attribute, value)
{
    var elem;
    var attr;

    elem = document.getElementById(element);

    if (elem != null)
    {
    	attr = document.createAttribute(attribute);
    	attr.value = value;
    	elem.setAttributeNode(attr)
    }
}

function isBlank( cArg )
{
    while ( cArg.length > 0 && cArg.charAt( cArg.length - 1 ) == " " )
    {
    	cArg = cArg.substring( 0, cArg.length - 1 );
    }

    return cArg == "";
}

function initValidation()
{
    setConstraint("nome", "ddv-required", "true");
    setConstraint("email", "ddv-regexp", "[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}");
}

function PopUpPage(page)
{
    var helpwin = OpenCenteredWin("",650,750);
    if (helpwin)
    {
        helpwin.location=page;
        helpwin.focus();
    }
}

