<!--//
$import("libjs/dialog_window.js");

if(!document.all)
	document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
var form     = document.all;

function mudaCor(event,color){
   var el=event.srcElement
   if (el.tagName=="INPUT"&&el.type=="button")
      Event.srcElement.style.backgroundColor=color
}

function sortNumber(a,b) {
   return a[1] < b[1]
}

String.prototype.trim = function() {
   a = this.replace(/^\s+/, '');
   return a.replace(/\s+$/, '');
};

String.prototype.strCount = function(str) {
   var wRet = this;
   var idx = wRet.indexOf(str);
   Cont = 0;
   while ( idx > -1 ) {
      wRet = wRet.replace(str, "");
      idx  = wRet.indexOf(str);
      Cont++;
   }
   return Cont;
};


String.prototype.ReplaceAll = function(str,sub){
   var wRet = this;
   var idx = wRet.indexOf(str);
   while ( idx > -1 ) {
      wRet = wRet.replace(str, sub);
      idx  = wRet.indexOf(str);
   }
   return wRet;
};

function printit(what,where,how) {
	window.open(what,where,how);
}

function $import(path){
	var i, base, src = "funcoes.js", scripts = document.getElementsByTagName("script");
	for (i=0; i<scripts.length; i++){if (scripts[i].src.match(src)){ base = scripts[i].src.replace(src, "");break;}}
	document.write("<" + "script src=\"" + base + path + "\"></" + "script>");
}


//-----------------------------------------------------------------------
//Funções da MacroMedia
   function MM_findObj(n, d) { //v4.01
      var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
         d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
         if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
         for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
         if(!x && d.getElementById) x=d.getElementById(n); return x;
   }
   function MM_swapImage() { //v3.0
      var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
      if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
   }
   function MM_swapImgRestore() { //v3.0
      var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
   }
   function MM_preloadImages() { //v3.0
      var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
      var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
      if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
   }
	function MM_reloadPage(init) {  //reloads the window if Nav4 resized
		if (init==true) with (navigator) {
			if((appName=="Netscape")&&(parseInt(appVersion)==4)){ 
	    		document.MM_pgW=innerWidth; 
	    		document.MM_pgH=innerHeight; 
	    		onresize=MM_reloadPage;
			}
		}else if(innerWidth!=document.MM_pgW || 
			      innerHeight!=document.MM_pgH)
			location.reload();
	}
//-----------------------------------------------------------------------
function val_dados_interfaceamentos(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;	
	if(trim(form.unidade.value) == ""){
		alert("Atenção,\nDeve ser inserido a Unidade !");
      form.unidade.focus();
		return false;
	} else if(trim(form.dias_arquivamento.value) == ""){
		alert("Atenção,\nDeve ser inserido o(s) Dia(s) p/ Arquivamento !");
      form.dias_arquivamento.focus();
		return false;
	} else if(trim(form.ip.value) == ""){
		alert("Atenção,\nDeve ser inserido o IP do Servidor !");
      form.ip.focus();
		return false;
	} else if(trim(form.banco.value) == ""){
		alert("Atenção,\nDeve ser inserido o nome do Banco !");
      form.banco.focus();
		return false;
	} else if(trim(form.usuario_banco.value) == ""){
		alert("Atenção,\nDeve ser inserido o Nome do Usuário do Banco de Dados !");
      form.usuario_banco.focus();
		return false;
	} else if(trim(form.diretorio.value) == ""){
		alert("Atenção,\nDeve ser inserido o Diretório onde está sendo gravado as imagens !");
      form.diretorio.focus();
		return false;
	} else if(trim(form.usuario_ftp.value) == ""){
		alert("Atenção,\nDeve ser inserido o Nome do Usuário p/ Acesso via FTP !");
      form.usuario_ftp.focus();
		return false;
	}
	return true;
}
//-----------------------------------------------------------------------
function val_dados_modulo(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;	
	if(trim(form.cNomeModu.value) == ""){
		alert("Atenção,\nDeve ser informado o Nome do Módulo !");
      form.cNomeModu.focus();
		return false;
   }
   return true;
}
//-----------------------------------------------------------------------
function val_dados_tipousua(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;	
	if(trim(form.cTipoNome.value) == ""){
		alert("Atenção,\nDeve ser informado a Descrição do Tipo de Usuário!");
      form.cTipoNome.focus();
		return false;
   }
   return true;
}

//-----------------------------------------------------------------------
function val_dados_menu(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;	
	if(trim(form.cNiveMenu.value) == ""){
		alert("Atenção,\nDeve ser informado o Nivel do menu !");
      form.cNiveMenu.focus();
		return false;
   } else if(trim(form.cNomeMenu.value) == "") {
		alert("Atenção,\nDeve ser informado o Nome do menu !");
      form.cNomeMenu.focus();
		return false;
   } else if(trim(form.cOrdeMenu.value) == "") {
		alert("Atenção,\nDeve ser informado a Ordem do menu !");
      form.cOrdeMenu.focus();
		return false;
   } else if(trim(form.cDescMenu.value) == "") {
		alert("Atenção,\nDeve ser informado o Descrição do menu !");
      form.cDescMenu.focus();
		return false;
   }
   return true;
}
//-----------------------------------------------------------------------
function VeriNivel(Server){
   var objCarregador              = form.carregador_pai;
   try {
      if (form.cNiveMenu.value!="") {
         var wNivel = form.cNiveMenu.value;
            objCarregador.style.display	 = "";
            objCarregador.style.visibility = "visible";
            var aConexao = new ServerRequest();
            var retorno = '';
            //alert("rsp.php?Server=" + Server + "&Pagina=www_veri_nivel.rsp?cNivel=" + wNivel);
            //aConexao.submit(Server + "www_veri_nivel.rsp?cNivel=" + wNivel);         
            aConexao.submit("rsp.php?Server=" + Server + "&Pagina=www_veri_nivel.rsp?cNivel=" + wNivel);         
            aConexao.onComplete = function (responseText, responseXML){
               objCarregador.style.display	 = "none";
               objCarregador.style.visibility = "hidden";
               linha   = responseText.split("\n");
               for(i=0; i<linha.length; i++) {
                  retorno = linha[i].split(":");
                  if(retorno[0] == "DADOS") {
                     var wVar = retorno[1].split("|");
                     form.cNiveMenu.value  = trim(wVar[0]);
                     form.DescNivel.value  = trim(wVar[1]);
                     form.cNomeMenu.focus();
                  } else if(retorno[0] == "ERRO") {
                     form.cNiveMenu.value  = "";
                     form.DescNivel.value  = "";
                     form.cNiveMenu.focus();
                     alert('Erro: ' + retorno[1]);
                  }
               }
            };         
      }
   } catch(e) {
      objCarregador.style.display	 = "none";
      objCarregador.style.visibility = "hidden";
      alert('Erro: ' + e.number);
   }
}
//-----------------------------------------------------------------------
function controla_botoes(str) {           
	var str;	
	var cont = 1;
	var form = document.forms[0];
	for(var i = 0; i < form.length; i++) {
		if(form.elements[i].name.substring(0,5) == 'cont_'){
			var aa = eval('document.all.' + form.elements[i].name.substr(5,3) + cont);
			aa.style.visibility = 'hidden';
			form.elements[i].disabled = false;
			if(instr(0,form.elements[i].name + cont,str) != '0'){
				aa.style.visibility = 'visible';
				form.elements[i].disabled = true;
			}
		cont++;
		}
	}
}
function ver(){
	var str;	
	var cont = 1;
	var form = document.forms[0];
	for(var i = 0; i < form.length; i++) {
		if(form.elements[i].name.substring(0,5) == 'cont_'){
			alert(form.elements[i].docHtml + '|' + form.elements[i].value);
		cont++;
		}
	}
}
function verifica_radio(texto){
   if(!texto)
      texto = 'Atenção,\nDeve ser escolhido pelo menos um laudo ! ! !';
	if(!document.buscaimg)
	   var form = document.ass_resv;
	else
	   var form = document.buscaimg;	
	for(var i = 0; i < document.forms[0].length; i++)
		if(document.forms[0].elements[i].checked)
			return true;
	alert(texto);
	return false;
}
function instr(n, s1, s2){
	// posicao de s1 em s2
	var numargs=instr.arguments.length;	
	if(numargs<3)
		return n.indexOf(s1)+1;
	else
		return s1.indexOf(s2, n)+1;
}
function verifica_check(){
	var form = document.buscaimg;
	for(var i = 0; i < document.forms[0].length; i++) {
		if(document.forms[0].elements[i].name.substring(0,6) == 'exibir'){
			if(document.forms[0].elements[i].checked){
				return true;
			}
		}
	}
	alert('Atenção,\nDeve ser escolhido pelo menos uma imagem ! ! !');
	return false;
}
function destaqueOn() {
	var form = document.buscaimg;
	for(var i = 0; i < document.forms[0].length; i++) {
		if(eval('form.destaque'+i)){
			if (form.babyface.checked) {
				eval('form.destaque'+i+'.disabled = false');
			} else {
				eval('form.destaque'+i+'.disabled = true');
			}
			eval('form.destaque'+i+'.checked = false');
		}
	}
}
//============== FUNCOES EM JAVASCRIPT UTILIZADAS NO SITE ==========================
function AbreFichaAnt(what,where, how) {
	window.open(what,where,how);
}
function setVariables() {
	if (navigator.appName == 'Netscape') {
		v  = '.top=';
		h  = '.left=';
		dS = 'document.';
		sD = '';
		y  = 'window.pageYOffset';
		x  = 'window.pageXOffset';
		iW = 'window.innerWidth';
		iH = 'window.innerHeight';
	} else {
      h  = '.pixelLeft=';
      v  = '.pixelTop=';
      dS = '';
      sD = '.style';
      y  = 'document.body.scrollTop';
      x  = 'document.body.scrollLeft';
      iW = 'document.body.clientWidth';
      iH = 'document.body.clientHeight';
	}
   xyz    = 500;
   innerX = eval(iW) - 905;
   innerY = eval(iH) - 480;
   object = 'logo';
	checkLocationA();
}
movex  = 0;
movey  = 0;
xdiff  = 0;
ydiff  = 0;
ystart = 0;
xstart = 0;

