// JavaScript Document
function AbreJanela(pagina,NovaJanela,configuracao) {
        window.open(pagina,NovaJanela,configuracao);
}
//enquete
function ChecaOpcao(frm) {

      var IsSelected;
      IsSelected = '0';

      for (var i = 0; i < frm.length; i++)
      if (frm[i].checked)
      {
         IsSelected = '1';
         break;
      }

      if (IsSelected == '0')
      {
        alert("Alguma Alternativa deve ser selecionada!");
        return false;
      }
      else
      {
        AbreJanela('../enquete/votar.php?radiobutton=' + frm[i].value, "_blank", 'width=300,height=250');
        return true;
      }
 }


function ChecaOpcao2(frm) {

      var IsSelected;
      IsSelected = '0';

      for (var i = 0; i < frm.length; i++)
      if (frm[i].checked)
      {
         IsSelected = '1';
         break;
      }

      if (IsSelected == '0')
      {
        alert("Alguma Alternativa deve ser selecionada!");
        return false;
      }
      else
      {
        AbreJanela('enquete/votar.php?radiobutton=' + frm[i].value, "_blank", 'width=300,height=250');
        return true;
      }
 }



/************************************************
* function bloquearSubmits
* Função para bloquear multiplos submits
************************************************/		

var bexec = true;
function bloquearSubmits(obj) {
  if (bexec) {
    bexec = false;
    if (obj == "") {
      return true;
    } else {
      obj.submit();
    }
  } else {
    return false;
  }
}

/************************************************
* function verificaData
* Verificar campo do tipo Data
************************************************/		

function verificaData(data){
      var dia = parseInt(data.substring(0,2),10);
      var mes = parseInt(data.substring(3,5),10);
      var ano = parseInt(data.substring(6,10),10);
       if (dia <= 31 && mes <=12 && ano >= 1000){
          if (data.substring(0,1)=='0' && data.substring(1,2) != '0' || data.substring(0,1)!='0'){
             if (data.substring(2,3)=="/"){
                if (data.substring(3,4)=='0' && data.substring(4,5)!='0' || data.substring(3,4)!='0'){
                    if (data.substring(5,6)=="/"){
                        if (data.substring(6,7)== '0' || data.substring(6,7)=='' && data.substring(7,8)!='0'){
                            return false;
                        } else {
                          if (mes == 2){
                            if ((dia > 0 ) && (dia <= 29)){
                              if (dia == 29){
                                if ((ano % 4) == 0){
                                  return true;
                                }else{
                                  return false;
                               }
                             }
                           } else {
                              return false;
                           }
                         }
                         if ((mes == 4)||(mes == 6)||(mes == 9)||(mes == 11)){
                           if ((dia > 0 ) && (dia <= 30)){
                             return true;
                           }else{
                             return false;
                           }
                         }
                 if ((mes == 1)||(mes == 3)||(mes == 5)||(mes ==7)||(mes == 8)||(mes == 10)||(mes == 12)) {
                           if ((dia > 0) && (dia <= 31)) {
                              return true;
                           }else{
                             return false;
                           }
                         }
                        }
                    }else{
                       return false;
                    }
                }else{
                  return false;
                }
             }else{
               return false;
             }
          }else{
            return false;
          }
       }else{
         return false;
       }
    return true;
}

/************************************************
* function checkField
* Verificação básica dos seguinte caracteres: & < > | \ / 
* Input: campo a ser verificado
************************************************/

