// JavaScript Document
/**************************
 * formata CPF     000.000.000-00
 * Ex.: <input type="text" name="cpf" size="15" maxlength="14" onKeyUp="fmtCPF(this, event);">
**************************/
function fmtCPF( campo, e ){
  valor = campo.value;
  res = "";

  if ( window.event ){   // internet explorer
    tecla = window.event.keyCode;
  }
  else if ( e ){  // firefox
    tecla = e.which;
  }

  if ( tecla != 8 ){
    for( i=0; i < valor.length; i++ ){
      if( !isNaN(valor.charAt(i)) && valor.charAt(i) != " " ){
        res += valor.charAt(i);
        if( res.length == 3 || res.length == 7 ){
          res += ".";
        }
        if( res.length == 11 ){
          res += "-";
        }
      }
    }
    campo.value = res;
  }
}



/**************************
 * verifica se o CPF digitado e valido
 * Ex.: <input type="text" name="cpf" size="15" maxlength="14" onBlur="validarCPF(this, event);">
**************************/
function validarCPF( cpf ){

  var valor = tiraFormatacao( cpf.value );
  var v1 = 0;
  var v2 = 0;

  //Calcula o primeiro dígito de verificação.
  for( i=0; i < 9; i++ ){
    v1 += parseInt( valor.charAt(i) ) * ( 10 - i );
  }
  if( v1 % 11 < 2 ){
    v1 = 0;
  }
  else{
    v1 = 11 - (v1 % 11);
  }
  
  //Calcula o segundo dígito de verificação.
  for( i=0; i < 10; i++ ){
    v2 += parseInt( valor.charAt(i) ) * ( 11 - i );
  }
  if( v2 % 11 < 2 ){
    v2 = 0;
  }
  else{
    v2 = 11 - (v2 % 11);
  }

  if( v1 != parseInt(valor.charAt(9)) || v2 != parseInt(valor.charAt(10)) ){
    return false;
  }
  else{
    return true;
  }
}



/**************************
 * formata CNPJ     00.000.000/0000-00
 * Ex.: <input type="text" name="cnpj" size="15" maxlength="14" onKeyUp="fmtCNPJ(this, event);">
**************************/
function fmtCNPJ( campo, e ){
  valor = campo.value;
  res = "";

  if ( window.event ){   // internet explorer
    tecla = window.event.keyCode;
  }
  else if ( e ){  // firefox
    tecla = e.which;
  }

  if ( tecla != 8 ){
    for( i=0; i < valor.length; i++ ){
      if( !isNaN(valor.charAt(i)) && valor.charAt(i) != " " ){
        res += valor.charAt(i);
        if( res.length == 2 || res.length == 6 ){
          res += ".";
        }
        if( res.length == 10 ){
          res += "/";
        }
        if( res.length == 15 ){
          res += "-";
        }        
      }
    }
    campo.value = res;
  }
}



/**************************
 * verifica se o cnpj digitado e valido
 * Ex.: <input type="text" name="cnpj" size="15" maxlength="14" onBlur="validarCNPJ(this, event);">
**************************/
function validarCNPJ( cnpj ){

  var valor = tiraFormatacao( cnpj.value );
  var v1 = 0;
  var v2 = 0;

  //Calcula o primeiro dígito de verificação.
  for( i=0; i < 4; i++ ){
    v1 += parseInt( valor.charAt(i) ) * ( 5 - i );
  }
  for( ; i < 12; i++ ){
    v1 += parseInt( valor.charAt(i) ) * ( 13 - i );
  }
  
  if( v1 % 11 < 2 ){
    v1 = 0;
  }
  else{
    v1 = 11 - (v1 % 11);
  }
  
  //Calcula o segundo dígito de verificação.
  for( i=0; i < 5; i++ ){
    v2 += parseInt( valor.charAt(i) ) * ( 6 - i );
  }
  for( ; i < 13; i++ ){
    v2 += parseInt( valor.charAt(i) ) * ( 14 - i );
  }
  
  if( v2 % 11 < 2 ){
    v2 = 0;
  }
  else{
    v2 = 11 - (v2 % 11);
  }
  
  if( v1 != parseInt(valor.charAt(12)) || v2 != parseInt(valor.charAt(13)) ){
    return false;
  }
  else{
    return true;
  }
}



/**************************
 * formata telefone     0000-0000
 * Ex.: <input type="text" name="telefone" size="10" maxlength="9" onKeyUp="fmtTel(this, event);">
**************************/
function fmtTel( campo, e ){
  valor = campo.value;
  res = "";

  if ( window.event ){   // internet explorer
    tecla = window.event.keyCode;
  }
  else if ( e ){  // firefox
    tecla = e.which;
  }

  if ( tecla != 8 ){
    for( i=0; i < valor.length; i++ ){
      if( !isNaN(valor.charAt(i)) && valor.charAt(i) != " " ){
        res += valor.charAt(i);
        if( res.length == 4 ){
          res += "-";
        }
      }
    }
    campo.value = res;
  }
}



/**************************
 * formata CEP     00000-000
 * Ex.: <input type="text" name="cep" size="10" maxlength="9" onKeyUp="fmtCEP(this, event);">
**************************/
function fmtCEP( campo, e ){
  valor = campo.value;
  res = "";

  if ( window.event ){   // internet explorer
    tecla = window.event.keyCode;
  }
  else if ( e ){  // firefox
    tecla = e.which;
  }

  if ( tecla != 8 ){
    for( i=0; i < valor.length; i++ ){
      if( !isNaN(valor.charAt(i)) && valor.charAt(i) != " " ){
        res += valor.charAt(i);
        if( res.length == 2 ){
          res += ".";
        }
        if( res.length == 6 ){
          res += "-";
        }
      }
    }
    campo.value = res;
  }
}



