/*##################################################################
Validos para todos os navegadores
####################################################################*/
//** Constantes dos Navegadores
var _val_agt=navigator.userAgent.toLowerCase();
var _val_is_major=parseInt(navigator.appVersion);
var _val_is_ie=((_val_agt.indexOf("msie")!=-1) && (_val_agt.indexOf("opera")==-1));
var _val_isNT=_val_agt.indexOf("windows nt")!=-1;
var _val_IE=(document.all);
var _val_IE4=(_val_is_ie && (_val_is_major==4) && (_val_agt.indexOf("msie 4")!=-1));
var _val_IE6=(_val_is_ie && (_val_agt.indexOf("msie 6.0")!=-1));
var _val_NS=(document.layers);
var _val_DOM=(document.getElementById);
var _val_isMac=(_val_agt.indexOf("Mac")==-1);
var _val_allString="document.";
_val_allString += (_val_IE)?"all.":-(_val_DOM)?"getElementById(\"":"";
var _val_styleString=(_val_IE)?".style":-(_val_DOM)?"\").style":"";
var _val_endAllString=(_val_DOM && !_val_IE)?"\")":"";
var _val_px=(_val_DOM)?"px":"";

/*//==================================================================
//Função para testar a segurança da senha
//==================================================================
function NivelSegurancaSenha(valor){
	var d = document.getElementById('Seguranca');
	ERaz = /[a-z]/;
	ERAZ = /[A-Z]/;
	ER09 = /[0-9]/;
	ERxx = /[@!#$%&*+=|-]/;
	
	if(valor.length == ''){
		d.innnerHtml = '<h4>Segurança da Senha: !</h4>';
	}else{
		if (valor.length < 5){d.innerHtml = '<h4>Segurança da senha: <font color=\'red\'>BAIXA</font></h4>';}
		}else{
			if (valor.length > 7 && valor.search(ERaz) != -1 && valor.search(ERAZ) != -1 && valor.search(ER09) != -1 || valor.search(ERaz) != -1
				 && valor.search(ERAZ) != -1 && valor.search(ERxx) || valor.search(ERaz) != -1 && valor.search(ERxx) != -1 && valor.search(ER09)
				 || valor.search(ERxx) != -1 valor.search(ERAZ) != -1 && valor.search(ER09) != -1){
				 	d.innerHtml = '<h4>Seguranca da Senha: <font color=\'green\'>ALTA</font></h4>';}
			}else{
				if (valor.search(ERaz) != -1 && valor.search(ERAZ) != -1 || valor.search(ERaz) != -1 && valor.search(ER09) != -1 ||
					valor.search(ERaz) != -1 && valor.search(ERxx) != -1 || valor.search(ERAZ) != -1 && valor.search(ER09) != -1 ||
					valor.search(ERAZ) != -1 && valor.search(ERxx) != -1 || valor.search(ER09) != -1 && valor.search(ERxx) != -1){
						d.innerHtml = '<h4>Seguranca da Senha: <font color=\'orange\'>BAIXA</h4>';}
				}else{
					d.innerHtml = '<h4>Segurança da senha: <font color=\'red\'>BAIXA</font></h4>';}
}*/

function containsElement(arr, ele) 
{
	var found = false, index = 0;
	while(!found && index < arr.length)
	if(arr[index] == ele)
		found = true;
	else
		index++;	
	return found;
}

function getIndex(input) 
{
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	if (input.form[i] == input)index = i;
	else i++;
	return index;
}

function validarQuantidadeDeCaracteres(txtBox, e, quantidadeCaracteres){
	if(e.keyCode != 8 && e.keyCode != 9 && e.keyCode != 17 && e.keyCode != 16 && e.keyCode != 27
		&& e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40 && e.keyCode != 46
		&& e.keyCode != 116){
		if(txtBox.value.length >= quantidadeCaracteres){
			e.setKeyCode = 0;
			return false;
		}
	}
	return true;
}
	
function corrigeQuantidadeCaracteres(txtBox, quantidadeCaracteres){
	if(txtBox.value.length >= quantidadeCaracteres){
		txtBox.value = txtBox.value.substring(0, quantidadeCaracteres);
		return false;
	}
	return true;
}

function autoTab(objeto,len, e) 
{
	var isNN = (navigator.appName.indexOf("Netscape")!=-1);
	var input;	
	input = (document.all ? document.all[objeto] : (document.getElementById ? document.getElementById(objeto) : null));
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	
	if(input.value.length >= len && !containsElement(filter,keyCode)) 
	{
		try
			{input.form[(getIndex(input) +1) % input.form.length].focus();}
		catch(err)
		{
			try
			{input.form[(getIndex(input) +4) % input.form.length].focus();}
			catch(err)
			{				
				input.form[(getIndex(input) +58) % input.form.length].focus();			
			}		
		}
		
		maxlen(objeto, len);
		/*input.form[(getIndex(input)+1) % input.form.length].focus();
		maxlen(objeto,len); 
		*/
	}	
	return true;
}

function maxlen(objeto,len) 
{	
	var input;
	input = (document.all ? document.all[objeto] : (document.getElementById ? document.getElementById(objeto) : null));
	if(input.value.length >= len)
	{
		input.value = input.value.substring(0,len);		
	}
	
	return true;
}

