 /**
 * @author: Thiago Hirabai Dias
 * @license: free
 * @website: hirabai.com
 */

/* --------------------- VARIÁVEIS CUSTOMIZÁVEIS ----------------------*/

var alerta0 = 'Por favor, aguarde. Processo em andamento!';
var alerta1 = 'Por favor, preencha o campo <nome_campo> corretamente!';
var alerta2 = 'O campo <nome_campo> deve conter apenas números!';

/* ------------------------ NÃO EDITAR ABAIXO -------------------------*/

var d = window.document;
var passou=0;
var typeEl;
var isNumeric = /^\d+$/;

String.prototype.trim = function(){
  return this.replace(/^\s*/, '').replace(/\s*$/, '');
}

String.prototype.haveNo = function(){
  return this.toLowerCase().search(/no/)>-1?true:false;
}


function rename(n){
	var n2 = n;
	n2 = n2.replace('area', 'área');
	n2 = n2.replace('comentario', 'comentário');
	n2 = n2.replace('email', 'e-mail');
	n2 = n2.replace('endereco', 'endereço');
	n2 = n2.replace('funcao', 'função');
	n2 = n2.replace('horario', 'horário');
	n2 = n2.replace('inscricao', 'inscrição');
	n2 = n2.replace('nivel', 'nível');
	n2 = n2.replace('numero', 'número');
	n2 = n2.replace('orgao', 'órgão');
	n2 = n2.replace('pais', 'país');
	n2 = n2.replace('profissao', 'profissão');
	n2 = n2.replace('razao', 'razão');
	n2 = n2.replace('referencia', 'referência');
	n2 = n2.replace('usuario', 'usuário');
	return n2.toString();
}


function alerta(nC, el, tipo){
  tipo = tipo.toString().trim().toLowerCase();
  newName = rename(nC).toUpperCase();

  switch(tipo){
	  case 'normal':
		  window.alert(alerta1.replace('<nome_campo>', newName));
		  break;
	  case 'numero':
		  window.alert(alerta2.replace('<nome_campo>', newName));
		  break;
	  default:
		  window.alert(alerta1.replace('<nome_campo>', newName));
  }

  if(typeEl != 'radio' && typeEl != 'checkbox'){
	  try{
		el.focus();
		el.select();
	  }
	  catch(e){}
  }
}


function checkCNPJ(str) {
	// onlyzero: se str = 00000000000000 (ou + zeros), retorna false
    var onlyzero = true;
    for(i=0; i<str.length; i++){
	  if(str[i] != '0') onlyzero = false;
	}

	if(!isNumeric(str) || onlyzero) return false;
	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;
}


function checkCPF(numcpf){
	if(!isNumeric(numcpf)) return false;
	x = 0;
	soma = 0;
	dig1 = 0;
	dig2 = 0;
	texto = '';
	numcpf1 = '';
	len = numcpf.length;
	x = len -1;
	// var numcpf = "12345678909";
	for (var i=0; i <= len - 3; i++) {
		y = numcpf.substring(i,i+1);
		soma = soma + ( y * x);
		x = x - 1;
		texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1=0 ;
	if (dig1 == 11) dig1=0 ;
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	x = 11; soma=0;
	for (var i=0; i <= len - 2; i++) {
		soma = soma + (numcpf1.substring(i,i+1) * x);
		x = x - 1;
	}
	dig2= 11 - (soma % 11);
	if (dig2 == 10) dig2=0;
	if (dig2 == 11) dig2=0;
	if ((dig1 + '' + dig2) == numcpf.substring(len,len-2)) {
		return true;
	}
	else{
		return false;
	}
}


/*---------------------------------------------------------------------*/


function mailCheck(m){
  return (m.search(/^[a-zA-Z][\.\w-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/)==-1||m.search(/\.{2,}|\.-|-\.|-{2,}|\._|_\./)>-1)?false:true;
}


function isRadio(f,t){
  var fld = f.elements[t];
  var x, len = fld.length;
  for(x=0; x<len; ++x) if(fld[x].checked) break;
  return len<=x?false:true;
}


function validarCampos(f){
  var i, el, nC, vC, totalEl=f.elements.length;

  for(var i=0; i<totalEl; i++){
    el=f.elements[i];
    nC=el.name;
    nClass=el.className.toLowerCase();
	vC=el.value;
	typeEl = el.type;

    if(typeEl!='hidden' && typeEl!='submit' && !nClass.haveNo()){

		if(typeEl!='file' && typeEl!='password' && !el.getAttribute('multiple')){
		  try{
			  vC=el.value.trim();
		  }catch(e){}
		  el.value=vC;
		}

		if(vC=='' && typeEl!='radio'){
		  alerta(nC,el,'normal');
		  return false;
		}

		if(typeEl=='radio' && !isRadio(f,nC)){
		  alerta(nC,el,'normal');
		  return false;
		}

		if((nClass.search(/email/)>-1 || nC.toLowerCase().search(/email/)>-1) && !mailCheck(vC)){
		  alerta(nC,el,'normal');
		  return false;
		}

		if((nClass.search(/number/)>-1 || nClass.search(/numero/)>-1) && !isNumeric.test(vC)){
		  alerta(nC,el,'numero');
		  return false;
		}

		if((nClass.search(/cpf/)>-1 || nC.toLowerCase().search(/cpf/)>-1) && !checkCPF(vC)){
		  alerta(nC,el,'normal');
		  return false;
		}

		if((nClass.search(/cnpj/)>-1 || nC.toLowerCase().search(/cnpj/)>-1) && !checkCNPJ(vC)){
		  alerta(nC,el,'normal');
		  return false;
		}

		if(passou==1){
		  window.alert(alerta0);
		  setTimeout('passou=0',3000);
		  return false;
		}

	}
  }
  passou=1;
  return true;
}


function findForm(){
  for(i=0; i < d.forms.length; i++){
    if(!d.forms[i].className.haveNo())
      d.forms[i].setAttribute('onsubmit','return validarCampos(this)');
  }
}

window.onload = findForm;