function checkLocation() {
	yy 	= eval(y);
	xx 	= eval(x);
	ydiff = ystart - yy;
	xdiff = xstart - xx;
	if ((ydiff < (-1)) || (ydiff > (1))) movey = Math.round(ydiff / 10), ystart -= movey;
	if ((xdiff < (-1)) || (xdiff > (1))) movex = Math.round(xdiff / 10), xstart -= movex;
	eval(dS + object + sD + v + (ystart + innerY));
	eval(dS + object + sD + h + (xstart + innerX));
	setTimeout('checkLocation()', 10);
}

function checkLocationA() {
	ystart = eval(y);
	xstart = eval(x);
}

function switchLogo(abc) {
	if (abc == 'menu') {
		eval(dS + object + sD + v + 0);
		eval(dS + object + sD + h + (-200));
		object = abc;
	} else {
		xyz = setTimeout('delayLogo()', 2000);
	}
}

function delayLogo() {
   eval(dS + object + sD + v + 0);
   eval(dS + object + sD + h + (-200));
   object = 'logo';
}

function mostrar(menu){
	if (menu.style.display=='none'){
		menu.style.display='';
	} else {
		menu.style.display='none'
	}
}

function val_dados_ass_unid(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;
	if(trim(form.unidade.value) == ""){
		alert("Atenção,\nDeve ser inserido a Unidade !");
      form.unidade.focus();
		return false;
	} else if(trim(form.dt_inicio.value) != "" || trim(form.dt_fim.value) != "") {
		alert("Atenção,\nDeve ser inserido as duas datas !");
      form.dt_inicio.focus();
		return false;
	}
}

function val_dados_ass(ass_area){
	if (ass_area == 'empresas') {
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
		var form;
		form = document.all ? document.all : document.layers;
		if(form.empresas1.value == 'ND'){
			alert("Atenção,\nDeve ser selecionado a Empresa !");
			form.empresas1.focus();
			return false;
		}
      return true;
	}	
}

/*----------------------------------------------------------------------------*/
/* - Função que jah existiam                                                  */
/*----------------------------------------------------------------------------*/
function textos(ass_area){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	if (ass_area == 'empresas') {
		document.all.arean.value = 'Aqui você deve escolher apenas uma das opções. Isso determina para quais unidades será possível dar permissão de assinatura.';
	} else if (ass_area == 'unidade') {
		document.all.arean.value = 'Você pode selecionar qualquer número de unidades, ou então selecionar a caixa Marcar Todas e depois desmarcar as que desejar.';
	} else if (ass_area == 'especial') {
		document.all.arean.value = 'Você pode selecionar qualquer número de especilidades, ou então selecionar a caixa Marcar Todas e depois desmarcar as que desejar.';
	} else if (ass_area == 'secoes') {
		document.all.arean.value = 'Você pode selecionar qualquer número de seções, ou então selecionar a caixa Marcar Todas e depois desmarcar as que desejar.';
	} else if (ass_area == 'mapas') {
		document.all.arean.value = 'Você pode selecionar qualquer número de mapas, ou então selecionar a caixa Marcar Todos e depois desmarcar os que desejar.';
	} else if (ass_area == 'exames') {
		document.all.arean.value = 'Você pode selecionar qualquer número de exames, ou então selecionar a caixa Marcar Todos e depois desmarcar os que desejar.';
	} else if (ass_area == 'convenio') {
		document.all.arean.value = 'Você pode selecionar qualquer número de convênioa, ou então selecionar a caixa Marcar Todos e depois desmarcar os que desejar.';
	} else {
		document.all.arean.value = 'Vazio';
	}
}
function help_but_on() {
	layerhelp.style.visibility="visible";
}	
function help_but_off() {
	layerhelp.style.visibility="hidden";
}
function CheckAll() {
	alert('ATENÇÃO: esta operação pode levar alguns minutos.');
	var qtcheck = 0;
	for (var i=0;i<document.permissions.elements.length;i++) {
		var e=document.permissions.elements[i];
		if (e.type == 'checkbox') {
			e.checked = document.permissions.marklabel.value=='marcar todos' ? true : false;
			qtcheck = Number(qtcheck) + 1;
		}
	}
	if (document.permissions.marklabel.value=='marcar todos') {
		document.permissions.marklabel.value='desmarcar todos'
		alert('Todos os ' + qtcheck + ' registros foram marcados.');
	} else {
		document.permissions.marklabel.value='marcar todos'
		alert('Todos os ' + qtcheck + ' registros foram desmarcados.');
	}
}
function setEnvio() {
	var totalE = document.permissions.elements.length;
	var unCheck = 0;
	var tCheck = 0;
	for (i=0;i<totalE;i++) {
		if (document.permissions.elements[i].type=='checkbox') {
			tCheck = tCheck + 1;
			if (!document.permissions.elements[i].checked) {
				document.permissions.hlinha.value = document.permissions.hlinha.value + ';' + document.permissions.elements[i].value;
				unCheck = unCheck + 1;
			}
		}
	}
	document.permissions.hlinha.value = document.permissions.hlinha.value + ';';
	if (unCheck == tCheck) {
		alert('Você deve escolher pelo menos um dos itens de permissão');
		document.permissions.hlinha.value = '';
		return false
	} else {
		if (document.permissions.hlinha.value == ';') {
			document.permissions.hlinha.value = '';
		}
		//alert(document.permissions.hlinha.value);
		return true;
	}
}
/*----------------------------      FIM       --------------------------------*/

/*----------------------------------------------------------------------------*/
/* - Função Valida o Form da Captura                                          */
/*----------------------------------------------------------------------------*/

function valida_dados_cap(){
	var form = document.cadastro;
	if(form.keytype[0].checked && trim(form.ficha.value) == ''){
		alert("Atenção,\nDeve ser inserido a Ficha ! ! !");
		form.ficha.focus();
		return false;
	} else if(form.keytype[1].checked && trim(form.nome.value) == ''){ 
		alert("Atenção,\nDeve ser inserido o Nome ! ! !");
		form.nome.focus();
		return false;
	} else if(trim(form.data.value) == ''){
		alert("Atenção,\nDeve ser inserido a Data ! ! !");
		form.data.focus();
		return false;
	}
	return true;
}
/*----------------------------------------------------------------------------*/
/* - Função Valida o Form da Captura                                          */
/*----------------------------------------------------------------------------*/

function valida_dados_cap_imagens(){
	return false;
}
/*----------------------------------------------------------------------------*/
/* - Função que retorna a data atual um ano antes                             */
/*----------------------------------------------------------------------------*/

function dataanterior(){
   var data = new Date(); 
	var dia = data.getDate(); 
	var mes = data.getMonth() + 1; 
	var ano = data.getFullYear() - 1; 
	dia = (dia < 10 ? "0"+dia : dia); 
	mes = (mes < 10 ? "0"+mes : mes); 
	return dia + "/" + mes + "/" + ano;
}

/*----------------------------------------------------------------------------*/
/* - Função usada p/ validar os campos de Estatistica                         */
/*----------------------------------------------------------------------------*/

function val_dados_estat(){
	var form = document.choose_stat;
   var ok = '0',ok2 = '0',i;
	if(form.byuser.checked && form.user_stat.value == 'ND'){
		alert("Atenção,\nDeve ser selecionado um usuário !");
      form.user_stat.focus();
		return false;
	}
	if(form.bytime.checked && (trim(form.dt_inicial.value) == '' || trim(form.dt_final.value) == '')){
		alert("Atenção,\nDeve ser inserido as Datas(Inicial/Final) !");
		return false;
	} else {
		if(!form.bytime.checked){
			alert("Atenção,\nCom a data não informada o sistema trará dados de um ano atrás,\na partir da data de hoje. (" + dataanterior() + ")")
		}
	}
	if(form.bytype.checked && form.tipo_stat.value == 'ND'){
		alert("Atenção,\nDeve ser selecionado um tipo de assinatura !");
      form.tipo_stat.focus();
		return false;
	}
	for (i=0;i<=form.elements.length;i++) {
		var e = form.elements[i];
		if (e.type == 'checkbox') {
			if (e.checked) {
				ok = '1';
			}
		}
		if (i == (form.elements.length - 1)){
		   if (ok != '1'){
		      alert('Você deve selecionar uma das opções antes de prosseguir!');
		      return false;
		   }		   	
		}
	}
	return true;
}