function digitaData(controle, event)
{
	//Somente números
	var navi = navigator.userAgent.toLowerCase();
	if(event.keyCode != 8 && event.keyCode != 9){
		
		var objeto;
		objeto = document.getElementById(controle);	

		if (objeto.value.length == 2 || objeto.value.length == 5)
			objeto.value += "/";
		
		if((event.keyCode == 9 || event.keyCode == 46 || event.keyCode == 48 ||	event.keyCode == 49 ||
			event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 ||
			event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57 ||
			event.keyCode == 96 || event.keyCode == 97 || event.keyCode == 98 || event.keyCode == 99 ||
			event.keyCode == 100 || event.keyCode == 101 ||	event.keyCode == 102 || event.keyCode == 103 ||
			event.keyCode == 104 ||	event.keyCode == 105) && (!event.shiftKey))
		{
			return true;
		}
		else{
			event.setKeyCode = 0;
			return false;
		}
	}
}

function somenteNumeros(controle, event){
	if((!event.shiftKey) && (event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 ||
		event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 ||
		event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57 ||
		event.keyCode == 96 || event.keyCode == 97 || event.keyCode == 98 || event.keyCode == 99 ||
		event.keyCode == 100 || event.keyCode == 101 ||	event.keyCode == 102 || event.keyCode == 103 ||
		event.keyCode == 104 || event.keyCode == 105 || event.keyCode == 8 || event.keyCode == 46 ||
		event.keyCode == 9))
	{
		return true;
	}
	else{
		event.setKeyCode = 0;
		return false;
	}
}

function somenteValor(controle, event){
	if((!event.shiftKey) && (event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 ||
		event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 ||
		event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57 ||
		event.keyCode == 96 || event.keyCode == 97 || event.keyCode == 98 || event.keyCode == 99 ||
		event.keyCode == 100 || event.keyCode == 101 ||	event.keyCode == 102 || event.keyCode == 103 ||
		event.keyCode == 104 || event.keyCode == 105 || event.keyCode == 8 || event.keyCode == 46 ||
		event.keyCode == 9 || event.keyCode == 110 || event.keyCode == 188))
	{
		return true;
	}
	else{
		event.setKeyCode = 0;
		return false;
	}
}

function isDate(strData)
{
	var dia, mes, ano;
	//critica valor de um campo de data
	//if((strData.length < 8) || (strData.length == 9)) return false;
		
	mes = parseInt(strData.split('/')[1], 10); //strData.substr(3,2);
	if(mes > 12 || mes == 0)
		return false;

	dia = parseInt(strData.split('/')[0], 10); //strData.substr(0,2);
	if(dia == 0)
		return false;

	ano = parseInt(strData.split('/')[2], 10);
	if(ano == 0)
		return false;
	
	if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12)
	{
		if(dia > 31)
			return false;
	}
	else if(mes == 4 || mes == 6 || mes == 9 || mes == 11)
	{
		if (dia > 30)
			return false;
	}
	else if(mes == 2)
	{
		if(ano % 4 == 0){
			if (dia > 29)
				return false;
		}
		else if(dia > 28)
			return false;
	}

	return true;
}

function CriticaData(sender, args)
{	
	var data = "";
	if (args.Value) data = args.Value;
	else data = args;
	if (args.IsValid) args.IsValid = isDate(data);		
	else return isDate(data);
}

function armazenaValoresParametros(crtlID, index, crtlCombo)
{	
	var vlrText = Trim(crtlID.value); 	
	var vlrCombo = (document.all ? document.all[crtlCombo] : (document.getElementById ? document.getElementById(crtlCombo) : null)).value;
	var idx = "#"+crtlID.name;
	if (vlrCombo.indexOf(idx) >= 0)
	{
		
		var vector = vlrCombo.split("#");
		vlrCombo = "";
		for(i=1;i<vector.length;i++)
		{			
			if (vector[i].indexOf(index) >=0){
				vlrCombo += idx + "=" + vlrText;				
			}else{
				vlrCombo += "#" + vector[i];				
			}
			vlrCombo = Trim(vlrCombo);
		}		
		(document.all ? document.all[crtlCombo] : (document.getElementById ? document.getElementById(crtlCombo) : null)).value = vlrCombo;
	}else
	{
		idx += "=" + vlrText
		var hddcrtl = (document.all ? document.all[crtlCombo] : (document.getElementById ? document.getElementById(crtlCombo) : null));
		hddcrtl.value += idx;	
	}		
}  

/*Recupera a QueryString*/          
qs=new Array()
varQuery=location.search.replace(/\x3F/,"").replace(/\x2B/g," ").split("&")
if(varQuery!=""){
	for(i=0;i<varQuery.length;i++){
		nvar=varQuery[i].split("=")
		qs[nvar[0]]=unescape(nvar[1])
	}
}
	
function QueryString(variavel){
	try
	{return qs[variavel];}
	catch(err)
	{
		return '';
	}	
}
			
/*######### Valida Componenetes Biometricos #############*/																									

var downloadEfetuado = false;
var TimerDownload  = 0;	
var LinkVoltar = false;																

function download(){	
	if (!downloadEfetuado){
		iframedownload.document.location = 'biosetup.exe';												
		downloadEfetuado = true;
	}
}		
	
