$(document).ready( function() {
/*Validação de Campos de Formulário*/
    function validaCampo(campo) {
        var error = false;
        var errorId = "errorMsg"+$(campo).attr("name");
        
        // campos requeridos
        if ($(campo).attr("class").indexOf("req") != -1) {
            if (!$(campo).val().length || $.trim($(campo).val()) == $.trim($(campo).attr("alt")))
                error = true;
                errorMsg = "<span id=req>Esse campo precisa ser preenchido!</span>";
        }
        // campos numéricos
        if ($(campo).attr("class").indexOf("num") != -1) {
            if (!/^[0-9]*$/.test($(campo).val())  || ($.trim($(campo).val()) == $.trim($(campo).attr("alt"))))
                error = true;
                errorMsg = "<span id=req>Esse campo precisa ser numérico</span>";
        }
        // campos de data
        if ($(campo).attr("class").indexOf("data") != -1) {
            if (!/^[[0-9]{2}\/[0-9]{2}\/[0-9]{4}]*$/.test($(campo).val())  || ($.trim($(campo).val()) == $.trim($(campo).attr("alt"))))
                error = true;
                errorMsg = "Insira uma data válida";
        }
        // strings (Somente Letras)
        if ($(campo).attr("class").indexOf("str") != -1) {
            if (!/^[a-zA-Z àÁÀáéÈÉèíÌÍìóÓÔôÒòúÚÙùöÖäÄåÅ]*$/.test($(campo).val())  || ($.trim($(campo).val()) == $.trim($(campo).attr("alt"))))
                error = true;
                errorMsg = "<span id=req>Esse campo precisa ser alfabético!</span>";
        }
        // emails
        if ($(campo).attr("class").indexOf("email") != -1) {
            if (!/^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3}$/.test($(campo).val())  || ($.trim($(campo).val()) == $.trim($(campo).attr("alt"))))
                error = true;
                errorMsg = "<span id=req>E-mail inválido</span>";
        }
		// cpf
		if ($(campo).attr("class").indexOf("cpf") != -1) 
		{

			var cpf = $(campo).val();
   			cpf = remove(cpf, ".");
   			cpf = remove(cpf, "-");
			
   			if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  		cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  		cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  		cpf == "88888888888" || cpf == "99999999999")
			{
                error = true;
                errorMsg = "<span id=req>CPF Inválido</span>";
   			}

   			soma = 0;
   			for(i = 0; i < 9; i++)
   	 			soma += parseInt(cpf.charAt(i)) * (10 - i);
   				resto = 11 - (soma % 11);
   			if(resto == 10 || resto == 11)
			 resto = 0;
   			if(resto != parseInt(cpf.charAt(9)))
			{
                error = true;
                errorMsg = "<span id=req>CPF Inválido</span>";
   			}
   			soma = 0;
  	 		for(i = 0; i < 10; i ++)
	 			soma += parseInt(cpf.charAt(i)) * (11 - i);
   				resto = 11 - (soma % 11);
   			if(resto == 10 || resto == 11)
	 			resto = 0;
   	 			if(resto != parseInt(cpf.charAt(10)))
   				{
                error = true;
                errorMsg = "<span id=req>CPF Inválido</span>";
   				}
        }
        
        // cnpj
        if ($(campo).attr("class").indexOf("cnpj") != -1) {	
				if(validaCNPJ($(campo).val())==false)
				{
				error = true;
                errorMsg = "<span id=req>CNPJ Inválido</span>";
					
				}
		}
        
        
       // tel
        if ($(campo).attr("class").indexOf("tel") != -1) {	
			var tel = $(campo).val();
			
			tel = remove(tel, "(");
			tel = remove(tel, ")");
			tel = remove(tel, "-");
			tel = remove(tel, "_");
			
			if(!is_numeric(tel)){
				error = true;
                errorMsg = "<span id=req>Telefone inválido</span>";
            }	
		}
        
               // DDD
        if ($(campo).attr("class").indexOf("ddd") != -1) {	
			var ddd = $(campo).val();		
			if(!is_numeric(ddd)){
				error = true;
                errorMsg = "<span id=req>ddd</span>";
            }	
		}
		
		
		
           
        if (error) {
            $(campo).addClass("error");
            if(errorMsg){
                if(!$("#"+errorId).html()){
                    $(campo).after("<span id=\""+errorId+"\">"+errorMsg+"</span>");
                    $("#"+errorId).show("slow");   
                }
            }
        } 
        else{
            $(campo).removeClass("error");
            var errorId = "errorMsg"+$(campo).attr("name");
            if("#"+errorId){
            	$("#"+errorId).html("Dados Corretos").css("color","green").addClass("correto");
            }else{
				 $(campo).removeClass("correto");
			}
        }
        
        return !error;
    }
    
    $("form").each( function() {
        //Pega os formulários
        $(this).submit(function () {
            var validationError = false;
            //Testa se os campos são válidos
            $("input, select, textarea", this).each( function() {
                if ($(this).attr("class")) {
                    if (!validaCampo(this))
                        validationError = true;
                }
            });
            return !validationError;
        });
    
        $("input, select, textarea", this).each( function() {
            if ($(this).attr("class")) {         
                  $(this).bind("blur", function() { validaCampo(this); } ); 
                  $(this).bind("dblclick",function() { if($(this).attr("type") != "submit") $(this).val("") } );
                }
        });
    });
    
    
    
     function remove(str, sub) {
   		i = str.indexOf(sub);
   		r = "";
  		 if (i == -1) return str;
  			 r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
  		 return r;
 	}

    
    
    function is_numeric(valor)
	{
    validChar = '0123456789.,-';
    	if ((typeof validChar != 'undefined') || (validChar != '') )
        {
    		for(var i=0;i<valor.length;i++)
        		if(validChar.indexOf(valor.substr(i,1))<0)
        		{
            		return false;
        		}
        		else{
    				return true;
    			}
		}
		else{
			return false;
		}
	}
    
    function validaCNPJ(CNPJ) {
                 
                 erro = new String;
                 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                 if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
                 }
                 //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x;
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
               }
               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
 				}
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]);
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                      erro +="Dígito verificador com problema!";
               }
               if (erro.length > 0){
                      
                       return false;
               } else {
                       return true;
               }
               return true;
       }

    
});