/*----------------------------------------------------------------------------*/
/* - Função usada p/ validar os campos de Alteraçao de Senha                  */
/*----------------------------------------------------------------------------*/

function val_dados_senha(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form
	if(document.all){
		form = document.all;
	}else{
		form = document.layers;
	}
	if(trim(form.senha_atual.value) == ""){
		alert("Atenção,\nDeve ser inserido sua Senha Atual !");
      form.senha_atual.focus();
		return false;
	} else
	if(trim(form.nova_senha.value) == ""){
		alert("Atenção,\nDeve ser inserido uma Senha !");
      form.nova_senha.focus();
		return false;
	} else
	if ((trim(form.nova_senha.value) != "") || (trim(form.confirmar.value) != "")){
		if (trim(form.nova_senha.value) != trim(form.confirmar.value)) {
			alert("Atenção,\nSenha confirmada não confere com a Nova Senha !");
			form.nova_senha.focus();
			return false;
		}
	} else {
      return true;
   }

}

/*----------------------------------------------------------------------------*/
/* - Função usada p/ validar se o campo se a permissao de tipo nao foi alterada*/
/*----------------------------------------------------------------------------*/
function val_dados_permissao_tipos(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;
	if((trim(form.permgrupo.value) == 'checked' && form.chkgrupo.checked) || (trim(form.permgrupo.value) == '' && !form.chkgrupo.checked)){
		alert("Atenção,\n Permissão não modificada!");
		return false;
	}
	return true;
}

/*----------------------------------------------------------------------------*/
/* - Função usada p/ validar se o campo se a permissao nao foi alterada       */
/*----------------------------------------------------------------------------*/

function val_dados_permissao(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;
	if(form.chkgrupo.checked && form.chkusuario.checked){
		alert("Atenção,\n Permissão já definida no Grupo!");
		form.chkusuario.checked = false;
		return false;		
	}
	if((trim(form.permusuario.value) == 'checked' && form.chkusuario.checked) || (trim(form.permusuario.value) == '' && !form.chkusuario.checked)){
		alert("Atenção,\n Permissão não modificada!");
		return false;
	}
	return true;
}

/*----------------------------------------------------------------------------*/
/* - Função usada p/ validar se o campo ficha não esta vazio                  */
/*----------------------------------------------------------------------------*/
function val_dados_usr(){
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
   var form = document.all;
   if (trim(form.usuario.value) == "") {
      alert("Deve ser inserido um Nome de Usuário !");
      form.usuario.focus();
		return false;
	} else 
   if (trim(form.nome.value) == "") {
      alert("Deve ser Dado o Nome !");
      form.nome.focus();
		return false;
	} else 
   if (trim(form.sobrenome.value) == "") {
      alert("Deve ser Dado o Sobrenome !");
      form.sobrenome.focus();
		return false;
	} else
	if (form.sexo.value == "ND"){
		alert("Deve ser escolhido o Sexo !");
		form.sexo.focus();
		return false;
	} else
	if (((trim(form.cidade.value) != "") || (trim(form.bairro.value) != "") || (trim(form.endereco.value) != "")) && (form.estado.value == "ND")){
		alert("Deve ser escolhido o Estado !");
		form.estado.focus();
		return false;
	}
   return true;
}


/*----------------------------------------------------------------------------*/
/* - Função usada p/ validar se o campo ficha não esta vazio                  */
/*----------------------------------------------------------------------------*/

	function val_login() {
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	   var form = document.all;
	   if (trim(form.u.value) == "") {
	      alert("Deve ser inserido um Login !");
	      form.u.focus();
			return false;
		} else if (trim(form.p.value) == "") {
			alert("Deve ser inserido sua Senha !");
	      form.p.focus();
			return false;
	   }
		return true;
	}

/*----------------------------------------------------------------------------*/
/* Recebe o evento e se for ENTER, simula o click do botão passado.
*  Se for passado um objInput como um input de Texto por exemplo, ele só
*  executará o click do botão se o objInput.value nao for vazio. 
*/
/*----------------------------------------------------------------------------*/
function executaseenter(){
	var form;
	form = document.formkey;
	if (document.all) // Internet Explorer
      var tecla = event.keyCode;
   else if(document.layers) // Nestcape
      var tecla = e.which;    
	if(tecla == 13){	
			form.submit;
			return true;
			alert('ok');
	}
}

function fEnter(event) {  
   try {
      event = ( event || window.event );
      key = ( event.keyCode || event.charCode || event.which || 0 ); 
      if(key == 13) {
         return event.keyCode = 9;
      }
   } catch(e) {
   }
}

/*----------------------------------------------------------------------------*/
/* - Função usada p/ controlar o campo                                        */
/*----------------------------------------------------------------------------*/

function controla_campo() {
	if(!document.all)
		document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );
	var form = document.all;	

   try {
   	var myString,index;
   	myString = form.t_value.value;
   	index = myString.indexOf(";" + form.tipo.value + ";");
   	if (index >= 0) {
   		form.conselho.disabled                     = false;
   		form.conselho.style.backgroundColor        = '#EBEBEB';
   		form.documento.disabled                    = false;
   		form.documento.style.backgroundColor       = '#EBEBEB';
   		form.cr_estado.disabled                    = false;
   		form.cr_estado.style.backgroundColor       = '#EBEBEB';
   		form.especializacao.disabled               = false;
   		form.especializacao.style.backgroundColor  = '#EBEBEB';
   		form.med_ativo.disabled                    = false;
   		form.med_ativo.style.backgroundColor       = '#EBEBEB';
   		form.med_libera.disabled                   = false;
   		form.med_libera.style.backgroundColor      = '#EBEBEB';
   		form.excluir_imagem.disabled               = false;
   		form.nova_assinatura.disabled              = false;
   		form.nova_assinatura.style.backgroundColor = '#EBEBEB';
   	} else {
   		form.conselho.disabled                     = true;
   		form.conselho.style.backgroundColor        = '#CCCCCC';
   		form.conselho.value                        = '';
   		form.documento.disabled                    = true;
   		form.documento.style.backgroundColor       = '#CCCCCC';
   		form.documento.value                       = '';
   		form.cr_estado.disabled                    = true;
   		form.cr_estado.style.backgroundColor       = '#CCCCCC';
   		form.cr_estado.value                       = '';
   		form.especializacao.disabled               = true;
   		form.especializacao.style.backgroundColor  = '#CCCCCC';
   		form.especializacao.value                  = '';
   		form.med_ativo.disabled                    = true;
   		form.med_ativo.style.backgroundColor       = '#CCCCCC';
   		form.med_ativo.value                       = '';
   		form.med_libera.disabled                   = true;
   		form.med_libera.style.backgroundColor      = '#CCCCCC';
   		form.med_libera.value                      = '';
   		form.excluir_imagem.disabled               = true;
   		form.nova_assinatura.disabled              = true;
   		form.nova_assinatura.style.backgroundColor = '#CCCCCC';
   		form.nova_assinatura.value                 = '';
   	}
   } catch (err) {
      alert(err.description);
   }
}
	
/*----------------------------------------------------------------------------*/
// Retorna o código do evento de acordo com o browser
/*----------------------------------------------------------------------------*/
function tecla(){
	return (e.which) ? e.which : event.keyCode;
}



//----------------------------------------------------------------------------------
//Verifica se existe algum radio ticado
//No captura
//Usar: onSubmit="return checa_radio('1');" 
//1 - P/ Pacientes     |     2 - P/ Figuras
function checa_radio(msg) {
   var form;
   var ok = '0';
   form = document.buscaimg;
	for (i=0;i<=form.elements.length;i++) {
		var e = form.elements[i];
		if (e.type == 'radio') {
			if (e.checked) {
				ok = '1';
			}
		}
		if (i == (form.elements.length - 1)){
		   if (ok != '1'){
		      switch (msg){
		         case '1':
		            alert('Você deve selecionar um dos pacientes antes de prosseguir!');
		            break;
		         case '2':
		            alert('Você deve selecionar um estilo antes de prosseguir!');
		            break;
		      }
		      return false;
		   } else {
		      return true;
		   }
		}
	}
}
//----------------------------------------------------------------------------------
//Verifica se existe algum checkbox ticado
//No Captura
//Usar: onSubmit="return checa_checkbox();"
function checa_checkbox(msg) {
   var form;
   var ok = '0';
   form = document.buscaimg;
	for (i=0;i<=form.elements.length;i++) {
		var e = form.elements[i];
		if (e.type == 'checkbox') {
			if (e.checked) {
				ok = '1';
			}
		}
		if (i == (form.elements.length - 1)){
		   if (ok != '1'){
		      alert('Você deve selecionar uma das imagens antes de prosseguir!');
		      return false;
		   } else {
		      return true;
		   }
		}
	}
}
//----------------------------------------------------------------------------------
//Função p/ tratar o Campo p/ aceitar apenas letras e numeros
//
//Usar: onKeypress="return KeyinPress(event);"
function KeyinPress(event)  {
   if (document.all) // Internet Explorer
      var tecla = event.keyCode;
   else if(document.layers) // Nestcape
      var tecla = e.which;    
      if ((tecla > 47 && tecla < 58) || (tecla > 64 && tecla < 91) || (tecla > 96 && tecla < 123) || (tecla == 13)) // numeros de 0 a 9 ou Letras A a Z ou Letras a a z
      return true;
   else {
      if (tecla  = 8) // backspace
         try {
            event.keyCode = 0;
         } catch (e) {
         }
      else
         return true;         
	}
}