/**************************
 * formata data     00/00/0000
 * Ex.: <input type="text" name="telefone" size="11" maxlength="10" onKeyUp="fmtData(this, event);">
**************************/

function fmtData( campo, e ){
  valor = campo.value;
  var res = "";  

  if ( window.event ){   // internet explorer
    tecla = window.event.keyCode;
  }
  else if ( e ){  // firefox
    tecla = e.which;
  }
 
  if( tecla != 8 ){
    for( i=0; i < valor.length; i++ ){
      if( !isNaN(valor.charAt(i)) && valor.charAt(i) != " " ){
        res += valor.charAt(i);
        if( res.length == 2 || res.length == 5 ){
          res += "/";
        }
      }
    }
    campo.value = res;
  }
}


/**************************
 * verifica data 00/00/0000
 * Ex.: validarData( obj );
**************************/
function validarData( data ){

  var  valor = tiraFormatacao( data.value );
  dia = valor.substr(0, 2);
  mes = valor.substr(2, 2);
  ano = valor.substr(4, 4);

  if( mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12 ){
    if( dia > 31 ){
      return false;
    }
  }
  else if( mes == 2 ){
    if( (ano % 4 == 0 && ano % 100 > 0) || ano % 400 == 0 ){ // ano bissexto é todo ano que é divisível por 4 e não é por 100, ou é por 400
      if( dia > 29 ){
        return false;
      }     
    }
    else{
      if( dia > 28 ){
        return false;
      }
    }
  }
  else{
    if( dia > 30 ){
      return false;
    }
  }
  return true;
}




/**************************
 * permite apenas a entrada de numeros
 * Ex.: <input type="text" name="numero" size="5" maxlength="4" onKeyUp="apenasNumeros(this);">
**************************/

function apenasNumeros( campo ){
  
  var valor = campo.value;
  var res = "";  
  for( i=0; i < valor.length; i++ ){
    if( !isNaN(valor.charAt(i)) && valor.charAt(i) != " " ){
      res += valor.charAt(i);
    }
  }

  campo.value = res;
}


function validarForm( formulario ){

  frm = document.getElementById( formulario );
  var qtd = 0;

  for( cont = 0; cont < frm.length; cont++ ){  // percorre todos os campos do formulario

    obj = frm.elements[cont];
    sTipo = obj.type;
    
    if( sTipo != "hidden" && sTipo != "submit" && sTipo != "reset" && sTipo != "button" && sTipo != "image" &&
        sTipo != "checkbox" && sTipo != "radio" ){

      objById = document.getElementById( obj.id );
      
      if( objById.getAttribute("obrigatorio") == "S" ){ // verifica se o campo obrigatorio esta vazio
        if( objById.value.length == 0 ){
          objById.style.backgroundColor = "#FAFCB6";
          qtd++;
        }
        else{
          objById.style.backgroundColor = "#FFFFFF";
        }
      }
     
    }
  }
  
  if( qtd == 1 ){
    alert("O campo destacado é obrigatório.");
    return false;
  }
  
  if( qtd > 1 ){
    alert("Os campos destacados são obrigatórios.");
    return false;
  }
  
  if( qtd == 0 ){ //quer dizer que todos os obrigatorios foram digitados; agora vamos validar os campos especiais (CNPJ, CPF, DATA)
    
    for( cont = 0; cont < frm.length; cont++ ){
      obj = frm.elements[cont];
      objById = document.getElementById( obj.id );
      
      if( objById.getAttribute("obrigatorio") == "S" || trim( obj.value ).length > 0 ){
      
        if( objById.getAttribute("validar") == "CNPJ" && !validarCNPJ( obj ) ){
          alert("Por favor, digite um CNPJ válido.");
          return false;
        }
        if( objById.getAttribute("validar") == "CPF" && !validarCPF( obj ) ){
          alert("Por favor, digite um CPF válido.");
          return false;
        }
        if( objById.getAttribute("validar") == "DATA" && !validarData( obj ) ){
          alert("Por favor, digite uma data válida.");
          return false;
        }
        
      }
    }
  
  }
  frm.submit();
}


/**************************
 * tira pontos(.), vírgulas(,), barras(/) e traços (-) de uma string
 * Ex.: var res = tiraFormatacao( str );
**************************/
function tiraFormatacao( str ){
  var res = str.replace(/[\.\,\/\-]/g, "");
  return res;
}


/**************************
 * tira todos os espaços de uma string
 * Ex.: var res = trim( str );
**************************/
function trim( str ){
  var res = "";
  for( i=0; i < str.length; i++ ){
    if( str.charAt(i) != " " ){
      res += str.charAt(i);
    }    
  }
  return res;
}
/**************************
 * Vetifica se tem @ na string
 * Ex.: <input type="text" name="numero" size="5" maxlength="4" onKeyUp="fmtEmail(this);">
**************************/
function fmtEmail( str ){
  var res = str.value;
  	if (res != ""){
	  var arroba = res.search("@");
   	  if (arroba >= 0) {
	  return str;
	  return true;
    }else{
	  alert('Este email esta faltando o @');
	  return false;
	  }
}}
/**************************
 * Retira as apas simples
 * Ex.: <input type="text" name="numero" size="5" maxlength="4" onKeyUp="formataVarchar(this);">
**************************/
function formataVarchar( str ){
	var res = str.value;
	if (res != ""){
	 var string = res.replace("'"," ");
	 document.form.name.value = string
	 return string;
	 return true;
}}