function contadorDownload()
{
	if (TimerDownload  > 0)
	{
		TimerDownload -= 1;
		d = document.getElementById('DivContadorDownload');
		d.innerHTML = '<b>Download Iniciando em: ' + TimerDownload + ' segundos. </b>';
	}else
	{
		if (!LinkVoltar)
		{
			d = document.getElementById("DivContadorDownload");
			d.innerHTML = '<b>Caso o Dowload n&atilde;o se inicie automaticamente <a href="biosetup.exe"><b>Clique aqui</b></a>.';
		}
	}
}

function MostraLinkVoltar()
{
	LinkVoltar = true;
	d = document.getElementById('DivContadorDownload');
	d.innerHTML = '<b><a href="../Biometria/DownloadBioSetup.aspx?urlpage=' + QueryString('urlpage') + '">Voltar ao Menu Principal >></a></b>';
}
																										
function validaBiometria(versao)
{
	try
	{   
		var ObjBiometria = new ActiveXObject("Biometria.CrtlBiometria"); 
		if (ObjBiometria.BioVersao() != versao)
		{
			ObjBiometria = null;
			TimerDownload = 16;  	
			window.setInterval('javascript:contadorDownload();', 1000);			
			window.setInterval('javascript:download();', 16000);
			window.setInterval('window.opener = window;alert("Seu navegador ser" + String.fromCharCode(225) + "  fechado para garantir que a atualiza" + String.fromCharCode(231) + String.fromCharCode(257) + "o seja feita com sucesso.");window.close();', 5000);
			return 1;	
		}
		return 0;
				
	}catch(e){	
		ObjBiometria = null;		
		TimerDownload = 16;  	
		window.setInterval('javascript:contadorDownload();', 1000);			
		window.setInterval('javascript:download();', 16000);
		window.setInterval('javascript:MostraLinkVoltar()', 40000);		
		return 2;
	}		
}

function iniciarComponente()
{
	var crtlBio =       (document.all ? document.all['CrtlBiometria'] : (document.getElementById ? document.getElementById('CrtlBiometria') : null));
	var hddBenef =	    (document.all ? document.all['HDDBenef_ID']	  : (document.getElementById ? document.getElementById('HDDBenef_ID')   : null));
	var hddUnimedId =   (document.all ? document.all['HDDunimed_ID']  : (document.getElementById ? document.getElementById('HDDunimed_ID')  : null));
	var hddUserId =     (document.all ? document.all['HDDuser_ID']    : (document.getElementById ? document.getElementById('HDDuser_ID')    : null));
	var hddSenha =      (document.all ? document.all['HDDsenha_ID']   : (document.getElementById ? document.getElementById('HDDsenha_ID')   : null));
	var hddWebService = (document.all ? document.all['Hddwebservice'] : (document.getElementById ? document.getElementById('Hddwebservice') : null));
    
	crtlBio.AtivaBiometria(hddBenef.value, hddUnimedId.value, hddUserId.value, hddSenha.value, hddWebService.value);
	
	//document.getElementById('CrtlBiometria').AtivaBiometria(document.all.HDDBenef_ID.value, document.all.HDDunimed_ID.value, document.all.HDDuser_ID.value, document.all.HDDsenha_ID.value, document.all.Hddwebservice.value);	
	//document.all.CrtlBiometria.AtivaBiometria(document.all.HDDBenef_ID.value, document.all.HDDunimed_ID.value, document.all.HDDuser_ID.value, document.all.HDDsenha_ID.value, document.all.Hddwebservice.value);
}//Inicia o Componenete Biométrico

function inserirComponenteBiometrico()
{
	document.write('<OBJECT id="CrtlBiometria" codeType="application/x-oleobject" classid="clsid:1CDA5E9F-5E41-4776-8CBF-AA290A270AF2" VIEWASTEXT></OBJECT>');
}

/*####################################################################*/

function Trim(str)
{
	while (str.charAt(0) == " ")
		str = str.substr(1,str.length -1);

	while (str.charAt(str.length-1) == " ")
		str = str.substr(0,str.length-1);
		
	return str;
} 

function MudarCampo(NomeDoCampo, ProximoCampo){
	var texto = eval('document.getElementById("' + NomeDoCampo + '").value');
	var tamanhoMaximo = eval('document.getElementById("' + NomeDoCampo + '").maxLength');
	var tamanhoTexto = texto.length;
			
	if(parseInt(tamanhoTexto, 10) >= parseInt(tamanhoMaximo, 10))
		eval('document.getElementById("' + ProximoCampo + '").focus()');
}

function perderFoco(txtBox){
	var texto = eval('document.getElementById(\'' + txtBox + '\').value');
	var tamanhoMaximo = eval('document.getElementById(\'' + txtBox + '\').maxLength');
	var tamanhoTexto = texto.length
	
	if((parseInt(tamanhoTexto, 10) >= parseInt(tamanhoMaximo, 10))){
		eval('if(document.getElementById(\'lnkTopo\') != null){document.getElementById(\'lnkTopo\').focus();}');
	}
}

