/**
 * @author bellom
 */
function validator(validaciones){
    var valido = true;
    for (validacion in validaciones) {
        var validacionObj = validaciones[validacion];
        var camposSelector = validacionObj.selector;
        var camposArray = camposSelector.split(',');
        for (camposItem in camposArray) {
            campo = camposArray[camposItem];
            validadorr = new validador($(campo));
            switch (validacionObj.regla) {
                case "esRequerido":
                    valido = validadorr.esRequerido() && valido;
                    break;
                case "esCorreo":
                    valido = validadorr.esCorreo() && valido;
                    break;
				case "esURL":
                    valido = validadorr.esURL() && valido;
                    break;
                case "opcionSeleccionada":
                    valido = validadorr.opcionSeleccionada() && valido;
                    break;
				case "opcionMultiple":
                    valido = validadorr.opcionMultiple() && valido;
                    break;
                case "radioSeleccionado":
                    valido = validadorr.radioSeleccionado() && valido;
                    break;
                case "esIgual":
                    valido = validadorr.esIgual() && valido;
                    break;
                case "minCaracteres":
                    numChars = validacionObj.caracteres;
                    valido = validadorr.minCaracteres(numChars) && valido;
                    break;
                case "minCaracteresNum":
                    numChars = validacionObj.caracteres;
                    valido = validadorr.minCaracteresNum(numChars) && valido;
                    break;
                case "checkSeleccionado":
                    valido = validadorr.checkSeleccionado() && valido;
                    break;
				case "esNumerico":
                    valido = validadorr.esNumerico() && valido;
                    break;
				case "esMayorCero":
                    valido = validadorr.esMayorCero() && valido;
                    break;
                default:
                    valido = false;
                    break;
            }
        }
        
    }
    return valido;
}



function validador(campo){

    this.campo = campo;
    var obj = this;
    this.campo.unbind("change");
    this.campo.unbind("keydown");
    this.mensaje = "";
    
    if (this.campo.attr("id") != "") 
        this.label = $("label[for=" + this.campo.attr("id") + "]");
    if (this.campo.is(":radio")) 
        this.label = $("label[for=" + this.campo.attr("name") + "]");
    if (this.campo.is(":checkbox"))
        this.label = $("label[for=" + this.campo.attr("name") + "]");

    
    
    this.campo.click(function(){
        //obj.label.hide();
    });
    
    
    
    this.campo.change(function(){
        obj.limpiarCampo();
    }).keydown(function(){
        obj.limpiarCampo();
    });
    
    //Defecto en IE6 evento limpiar
    if (this.campo.is(":radio")) {
        $(this.campo.selector).click(function(){
            obj.limpiarCampo();
        })
    }
    
    this.esCorreo = function(){
        if (this.esRequerido()) {
            this.mensaje = "Este campo no es un correo válido";
            var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
            var test = pattern.test(this.campo.val());
            return this.validar(test);
        }
        else {
            return false;
        }
    };
	
	this.esURL=function(){
		if (this.esRequerido()) {
			var pattern = new RegExp(); 
	    	pattern.compile("^http+(s)?://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_#%&\?\/.=]+$");
            this.mensaje = "Este campo no es un vinculo (link) válido";
            var test = pattern.test(this.campo.val());
            return this.validar(test);
        }
        else {
            return false;
        }
	}
    
    this.radioSeleccionado = function(){
        this.mensaje = "No haz seleccionado una opci&oacute;n";
        var test = this.campo.filter(":checked").size() > 0;
        return this.validar(test);
    };
    
    this.opcionSeleccionada = function(){
        this.mensaje = "Seleccione una opci&oacute;n";
        var test = this.campo.get(0).selectedIndex > 0;
        return this.validar(test);
    };
	
	this.opcionMultiple = function(){
        this.mensaje = "Seleccione al menos una opci&oacute;n";
        var test = this.campo.val()!=null;
        return this.validar(test);
    };
    
    this.esRequerido = function(){
        this.mensaje = "Este campo es requerido";
        var test = this.campo.val() != "";
        return this.validar(test);
    };
    
    this.esIgual = function(otroCampo){
        if (this.esRequerido()) {
            this.mensaje = "Este campo no coincide";
            var otroValor = $(otroCampo).val();
            var test = this.campo.val() == otroValor;
            return this.validar(test);
        }
        else {
            return false;
        }
    };
    
    this.minCaracteres = function(numCaracteres){
        if (this.esRequerido()) {
            this.mensaje = "El Campo debe contener mínimo " + numCaracteres + " caracteres";
            var test = this.campo.val().length >= numCaracteres;
            return this.validar(test);
        }
        else {
            return false;
        }
    };
    
    this.minCaracteresNum = function(numCaracteres){
        if (this.esNumerico()) {
            this.mensaje = "El Campo debe contener mínimo " + numCaracteres + " caracteres numericos";
            var test = this.campo.val().length >= numCaracteres;
            return this.validar(test);
        }
        else {
            return false;
        }
    };
    
    this.esNumerico = function(){
        if (this.esRequerido()) {
            this.mensaje = "El Campo debe contener numeros";
            var test = !isNaN(this.campo.val());
            return this.validar(test);
        }
        else {
            return false;
        }
    };
	
	this.esMayorCero = function(){
        if (this.esNumerico()) {
            this.mensaje = "El numero debe ser mayor que cero";
            var test = (this.campo.val()>0);
            return this.validar(test);
        }
        else {
            return false;
        }
    };
	
    
    this.checkSeleccionado = function(){
        this.mensaje = "No haz seleccionado opciones";
        var test = this.campo.filter(":checked").size() > 0;
        return this.validar(test);
    };
    
    
    this.validar = function(test){
        if (!test) {

            var mensaje = this.mensaje;
			var error= mensajeErrorFlotante(mensaje);


            this.label.empty().append(error).append(this.label.attr("title"));
            if (!this.campo.is(":radio")) 
                this.campo.addClass("error");
            return false;
        }
        else {
            this.limpiarCampo();
            return true;
        }
    };
    
    
    this.limpiarCampo = function(){
        this.label.html(this.label.attr("title"));
        this.campo.removeClass("error");
    };
}


function mensajeErrorFlotante(mensaje){
    var error = $("<a class='errorVal' href='javascript:'></a>");
    xOffset = 15;
    yOffset = 20;
    
    
    error.hover(function(e){
        $("body").append("<p id='errorValidac'>" + mensaje + "</p>");
        $("#errorValidac").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px").fadeIn("fast");
    }, function(e){
        $("#errorValidac").remove();
    }).mousemove(function(e){
        $("#errorValidac").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px");
    });
	return error;
}