//----------------------------------------------------------------------------------
//Função p/ tratar o Campo p/ aceitar tudo menos caracter especiais
//
//Usar: onKeypress="return trata(event);"
function trata()  {
   if (document.all) // Internet Explorer
      var tecla = event.keyCode;
   else if(document.layers) // Nestcape
      var tecla = e.which;    
   if ((tecla == 40) || (tecla == 41))
   	return true;
   if ((tecla >  32 && tecla <  48) || 
   	 (tecla >  57 && tecla <  65) ||
   	 (tecla >  90 && tecla <  94) ||
   	 (tecla > 122 && tecla < 126) ||
   	 (tecla == 95))
      return false;
   return true;
}
//----------------------------------------------------------------------------------
//Função p/ tratar o Campo p/ aceitar apenas letras e numeros e espaço
//
//Usar: onKeypress="return KeyinPressespaco(event);"
function KeyinPressespaco()  {
   if (document.all) // Internet Explorer
      var tecla = event.keyCode;
   else if(document.layers) // Nestcape
      var tecla = e.which;    
   if ((tecla > 47 && tecla < 58) || (tecla > 64 && tecla < 91) || (tecla > 96 && tecla < 123) || (tecla == 13) || (tecla == 32)) // numeros de 0 a 9 ou Letras A a Z ou Letras a a z
      return true;
   else {
      if (tecla  = 8) // backspace
         event.keyCode = 0;
      else
         return true;         
	}
}

//----------------------------------------------------------------------------------
//Função usada p/ validar se o campo ficha não esta vazio
function val_dados() {
   var form = document.formkey;
   if (trim(form.ficha.value) == "") {
      alert("Deve ser inserido uma Ficha !");
      form.ficha.focus();
		return false;
	} else {
      return true;
   }
}
//----------------------------------------------------------------------------------
//Função usada p/ validar se o campo ficha não esta vazio
function val_dados_usuarios(str) {
   var form = document.cadastro;
   if (trim(form.usuario.value) == "") {
      alert("Deve ser inserido um Nome de Usuário !");
      form.usuario.focus();
		return false;
	} else 
   if (trim(form.nome.value) == "") {
      alert("Deve ser Dado o Nome !");
      form.nome.focus();
		return false;
	} else 
   if (trim(form.sobrenome.value) == "") {
      alert("Deve ser Dado o Sobrenome !");
      form.sobrenome.focus();
		return false;
	} else
	if (form.sexo.value == "ND"){
		alert("Deve ser escolhido o Sexo !");
		form.sexo.focus();
		return false;
	} else
	if (((trim(form.cidade.value) != "") || (trim(form.bairro.value) != "") || (trim(form.endereco.value) != "")) && (form.estado.value == "ND")){
		alert("Deve ser escolhido o Estado !");
		form.estado.focus();
		return false;
	} else
	if (form.tipo.value == "ND"){
		alert("Deve ser escolhido o Tipo !");
		form.tipo.focus();
		return false;
	} else
	if ((!str) && (trim(form.nova_senha.value) == "")){
		alert("Atenção,\nDeve ser inserido uma Senha !");
		form.nova_senha.focus();
		return false;
	} else
	if ((trim(form.nova_senha.value) != "") || (trim(form.confirmar.value) != "")){
		if (trim(form.nova_senha.value) != trim(form.confirmar.value)) {
			alert("Atenção,\nSenha confirmada não confere com a Nova Senha !");
			form.nova_senha.focus();
			return false;
		}
	} else {
      return true;
   }
}
//----------------------------------------------------------------------------------
//Função usada p/ validar se o campo ficha não esta vazio
function val_dados_clientes(){
   var form = document.cadastro;
   if (trim(form.nome.value) == "") {
      alert("Deve ser dado o Nome da Empresa !");
      form.nome.focus();
		return false;
	} else {
      return true;
   }
}
//----------------------------------------------------------------------------------
//Função usada p/ validar se o campo ficha não esta vazio
function val_dados_unidades() {
   var form = document.cadastro;
   if (trim(form.nome.value) == "") {
      alert("Deve ser dado o Nome da Empresa !");
      form.nome.focus();
		return false;
	} else if (trim(form.cidade.value) == "") {
      alert("Deve ser inserido a Cidade !");
      form.cidade.focus();
		return false;
   } else if (trim(form.cidade.value) == "") {
      alert("Deve ser inserido a Cidade !");
      form.cidade.focus();
		return false;
   } else if (trim(form.estado.value) == "ND") {
      alert("Deve ser seleciona um Estado !");
      form.estado.focus();
		return false;
	}
   return true;
}
//----------------------------------------------------------------------------------
// Função para confirmar 
//Usar: onclick='confirma('oque?');'
function verificacep(val,local){
   var form;
   form = document.cadastro;
   if(trim(form.cep.value)){
   	if(val){
			form.action= local + "?id=" + val + "&verificacep=1";
		}else{
			form.action= local + "?verificacep=1";
		}
		form.submit();
	}else{
		alert('Atenção,\nInsira o CEP !!!');
		form.cep.focus();
	}
}

//----------------------------------------------------------------------------------
// Função para confirmar 
//Usar: onclick='confirma('oque?');'
function confirma(str,verdade){
   var form,val;
   form = document.cadastro;
   val = confirm(str);
   if(val){
      form.method = 'post';
      form.action = form.action + verdade;
      form.submit();
   }
}
//----------------------------------------------------------------------------------
// Função para confirmar 
//Usar: onclick='confirma('oque?');'
function confirmar(str,verdade){
   var form,val;
   form = document.cadastro;
   val = confirm(str);
   if(val){
      form.action = form.action + verdade;
      return true;
   } 
   return false;
}

function vai(){
	var form;
	form = document.formkey;
	form.submit();
}

//----------------------------------------------------------------------------------
// Função para submeter o formulário
//Usar: onclick='submeter();'
function submeter(){
	var form = document.all;	

	if(form.tipo.value != 'ND' && form.tipo.value != 'nd'){
		if(form.tipo.value == 'TT' || form.tipo.value == 'tt')
			form.tipo.value = '';
		form.action = 'usuarios.php';
		form.submit();
	}
	if(trim(form.nome.value) != ''){
		form.tipo.value = '';
		form.action     = 'usuarios.php';
		form.submit();
	}
}
//----------------------------------------------------------------------------------
// Função para submeter o formulário
//Usar: onclick='submeter2(exames.php);'
function submeter2(onde){
	//alert(onde);
	var form = document.cadastro;
	if(form.tipo.value != 'ND' && form.tipo.value != 'nd'){
		if(form.tipo.value == 'TT' || form.tipo.value == 'tt'){
			form.tipo.value = '';
		}
		form.action = onde;
		form.submit();
	}
	if(trim(form.nome.value) != ''){
	   
		form.tipo.value = '';
		form.action     = onde;
		form.submit();
	}
}

//----------------------------------------------------------------------------------
// Função para atualzar a Página
//Usar: onclick='atualiza();'
function atualiza(){
   window.location.reload();   
}
//----------------------------------------------------------------------------------
//Função p/ retirar os espaços entre a esquerda e a direita da string
function trim(vartotrim) { 
	while (vartotrim.substring(0,1) == " ") { 
		vartotrim=vartotrim.substring(1,vartotrim.length);
	}
	while (vartotrim.substring(vartotrim.length -1,vartotrim.length) == " ") {
		vartotrim=vartotrim.substring(0,vartotrim.length -1);
	}
	return vartotrim;
}
//----------------------------------------------------------------------------------         
//Função que completa com caracteres à esquerda
function rpad(str, tipo, tam){
	var esp = "";
	var tam = (tam - str.length);
	var i;
	for(i = 0; i < tam ; i++){
		esp = esp + tipo;
	}
	str = esp + str;
	return str;
}
//----------------------------------------------------------------------------------         
//Função que abre uma janela popup tomando como argumentos:
//url (string), nome interno controlador (string), largura (integer), altura (integer)
function abre(url, nome, largura, altura) {
	var popup = window.open(url, nome, "scrollbars, resizable=0, width=" + largura + ", height=" + altura);
	popup.focus();
	popup.moveTo((screen.width / 2 - largura / 2), (screen.height / 2 - altura / 2));
}
//----------------------------------------------------------------------------------         
//Função que abre uma janela popup tomando como argumentos:
//url (string), nome interno controlador (string), largura (integer), altura (integer)
function abreModal(url, nome, largura, altura) {
	var popup = window.open(url, nome, "modal=1,scrollbars, resizable=0, width=" + largura + ", height=" + altura);
   popup.moveTo((screen.width / 2 - largura / 2), (screen.height / 2 - altura / 2));
   var ModalFocus = function(){
      if(!popup.closed)
         popup.focus();
      else {
         popup = null;
         window.removeEventListener(ModalFocus,"focus");
         ModalFocus = null;
      }
   };
   window.addEventListener( "focus",ModalFocus, false ); 
//	popup.focus();
	
}