function MudarCampoTab(controle, teclapres)
{
	var tecla = teclapres.keyCode;
	if ( ((tecla > 47) && (tecla < 48)) || ((tecla > 95) && (tecla < 106)) )
	{
		var texto = controle.value;
		var tamanhoMaximo = parseInt(controle.maxLength, 10);
		var tamanhoTexto = parseInt(texto.length, 10);				
		if((tamanhoTexto >= (tamanhoMaximo-1)) && (tecla != 8))
		{
			switch (tecla)
			{
				case 96: tecla = 48;break;
				case 97: tecla = 49;break;
				case 98: tecla = 50;break;
				case 99: tecla = 51;break;
				case 100:tecla = 52;break;
				case 101:tecla = 53;break;
				case 102:tecla = 54;break;
				case 103:tecla = 55;break;
				case 104:tecla = 56;break;
				case 105:tecla = 57;break;		
			}				
			controle.value+= String.fromCharCode(tecla);
			teclapres.keyCode = 9;
		}
	}
}

function FormataData(controle, e){
	var tecla = e.keyCode;

	if(tecla != 8 && tecla != 9){
		vr = controle.value;
		vr = vr.replace(".", "");
		vr = vr.replace("/", "");
		vr = vr.replace("/", "");
		tam = vr.length + 1;

		if ( tam > 2 && tam < 5 )
			controle.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			controle.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
	}
}

function ValidarDataDeNascimento(sender, args){	
	var data = new Date();
	var anoAtual = data.getFullYear();
	var mesAtual = data.getMonth() + 1;
	var diaAtual = data.getDate();
		
	var valor = "";
	if (args.Value) valor = args.Value;
	else valor = args;
		
	if (isDate(valor)){
		var nascimento = valor.split("/");
		var resultado = false;
		//Verificação da Data
		if(nascimento.length == 3){
			var dia = nascimento[0];
			var mes = nascimento[1];
			var ano = nascimento[2];
			if(!isNaN(ano) && (parseInt(ano, 10) < parseInt(anoAtual, 10)))//Verifica se o ano é menor que o atual
				resultado = true;
			else if(!isNaN(ano) && (parseInt(ano, 10) == parseInt(anoAtual, 10))){//Verifica se o ano é igual ao atual
				if(!isNaN(mes) && (parseInt(mes, 10) < parseInt(mesAtual, 10)))//Verifica se o mes é menor que o atual
					resultado = true;
				else if(!isNaN(mes) && (parseInt(mes, 10) == parseInt(mesAtual, 10))){
					if(!isNaN(diaAtual) && (parseInt(dia, 10) <= parseInt(diaAtual, 10)))//Verifica se o dia é menor ou igual ao dia atual
						resultado = true;
					else
						resultado = false;
				}
				else
					resultado = false;
			}
			else
				resultado = false;
		}		
	}
	else
	{
	resultado = false;
	var obj = (document.all ? document.all["txt" + sender.id.substring(2)] : (document.getElementById ? document.getElementById("txt" + sender.id.substring(2)) : null));
	obj.focus();
	resultado = false;
	}
	
	if (args.IsValid) args.IsValid = resultado;		
	else return resultado;	
}

function ValidarDataDePrevisaoDeInternacao(sender, args){
	
	var _return = false;
	if (CriticaData(sender, args))
	{
		var data = new Date();
		var anoAtual = data.getFullYear();
		var mesAtual = data.getMonth() + 1;
		var diaAtual = data.getDate();
	
		var valor = "";
		if (args.Value) data = args.Value;
	else data = args;
	if (args.IsValid) args.IsValid = isDate(data);		
	else return isDate(data);
}
	
	var valor = args;
	var nascimento = valor.split("/");
	var resultado = false;			
	//Verificação da Data
	if(nascimento.length == 3){
		var dia = nascimento[0];
		var mes = nascimento[1];
		var ano = nascimento[2];	
		if(!isNaN(ano) && (parseInt(ano, 10) > parseInt(anoAtual, 10)))//Verifica se o ano é maior que o atual
			resultado = true;
		else if(!isNaN(ano) && (parseInt(ano, 10) == parseInt(anoAtual, 10))){//Verifica se o ano é igual ao atual
			if(!isNaN(mes) && (parseInt(mes, 10) > parseInt(mesAtual, 10)))//Verifica se o mes é maior que o atual
				resultado = true;
			else if(!isNaN(mes) && (parseInt(mes, 10) == parseInt(mesAtual, 10))){
				if(!isNaN(diaAtual) && (parseInt(dia, 10) >= parseInt(diaAtual, 10)))//Verifica se o dia é maior ou igual ao dia atual
					resultado = true;
				else
					resultado = false;
			}
			else
				resultado = false;
		}
		else
			resultado = false;
	}	
	args.IsValid = resultado;
	
}

