
function mensagem(msg) {
  alert(msg);
}
/**
* 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_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;
}

function formataValorBIII(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 > 2){
    strNumero = strSepGrupo + numInteiro.substr(numInteiro.length-2) + strNumero;
    numInteiro = numInteiro.substr(0, numInteiro.length-2);
  }
  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 e onchange (nos dois).
 *
 * @param inputData: Input que será formatado
 *
 * @author: Daniel Dantas de Souto
 */
function formataData(inputData){
  strData = inputData.value.replace(/[^0-9]/g, '');
  if (strData.length > 2)
    strData = strData.substr(0, 2) + '/' + strData.substr(2);
  if (strData.length > 5)
    strData = strData.substr(0, 5) + '/' + strData.substr(5);
  if (strData.length > 10)
    strData = strData.substr(0, 10);
  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 ? '' : 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,'');
}

/**
 * Retira todos caracteres diferentes de letras e espaço.
 * Utilize esta função nos eventos onkeypress e onchange (nos dois).
 *
 * @param inputTexto: Input que será formatado
 * @author: Walker de Alencar Oliveira
 */
function formataApenasTexto(inputTexto) {
  inputTexto.value = inputTexto.value.replace(/[^a-zA-Z ]+\b/,'');
}

/**
 * Validações específicas para o campo nome.
 * Utilize esta função nos eventos onkeypress e onkeyup (nos dois).
 *
 * @param inputTexto: Input que será formatado
 * @author: Evandro Moraes Abdão / Marcos Paulo Giron Rosa
 */
function formataNome(inputTexto) {
  inputTexto.value = inputTexto.value.replace(/^ {1,}/,'');
  inputTexto.value = inputTexto.value.replace(/ {2,}/g,' ');
  inputTexto.value = inputTexto.value.replace(/[^a-zA-ZáéíóúàâêôãõçÁÉÍÓÚÀÂÊÔÃÕÇ ]/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 o Cep
 * 
 * @param input
 * @return
 */
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;
	}


/**
 * 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 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 getRadioValue(radioName){
	var radioChecked = $$('input').find(function(input){
    return input.name == radioName && input.checked == true;
  });
  
  return radioChecked ? radioChecked.value : '';
}

function desabilitaSe(id, condicao){
  $(id).disabled = condicao;
  $(id).value = '';
}
  
  
function colocaMascaraNumerica(id){
  Event.observe($(id), "keyup", function() {
    formataApenasNumero($(id));
  });
  Event.observe($(id), "change", function() {
    formataApenasNumero($(id));
  });
}

function colocaMascaraValor(id, intCasasDecimais, strSepDecimal, strSepGrupo){
  Event.observe($(id), "keyup", function() {
    formataValor($(id), intCasasDecimais, strSepDecimal, strSepGrupo);
  });
  Event.observe($(id), "change", function() {
    formataValor($(id), intCasasDecimais, strSepDecimal, strSepGrupo);
  });
}

function colocaMascaraTelefone(id){
  Event.observe($(id), "keyup", function() {
    formataTelefone($(id));
  });
  Event.observe($(id), "change", function() {
    formataTelefone($(id));
  });
}

function formataNumeroSala(inputValor, tamanho) {
  strNumero = inputValor.value;
  strNumero = strNumero.replace(/[^0-9]/g, '');
  strNumero = strNumero.replace(/^0+/g, '');
  while (strNumero.length < tamanho){
    strNumero = '0' + strNumero; 
  }
  inputValor.value = strNumero;
}

/**
 * Função que checa se a data é válida
 * @author Girón
 * @param data
 * @return boolean
 * 21/09/2009
 * 
 */
function formataDataValida3(pObj) {
	  var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
	  var aRet = true;
	  if ((pObj) && (pObj.value.match(expReg)) && (pObj.value != '')) {
	        var dia = pObj.value.substring(0,2);
	        var mes = pObj.value.substring(3,5);
	        var ano = pObj.value.substring(6,10);
	        if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30) 
	          aRet = false;
	        else 
	          if ((ano % 4) != 0 && mes == 2 && dia > 28) 
	                aRet = false;
	          else
	                if ((ano%4) == 0 && mes == 2 && dia > 29)
	                  aRet = false;
	  }  else 
	        aRet = false;  
	  return aRet;
}



/**
 * Função que checa se a data é válida
 * @author Girón
 * @param data
 * @return boolean
 * 21/09/2009
 * 
 */

function formataDataValida2(campo)
{
        if (campo.value!="")
        {
                erro=0;
                hoje = new Date();
                anoAtual = hoje.getFullYear();
                barras = campo.value.split("/");
                if (barras.length == 3)
                {
                        dia = barras[0];
                        mes = barras[1];
                        ano = barras[2];
                        resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano <= anoAtual && ano >= 1900));
                        if (!resultado)
                        {
                                alert("Data inválida.");
                                campo.focus();
                                return false;
                        }
                 } 
                 else
                 {
                         alert("Data inválida.");
                         campo.focus();
                         return false;
                 }
        return true;
        }
}


/**
 * Função que checa se a data é válida
 * @author Alberto Guimarães Viana (albertogviana@gmail.com)
 * @param data
 * @return boolean
 * Alterada em 21/09/2009
 * Girón
 */

function formataDataValida(datta)
{ 
 var data = datta.value;
 var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
 if(!data.match(expReg))
 {
  if (datta.value != '')
  {
   alert('A Data: '+data+ ' é inválida, favor digitar uma data válida!');
    datta.value = '';
  }
  return false;
 }
  
 var dia = data.substring(0, 2);
 var mes = data.substring(3, 5);
 var ano = data.substring(6, 10);
  
 var myDate = new Date();  
  myDate.setFullYear( ano, (mes - 1), dia );  
  if((myDate.getMonth()+1) == mes && dia<32)
  {
   return true;
  }
  else
  {
   return false;
  }   
}