//----------------------------------------------------------------------------------         
// Função que gera uma POPUP
//Usar: abrepopup(teste.php, 'Texto Principal', 100, 50);
function abrepopup(url, nome, largura, altura) {
   var popup = window.open(url, nome, "scrollbars=0, resizable=0, width=" + largura + ", height=" + altura);
	popup.focus();
	popup.moveTo((screen.width / 2  - largura / 2), (screen.height / 2 - altura / 2 ));
	return false;
}
//----------------------------------------------------------------------------------         
// Função que gera uma POPUP
//Usar: abrepopup(teste.php, 'Texto Principal', 100, 50);
function abrepopup_barras(url, nome, largura, altura) {
   var popup = window.open(url, nome, "scrollbars=1, resizable=0, width=" + largura + ", height=" + altura);
	popup.focus();
	popup.moveTo((screen.width / 2  - largura / 2), (screen.height / 2 - altura / 2 ));
	return false;
}
//----------------------------------------------------------------------------------         
// Função que reecaminha o site
function reecaminhar(URL){
   document.location = URL;
}

//----------------------------------------------------------------------------------         
// Função que reecaminha o site
function redirecionar(URL){
   document.location = URL;
}
//----------------------------------------------------------------------------------         
// Função imprime a page
function imprimir(){
	print(document.window);
}
//----------------------------------------------------------------------------------         
// Função volta
function voltar(){
	history.go(-1);
}
//----------------------------------------------------------------------------------         
// Função Fecha
function fechar(){
	window.close();
}
//------------------------------------------------------------------------------
// - Mascara 
   function mascara (formato, objeto){
   
      var Form;
      Form = document.cadastro;
   
      campo = eval (objeto);
   
      // CPF
      if (formato=='CPF'){
      
         separador1 = '.';
         separador2 = '.';
         separador3 = '-';
         conjunto1 = 3;
         conjunto2 = 7;
         conjunto3 = 11;
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador2;
         }
         if (campo.value.length == conjunto3){
            campo.value = campo.value + separador3;
         }
         
      }
      
      //IDENTI
      
      if (formato == 'IDENTI') {
         
         separador1 = '.';
         conjunto1  = 2;

         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
  
      }

      //IDENTI_ANEXO
      
      if (formato == 'IDENTI_ANEXO') {
         
         separador1 = '.';
         conjunto1  = 1;

         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
  
      }
   
      // CGC
      if (formato=='CGC'){
      
         separador1 = '.';
         separador2 = '/';
         separador3 = '-';
         conjunto1 = 2;
         conjunto2 = 6;
         conjunto3 = 10;
         conjunto4 = 15; 
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador1;
         }
         if (campo.value.length == conjunto3){
            campo.value = campo.value + separador2;
         }
         if (campo.value.length == conjunto4){
            campo.value = campo.value + separador3;
         }          
         
      }
   
      // CGC/CPF
      if (formato=='CGCCPF'){
      
         // CGC
         if (Form.cTipo.value == "J") 
         {
   
            separador1 = '.';
            separador2 = '/';
            separador3 = '-';
            conjunto1 = 2;
            conjunto2 = 6;
            conjunto3 = 10;
            conjunto4 = 15; 
            
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto3){
               campo.value = campo.value + separador2;
            }
            if (campo.value.length == conjunto4){
               campo.value = campo.value + separador3;
            }          
         }
   
         // CPF
         if (Form.cTipo.value == "F") 
         {
   
            separador1 = '.';
            separador2 = '.';
            separador3 = '-';
            conjunto1 = 3;
            conjunto2 = 7;
            conjunto3 = 11;
            
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador2;
            }
            if (campo.value.length == conjunto3){
               campo.value = campo.value + separador3;
            }
         }
         
      }
      
      // CEP
      if (formato=='CEP'){
      
         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
      
         separador = '-';
         conjunto1 = 5;
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
      }

      // IP
      if (formato=='IP'){
      
         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
      
         separador = '.';
         conjunto1 = 3;
         conjunto2 = 7;
         conjunto3 = 11;
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador;
         }
         if (campo.value.length == conjunto3){
            campo.value = campo.value + separador;
         }
      }
      
      // DATA
      if (formato=='DATA'){
   
         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
   
         separador = '/';
         conjunto1 = 2;
         conjunto2 = 5;
   
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador;
         }
      }
      
      // TELEFONE
      if (formato=='TELEFONE'){
   
         separador = '(';
         conjunto1 = 1;
         if (campo.value.length == conjunto1) {
            campo.value = separador + campo.value;
         }
         
         separador = ')';
         conjunto1 = 3;
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
      }
   
      // CNAE
      if (formato=='CNAE'){
   
            separador1 = '-';
            separador2 = '/';
            conjunto1 = 4;
            conjunto2 = 6;
            
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador2;
            }
      }
   }
   
   // Mascara 2
   function Mascara (formato, objeto, event){
   
      var Form;
      Form = document.cadastro;
   
      campo = eval (objeto);
   
      // CPF
      if (formato=='CPF'){
      
         separador1 = '.';
         separador2 = '.';
         separador3 = '-';
         conjunto1 = 3;
         conjunto2 = 7;
         conjunto3 = 11;
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador2;
         }
         if (campo.value.length == conjunto3){
            campo.value = campo.value + separador3;
         }
         
      }
      
      //IDENTI
      
      if (formato == 'IDENTI') {
         
         separador1 = '.';
         conjunto1  = 2;

         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
  
      }

      //IDENTI_ANEXO
      
      if (formato == 'IDENTI_ANEXO') {
         
         separador1 = '.';
         conjunto1  = 1;

         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
  
      }
   
      // CGC
      if (formato=='CGC'){
      
         separador1 = '.';
         separador2 = '/';
         separador3 = '-';
         conjunto1 = 2;
         conjunto2 = 6;
         conjunto3 = 10;
         conjunto4 = 15; 
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador1;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador1;
         }
         if (campo.value.length == conjunto3){
            campo.value = campo.value + separador2;
         }
         if (campo.value.length == conjunto4){
            campo.value = campo.value + separador3;
         }          
         
      }
   
      // CGC/CPF
      if (formato=='CGCCPF'){
      
         // CGC
         if (Form.cTipo.value == "J") 
         {
   
            separador1 = '.';
            separador2 = '/';
            separador3 = '-';
            conjunto1 = 2;
            conjunto2 = 6;
            conjunto3 = 10;
            conjunto4 = 15; 
            
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto3){
               campo.value = campo.value + separador2;
            }
            if (campo.value.length == conjunto4){
               campo.value = campo.value + separador3;
            }          
         }
   
         // CPF
         if (Form.cTipo.value == "F") 
         {
   
            separador1 = '.';
            separador2 = '.';
            separador3 = '-';
            conjunto1 = 3;
            conjunto2 = 7;
            conjunto3 = 11;
            
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador2;
            }
            if (campo.value.length == conjunto3){
               campo.value = campo.value + separador3;
            }
         }
         
      }
      
      // CEP
      if (formato=='CEP'){
      
         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
      
         separador = '-';
         conjunto1 = 5;
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
      }

      // IP
      if (formato=='IP'){
      
         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
      
         separador = '.';
         conjunto1 = 3;
         conjunto2 = 7;
         conjunto3 = 11;
         
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
         if (campo.value.length == conjunto2){
            campo.value = campo.value + separador;
         }
         if (campo.value.length == conjunto3){
            campo.value = campo.value + separador;
         }
      }
      
      // DATA
      if (formato=='DATA'){

         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
   
         separador = '/';
         conjunto1 = 2;
         conjunto2 = 5;
   
         if (event.keyCode!=8) {
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador;
            }
         }
      }

      // Valor
      if (formato=='VALOR'){

         if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
   
         if (event.keyCode!=8)  {
            var whichCode = (window.Event) ? event.which : event.keyCode;
            if (whichCode == 13) return true;
            key = String.fromCharCode(whichCode);
            //alert(key);
            if (campo.value.length==0) {
               campo.value = "_._" + campo.value
            } else {
               campo.value = campo.value.ReplaceAll("_","");
               campo.value = campo.value.ReplaceAll(".","");
               if (campo.value.length==1) {
                  campo.value = "_." + campo.value;
               } else {            
                  //alert(campo.value);
                  //alert(campo.value.substr(0,campo.value.length-1));
                  //alert(campo.value.substr(campo.value.length-1,1));
                  campo.value = campo.value.substr(0,campo.value.length-1) + "." + campo.value.substr(campo.value.length-1,1);
               }
            //   alert(campo.value.substr(2,1));
            //   alert(campo.value.substr(0,1));
            //
            //      campo.value = "0." + campo.value
            //} else if (campo.value.length==2) {
            }
            //
            //
            //separador = '.';
            //conjunto1 = 2;
            //
            //if (campo.value.length == conjunto1){
            //   campo.value = campo.value + separador;
            //}
         }
         
      }
      
      // TELEFONE
      if (formato=='TELEFONE'){
   
         separador = '(';
         conjunto1 = 1;
         if (campo.value.length == conjunto1) {
            campo.value = separador + campo.value;
         }
         
         separador = ')';
         conjunto1 = 3;
         if (campo.value.length == conjunto1){
            campo.value = campo.value + separador;
         }
      }
   
      // CNAE
      if (formato=='CNAE'){
   
            separador1 = '-';
            separador2 = '/';
            conjunto1 = 4;
            conjunto2 = 6;
            
            if (campo.value.length == conjunto1){
               campo.value = campo.value + separador1;
            }
            if (campo.value.length == conjunto2){
               campo.value = campo.value + separador2;
            }
      }
   }   