function ValidarDataDePrevisaoDeAlta(sender, args){
	var anoInternacao = 0;
	var mesInternacao = 0;
	var diaInternacao = 0;
	var txtDataInternacao = document.all.txtDataPrevisaoInternacao.value;//Campo que contém a data de Internação
	var dataInternacao = txtDataInternacao.split("/");
	if(dataInternacao.length == 3){
		diaInternacao = dataInternacao[0];
		mesInternacao = dataInternacao[1];
		anoInternacao = dataInternacao[2];
	}
	else{
		args.IsValid = false;
		return;
	}
	var valor = args;
	var nascimento = valor.split("/");
	//Verificação da Data
	if(nascimento.length == 3){
		var dia = nascimento[0];
		var mes = nascimento[1];
		var ano = nascimento[2];
		if((!isNaN(ano) && !isNaN(anoInternacao)) && (parseInt(ano, 10) > parseInt(anoInternacao, 10)))//Verifica se o ano é maior que o anoInternação
			args.IsValid = true;
		else if((!isNaN(ano) && !isNaN(anoInternacao)) && (parseInt(ano, 10) == parseInt(anoInternacao, 10))){//Verifica se o ano é igual ao anoInternação
			if((!isNaN(mes) && !isNaN(mesInternacao)) && (parseInt(mes, 10) > parseInt(mesInternacao, 10)))//Verifica se o mes é maior que o mesInternação
				args.IsValid = true;
			else if((!isNaN(mes) && !isNaN(mesInternacao)) && (parseInt(mes, 10) == parseInt(mesInternacao, 10))){//verifiva se o mes é igual ao mesInternação
				if((!isNaN(dia) && !isNaN(diaInternacao)) && (parseInt(dia, 10) >= parseInt(diaInternacao, 10)))//Verifica se o dia é maior ou igual ao diaInternação
					args.IsValid = true;
				else
					args.IsValid = false;
			}
			else
				args.IsValid = false;
		}
		else
			args.IsValid = false;
	}
}

function ValidarDataDeValidade(NomeCampo){
	var data = new Date();
	var dataCampo = eval('document.all.' + NomeCampo + '.value');
	var anoAtual = data.getFullYear();
	var mesAtual = data.getMonth() + 1;
	var diaAtual = data.getDate();
	//Verificação da Data
	var dataDeValidade = dataCampo.split("/");
	if(dataDeValidade.length == 3){
		var dia = dataDeValidade[0];
		var mes = dataDeValidade[1];
		var ano = dataDeValidade[2];
		if(!isNaN(ano) && (parseInt(ano, 10) > parseInt(anoAtual, 10)))//Verifica se o ano é maior que o atual
			return true;
		else if(!isNaN(ano) && (parseInt(ano, 10) == parseInt(anoAtual, 10))){//Verifica se o ano é igual ao atual
			if(!isNaN(mes) && (parseInt(mes, 10) > parseInt(mesAtual, 10)))//Verifica se o mes é maior que o atual
				return true;
			else if(!isNaN(mes) && (parseInt(mes, 10) == parseInt(mesAtual, 10))){
				if(!isNaN(diaAtual) && (parseInt(dia, 10) >= parseInt(diaAtual, 10)))//Verifica se o dia é maior ou igual ao dia atual
					return true;
				else
					return false;
			}
			else
				return false;
		}
		else
			return false;
	}
	else
		return false;
}

function ValidacaoFinalizandoAuditoria(){
	var msg = '';

	//Funções que validarão todos os campos da página!
	if(!ValidarDataDeValidade('txtDtValAuto'))
		msg = 'A data de validade deve ter o formato dd/MM/yyyy, e ser maior que a data de hoje!\n';
	//*******
	
	//Fim da Função
	if(msg.length < 1)
		return true;
	else{
		alert(msg);
		return false;
	//******
	}
}

function FocoInicial(NomeCampo){
	
	(document.all ? document.all[NomeCampo]   : (document.getElementById ? document.getElementById(NomeCampo)   : null)).focus();
	//eval('document.all.'+NomeCampo+'.focus();');
		
}


function autoTabProcedimentos(objeto,len, e) 
{
	var isNN = (navigator.appName.indexOf("Netscape")!=-1);
	var input;	
	//alert(_val_allString + '-<>-' + objeto + '-<>-' + _val_endAllString);
	eval("input = document.getElementById('" + objeto + "');");
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	
	if (keyCode == 13)
	{
		if (isNN) e.which = 9;
		else e.setKeyCode = 9;
		return true;
	}
	
	if(input.value.length >= len && !containsElement(filter,keyCode)) 
	{
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}	
	return true;
}

function contaCaracteres(txtMensagem){
	d = document.getElementById("divQtdCaracteresFaltando");
	d.innerHTML = (120 - txtMensagem.value.length).toString() + ' de 120 caracteres dispon&iacute;veis.';
	return false;
}

function contaCaracteresTrocaMensagem(txtMensagem, tamanho){
	d = document.getElementById("divQtdCaracteresFaltando");
	d.innerHTML = (tamanho - txtMensagem.value.length).toString() + ' de ' + tamanho + ' caracteres dispon&iacute;veis.';
	return false;
}

function validarNumerico(txtBox){
	var valor = txtBox.value;
	
	if(!isNaN(valor)){
		return true;
	}
	else{
		txtBox.value = '';
		txtBox.focus();
		var mens = 'Este campo deve conter valor num' + String.fromCharCode(279) + 'rico';
		alert(mens);
		return false;
	}
}

//Identificação de PopUps!!!
function NeedToDetect()
{
    try
    {
        var allcookies = document.cookie;    
        return (allcookies.indexOf(POPUP_DETECTED_COOKIE) == -1);
    }
    catch (exception)
    {
        return true;
    }
}

