


/**
* verifica se o email é valido e retorna o valor true ou false
* @param mail: string do email a ser avaliada
*/

function checkMail(mail){
    //var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
   var er = new RegExp(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i);

    
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}

/**
* calcula a idade de acordo com a data de nascimento passada
*
*/
function calculaIdade(nascimento) {
  d = nascimento.split('/');
  dia = d[0];
  mes = d[1];
  ano = d[2];

  //calculo a data de hoje
  hoje = new Date();

  //subtraio os anos das duas datas
  idade=hoje.getFullYear() - ano - 1; //-1 porque ainda nao fez anos durante este ano

  //se subtraio os meses e for menor que 0 entao nao cumpriu anos. Se for maior sim ja cumpriu
  if (hoje.getMonth() + 1 - mes < 0) //+ 1 porque os meses comecam em 0
     return idade;
  if (hoje.getMonth() + 1 - mes > 0)
     return idade+1;

  //entao eh porque sao iguais. Vejo os dias
  //se subtraio os dias e der menor que 0 entao nao cumpriu anos. Se der maior ou igual sim que já cumpriu
  if (hoje.getUTCDate() - dia >= 0)
     return idade + 1;

  return idade;
}


/**
* Conta os caracteres do campo passado no primeiro parâmetro 
* e mostra o número de digitados no div definido no segundo parâmetro. 
* Se o valor for maior que o máximo de caracteres, definido
* no terceiro parâmetro, da um alerta. 
*/

function conta_caracteres(campo, div_atualizar, maxlimit) {
    
    if ($(campo).value.length > maxlimit) {
        
        $(campo).value = $(campo).value.substring(0, maxlimit);
    
    } else {
        var num = 0 + $(campo).value.length;
        $(div_atualizar).update('digitados '+num+' de '+maxlimit);
    }
    
}

function conta_caracteres_com_aviso(campo, div_atualizar, div_aviso, maxlimit) {
    
    var num = $(campo).value.replace(/([\n\r])+/g, "  ").length;
    if ($(campo).value.replace(/([\n\r])+/g, "  ").length > maxlimit) {        
        $(div_aviso).innerHTML = "<font color='#FF0000'>Limite de caracteres foi ultrapassado.</font>";
        //num = $(campo).value.length;
        $(div_atualizar).update('digitados '+num+' de '+maxlimit);
    
    } else {
        //num = $(campo).value.length;
        $(div_aviso).innerHTML = '';
        $(div_atualizar).update('digitados '+num+' de '+maxlimit);
    }
    
}

/*
function conta_caracteres(campo_contar,div_atualizar,max) {
  var num = $(campo_contar).getValue().length;
  if(num>max) {
     alert('Você digitou mais que o permitido para este campo, removemos '+(num-max)+' caracteres para possibilitar a gravação.');
     $(campo_contar).setValue( $(campo_contar).getValue().substr(0,300) );
  }
  $(div_atualizar).update('digitados '+num+' de '+max);
}
*/
/**
 * Transforma um numero em um texto formatado.
 *
 * @param dblNumero                  : Numero que será formatado
 * @param intCasasDecimais [opcional]: Número de casas decimais (default   2)
 * @param strSepDecimal    [opcional]: Caracter separador decimal (default ',')
 * @param strSepGrupo      [opcional]: Caracter separador de grupos (default '.')
 * @result string                    : Texto formatado
 *
 * @author: Daniel Dantas de Souto
 */
function floatToString(dblNumero, intCasasDecimais, strSepDecimal, strSepGrupo){
  //Valores padrões
  intCasasDecimais = intCasasDecimais == undefined ?   2 : intCasasDecimais;
  strSepDecimal    = strSepDecimal    == undefined ? ',' : strSepDecimal;
  strSepGrupo      = strSepGrupo      == undefined ? '.' : strSepGrupo;
  
  //Parte inteira e decimal
  var strInteiro = Math.floor(dblNumero) + '';
  var strDecimal = dblNumero + '';
  strDecimal = strDecimal.substr(strInteiro.length+1);
  
  //Ajustando a parte decimal para o nº de casas
  strDecimal = strDecimal.substr(0, intCasasDecimais);
  while (strDecimal.length < intCasasDecimais){
    strDecimal += '0';
  }
  
  //Inserindo os separadores de grupo
  var strNumero = '';
  while (strInteiro.length > 3){
    strNumero = strInteiro.substr(strInteiro.length-3) + (strNumero.length >0 ? strSepGrupo : '') + strNumero;
    strInteiro = strInteiro.substr(0, strInteiro.length-3);
  }
  strNumero = strInteiro + (strNumero.length >0 ? strSepGrupo : '') + strNumero;
  
  //Inserindo o separador decimal
  if (strDecimal.length > 0){
    strNumero += strSepDecimal + strDecimal;
  }
  
  return strNumero;
}