//----------------------------------------------------------------------------------
// Funções Complementares do Telefone
   function telaux1(objeto){
      var form;
      form = document.cadastro;
      campo = eval (objeto);
      campo.value = trim(campo.value);
      if (campo.value.length == '0'){
         campo.value = '(';
      }
   }
//----------------------------------------------------------------------------------
// Funções Complementares do Telefone
   function telaux2(objeto){
      var form;
      form        = document.cadastro;   
      campo       = eval (objeto);
      campo.value = trim(campo.value);
      //alert(campo.value.length);
      if ((campo.value.length == '13') && (str_word(campo.value,"-") == '0')){
         campo.value = campo.value.substr(0,9) + '-' + campo.value.substr(9,4);
      } else if (campo.value.length == '12' && (str_word(campo.value,"-") == '0')) {
         campo.value = campo.value.substr(0,8) + '-' + campo.value.substr(8,4);
      } else if (campo.value.length == '1') {
         campo.value =  "";
      }
   }
//----------------------------------------------------------------------------------
// - Conta quantas vezes uma palavra esta contida numa string
   function str_word(str,oque){
      var qtos = 0;
      for(i = 0; i <= str.length ; i++){
         if(str.substr(i,1) == oque){
            qtos = qtos + 1;
         }
      }
      return qtos;
   }
//----------------------------------------------------------------------------------
//Função p/ tratar o Campo p/ aceitar apenas numeros
//Usar: onKeypress="return KeyinPress(event);"
   function KeyinPressnum()  {
      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;
         else
            return true;
         }
   }

	function isDate(data){
		if(data==""){
			return true;
		}
		var m_strDate = FormatDate(data);
		if(m_strDate==""){
			return false;
		}
		var m_arrDate = m_strDate.split("/");
		var m_DAY = m_arrDate[0];
		var m_MONTH = m_arrDate[1];
		var m_YEAR = m_arrDate[2];
		if ((m_YEAR.length != 2) && (m_YEAR.length != 4)){return false;}
		m_strDate = m_MONTH + "/" + m_DAY + "/" + m_YEAR;
		var testDate=new Date(m_strDate);
		if(testDate.getMonth()+1==m_MONTH){
			return true;
		} else {
			return false;
		}
	}

	function FormatDate(DateToFormat,FormatAs){
		if(DateToFormat==""){return"";}
		if(!FormatAs){FormatAs="dd/mm/yyyy";}
		var strReturnDate;
		FormatAs = FormatAs.toLowerCase();
		DateToFormat = DateToFormat.toLowerCase();
		var arrDate
		var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		var strMONTH;
		var Separator;
		while(DateToFormat.indexOf("st")>-1){
			DateToFormat = DateToFormat.replace("st","");
		}
		while(DateToFormat.indexOf("nd")>-1){
			DateToFormat = DateToFormat.replace("nd","");
		}
		while(DateToFormat.indexOf("rd")>-1){
			DateToFormat = DateToFormat.replace("rd","");
		}
		while(DateToFormat.indexOf("th")>-1){
			DateToFormat = DateToFormat.replace("th","");
		}
		if(DateToFormat.indexOf(".")>-1){
			Separator = ".";
		}
		if(DateToFormat.indexOf("-")>-1){
			Separator = "-";
		}
		if(DateToFormat.indexOf("/")>-1){
			Separator = "/";
		}
		if(DateToFormat.indexOf(" ")>-1){
			Separator = " ";
		}
		arrDate = DateToFormat.split(Separator);
		DateToFormat = "";
		for(var iSD = 0;iSD < arrDate.length;iSD++){
			if(arrDate[iSD]!=""){
				DateToFormat += arrDate[iSD] + Separator;
			}
		}
		DateToFormat = DateToFormat.substring(0,DateToFormat.length-1);
		arrDate = DateToFormat.split(Separator);
		if(arrDate.length < 3){
			return "";
		}
		var DAY   = arrDate[0];
		var MONTH = arrDate[1];
		var YEAR  = arrDate[2];
		if(parseFloat(arrDate[1]) > 12){
			DAY   = arrDate[1];
			MONTH = arrDate[0];
		}
		if(parseFloat(DAY) && DAY.toString().length==4){
			YEAR  = arrDate[0];
			DAY   = arrDate[2];
			MONTH = arrDate[1];
		}
		for(var iSD = 0;iSD < arrMonths.length;iSD++){
			var ShortMonth = arrMonths[iSD].substring(0,3).toLowerCase();
			var MonthPosition = DateToFormat.indexOf(ShortMonth);
			if(MonthPosition > -1){
				MONTH = iSD + 1;
				if(MonthPosition == 0){
					DAY  = arrDate[1];
					YEAR = arrDate[2];
				}
				break;
			}
		}
		var strTemp = YEAR.toString();
		if(strTemp.length==2){
			if(parseFloat(YEAR)>40){
				YEAR = "19" + YEAR;
			} else {
				YEAR = "20" + YEAR;
			}
		}
		if(parseInt(MONTH)< 10 && MONTH.toString().length < 2){
			MONTH = "0" + MONTH;
		}
		if(parseInt(DAY)< 10 && DAY.toString().length < 2){
			DAY = "0" + DAY;
		}
		switch (FormatAs){
			case "dd/mm/yyyy":
				return DAY + "/" + MONTH + "/" + YEAR;
			case "mm/dd/yyyy":
				return MONTH + "/" + DAY + "/" + YEAR;
			case "dd/mmm/yyyy":
				return DAY + " " + arrMonths[MONTH -1].substring(0,3) + " " + YEAR;
			case "mmm/dd/yyyy":
				return arrMonths[MONTH -1].substring(0,3) + " " + DAY + " " + YEAR;
			case "dd/mmmm/yyyy":
				return DAY + " " + arrMonths[MONTH -1] + " " + YEAR;	
			case "mmmm/dd/yyyy":
				return arrMonths[MONTH -1] + " " + DAY + " " + YEAR;
		}
		
		return DAY + "/" + strMONTH + "/" + YEAR;;
	} //End Function