function IsYBI()
{
	var i = false;
	try
	{
        var xObj = new ActiveXObject("YBIOCtrl.CompanionBHO");
		if (xObj==null) i = false;
		else i = true;
	}
	catch(ex) { i = false; }
	return i;
}

function detectarPopUp()
{
	var e = false;
	var pw1 = null;
	var pw2 = null;
	try
	{
	    if (!NeedToDetect())
	    {
	        return false;
	    }
	    
		do
		{
			var d = new Date();
			var wName = "ptest_" + d.getTime();
			var testUrl = IsYBI() ? "popupTest.aspx" : "";
			pw1 = window.open(testUrl, wName,"width=1,height=1,left=3000,top=3000",true);
			if (null == pw1 || true == pw1.closed)
			{
				e = true;
				break;
			}
			pw2 = window.open(testUrl, wName,"width=1,height=1,left=3000,top=3000");
			if (null == pw2 || true == pw2.closed)
			{
				e = true;
				break;
			}
			if (IsYBI())
			{
				if (pw1 != pw2)
				{
					e = true;
					break;
				}
			}
			pw1.close();
			pw2.close();
			pw1 = pw2 = null;
		}
		while(false);
	}
	catch(ex)
	{
		e = true;
	}
	if (null != pw1)
	{
		try { if (!pw1.closed) pw1.close(); } catch(ex){}
	}
	if (null != pw2)
	{
		try { if (!pw2.closed) pw2.close(); } catch(ex){}
	}
	return e;
}
//***Identificação de PopUps!!!

//Janelas Modal e dialogs
String.prototype.isArgument=function()
{
	return /^([a-zA-Z]){1,}=([0-9]){1,}$/.test(this);
}

/*
call this function just work like window.open(url,name,feature);
however, for IE5.0+, it will open a showModelessDialog window;
and For Gecko(Mozilla or Netscape), the child window will stay on top focus untill user close it.
programmed by hedger
hedger@yahoo-inc.com
*/

function dialog(url,name,feature,isModal)
{
 if(url==null){return false;}
 url = url
 if(name==null){name=""}
 if(feature==null){feature=""};
 if(window.showModelessDialog)
 {
  	var WindowFeature = new Object();
	WindowFeature["width"] = 400;
	WindowFeature["height"]  =400;
	WindowFeature["left"]  = "";
	WindowFeature["top"]  =  "";
	WindowFeature["resizable"]  = "";

	if(feature !=null && feature!="")
	{
      feature = ( feature.toLowerCase()).split(",");
	
      for(var i=0; i < feature.length; i++)
		{
          if( feature[i].isArgument())
			{
               var featureName = feature[i].split("=")[0];
			   var featureValue = feature[i].split("=")[1];
			  
			   if(WindowFeature[featureName]!=null){WindowFeature[featureName] = featureValue; }
			}
		}
	}
 
  if(WindowFeature["resizable"]==1 || WindowFeature["resizable"]=="1" || WindowFeature["resizable"].toString().toLowerCase()=="yes"){WindowFeature["resizable"] = "resizable:1;minimize:1;maximize:1;"}
  if(WindowFeature["left"]!=""){WindowFeature["left"] ="dialogLeft:" +  WindowFeature["left"] +"px;";}
  if(WindowFeature["top"]!=""){WindowFeature["top"] ="dialogTop:" +  WindowFeature["Top"] +"px;"; }
  if(window.ModelessDialog ==null){window.ModelessDialog = new Object() ; };
  if(name!="")
  {
   if(window.ModelessDialog[name]!=null && !window.ModelessDialog[name].closed )
   {
     window.ModelessDialog[name].focus();
	 return window.ModelessDialog[name];
   }
  }
	var F = WindowFeature["left"] +WindowFeature["top"] +  "dialogWidth:"+WindowFeature["width"] +" px;dialogHeight:"+WindowFeature["height"]+"px;center:1;help:0;" + WindowFeature["resizable"] +"status:0;unadorned:0;edge: raised; ;border:thick;"
	if(isModal)
	{
		window.showModalDialog(url,self,F);
		return false;
	}
	else
	{
		window.ModelessDialog[name] = window.showModelessDialog(url,self,F);
		return window.ModelessDialog[name];
	}	
 }
 else
 {
   if(document.getBoxObjectFor)
   {
	

	 if(isModal)
	 {		 
		 var Modal = window.open(url,name,"modal=1," + feature);
		 var ModalFocus = function()
		 {
			if(!Modal.closed){Modal.focus();}
			else{Modal =null;window.removeEventListener(ModalFocus,"focus");ModalFocus = null; };					
		 }
		 window.addEventListener( "focus",ModalFocus, false ); 
		 return false;
	 }
	 else
	 {
		return window.open(url,name,"modal=1," + feature);
	 }	 
   }
   else
   { 
     return window.open(url,name,feature);
   }
   //
 }
 return null;
}
   
function modal(url,feature)
{
	dialog(url,"",feature,true);
	return false;
}

function PoupUpCentralizado(url,TamanhoVertical,TamanhoHorizontal){
	var Width = window.screen.availWidth;
	var Heigth = window.screen.availHeight;
		
	var WidthLeft = (Width - TamanhoHorizontal) / 2;
	var HeigthTop = (Heigth - TamanhoVertical) / 2;
			
	window.open(url,"","left="+WidthLeft+",top="+HeigthTop+",width="+TamanhoHorizontal+",height="+TamanhoVertical+", scrollbars=yes, status=yes");
}

