if(typeof Prototype=='undefined')
throw("WBS Validate Form requires the Prototype JavaScript framework");

if(typeof Effect=='undefined')
throw("WBS Validate Form requires the Effect JavaScript framework");

var WBSValidateFormMessages = {
    req: 'Dato obligatorio',
    lenmin: 'Minimo de caracteres ',
    lenmax: 'Maximo de caracteres ',
    email: 'Email no valido'
};

function WBSValidateForm(fields)
{
    var errors = $A(document.getElementsByClassName('wbsvalidateform_error'));
    errors.each(function(error)
    {
        Element.remove($(error));
    });

    for(i=0; i<fields.length; i++)
    {
        if(typeof $(fields[i].id) != 'undefined')
        {
            if(!WBSFieldRequiered(fields[i]))
            return false;

            if(!WBSFieldLen(fields[i]))
            return false;

            if(!WBSFieldEmail(fields[i]))
            return false;
        }
    }

    return true;
};

function WBSFieldActivate(field)
{
    Field.activate(field);
    new Effect.Shake(field);
}

function WBSFieldInsertion(field,msg)
{
    new Insertion.Before(field, '<div class="wbsvalidateform_error">'+msg+'</div>');
}

function WBSFieldRequiered(control)
{
    if(control.req && !Field.present(control.id))
    {
        var msg = (control.msg && control.msg.req)?control.msg.req:WBSValidateFormMessages.req;
        WBSFieldInsertion(control.id,msg);
        WBSFieldActivate(control.id);
        return false;
    }

    return true;
}

function WBSFieldLen(control)
{
    if(control.len && $F(control.id))
    {
        if(control.len.min && control.len.min > $F(control.id).length)
        {
            var msg = (control.msg && control.msg.lenmin)?control.msg.lenmin:WBSValidateFormMessages.lenmin+control.len.min;
            WBSFieldInsertion(control.id,msg);
            WBSFieldActivate(control.id);
            return false;
        }

        if(control.len.max && control.len.max < $F(control.id).length)
        {
            var msg = (control.msg && control.msg.lenmax)?control.msg.lenmax:WBSValidateFormMessages.lenmax+control.len.max;
            WBSFieldInsertion(control.id,msg);
            WBSFieldActivate(control.id);
            return false;
        }
    }

    return true;
}

function WBSFieldEmail(control)
{

    if(control.type == 'email' && $F(control.id))
    {
        var regexpMail = /[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+/;

        if(!regexpMail.test($F(control.id)))
        {
            var msg = (control.msg && control.msg.email)?control.msg.email:WBSValidateFormMessages.email;
            WBSFieldInsertion(control.id,msg);
            WBSFieldActivate(control.id);
            return false;
        }

    }

    return true;
}