// ------------------- Funcoes da parte de Assintatura -------------------
	function SelKeyType(modo) {
		var form = document.auto_search;
		if (modo=='1') {
			form.paci_nome.disabled              = true     ;
			form.paci_nome.style.backgroundColor = '#CCCCCC';
			form.paci_nome.value                 = ''       ;
			form.ficha.disabled                  = false    ;
			form.ficha.style.backgroundColor     = '#FFFFFF';
			form.ficha.focus();
		} else {
			form.ficha.disabled                  = true     ;
			form.ficha.style.backgroundColor     = '#CCCCCC';
			form.ficha.value                     = ''       ;
			form.paci_nome.disabled              = false    ;
			form.paci_nome.style.backgroundColor = '#FFFFFF';
			form.paci_nome.focus();
		}
	}
	function putFocus() {
		var form   = document.repeat;
		var totalE = form.elements.length;
		var nRad   = '0';
		for (i=0;i<totalE;i++) {
			if ((form.elements[i].type=='radio') && (nRad=='0')) {
				form.elements[i].focus();
				nRad = '1';
			}
			if ((form.elements[i].type=='submit') && (nRad=='0')) {
				form.elements[i].focus();
				nRad = '1';
			}					
		}
	}

   function flash(file, width, height){
       document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="' + width + '" height="' + height + '">');
       document.write('<param name="movie"   value="' + file + '" />');
       document.write('<param name="quality" value="high"         />');
       document.write('<param name="wmode"   value="transparent"  />');
       document.write('<embed src="' + file + '" wmode="transparent" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '"></embed>');
       document.write('</object>');
   }

//-------------------------------------------------------------------------

//-----------------------------------------------------------------------
// Funcoes Sistema Rhesus

function fSpace(pParm) {
   var pRet;
   pRet = pParm
   pRet = pRet.ReplaceAll("+","%2B");
   pRet = pRet.ReplaceAll(" ","+");
   pRet = pRet.ReplaceAll("%","%25");
   pRet = pRet.ReplaceAll("#","%23");
   pRet = pRet.ReplaceAll("<","%3C");
   pRet = pRet.ReplaceAll(">","%3E");
   pRet = pRet.ReplaceAll("\\","%5C"); 
   return pRet;
}

function fSpace2(pParm) {
   var pRet;
   pRet = pParm
   pRet = pRet.ReplaceAll(" ","_");
   return pRet;
}


//-----------------------------------------------------------------------
// Valida Usuario
function VeriUsua(Server,cUsuario,cTipo){
   var objCarregador              = form.carregador_pai;
   campo = eval (cUsuario);
   try {
      if ((campo.value!="") && (form.codigo.value=='NC')) {
         var wUsua = campo.value;
         objCarregador.style.display	 = "";
         objCarregador.style.visibility = "visible";
         var aConexao = new ServerRequest();
         var retorno = '';
         var lRetorno = false;
         //alert("rsp.php?Server=" + Server.value + "&Pagina=www_veri_usua.rsp?cUsua=" + wUsua + "%26cTipo=" + cTipo);
         aConexao.submit("rsp.php?Server=" + Server.value + "&Pagina=www_veri_usua.rsp?cUsua=" + wUsua + "%26cTipo=" + cTipo);         
         aConexao.onComplete = function (responseText, responseXML){
            objCarregador.style.display	 = "none";
            objCarregador.style.visibility = "hidden";
            linha   = responseText.split("\n");
            for(i=0; i<linha.length; i++) {
               retorno = linha[i].split(":");
               if(retorno[0] == "ERRO") {
                  alert('Erro: ' + retorno[1]);
                  campo.focus();
                  lRetorno = true;
               } else if (retorno[0] == 'STATUS') {
                  lRetorno = true;
               }
            }
            if (!lRetorno) {
               alert('Erro Inesperado Comunique o setor de Desenvolvimento!');
               campo.focus();
            }
         };         
      }
   } catch(e) {
      objCarregador.style.display	 = "none";
      objCarregador.style.visibility = "hidden";
      alert('Erro: ' + e.number + '\n' + e.description);
   }
}

//-----------------------------------------------------------------------
// Valida CEP

function VeriCEP(Server,oCep, oEnde, oCida, oBair, oUF){
   var objCarregador              = form.carregador_pai;
   try {
      if (oCep.value!="") {
         objCarregador.style.display	 = "";
         objCarregador.style.visibility = "visible";
         var aConexao = new ServerRequest();
         var retorno = '';
         var lRetorno = false;
         aConexao.submit("rsp.php?Server=" + Server.value + "&Pagina=www_veri_cep.rsp?cCep=" + oCep.value);
         aConexao.onComplete = function (responseText, responseXML){
            objCarregador.style.display	 = "none";
            objCarregador.style.visibility = "hidden";
            linha   = responseText.split("\n");
            for(i=0; i<linha.length; i++) {
               retorno = linha[i].split(":");
               if(retorno[0] == "ERRO") {
                  alert('Erro: ' + retorno[1]);
                  oCep.focus();
                  lRetorno = true;
               } else if (retorno[0] == 'ENDERECO') {
                  oEnde.value = retorno[1];
                  lRetorno = true;
               } else if (retorno[0] == 'CIDADE') {
                  oCida.value = retorno[1];
                  lRetorno = true;
               } else if (retorno[0] == 'BAIRRO') {
                  oBair.value = retorno[1];
                  lRetorno = true;
               } else if (retorno[0] == 'UF') {
                  oUF.value = retorno[1];
                  lRetorno = true;
               } else if (retorno[0] == 'STATUS') {
                  lRetorno = true;
               }
            }
            if (!lRetorno) {
               alert('Erro Inesperado Comunique o setor de Desenvolvimento!');
               oCep.focus();
            }
         };         
      }
   } catch(e) {
      objCarregador.style.display	 = "none";
      objCarregador.style.visibility = "hidden";
      alert('Erro: ' + e.number + '\n' + e.description);
   }
}

//-----------------------------------------------------------------------
// Valida Tipo de Usuario

function VeriTipoUsua(Server,oVar,oConselho,oDoc,oUF,oAss,oLaudo,oImagem){
   var objCarregador              = form.carregador_pai;
   try {
      if (oVar.value!="") {
         objCarregador.style.display	 = "";
         objCarregador.style.visibility = "visible";
         var aConexao = new ServerRequest();
         var retorno = '';
         var lRetorno = false;
         //alert("rsp.php?Server=" + Server.value + "&Pagina=www_veri_tipousua.rsp?cVar=" + oVar.value);
         aConexao.submit("rsp.php?Server=" + Server.value + "&Pagina=www_veri_tipousua.rsp?cVar=" + oVar.value);
         aConexao.onComplete = function (responseText, responseXML){
            objCarregador.style.display	 = "none";
            objCarregador.style.visibility = "hidden";
            linha   = responseText.split("\n");
            for(i=0; i<linha.length; i++) {
               retorno = linha[i].split(":");
               if(retorno[0] == "ERRO") {
                  alert('Erro: ' + retorno[1]);
                  oVar.focus();
                  lRetorno = true;
               } else if (retorno[0] == 'DADOS') {
                  if (retorno[1]==1) {
   		            oConselho.disabled              = false    ;
                     oDoc.disabled                   = false    ;
                     oUF.disabled                    = false    ;
                     oAss.disabled                   = false    ;
   		            oConselho.style.backgroundColor = '#EBEBEB';
                     oDoc.style.backgroundColor      = '#EBEBEB';
                     oUF.style.backgroundColor       = '#EBEBEB';
                     oAss.style.backgroundColor      = '#EBEBEB';
   	            } else {
                     oConselho.value                 = ''       ;
                     oDoc.value                      = ''       ;
                     oUF.value                       = ''       ;
                     oLaudo.value                    = ''       ;
                     oAss.value                      = 'N'      ;
   		            oConselho.disabled              = true     ;
                     oDoc.disabled                   = true     ;
                     oUF.disabled                    = true     ;
                     oAss.disabled                   = true     ;
                     oLaudo.disabled                 = true     ;
                     oImagem.disabled                = true     ;
   		            oConselho.style.backgroundColor = '#CCCCCC';
                     oDoc.style.backgroundColor      = '#CCCCCC';
                     oUF.style.backgroundColor       = '#CCCCCC';
                     oAss.style.backgroundColor      = '#CCCCCC';
                     oLaudo.style.backgroundColor    = '#CCCCCC';
                     oImagem.style.backgroundColor   = '#CCCCCC';
                  }
               } else if (retorno[0] == 'STATUS') {
                  lRetorno = true;
               }
            }
            if (!lRetorno) {
               alert('Erro Inesperado Comunique o setor de Desenvolvimento!');
               oVar.focus();
            }
         };         
      } else {
         oConselho.value                 = ''       ;
         oDoc.value                      = ''       ;
         oUF.value                       = ''       ;
         oLaudo.value                    = ''       ;
         oAss.value                      = 'N'      ;
         oConselho.disabled              = true     ;
         oDoc.disabled                   = true     ;
         oUF.disabled                    = true     ;
         oAss.disabled                   = true     ;
         oLaudo.disabled                 = true     ;
         oImagem.disabled                = true     ;
         oConselho.style.backgroundColor = '#CCCCCC';
         oDoc.style.backgroundColor      = '#CCCCCC';
         oUF.style.backgroundColor       = '#CCCCCC';
         oAss.style.backgroundColor      = '#CCCCCC';
         oLaudo.style.backgroundColor    = '#CCCCCC';
         oImagem.style.backgroundColor   = '#CCCCCC';
      }
   } catch(e) {
      objCarregador.style.display	 = "none";
      objCarregador.style.visibility = "hidden";
      alert('Erro: ' + e.number + '\n' + e.description);
   }
}

//-----------------------------------------------------------------------
// Valida Tipo de Usuario

function VeriAss(oVar,oLaudo,oImagem){
   if (oVar.value=="S") {
      oLaudo.disabled                 = false    ;
      oImagem.disabled                = false    ;
      oLaudo.style.backgroundColor    = '#EBEBEB';
      oImagem.style.backgroundColor   = '#EBEBEB';
   } else {
      oLaudo.value                    = ''       ;
      oLaudo.disabled                 = true     ;
      oImagem.disabled                = true     ;
      oLaudo.style.backgroundColor    = '#CCCCCC';
      oImagem.style.backgroundColor   = '#CCCCCC';
   }
}


//-----------------------------------------------------------------------
// Valida Convenio Apoio

function VeriConvApoio(Server,cAc,oVar,oCod,oRet) {
   var objCarregador              = form.carregador_pai;
   try {
      if (oVar.value!="") {
         objCarregador.style.display	 = "";
         objCarregador.style.visibility = "visible";
         var aConexao = new ServerRequest();
         var retorno = '';
         var lRetorno = false;
         //alert("rsp.php?Server=" + Server.value + "&Pagina=www_veri_convapo.rsp?cVar=" + oVar.value + "%26cAc=" + cAc + "%26cID=" + oCod.value);
         aConexao.submit("rsp.php?Server=" + Server.value + "&Pagina=www_veri_convapo.rsp?cVar=" + oVar.value + "%26cAc=" + cAc + "%26cID=" + oCod.value);
         aConexao.onComplete = function (responseText, responseXML){
            objCarregador.style.display	 = "none";
            objCarregador.style.visibility = "hidden";
            linha   = responseText.split("\n");
            for(i=0; i<linha.length; i++) {
               retorno = linha[i].split(":");
               if(retorno[0] == "ERRO") {
                  alert('Erro: ' + retorno[1]);
                  //oVar.focus();
                  oVar.value = '';
                  if (oRet) {
                     oRet.value = '';
                  }
                  lRetorno = true;
               } else if (retorno[0] == 'DADOS') {
                  //oVar.value = retorno[1];
               } else if (retorno[0] == 'NOMEAPO') {
                  if (oRet) {
                     oRet.value = retorno[1];
                  }
               } else if (retorno[0] == 'CODUNID') {
                  if (cAc==2) {
                     if (confirm('Confirma Inclusão do Apoiado: ' + oVar.value)) {
                        incluir(oVar.value,oRet.value,retorno[1],'Excluir')
                        oRet.value = '';
                        oVar.value = '';
                        oVar.focus();
                     }
                  }
               } else if (retorno[0] == 'STATUS') {
                  lRetorno = true;
               }
            }
            if (!lRetorno) {
               alert('Erro Inesperado Comunique o setor de Desenvolvimento!');
               oVar.focus();
            }
         };         
      } else {
      }
   } catch(e) {
      objCarregador.style.display	 = "none";
      objCarregador.style.visibility = "hidden";
      alert('Erro: ' + e.number + '\n' + e.description);
   }
}

//-----------------------------------------------------------------------------


function VeriEspecime(oEsp,oRaca,oResp) {
   var indice = oEsp.selectedIndex;
   var cEspe  = oEsp.options[indice].getAttribute('value');
   if (cEspe.length > 0) {
      oRaca.disabled = false;
      oResp.disabled = false;
      oRaca.focus();
      //new_opcao = create_raca(dados[0],dados[1]);
      //oRaca.appendChild(new_opcao);   
   } else {
      oRaca.selectedIndex = 0;
      oResp.value='';
      oRaca.disabled = true;
      oResp.disabled = true;
   }
   
}

//-----------------------------------------------------------------------------

function fV(event, campo) {
   try {
      event = ( event || window.event );
      key = ( event.keyCode || event.charCode || event.which || 0 ); 
      if(key == 13) {
         var elementos = document.forms[0];
         for(var i = 0; i < elementos.length; i++) {
            if(campo.name == elementos.elements[i].name) {
               if (elementos.elements[i + 1].type=="button") {
                  elementos.elements[i + 1].focus();
               } else if(elementos.elements[(i + 1)]) {
                  var nForm = eval(elementos.elements[i + 1].name);
                  if (!nForm.disabled) {
                     if (elementos.elements[i + 1].type=="button") {
                        elementos.elements[i + 1].focus();
                     } else {
                        nForm.focus();
                     }
                  } else {
                     if (elementos.elements[i + 2].type=="button") {
                        elementos.elements[i + 2].focus();
                     } else {
                        var nForm = eval(elementos.elements[i + 2].name);
                        if (nForm.disabled) {
                           var nForm = eval(elementos.elements[i + 3].name);
                        }
                        nForm.focus();
                     }
                  }
               }
               break;
            }
         }
         return false;
      } 
   } catch(e) {
   }
}

//-----------------------------------------------------------------------------

function KeyRecital(event)  {
   event = ( event || window.event );
   tecla = ( event.keyCode || event.charCode || event.which || 0 ); 
   if ((tecla > 47 && tecla < 58) || (tecla > 64 && tecla < 91) || (tecla > 96 && tecla < 123) || (tecla == 13) || (tecla == 32)) { // numeros de 0 a 9 ou Letras A a Z ou Letras a a z
      //alert(tecla);
      return true;
   } else {    
      if ((tecla==8) || (tecla==9) || (tecla==13)) // backspace
         return true;
      else
         return false;
	}
}

//-----------------------------------------------------------------------------

function KeyRecitalNum(event)  {
   event = ( event || window.event );
   tecla = ( event.keyCode || event.charCode || event.which || 0 ); 
   if (tecla > 47 && tecla < 58) { // numeros de 0 a 9
      return true;
   } else {    
      if ((tecla==8) || (tecla==9) || (tecla==13)) // backspace
         return true;
      else
         return false;
	}
}

//-----------------------------------------------------------------------------

function KeyRecitalNumV(event)  {
   event = ( event || window.event );
   tecla = ( event.keyCode || event.charCode || event.which || 0 ); 
   if (tecla > 47 && tecla < 58) { // numeros de 0 a 9
      return true;
   } else {    
      if ((tecla==8) || (tecla==9) || (tecla==13) || (tecla==46)) // backspace
         return true;
      else
         return false;
	}
}

//-----------------------------------------------------------------------------

function RetRecital(oVar,cTp,cConf,oRet,lFim)  {
   // oVar  - Objeto que recebe o retorno
   // cTp   - 1. Caso Erro Zera oVar e manda focu para o Obj
   //         2. Zera oVar mas nao manda focu
   // cConf - 1. Se Afirmativo manda focu para oVar (confirm())
   //         2. Se Negativo manda focu para oVar   (confirm())
   // cVar  - Variavel do Retorno
   //alert(oRet[1]);
   lFim = lFim;
   if(oRet[0] == "ERRO") {
      alert('Erro:\n' + oRet[1]);
      if (cTp==1) {
         oVar.value='';
         oVar.focus();
      } else if (cTp==2) {
         oVar.value='';
      }
      lFim = true;
   } else if (oRet[0] == 'MSGBOX') {
      lFim = true;
      if (oRet[1]=="MSG_FIM") {
         if (cTip=='32') {
            alert('ATENÇÃO\n'+cMsg,cTit);
         } else if (cTip=='16') {
            alert('ERRO!\n' + cMsg,cTit);
            if (cTp==1) {
               oVar.value='';
               oVar.focus();
            } else if (cTp==2) {
               oVar.value='';
            }
         } else if (cTip=='36') {
            cRetConf = confirm(cMsg,cTit);
            if ((cConf==1) && (cRetConf)) {
               oVar.focus();
            } else if ((cConf==2) && (!cRetConf)) {
               oVar.focus();
            }
         }
      } else if (oRet[1]=="MSG_INICIO") {
         cMsg = ' ';
         cTit = ' ';
         cTip = '32';
      } else {
         aMsg = oRet[1].split("|");
         if (aMsg[0]=='MSG') {
            cMsg = cMsg + aMsg[1] + "\n";
         } else if (aMsg[0]=='TIPO') {
            cTip = aMsg[1];
         } else if (aMsg[0]=='TITULO') {
            cTit = aMsg[1];
         }
      }
   } else if (oRet[0] == 'TELA_NEW') {
      if (oRet[1] == 'CRM') {
         alert('Abrir pop-up CRM');
      } else if (retorno[1] == 'RESPONSAVEL') {
         alert('Abrir pop-up Reponsavel');
      } else if (retorno[1] == 'ESPECIME') {
         alert('Abrir pop-up ESPECIME');
      }
      lFim = true;
   } else if (oRet[0] == 'STATUS') {
      lFim = true;
   }
   return lFim;
}

//----------------------------------------------------------------------------

function MascaraMoeda(tamanho, objeto, event){
   var Form;
   Form = document.cadastro;
   
   campo = eval (objeto);
   
   if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
   
   if ((event.keyCode!=8) && (event.keyCode!=13))  {
      if (campo.value.length==0) {
         campo.value = "_._" + campo.value
      } else {
         campo.value = campo.value.ReplaceAll("_","");
         campo.value = campo.value.ReplaceAll(".","");
         if (campo.value.length==1) {
            campo.value = "_." + campo.value;
         } else {            
            if ((campo.value.length + 1) < tamanho) {
               campo.value = campo.value.substr(0,campo.value.length-1) + "." + campo.value.substr(campo.value.length-1,1);
            } else {
               campo.value = campo.value.substr(0,campo.value.length-2) + "." + campo.value.substr(campo.value.length-2,2);
            }
         }
      }
   }

}
// Soma Data
function somaData(cDt1,cDt2,nDia) {
   try {
      var aConexao = new ServerRequest();  
      var cAjax    = "soma_data.php?cDt1=" + cDt1 + "&cDia=" + nDia;
      //alert(cAjax);
      aConexao.submit(cAjax);
      aConexao.onComplete = function (responseText, responseXML){
         linha   = responseText.split("\n");
         for(i=0; i<linha.length; i++) {
            retorno = linha[i].split(":");
            if (retorno[0] == 'DATA') {
               if (cDt2.value!=retorno[1]) {
                  cDt2.value = retorno[1];
               }
               cDt2.focus();
            }
         }
      };         
   } catch(e) {
      alert('Erro: ' + e.number + '\n' + e.description);
   }
}
//-->
// Verifica e-mail
function isEmail(theElement) {
   var s = theElement.value;
   var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
   if (s.length == 0 ) {
      return true;
   }
   if (filter.test(s)) {
      return true;
   } else {
      alert("e-Mail Invalido!");
      theElement.focus();
      return false;
   }
}