function PoupUpCentralizadoRedimensionavel(url,TamanhoVertical,TamanhoHorizontal){
	var Width = window.screen.availWidth;
	var Heigth = window.screen.availHeight;
		
	var WidthLeft = (Width - TamanhoHorizontal) / 2;
	var HeigthTop = (Heigth - TamanhoVertical) / 2;
			
	window.open(url,"","left="+WidthLeft+",top="+HeigthTop+",width="+TamanhoHorizontal+",height="+TamanhoVertical+", scrollbars=yes, status=yes, resizable=yes");
}

function PoupUpCentralizadoModal(url,TamanhoVertical,TamanhoHorizontal){
	var Width = window.screen.availWidth;
	var Heigth = window.screen.availHeight;
		
	var WidthLeft = (Width - TamanhoHorizontal) / 2;
	var HeigthTop = (Heigth - TamanhoVertical) / 2;
			
	modal(url,"left="+WidthLeft+",top="+HeigthTop+",width="+TamanhoHorizontal+",height="+TamanhoVertical+", scrollbars=yes, status=yes");
}
//***Janelas Modal e dialogs

//Css
function trocarCss(objHtml, NomeDaCSS){
	objHtml.className = NomeDaCSS;
}
//***Css

//****************Telefone*******************//
function FormataTelefone(textBox, event){
	if(event.keyCode != 8){
		var valor = textBox.value;
		valor = valor.replace("-", "");
		if(textBox.value.length > 4)
			textBox.value = valor.substr(0, 4) + '-' + valor.substr(4, 8);
	}
	else
		textBox.value = textBox.value.substr(0, textBox.value.length);
}

/*Caracters Válidos*/
function retirarCaracteresDown(obj, e, span){
	var valores = "*<>;#&'\"\\/";
	for (i=0; i< valores.length; i++) {
		if (obj.value.substring(obj.value.toString().length-1  , obj.value.toString().length).charCodeAt(0) == valores.charCodeAt(i) ) {
			obj.value = obj.value.substring(0  , obj.value.toString().length-1);
		}		      
	}
	
}

function retirarCaracteresUp(obj, span) {
	var valores = "*<>;#&'\"\\/";
	var tamanho = obj.value.length;
	var mensagem = false;
	for (i=0; i< valores.length; i++) {
		for(j=0; j < tamanho; j++){
			if(obj.value.indexOf(valores.charAt(i)) > -1){
				obj.value = obj.value.replace(valores.charAt(i), "");
				mensagem = true;
			}
		}
	}
	if(mensagem == true)
		alert("Caracteres invalidos: *<>;#&'\"\\/");
}


//PTU Unimeds
function ocultarExibirNomePrestadorAltoCusto(){
	if(document.getElementById('chkAltoCusto').checked == false){
		document.getElementById('trPrestadorAltoCusto').style.display = 'none';
	}
	else{
		var navi = navigator.userAgent.toLowerCase();
		if(navi.indexOf('msie') > -1){
			document.getElementById('trPrestadorAltoCusto').style.display = 'inline';
		}
		else{
			document.getElementById('trPrestadorAltoCusto').style.display = 'table-row';
		}
	}
}

function exibirPTUMaior26(exibir){
	var navi = navigator.userAgent.toLowerCase();
	var tbAltoCusto = document.getElementById('tbAltoCusto');
	var trDiasAcomodacao = document.getElementById('trDiasAcomodacao');
	var trDiasUTI = document.getElementById('trDiasUTI');
	
	if(exibir == true){
		if(navi.indexOf('msie') > -1){
			tbAltoCusto.style.display = "inline";
			
			if(trDiasAcomodacao != null)
				trDiasAcomodacao.style.display = "none";
			if(trDiasUTI != null)
				trDiasUTI.style.display = "none";
		}
		else{
			tbAltoCusto.style.display = "table";
			
			if(trDiasAcomodacao != null)
				trDiasAcomodacao.style.display = "none";
			if(trDiasUTI != null)
				trDiasUTI.style.display = "none";
		}
	}
	else{
		if(navi.indexOf('msie') > -1){
			tbAltoCusto.style.display = "none";
			
			if(trDiasAcomodacao != null)
				trDiasAcomodacao.style.display = "inline";
			if(trDiasUTI != null)
				trDiasUTI.style.display = "inline";
		}
		else{
			tbAltoCusto.style.display = "none";
			
			if(trDiasAcomodacao != null)
				trDiasAcomodacao.style.display = "tablerow";
			if(trDiasUTI != null)
				trDiasUTI.style.display = "tablerow";
		}
	}
}

function exibirPTU30(exibir){
	if(exibir == true){
		var navi = navigator.userAgent.toLowerCase();
		if(navi.indexOf('msie') > -1){
			document.getElementById('tbPTU30').style.display = "inline";
		}
		else{
			document.getElementById('tbPTU30').style.display = "table";
		}
	}
	else
		document.getElementById('tbPTU30').style.display = "none";
}
//***********