/**
 * Formata um texto para um formato numérico.
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputValor                 : Input que será formatado
 * @param intCasasDecimais [opcional]: Número de casas decimais (default   2)
 * @param strSepDecimal    [opcional]: Caracter separador decimal (default ',')
 * @param strSepGrupo      [opcional]: Caracter separador de grupos (default '.')
 *
 * @author: Daniel Dantas de Souto
 */
function formataValor(inputValor, intCasasDecimais, strSepDecimal, strSepGrupo){
  strNumero        = inputValor.value;
  intCasasDecimais = intCasasDecimais == undefined ?   2 : intCasasDecimais;
  strSepDecimal    = strSepDecimal    == undefined ? ',' : strSepDecimal;
  strSepGrupo      = strSepGrupo      == undefined ? '.' : strSepGrupo;
  
  strNumero = strNumero.replace(/[^0-9]/g, '');
  strNumero = strNumero.replace(/^0+/g, '');
  while (strNumero.length < intCasasDecimais + 1){
    strNumero = '0' + strNumero;
  }
  
  numInteiro = strNumero.substr(0, strNumero.length-intCasasDecimais);
  numDecimal = strNumero.substr(strNumero.length-intCasasDecimais);
  
  strNumero = '';
  while (numInteiro.length > 3){
    strNumero = strSepGrupo + numInteiro.substr(numInteiro.length-3) + strNumero;
    numInteiro = numInteiro.substr(0, numInteiro.length-3);
  }
  strNumero = numInteiro + strNumero;
  
  if (numDecimal.length > 0){
    strNumero += strSepDecimal + numDecimal;
  }
  
  inputValor.value = strNumero;
}

/**
 * Formata um texto para o formato de data (dd/mm/aaaa).
 * Utilize esta função nos eventos onkeypress, onkeyup e onchange (nos três).
 *
 * @param inputData: Input que será formatado
 *
 * @author: Daniel Dantas de Souto
  */
 
 function formataData(inputData){
	  var strData = inputData.value.replace(/[^0-9]/g, '');
	  
	  var dia = strData.substr(0, 2);
	  var mes = strData.substr(2, 2);
	  var ano = strData.substr(4, 4);
	  
	  if (strData.length > 2){
		strData = strData.substr(0, 2) + '/' + strData.substr(2);
		  if (dia > 31 || dia < 01) {
			  alert('Dia especificado esta incorreto');
			  strData = '';
		  } else {
		     if((mes==01 && dia > 31) || (mes==03 && dia > 31) || (mes==05 && dia > 31) || (mes==07 && dia > 31) || (mes==08 && dia > 31) || (mes==10 && dia > 31) || (mes==12 && dia > 31)){
			    alert("Mês especificado contém no máximo 30 dias.");
			    strData = '';
		     }
		     if((mes==04 && dia > 30) || (mes==06 && dia > 30) || (mes==09 && dia > 30) || (mes==11 && dia > 30)){
			    alert("Mês especificado contém no máximo 30 dias.");
			    strData = '';
		     }
		     if(ano%4!=0 && mes==2 && dia>28){
			    alert("Mês especificado contém no máximo 28 dias.");
			    strData = '';
		     }
		     if(ano%4==0 && mes==2 && dia>29){
			    alert("Mês especificado contém no máximo 29 dias.");
			    strData = '';
		     }
		  }
	  }
	  if (strData.length >= 5){
		strData = strData.substr(0, 5) + '/' + strData.substr(5);
		  if (mes > 12){
	    	alert("Mes especificado está incorreto, selecione o mês entre 01 e 12.");
	    	strData = '';
		  }
	  }
	  if (strData.length == 10){
		strData = strData.substr(0, 10);  
	  }
	  
	  if (strData.length > 10) {
		alert("Limite de caracteres ultrapassado.");
		strData = '';
	  }
	  inputData.value = strData;
	}
 
 