function checkField(s) {
  if ((s.indexOf("&")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
    return false;
  return true;
}

/************************************************
* function isDigit
* Verifica se o caracter é um dígito de 0 a 9
* Input: campo a ser verificado
************************************************/		

function isDigit (c) {
  return ((c >= "0") && (c <= "9")); 
}


/************************************************
* function isNumeric
* Verifica se um campo é numérico. Se contém apenas dígitos de 0 a 9
* Input: campo a ser verificado
************************************************/

function isNumeric(s){
	var i;
	if (isEmpty(s)) 
		return false;
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (!isDigit(c)) return false;
	}
	return true;
}

/************************************************
* function isEmpty
* Verifica se um campo está vazio
* Input: campo a ser verificado
************************************************/		

function isEmpty(s) {
	return ((s == null) || (s.length == 0));
}

/************************************************
* function alinhaNumero
* Alinha numero
* Input: campo a ser verificado
************************************************/		

function alinhaNumero( num , tam , dir ) {
    var aux = "" , len = 0 , i = 0 ;
    len = num.length ;
    for ( i = 0 ; i < len ; i++ )
        if ( num.charAt( i ) != ' ' )
            aux += num.charAt( i ) ;
            len = aux.length ;
    if ( len < tam ) {
        if ( (dir == "e" ) || (dir == "E") )
            for ( i = 0 ; i < ( tam - len ) ; i++ )
                aux = "0" + aux ;
        else
            for( i = 0 ; i < ( tam - len ) ; i++ )
                aux = aux + "0" ;
    }
    return aux ;
}

/************************************************
* function Limpa
* deixa só os digitos no numero (CPF/CGC)
* Input: campo a ser verificado
************************************************/		

function Limpa(S){
    var Digitos = "0123456789";
    var temp = "";
    var digito = "";
    for (var i=0; i<S.length; i++){
        digito = S.charAt(i);
        if (Digitos.indexOf(digito)>=0){
            temp=temp+digito
        }
    }
    return temp
}

/************************************************
* function Resto
* retorna o digito verificador (entrar com S "limpo")
* Input: campo a ser verificado
************************************************/		

function Resto(S){
    var invertido = Inverte(Limpa(S));
    var soma = 0;
    for (var i=0; i<invertido.length; i++){
        soma=soma+(i+2)*eval(invertido.charAt(i));
    }
    soma*=10;
    return ((soma % 11) % 10);
}

/************************************************
* function Inverte
* inverte o string S
* Input: campo a ser verificado
************************************************/		

function Inverte(S){
    var temp="";
    for (var i=0; i<S.length; i++){
        temp=S.charAt(i)+temp;
    }
  return temp;
}

/************************************************
* function validacpf
* Verifica se o numero do CPF é válido
* Input: campo a ser verificado
************************************************/		

function validacpf(cpf) {
    cpf.value = alinhaNumero( cpf.value , 11 , "E" ) ;
//confere se o cpf dado esta OK
    numero = cpf.value;
    if((numero.substr(0,11)=="00000000000") || (numero.substr(0,11)=="11111111111") || (numero.substr(0,11)=="22222222222") || (numero.substr(0,11)=="33333333333") || (numero.substr(0,11)=="44444444444") || (numero.substr(0,11)=="55555555555") || (numero.substr(0,11)=="66666666666") || (numero.substr(0,11)=="77777777777") || (numero.substr(0,11)=="88888888888") || (numero.substr(0,11)=="99999999999") || (numero.substr(0,11)=="00000000191")) {
        return false;
    }
    var result = "";
    var OK = false;
    var temp = Limpa(cpf.value);

    if (temp.length>10){
        var work=temp.substring(0,(temp.length)-2)
        var resto = Resto(work);
        OK = (resto==eval(temp.charAt((temp.length)-2)));
        if (OK){
            work=work+resto;
            resto= Resto(work);
            OK = (resto==eval(temp.charAt((temp.length)-1)));
        }
    }
    if (OK){
        result="CPF valido"
        return true;
    }else{
        result="CPF invalido"
        return false;
    }
}

/************************************************
* function validacgc
* Verifica se o numero do CGC é válido
* Input: campo a ser verificado
************************************************/		

function validacgc(cgc){
    if (cgc.length=="") {
        return false;
    }
    var i;
    cgcp = Limpa(cgc.value);
    var c = cgcp.substr(0,12);
    var dv = cgcp.substr(12,2);
    var d1 = 0;
    for (i = 0; i < 12; i++){
            d1 += c.charAt(11-i)*(2+(i % 8));
    }
    if (d1 == 0) return false;
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1){
            return false;
    }

    d1 *= 2;
    for (i = 0; i < 12; i++){
            d1 += c.charAt(11-i)*(2+((i+1) % 8));
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1){
            return false;
    }
    return true;
}

/************************************************
* function vogalAcentuada
* Verifica se uma string tem vogais acentuadas
* Input:  valor a ser verificado
************************************************/

function vogalAcentuada(s) {
	ls = s.toLowerCase();
	if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
		return true;
}

/************************************************
* function verificaEmail
* Verifica se um email é válido
* Input: email a ser verificado
************************************************/