//Empresas
function FormataCNPJ(textBox, event){ 
	if(event.keyCode != 8){
		var valor = textBox.value;
		var tamanho = valor.length;

		valor = valor.replace(".", "");
		valor = valor.replace(".", "");
		valor = valor.replace(".", "");
		
		valor = valor.replace("/", "");
		valor = valor.replace("/", "");
		
		valor = valor.replace("-", "");
		valor = valor.replace("-", "");

		if ((tamanho > 2) && (tamanho <= 6))
			textBox.value = valor.substr(0, 2) + '.' + valor.substr(2, tamanho);
		
		if ((tamanho >= 7) && (tamanho <= 10))
			textBox.value = valor.substr( 0, 2 ) + '.' + valor.substr( 2, 3 ) + '.' + valor.substr( 5, 3 ) + '/';
			
		if ((tamanho >= 11) && (tamanho <= 18))
			textBox.value = valor.substr(0, 2) + '.' + valor.substr(2, 3) + '.' + valor.substr(5, 3) + '/' + valor.substr(8, 4) + '-' + valor.substr(12, 2);
	}
	else
		textBox.value = textBox.value.substr(0, textBox.value.length);
}

function FormataCPF(textBox, event){ 
	if(event.keyCode != 8){
		var valor = textBox.value;
		var tamanho = valor.length;

		valor = valor.replace(".", "");
		valor = valor.replace(".", "");
		valor = valor.replace(".", "");
		valor = valor.replace("-", "");
		valor = valor.replace("-", "");

		if ((tamanho > 3) && (tamanho < 7))
			textBox.value = valor.substr(0, 3) + '.' + valor.substr(3, tamanho);
		
		if ((tamanho >= 7) && (tamanho < 11))
			textBox.value = valor.substr(0, 3) + '.' + valor.substr( 3, 3 ) + '.' + valor.substr( 6, tamanho );
			
		if ((tamanho >= 11) && (tamanho < 14))
			textBox.value = valor.substr(0, 3) + '.' + valor.substr( 3, 3 ) + '.' + valor.substr( 6, 3 ) + '-' + valor.substr( 9, tamanho );
			
	}
	else
		textBox.value = textBox.value.substr(0, textBox.value.length);
}
//***********


function limitaCaracteres(controle, event){
	//alert(document.getElementById(controle.id).maxLength);
	/*
	for(item in document.getElementById(controle.id)){
		document.write(item + ' = ' + item.value + '<br>');
	}
	alert(controle.maxLength);
	*/
	if(event.keyCode != 8 && event.keyCode != 9){
		if(controle.value.length > controle.maxLength){
			event.setKeyCode = 0;
		}
	}
}

function retiraCaracteresAMais(controle){
	if(controle.value.length > controle.maxLength){
		controle.value = controle.value.substr(0, controle.maxLength);
	}
}

function validarDataAtendimento(sender, args){
	var dataControle = args.split('/');
	
	var dataAtendimento = new Date();
	dataAtendimento.setDate(dataControle[0]);
	dataAtendimento.setMonth(parseInt(dataControle[1], 10) -1);
	dataAtendimento.setFullYear(dataControle[2]);
	
	var dataAtual = new Date();
	dataAtual.setDate(dataAtual.getDate() -45);
	
	if(dataAtendimento < dataAtual)
		return false;
	else
		return true;
}

function validarDataCalendario(sender, args){
	if(isDate(args)){
		if(parseInt(args.split('/')[2], 10) > 1901)
			return true;
	}

	return false;
}

function FormataValor(Controle,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Controle.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	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 <= 2 ){ 			 		
	 		Controle.value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		Controle.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		Controle.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		Controle.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		Controle.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		Controle.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 formataHora(controle, event){
	if((!event.shiftKey) && (event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 ||
		event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 ||
		event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57 ||
		event.keyCode == 96 || event.keyCode == 97 || event.keyCode == 98 || event.keyCode == 99 ||
		event.keyCode == 100 || event.keyCode == 101 ||	event.keyCode == 102 || event.keyCode == 103 ||
		event.keyCode == 104 || event.keyCode == 105 || event.keyCode == 8 || event.keyCode == 46 ||
		event.keyCode == 9))
	{
		if(controle.value.length == 2 && event.keyCode != 8){
			controle.value += ':';
		}
		
		return true;
	}
	
	return false;
}

// URL Enconde do JavaScript corrigindo erros como o + q não é subistituido
function urlEncode(texto)
{
	texto = escape(texto);
	var charOrigem	= '+=';
	var charDestino = new Array('%2b','%3d');
	var Posic, Carac;
	var TempLog = "";
	for (var i=0; i < texto.length; i++)
	{
		Carac = texto.charAt(i);
		Posic  = charOrigem.indexOf(Carac);
		if (Posic > -1)
			TempLog += charDestino[Posic];
		else
			TempLog += texto.charAt(i);
	}
    return (TempLog);
}

// PadLeft and PadRight
function padLeft(_text, _count, _char)
{
	for(var i=_text.length; i < _count; i++)
	{
		_text = _char + _text;
	}
	return _text;
}

function padRight(_text, _count, _char)
{	
	for(var i=_text.length; i < _count; i++)
	{
		_text += _char;
	}
	return _text;
}