function gE(id){
    return document.getElementById(id);
}
function msgAbort(id, msg){
    alert(msg);
    gE(id).focus();
}
function execScript(script){
	  var matches = script.match('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)');
   eval(matches[1]);
}
//Mascara para os campos
//    * "#" - Numeros
//    * "A" - Letras UpperCase
//    * "a" - Letras LowerCase
//    * "Z" - Letras
//    * "*" - Qualquer Caracter
//    * "/", ".", "-", " ", ":" - Caracteres Fixos
//=============================================================================================================
function Mascara(objeto, evt, mask) {
 
var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var Numeros = '0123456789';
var Fixos  = '().-:/ ';
var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";

evt = (evt) ? evt : (window.event) ? window.event : "";
var value = objeto.value;
if (evt) {
 var ntecla = (evt.which) ? evt.which : evt.keyCode;
 tecla = Charset.substr(ntecla - 32, 1);
 if (ntecla < 32) return true;

 var tamanho = value.length;
 if (tamanho >= mask.length) return false;

 var pos = mask.substr(tamanho,1);
 while (Fixos.indexOf(pos) != -1) {
  value += pos;
  tamanho = value.length;
  if (tamanho >= mask.length) return false;
  pos = mask.substr(tamanho,1);
 }

 switch (pos) {
   case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
   case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
   case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
   case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
   case '*' : objeto.value = value; return true; break;
   default : return false; break;
 }
}
objeto.value = value;
return true;
}

//===================================================================================================================
//SCRIPT DE MOEDA
//onKeydown="Formata(this,20,event,2);"
function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

if (tecla == 8 )
{ tam = tam - 1 ; }

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
{

if ( tam <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
}
}