/**
 * Formata um texto deixando apenas números e sem zeros a esquerda.
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputNumero: Input que será formatado
 * @param srtDefault [opcional]: Valor padrão caso seja vazio
 *
 * @author: Daniel Dantas de Souto
 */
function formataNumero(inputNumero, strDefault) {
  strDefault = strDefault == undefined ? '0' : strDefault;
  
  inputNumero.value = inputNumero.value.replace(/0*[^0-9]/g,"");
  inputNumero.value = inputNumero.value.replace(/^0+/g, '');
  if(inputNumero.value == '') {
    inputNumero.value = strDefault;
  }
}

/**
 * Retira todos caracteres diferentes de números.
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputTexto: Input que será formatado
 *
 * @author: Daniel Dantas de Souto
 */
function formataApenasNumero(inputTexto) {
  inputTexto.value = inputTexto.value.replace(/[^0-9]/g,'');
}


/**
 * Formata um texto com a mascara de CNPJ (00.000.000/0000-00).
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputCNPJ: Input que será formatado
 *
 * @author: Daniel Dantas de Souto
 */
function formataCNPJ(inputCNPJ){
  strCNPJ = inputCNPJ.value.replace(/[^0-9]/g, '');
  if (strCNPJ.length > 14)
    strCNPJ = strCNPJ.substr(0, 14);
  if (strCNPJ.length > 12)
    strCNPJ = strCNPJ.substr(0, 12) + '-' + strCNPJ.substr(12);
  if (strCNPJ.length > 8)
    strCNPJ = strCNPJ.substr(0, 8) + '/' + strCNPJ.substr(8);
  if (strCNPJ.length > 5)
    strCNPJ = strCNPJ.substr(0, 5) + '.' + strCNPJ.substr(5);
  if (strCNPJ.length > 2)
    strCNPJ = strCNPJ.substr(0, 2) + '.' + strCNPJ.substr(2);
  inputCNPJ.value = strCNPJ;
}

/**
 * Formata um texto com a mascara de CPF (000.000.000-00).
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputCPF: Input que será formatado
 *
 * @author: Daniel Dantas de Souto
 */
function formataCPF(inputCPF){
  strCPF = inputCPF.value.replace(/[^0-9]/g, '');
  if (strCPF.length > 11)
    strCPF = strCPF.substr(0, 11);
  if (strCPF.length > 9)
    strCPF = strCPF.substr(0, 9) + '-' + strCPF.substr(9);
  if (strCPF.length > 6)
    strCPF = strCPF.substr(0, 6) + '.' + strCPF.substr(6);
  if (strCPF.length > 3)
    strCPF = strCPF.substr(0, 3) + '.' + strCPF.substr(3);
  inputCPF.value = strCPF;
}

/**
 * Formata um texto com a mascara de Telefone (0000-0000).
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputTelefone: Input que será formatado
 *
 * @author: Daniel Dantas de Souto
 */
function formataTelefone(inputTelefone){
  strTelefone = inputTelefone.value.replace(/[^0-9]/g, '');
  if (strTelefone.length > 8)
    strTelefone = strTelefone.substr(0, 8);
  if (strTelefone.length > 4)
    strTelefone = strTelefone.substr(0, 4) + '-' + strTelefone.substr(4);
   inputTelefone.value = strTelefone;
}

function formataCep(input){
  str = input.value.replace(/[^0-9]/g, '');
  if (str.length > 8)
    str = str.substr(0, 8);
  if (str.length > 2)
   str = str.substr(0, 2) + '.' + str.substr(2);
  if (str.length > 6)
   str = str.substr(0, 6) + '-' + str.substr(6);
  input.value = str;
}

function formataHora(input){
  str = input.value.replace(/[^0-9]/g, '');
  if (str.length > 6)
    str = str.substr(0, 6);
  if (str.length > 4)
   str = str.substr(0, 4) + ':' + str.substr(4);
  if (str.length > 2)
   str = str.substr(0, 2) + ':' + str.substr(2);
  input.value = str;
}