/**
 *Função para calcular os dias decorridos entre duas datas
 *@author Leonardo C Magalhães
 * @return boolean
 * 25/09/2009
 * Girón
 */

function calculaDiasDecorridos(dt_termino, dt_inicio){ 
	
	//dt_termino  = string2Data(dt_termino.value);
	dt_termino_aux = string2Data(dt_termino.value);
	dt_inicio      = string2Data(dt_inicio.value);
	var diferenca  = dt_termino_aux.getTime() - dt_inicio.getTime(); 
	var ch_total   = 40;
	var dias_total = 60;
	
	if(diferenca > 0){
		var resultado = Math.ceil(ch_total / 8);
		    diferenca = Math.ceil(diferenca / (1000 * 60 * 60 * 24));
		
			if(diferenca < resultado){
				alert('A carga horária não pode ser menor que a quantidade de dias possa comportar!');
				dt_termino.value = '';
			}
			else if(diferenca > dias_total){
				alert('O intervalo de dias entre a data de início da turma e a data de término da turma não pode ser superior 60 dias');
				dt_termino.value = '';
			}
	}else{
//		alert('A data não pode ser menor ou igual a data início da turma!');
	}
}
function calculaDiasEntreDuasDatas(dt_termino, dt_inicio){ 
	
	dt_termino_aux = string2Data(dt_termino.value);
	dt_inicio   = string2Data(dt_inicio.value);
	var diferenca = dt_termino_aux.getTime() - dt_inicio.getTime(); 
	var day = 24 * 60 * 60 * 1000;
	return diferenca * day;
//	var ch_total  = 40;
	
//	if(diferenca > 0){
//		var resultado = Math.ceil(ch_total / 8);
//		diferenca = Math.ceil(diferenca / (1000 * 60 * 60 * 24));
//		
//		if(diferenca < resultado){
//			alert('A carga horária não pode ser menor que a quantidade de dias possa comportar!');
//			dt_termino.value = '';
//		}
//	}else{
//		alert('A data não pode ser menor ou igual a data atual!');
//	}
}

function string2Data(stData){
var data = stData.split("/");
return new Date( data[2], data[1]-1, data[0] );
}

/**
 * Função para mostrar informações sobre uma variável
 * @author Leandro Guimarães Fernandes (leandrogf@gmail.com)
 * @param obj
 * @return string
 */
function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}

function veficaEmail(email,confEmail){ 
    var email     = email.value;
    var emailAux  = confEmail.value;

    if(email != emailAux) {
        alert('Os e-mails são diferentes!');
        confEmail.value = '';
        return false;
    }
    return true;
}

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9_-])+\.)+([a-zA-Z0-9]{2,3})$/;
	if (!filter.test(email.value)) {
	alert('Informe um e-mail válido');
	email.focus;
	email.value = '';
	return false;
	}
}

function verificaSenha(senha,senha_nova){ 
    var senha     = senha.value;
    var senhaAux  = senha_nova.value;

    if(senha != senhaAux) {
        alert('As senhas são diferentes!');
        senha_nova.value = '';
    } else if (senha.length < 8){
    	alert('Senha menor que oito digitos');
    	senha_nova.value = '';
    }
}
/**
 * Função que soma um determinado número de dias a uma data e retorna
 * a data resultante desta soma
 * @author Leandro Guimarães Fernandes (leandrogf@gmail.com)
 * @param date {Date} Data a inicial
 * @param days_add {Number} Número de dias que serão adicionados a data
 * @return {Date}
 */
function addDays(date, days_add){
   var day = 24 * 60 * 60 * 1000;
   return new Date(date.getTime() + day * days_add);
}


/**
 * Função para selecionar todas as checkbox de
 * um determinado grupo em um formulário
 * @author Leandro Guimarães Fernandes (leandrogf@gmail.com)
 * @param frm {Element} Formulário que contém as caixas de seleção
 * @param elGroupName {Sring} Nome do grupo de elementos que sofrerão as
 * 		  alterações
 */
function checkAll(frm, elGroupName){
	checkUnckeckAll(frm, elGroupName, true);
}

/**
 * Função para remover a seleção de todas as checkbox de
 * um determinado grupo em um formulário
 * @author Leandro Guimarães Fernandes (leandrogf@gmail.com)
 * @param frm {Element} Formulário que contém as caixas de seleção
 * @param elGroupName {Sring} Nome do grupo de elementos que sofrerão as
 * 		  alterações
 */
function uncheckAll(frm, elGroupName){
	checkUnckeckAll(frm, elGroupName, false);
}

/**
 * Função para selecionar e descelecionar todas as checkbox de
 * um determinado grupo em um formulário
 * @author Leandro Guimarães Fernandes (leandrogf@gmail.com)
 * @param frm {Element} Formulário que contém as caixas de seleção
 * @param elGroupName {Sring} Nome do grupo de elementos que sofrerão as
 * 		  alterações
 * @param ckeck Caso true seleciona todas a checkboxes do grupo, caso
 * 		  contrário, remove a seleção
 */
function checkUnckeckAll(frm, elGroupName, check){
	 for(var i = 0; i < frm.elements.length; i++){
	   var el = frm.elements[i];
	   if(el.type == 'checkbox'){
		   if(el.name == elGroupName){
			   if(check == true){
			 	el.checked = true;
			   }
			   else{
			 	el.checked = false;
			   }
		   }
	   }
   }
 }