function verificaEmail(email) {
	var s = new String(email);
	// { } ( ) < > [ ] | \ /
	if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	if (vogalAcentuada(email))
		return false;
	// & * $ % ? ! ^ ~ ` ' "
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )
		return false;
	// , ; : = #
	if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) )
		return false;
	// procura se existe apenas um @
	if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )
		return false;
	// verifica se tem pelo menos um ponto após o @
	if (s.lastIndexOf(".") < s.indexOf("@"))
		return false;
	return true;
}

/************************************************
* function Login
* Verifica se um Login é válido
* Input: Login a ser verificado
************************************************/

function verificaLogin(login) {
	var s = new String(login);
	// { } ( ) < > [ ] | \ /
	if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	if (vogalAcentuada(login))
		return false;
	// & * $ % ? ! ^ ~ ` ' " @
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) || (s.indexOf("@")>=0))
		return false;
	// , ; : = # ESPACO
	if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0)
|| (s.indexOf(" ")>=0) )
		return false;
	return true;
}


/************************************************
* function Trim
* Retira espaços antes e depois da string
* Input: String a ser verificada
************************************************/

function Trim( str ) {
  var resultStr = "";

  resultStr = TrimLeft(str);
  resultStr = TrimRight(resultStr);

  return resultStr;
}

/************************************************
* function TrimLeft
* Retira espaços antes da string
* Input: String a ser verificada
************************************************/

function TrimLeft( str ) {
  var resultStr = "";
  var i = len = 0;

  if (str+"" == "undefined" || str == null) 
    return null;

  str += "";

  if (str.length == 0) 
    resultStr = "";
  else { 
    len = str.length;

    while ((i <= len) && (str.charAt(i) == " "))
      i++;

      resultStr = str.substring(i, len);
  }

  return resultStr;
} 


/************************************************
* function Trim
* Retira espaços depois da string
* Input: String a ser verificada
************************************************/

function TrimRight( str ) {
  var resultStr = "";
  var i = 0;

  if (str+"" == "undefined" || str == null) 
    return null;

  str += "";

  if (str.length == 0) 
    resultStr = "";
  else {
    i = str.length - 1;
    while ((i >= 0) && (str.charAt(i) == " "))
      i--;

      resultStr = str.substring(0, i + 1);
  }
  return resultStr;  
} 

/************************************************
* function warnInvalid
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/

function warnInvalid (theField, warnText) {
  theField.focus();
  theField.select();
  alert(warnText);
  return false;
}

//central de parceiro
function validaParceiroLogin() {

      if (isEmpty(document.parceiros.matricula.value)) {
        warnInvalid(document.parceiros.matricula,'Matrícula não preenchida!');
        return false;
      } else if (isEmpty(document.parceiros.senha.value)) {
        warnInvalid(document.parceiros.senha,'Senha não preenchida!');
        return false;
      } else {
      document.parceiros.submit();
	  return true;
      }
}

function validaMatricula() {
	  if (isEmpty(document.frmCadastro.nomeMat.value) || !checkField(document.frmCadastro.nomeMat.value))	{
        warnInvalid(document.frmCadastro.nomeMat,'Nome não preenchido ou contém caracteres inválidos!');
        return false;
      }
	  if (isEmpty(document.frmCadastro.cpfMat.value) || !validacpf(document.frmCadastro.cpfMat)) {
          warnInvalid(document.frmCadastro.cpfMat,'Número do CPF não preenchido ou inválido!');
          return false;
      }
	  
	  if (isEmpty(document.frmCadastro.ddd_resMat.value) || !isNumeric(document.frmCadastro.ddd_resMat.value)) {
        warnInvalid(document.frmCadastro.ddd_resMat,'DDD não preenchido ou contém caracteres inválidos!');
        return false;
      } else if (isEmpty(document.frmCadastro.tel_resMat.value)) {
        warnInvalid(document.frmCadastro.tel_resMat,'Número do Telefone não preenchido!');
        return false;
      } 
	  
	  var objRegExp  = /^[A-Za-z]([\w\.]*)@([A-Za-z0-9\.]*)\.(([A-Za-z]{3}\.[A-Za-z]{2}$)|([A-Za-z]{3}$)|([a-z]{2}$))/i ;
	  if(!objRegExp.test(document.frmCadastro.emailMat.value)) {
		  warnInvalid(document.frmCadastro.emailMat,'E-mail inválido!');
	      return false;  
	  }
	  
	  return bloquearSubmits("");	  
	  
}