jQuery.validar = {};

jQuery.validar.isEmpty = function(val) {
    var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
    if ((val.length == 0) || (val == null) || ((val.search(re)) > -1)) {
        return true;
    } else {
        return false;
    }
};
// End jQuery.validar.isEmpty

jQuery.validar.isCPF = function(arg) {
    var pri = arg.substring(0, 3);
    var seg = arg.substring(4, 7);
    var ter = arg.substring(8, 11);
    var qua = arg.substring(12, 14);
    var i;
    var numero = (pri + seg + ter + qua);
    var s = numero;
    var c = s.substr(0, 9);
    var dv = s.substr(9, 2);
    var d1 = 0;
    for (i = 0; i < 9; i++)
        d1 += c.charAt(i) * (10 - i);
    var result;
    if (d1 == 0) result = "falso";
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1) result = "falso";
    d1 *= 2;
    for (i = 0; i < 9; i++) d1 += c.charAt(i) * (11 - i);
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1) result = "falso";
    return !(result == "falso");
};
// End jQuery.validar.isCPF

jQuery.validar.isCNPJ = function(str) {
    if (!(str = /^\d?(\d{2})\.?(\d{3})\.?(\d{3})\/?(\d{4})\-?(\d{2})/.exec(str))) return false;

    var sum1 = 0,
    sum2 = 0,
    sum3 = 0,
    calc1 = 5,
    calc2 = 6;

    str.shift();
    str = str.join("");

    for (var i = 0; i <= 12; i++) {
        calc1 = (calc1 < 2) ? 9 : calc1;
        calc2 = (calc2 < 2) ? 9 : calc2;

        if (i <= 11) sum1 += str[i] * calc1;

        sum2 += str[i] * calc2;
        sum3 += str[i];
        calc1--;
        calc2--;
    }

    sum1 %= 11;
    sum2 %= 11;

    return (sum3 && str[12] == (sum1 < 2 ? 0 : 11 - sum1) && str[13] == (sum2 < 2 ? 0 : 11 - sum2)) ? str : false;
}
// End jQuery.validar.isCNPJ

jQuery.validar.isEmail = function(str) {
    var apos = str.indexOf("@");
    return !(apos < 1 || str.lastIndexOf(".") - apos < 2);
}
// End jQuery.validar.isEmail

jQuery.validar.isData = function(str){
    var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
    var aRet = true;
    if ((str) && (str.match(expReg)) && (str != '')) {
        var dia = str.substring(0,2);
        var mes = str.substring(3,5);
        var ano = str.substring(6,10);
        if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30) 
            aRet = false;
        else 
        if ((ano % 4) != 0 && mes == 2 && dia > 28) 
            aRet = false;
        else
        if ((ano%4) == 0 && mes == 2 && dia > 29)
            aRet = false;
    } else 
        aRet = false;  
    return aRet;
};
// End jQuery.validar.isData

jQuery.validar.isNascimento = function(str, anoAtual, idadeMaxima){
    if(jQuery.validar.isData(str)){
        var arr = str.split("/");
        return (parseInt(arr[2]) - parseInt(anoAtual)) <= idadeMaxima;
    }
    return false;
};
// End jQuery.validar.isNascimento

jQuery.validar.filtro = "[validar=texto], [validar=email], [validar=cpf], [validar=igual], [validar=cnpj], [validar=nascimento], [validar=data], [opcional=email], [opcional=cpf], [opcional=igual], [opcional=cnpj], [opcional=nascimento], [opcional=data]";

jQuery.validar.marcar = function(el){
    jQuery(el).find("input, select, textarea")
    .filter(jQuery.validar.filtro)
    .filter(":visible")
    .each(function() {
        $(this).after("<em> *</em>");
    });
};
// End jQuery.validar.marcar