function formataDataHora(input){
  str = input.value.replace(/[^0-9]/g, '');
  if (str.length > 14)
    str = str.substr(0, 14);
  if (str.length > 12)
   str = str.substr(0, 12) + ':' + str.substr(12);
  if (str.length > 10)
   str = str.substr(0, 10) + ':' + str.substr(10);
  if (str.length > 8)
   str = str.substr(0, 8) + ' ' + str.substr(8);
  if (str.length > 4)
   str = str.substr(0, 4) + '/' + str.substr(4);
  if (str.length > 2)
   str = str.substr(0, 2) + '/' + str.substr(2);
  input.value = str;
}

function ajaxSegmentoExcluir(div, nu_seq_segmento_conselho, form, url) {
	$('conselho_tutelar_nu_seq_segmento_conselho').value = nu_seq_segmento_conselho;
	new Ajax.Updater(
      div, 
      url, 
      {
         asynchronous:true, 
         evalScripts:true, 
         parameters:Form.serialize(form), 
         method: 'post', 
         onComplete:function(request, json)
         {
    	   Element.hide('indicator')
    	 }, 
    	 onLoading:function(request, json)    	  
    	 {
    	     Element.show('indicator')
    	 }
       }
    );
}

function validarCPF(input) {	
 	var i;
	aux = new String;
	cpf = new String;
		
  cpf = input.value;
  cpf = cpf.replace('.', '');
	cpf = cpf.replace('.', '');
	cpf = cpf.replace('-', ''); 
  	
	var c		= cpf.substr(0,9);
	var dv	= cpf.substr(9,2);
	var d1	= 0;
		
	if (cpf.length < 11) {
		alert("São necessários 11 digitos para verificação do CPF!");
		input.focus();
		return false;
	}

	// Verifica se todos digitos são iguais. Ex: 11111111111
  for (i = 0; i < 10; i++){
   	aux = '';
   	
   	for(ii = 0; ii < 11; ii++) {
   		aux = aux + i;
   	}

   	if (cpf == aux){
   		alert("CPF inválido!");
   		input.focus();
     	return false;
		}

	}
	
	for (i = 0; i < 9; i++) {
			d1 += c.charAt(i)*(10-i);
	}
	
	if (d1 == 0){
		alert("CPF inválido!")
		input.focus();
		return false;
	}

	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	
	if (dv.charAt(0) != d1) {
		alert("CPF inválido!");
		input.focus();
		return false;
	}

	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) {
		alert("CPF inválido!");
		input.focus();
		return false;
	}

	return true;
}

function fechaSegmento() {
	var where_to = confirm2('Deseja realmente cancelar a operação?');
	
	if (where_to == true) {
		$('conselho_novo_s').checked = false;
		$('div_segmento').hide();
	}	else {
		return false;
  }
}

function confirm2(msg) {
	confirma = confirm(msg+'\nClique em OK, para confirmar essa operação e continuar o cadastramento.\nClique em CANCELAR para cancelar a operação e permanecer nesta tela.');
	if(confirma) {
		return true;
	} else {
		return false;
	}
}

function confirmExcluirReg(msg) {
	confirma = confirm(msg+'\nClique em OK, para confirmar essa operação.\nClique em CANCELAR para cancelar a operação e permanecer nesta tela.');
	if(confirma) {
		return true;
	} else {
		return false;
	}
}
	
msgBox = function(msg, actionOk){
  var title = 'Atenção';
  this.show = function() {
    $('msgBox-Title').innerHTML = title;
    $('msgBox-Message').innerHTML = msg;
    $('msgBox-Buttons').innerHTML = 
        '<button id="msgBox-btnYes" title="Confirma a ação" onclick="msgBox.hide(); '+ actionOk +'; return true;">OK</button>';      
    $('msgBox').show();
    $$('select').invoke('hide');
    new Draggable('msgBox-Body', {handle: 'msgBox-Header'});
  }
  this.show();
}

msgBox.hide = function(){
  $$('select').invoke('show');
  $('msgBox').hide();
}