function validarCampoNumerico(evnt)
{ 
	var Digit = eval(((navigator.appName != "Microsoft Internet Explorer")?"evnt.which":"event.keyCode"))	
	var isDigit 
	isDigit = ((Digit >= 48 && Digit <= 57) || (Digit == 0 || Digit == 8));
	return isDigit; 
}
var HttpRequest;
AppAjaxLoad = function(sMethod, sUrl, sPost){
	HttpRequest = null;
	if (window.XMLHttpRequest) {
		HttpRequest = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		try{
			HttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				HttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				try {
					HttpRequest = new ActiveXObject("Msxml2.XMLHTTP.4.0");
				}catch(e){
					HttpRequest = null;
				}
			}
		}
	}
	if(HttpRequest){
		HttpRequest.onreadystatechange = StateHttpRequestChange;
		HttpRequest.open(sMethod, sUrl, true);
		HttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
		HttpRequest.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
		HttpRequest.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0');
		HttpRequest.setRequestHeader('Pragma', 'no-cache');
		HttpRequest.send(sPost);
	}else{
		alert("Houve um problema ao obter os dados:\nA versão do browser não é compatível!");
	}
}
StateHttpRequestChange = function(){
	if (HttpRequest.readyState == 4) {
		if (HttpRequest.status == 200) {
			gE('body').innerHTML = HttpRequest.responseText;
			execScript(HttpRequest.responseText);
		} else {
			alert("Houve um problema ao obter os dados:\n" + HttpRequest.statusText);
		}
	}
}
function getFormValues(frm){
	var objForm = gE(frm);
	var formElements = objForm.elements;
	var sUrl = '';
	for( var i=0; i < formElements.length; i++){
		if (!formElements[i].name)
			continue;
		if (formElements[i].type && (formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false)
			continue;
		var name = formElements[i].name;
		if (name){
			if (sUrl != '')
				sUrl += '&';
			if(formElements[i].type=='select-multiple'){
				for (var j = 0; j < formElements[i].length; j++){
					if (formElements[i].options[j].selected == true)
						sUrl += name+"="+encodeURIComponent(formElements[i].options[j].value)+"&";
				}
			}
			else{
				sUrl += name+"="+encodeURIComponent(formElements[i].value);
			}
		} 
	}	
	return sUrl;
}
function verificaForm(frm){
	var objForm = document.getElementById(frm);
	var formElements = objForm.elements;
	for( var i=0; i < formElements.length; i++){
		if (!formElements[i].name)
			continue;
		if (formElements[i].type && (formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false)
			continue;
		var value = formElements[i].value;
		var required = formElements[i].getAttribute('required');
		var label = formElements[i].getAttribute('label');
		
		if(required && value == ''){
			try{ 
				alert('É necessário '+ label);
				formElements[i].focus();
			}catch(e){
				// esconde o erro
			}
			return false;
		}
	}
	return true;
}
function isMail(mailField){
	strMail = mailField;
	var re = new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");
	var arr = re.exec(strMail);
	if (arr == null){
    	return false;
	}else{
    	return true;
	}
}
function RemoveMascaraCPF(cpf){
 
  var primeira_parte_cpf = cpf.split(".");
  var segunda_parte_cpf = primeira_parte_cpf[primeira_parte_cpf.length - 1].split("-");
  
  var novo_cpf = "";
  for(var i = 0; i < (primeira_parte_cpf.length-1); i++)
  {
     novo_cpf = novo_cpf + primeira_parte_cpf[i];
  }
  for(var i = 0; i < segunda_parte_cpf.length; i++)
  {
     novo_cpf = novo_cpf + segunda_parte_cpf[i];
  }
  return novo_cpf;
  
}
function isCPF(st) {
  if (st == "")
    return (false);
  l = st.length;

  //aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
  if ((l == 9) || (l == 8)){
    for (i = l ; i < 10; i++){
      st = '0' + st
    }
  }
  l = st.length;
  st2 = "";
  for (i = 0; i < l; i++) {
    caracter = st.substring(i,i+1);
    if ((caracter >= '0') && (caracter <= '9'));
      st2 = st2 + caracter;
  }
  if ((st2.length > 11) || (st2.length < 10))
    return (false);
  if (st2.length==10)
    st2 = '0' + st2;
  digito1 = st2.substring(9,10);
  digito2 = st2.substring(10,11);
  digito1 = parseInt(digito1,10);
  digito2 = parseInt(digito2,10);
  sum = 0; mul = 10;
  for (i = 0; i < 9 ; i++) {
    digit = st2.substring(i,i+1);
    tproduct = parseInt(digit ,10) * mul;
    sum += tproduct;
    mul--;
  }
  dig1 = ( sum % 11 );
  if ( dig1==0 || dig1==1 )
    dig1=0;
  else
    dig1 = 11 - dig1;
  if (dig1!=digito1)
    return (false);
  sum = 0;
  mul = 11;
  for (i = 0; i < 10 ; i++) {
    digit = st2.substring(i,i+1);
    tproduct = parseInt(digit ,10)*mul;
    sum += tproduct;
    mul--;
  }
  dig2 = (sum % 11);
  if ( dig2==0 || dig2==1 )
    dig2=0;
  else
    dig2 = 11 - dig2;
  if (dig2 != digito2)
    return (false);
 return (true);
}

//Valida data.
function ValidaData(data){
	var DATA   = new Array();
	var expReg = new RegExp("[/-]");
	var chr    = null;
	var posChr = null;
	var dia    = null;
	var mes    = null;
	var ano    = null;

	if(data.length != 10){
		alert("Data inválida!\nDigite a data no formato dd(dia) mm(mês) aaaa(ano).");
		return false;
	}

	chr    = expReg.exec(data);
	posChr = data.search(expReg);
	DATA   = data.split(chr);

	switch(posChr){
		case 2:
			dia = DATA[0];
			mes = DATA[1];
			ano = DATA[2];
			break;
		case 4:
			dia = DATA[2];
			mes = DATA[1];
			ano = DATA[0];
			break;
	}
   
   
	if(!(dia > 0 && dia < 32)){
		alert("Dia inválido!");
		return false;

	}else if(!(mes > 0 && mes < 13)){
		alert("Mês inválido!");
		return false;

	}else if(!(ano > 0 && ano.length == 4)){
		alert("Ano inválido!");
		return false;
	
	}else if((mes == 2 && dia > 0 && dia > 29)){
		alert("Dia inválido!");
		return false;
	}

	return true;
}

function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

function ValidaAgenda(theForm)
{
 var msg_erro = "";
	if (theForm.prontuario_agenda_paciente.value == '')
		msg_erro += "Preencha o campo \"Paciente\".\n";
	if (theForm.prontuario_paciente_data_nasc.value == '')
	    msg_erro += "Preencha o campo \"Data nasc\".\n";
	if (theForm.prontuario_agenda_nome_mae.value == '')
		msg_erro += "Preencha o campo \"Nome mãe\".\n";
	if (theForm.prontuario_agenda_medico.selectedIndex == 0)
		msg_erro += "Selecione o campo \"Médico\".\n";
	if (theForm.prontuario_agenda_atendimento.selectedIndex == 0)
		msg_erro += "Selecione o campo \"Atendimento\".\n";
	if (theForm.prontuario_agenda_data.value == '')
		msg_erro += "Preencha o campo \"Data\".\n";
	if (theForm.prontuario_agenda_hora.value == '')
		msg_erro += "Preencha o campo \"Hora\".\n";
	
	if(msg_erro == "")
		return true;
	else
	{
		alert(msg_erro);
		return false;
	}
}

function removeEspacoInicio(var_dado)
{
	var texto = var_dado;
	var novo_texto =  "";
	var letra;
	for(var i = 0; i < texto.length; i++)
	{
		letra = texto.charAt(i);
		if(i == 0)
		{
			if(letra == " ")
				novo_texto = novo_texto;
			else
				novo_texto = novo_texto + letra;	
		}
		else
		{
			novo_texto = novo_texto + letra;
		}
	}
	return novo_texto;
}

function removeEspacoFinal(var_dado)
{
	var texto = var_dado;
	var novo_texto =  "";
	var letra;
	for(var i = 0; i < texto.length; i++)
	{
		letra = texto.charAt(i);
		if(i == (texto.length - 1))
		{
			if(letra == " ")
				novo_texto = novo_texto;
			else
				novo_texto = novo_texto + letra;	
		}
		else
		{
			novo_texto = novo_texto + letra;
		}
	}
	return novo_texto;
}

function FormataValor(campo) 
{
	document.form_consulta_retorno[campo].value = FiltraCampo(campo);
	vr = document.form_consulta_retorno[campo].value;
	tam = vr.length;

	if ( tam <= 2 || tam == 3) 
 		document.form_consulta_retorno[campo].value = vr ;
 	else if ( (tam > 2) && (tam <= 5) ) 
 		document.form_consulta_retorno[campo].value = vr.substr( 0, tam - 2 ) + '.' + vr.substr( tam - 2, tam ) ;  
 	else if ( (tam >= 6))
 		document.form_consulta_retorno[campo].value = vr.substr( 0, tam - 3 ) + '.' + vr.substr(tam - 3, tam );
}

function FiltraCampo(campo){
	var s = "";
	var cp = "";
	vr = document.form_consulta_retorno[campo].value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {  
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	document.form_consulta_retorno[campo].value = s;
	return cp = document.form_consulta_retorno[campo].value
}

function SaltaCampo(campo,prox,tammax,event){
	var tecla = event.which;
	vr = document.form[campo].value;
	tam = vr.length;
	
 	if (tecla != 0 && tecla != 9 && tecla != 16 ){
		if ( tam == tammax ){
			if ( prox == "senhaConta" || (document.form.elements[prox] && document.form.elements[prox].name == "senhaConta")){
				if ( document.applets['tclJava'] )
					document.applets['tclJava'].setFocus();
				else if ( document.form.senhaConta )
					document.form.senhaConta.focus();
			}
			else{
				if ( document.form[prox] )
					document.form[prox].focus();
			}
		}
	}
		
}


function CalculaIdade(DataNascimento,id)

//*************************************************************
// Calcula a idade com base na data de nascimento passada
// pelo parâmetro 'Datanascimento' no formato 99*99*9999
// onde * é um caracter qualquer Ex.: dd/mm/yyyy e retorna
// o resultadade para o objeto de ID passado no parâmetro 'id'.
//*************************************************************

{

 
  DiaNascimento = parseInt(DataNascimento.substring(0,2));  //pega os dois primeiros caracteres da string 'DataNascimento' e converte para inteiro.
  MesNascimento = parseInt(DataNascimento.substring(3,6));  //pega o quarto e quinto caracter da string 'DataNascimento' e converte para inteiro.
  AnoNascimento = parseInt(DataNascimento.substring(6,10)); //pega os quatro últimos caracteres da string 'DataNascimento' e converte para inteiro.
  
  DataHoje = new Date();
  DiaHoje = DataHoje.getDate();      //pega o dia atual do sistema.
  MesHoje = DataHoje.getMonth() + 1; //pega o mês atual do sistema(esta função conta os meses como índices de um array iniciando o índice do zero por isso é necessário somar 1).
  AnoHoje = DataHoje.getFullYear();      //pega o ano atual do sistema.
  
  if(MesNascimento < MesHoje)
    {
    gE('prontuario_paciente_idade').value = AnoHoje - AnoNascimento;
    }

  else if(MesNascimento == MesHoje)
    {
    if(DiaNascimento <= DiaHoje)
      {
      gE('prontuario_paciente_idade').value = AnoHoje - AnoNascimento;
      }
    else
      {
      gE('prontuario_paciente_idade').value = AnoHoje - AnoNascimento - 1;
      }
    }

  else if(MesNascimento > MesHoje)
    {
    gE('prontuario_paciente_idade').value = AnoHoje - AnoNascimento - 1;
    }

 document.getElementById(id).value = gE('prontuario_paciente_idade').value;
 
 
}//Fim da função CalculaIdade.
function newPopUp( mypage, myname, w, h, scrollbar ) {
	var winl = ( screen.width  - w ) / 2;
	var wint = ( screen.height - h ) / 2;

	winprop = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scrollbar;
	win = window.open( mypage, myname, winprop );

	if ( parseInt( navigator.appVersion ) >= 4 )
		win.window.focus();
}
function impressao(){
}

function saltaCampoData(campo, campo_focus)
{
  	var tam;
	tam = document.form[campo].value.length;
	if(tam >= 10)
		document.form[campo_focus].focus();
}

function numeros(){   
       
    if (document.all) // Internet Explorer   
            var tecla = event.keyCode;   
    else if(document.layers) // Nestcape   
            var tecla = e.which;   
  
    if ((tecla > 47 && tecla < 58)) // numeros de 0 a 9   
        return true;   
    else {   
        if (tecla != 8) // backspace   
            //event.keyCode = 0;   
            return false;   
        else   
            return true;   
    }   
}