// function factory para o validar.me
jQuery.fn.validar = function(_opts) {
    var opts = $.extend({}, jQuery.fn.validar.options, _opts);

    if(opts.marcar) jQuery.validar.marcar(this);
	
    this.submit(function() {
        var $this = $(this);
        return $this.validar.me.call($this, opts);
    });
};
// End jQuery.fn.validar
        
// function que valida o form (this)
jQuery.fn.validar.me = function(o) {
    var r = true;
	
    try {
        r = o.before.call(this);
    } catch (e) {
        //alert(e);
        r = false;
    }
	
    try {
        var $form = this;
        this.find("input, select, textarea")
        .filter(jQuery.validar.filtro)
        //.filter(":visible")
        .each(function() {
        	
        	//console.log(this);
        	
            var $this = jQuery(this),
            val = jQuery.trim($this.val()),
            label = '',
            req = $this.attr("validar"),
			opc = $this.attr("opcional");
			
			if (typeof jQuery("label[for=" + $this.attr("id") + "]")[0] == "object") {
                label = jQuery.trim($form.find("label[for=" + $this.attr("id") + "]").text());
            } else {
                label = jQuery.trim($this.attr("label"));
            }
	
            try {
                if (r) {
					if(req){
						if (jQuery.validar.isEmpty(val) || $this.val() == $this.attr('holder')) {
							throw "Por favor, preencha o campo " + label + ".";
						}
					}
					
					if(opc || req){
						req = opc || req;
						
						//console.log(req);
						
						if (req == "email") {
							if (!jQuery.validar.isEmail(val)) {
								throw "Por favor, preencha corretamente o campo " + label + ".";
							}
						} else if (req == "cpf") {
							if (!jQuery.validar.isCPF(val)) {
								throw "Por favor, preencha corretamente o campo " + label + ".";
							}
						} else if (req == "cnpj") {
							if (!jQuery.validar.isCNPJ(val)) {
								throw "Por favor, preencha corretamente o campo " + label + ".";
							}
						} else if (req == "igual") {
							if (val != jQuery($this.attr("validarIgual")).val()) {
								throw "Por favor, preencha corretamente o campo " + label + ".";
							}
						}else if (req == "data"){
							if (!jQuery.validar.isData(val)) {
								throw "Por favor, preencha corretamente o campo " + label + ".";
							}
						}else if (req == "nascimento") {
							if (!jQuery.validar.isNascimento(val, jQuery.fn.validar.options.anoAtual, jQuery.fn.validar.options.idadeMaxima)) {
								throw "Por favor, preencha corretamente o campo " + label + ".";
							}
						}
					}
                    $this.addClass(jQuery.fn.validar.options.classSucesso);
                }
            } catch (e) {
                r = false;
	                    	
                $this.removeClass(jQuery.fn.validar.options.classSucesso).addClass(jQuery.fn.validar.options.classErro);
	                    	
                o.alert(e);
                setTimeout(function() {
                    var el_foco_ui = document.getElementById("#"+$this.attr('id')+"-button");
		            if(el_foco_ui) {
		            	$(el_foco_ui).focus();
		            }else{
		            	$this.focus();
		            }
                }, 10);
            }
        });
                
    } catch (e) {
        alert(e);
        r = false;
    }

    if (r && typeof o.after == "function") {
        try {
            r = o.after.call(this);
        } catch (e) {
            alert(e);
            r = false;
        }
    }

    return r;
};
// End jQuery.fn.validar.me
        
// options defaults
jQuery.fn.validar.options = {};
jQuery.fn.validar.options.before = function(){
    return true;
};
jQuery.fn.validar.options.after = function(){
    return true;
};
jQuery.fn.validar.options.alert = function(message){
    alert(message);
};
jQuery.fn.validar.options.marcar = true;
jQuery.fn.validar.options.anoAtual = 2011;
jQuery.fn.validar.options.idadeMaxima = 122;
jQuery.fn.validar.options.classSucesso = "validar-sucesso";
jQuery.fn.validar.options.classErro = "validar-erro";
// End jQuery.fn.validar.options
