var designMode;
var clientNavigator;
var numdias;
//Caso Internet Explorer(IE) outros (Other)
if (navigator.appName.indexOf('Microsoft') != -1){
	clientNavigator = "IE";
}else{
	clientNavigator = "Other";
}

function isBrowserInternetExplorer() {
	return clientNavigator == "IE";
}

function abreJanelaMaximizada(url){
	var str = 'left=0,screenX=0,top=0,screenY=0,resizable'; 
	if (window.screen) { 
		var ah = screen.availHeight - 30; 
		var aw = screen.availWidth - 10;
       	str += ',height=' + ah; 
       	str += ',innerHeight=' + ah; 
       	str += ',width=' + aw; 
       	str += ',innerWidth=' + aw; 
       	str += ',resizable=1,scrollbars=1';
	} 
	win=window.open(url,'Wink',str); 
}

function abreJanela(url,target,width,height) {
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	if (width==0) {
		width=screen.width;
	}
	if (height==0) {
		width=screen.height;
	}
   	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
 	var	popupWin;
 	popupWin = window.open(url,target,'nomenubar,notoolbar,nolocation,nodirectories,nostatus,dependent,alwaysRaised=yes,scrollbars=yes'+','+winParms);
	popupWin.focus();
}

// tratamento padrão de erros
function myFunc(a,b,c) {
   alert("Error: "+a+" \r\n(Page: "+b+"  -   Line: "+c+")"); 
   return true;
}
window.onerror= myFunc;

function formataNumero(num,dec){
  num=String(num);
  if (num=="NaN") return num;
  if(dec==undefined) dec=2;
  sinal=(num<0)?"-":"";
  num=num.replace(/,/g,".");
  num= String(Math.abs(num));
  if (num=="NaN") return num;
  nm=Math.round(num*Math.pow(10,dec));
  inte = String(parseInt(num,10)); 
  if (inte.length>16) return "";
  l=Math.ceil(inte.length/3);
  c="___"; for (i=1; i<l; i++) c+=".___";
  p=String(num).lastIndexOf("."); dc=String(num).substr(p+1);
  d=",";  if (dec==0) d=""; 
  if ((p!=-1)||(dec>0)) {for (i=0; i<dec; i++) d+="_";}
  return sinal+FormatarInv(String(nm),c+d);
}

// remove formatação de numeros, deixando apenas um ponto decimal
// exemplo: limpaNumero("1.234,56") -> retorna 1234.56
function limpaNumero(c){
  c=c.replace(/,/g,".");
  p=c.lastIndexOf(".")
   if (p == -1) p = c.length;
  c=c.substr(0,p).replace(/\./g,"")+c.substr(p);
  return c;
}

function FormatarInv(Str, Fmt) {
// O mesmo que o anterior, iniciando pelo final do molde.
  var Sai = "";
  var j = Str.length-1;
  for (var i=Fmt.length-1; i>=0; i--)
    if (Fmt.substring(i,i+1)=="_") {
       Sai = Str.substring(j,j+1) + Sai;
       j = j - 1;
       if (j<0) break;
    } else {
      Sai = Fmt.substring(i, i+1) + Sai;
    }
  return Sai;
}

var wiObj = null;
function msgErr(obj,msg) {
   if (msg!="") alert (msg);
   wiObj = obj;
   setTimeout("selObj()",10);
}

function selObj () {
   if (!wiObj) return;
   wiObj.focus(); 
   wiObj.select();
   wiObj = null;
}

function mTr(s,s1,s2) {
   var p;
   var sai="";
   for (var j=0; j<s.length; j++) {
    p=s1.indexOf(s.substring(j,j+1));
    sai=sai + (p<0 ? s.substring(j, j+1) : s2.substring(p, p+1));
   }
   return sai;
}

function Limpar(valor, validos) {
// retira caracteres invalidos da string
  var result = "";
  var aux;
  for (var i=0; i < valor.length; i++) {
    val = valor.substring(i, i+1);
    aux = validos.indexOf(val);
      if (aux>=0) {
        result += val;
      }
  }
  return result;
}

function cData(data,mask) {
/* retorna -1 se data nao tiver 6 ou 8 digitos numericos
   retorna -2 se mes for invalido
   retorna -3 se dia for invalido
   retorna a data (ddmmaaaa) se ok
*/
  data = Limpar(data,"0123456789");
  if ((data.length != 8) &&(data.length != 6)) { return -1; }
  // transforma os valores em inteiros
  var dia = parseInt(data.substring(0,2),10);
  var mes = parseInt(data.substring(2,4),10);
  var ano = parseInt(data.substring(4),10);
  // corrige ano (no caso de ter apenas 2 digitos)
  if (ano < 100) { 
    if (ano < 50) { ano += 2000; }
    else { ano += 1900; }
  }
  //verifica o mes
  if (mes > 12) { return -2; }
  // verifica o numero de dias do mes
  switch (mes) {
  case 1: case 3: case 5: case 7: case 8: case 10: case 12:
      numdias = 31;
      break;
  case 4: case 6: case 5: case 9: case 11:
      numdias = 30;
      break;
  case 2:
    if (bissexto(ano)) { numdias = 29; }
    else {numdias = 28; }
  }
  //verifica o numero de dias
  if (dia > numdias) { return -3; }
  sdia = ((dia<10) ? "0" : "") + dia;
  smes = ((mes<10) ? "0" : "") + mes;
  sano4 = ano+""; 
  sano2= (ano+"").substring(2,4);
  d = /dd/; m = /MM/; y2 = /yy/; y4= /yyyy/;
  ret=mask.replace(d, sdia).replace(m,smes).replace(y4,sano4).replace(y2,sano2);
  return ret;
}

function bissexto(strano) {
/* retorna true se o ano for bissexto */
  var ano = parseInt(strano+"",10);
  if ((ano%4)!= 0) { return false; }
  if (((ano%100) == 0) &&((ano%400)!=0)) { return false; }
  return true;
}


function CNPJdv(CNPJ) {
  CNPJ = Limpar(CNPJ,"0123456789");
  if (CNPJ.length != 12) { return ""; }
  var checar = CNPJ.substring(12);
  CNPJ = CNPJ.substring(0,12);
  var soma = 0;
  for (var i=0; i<4; i++) { 
    soma = soma + CNPJ.substring(i,i+1)*(5-i);
  }
  for (var i=4; i<12; i++) { 
    soma = soma + CNPJ.substring(i,i+1)*(13-i);
  }
  var cnpjdv = 11 - (soma % 11);
  if ( cnpjdv >= 10 ) { 
    cnpjdv = 0;
  }
  soma = 0;
  for (var i = 0; i<5; i++) { 
    soma = soma + CNPJ.substring(i,i+1)*(6-i);
  }
  for (var i = 5; i<12; i++) { 
    soma = soma + CNPJ.substring(i,i+1)*(14-i);
  }
  soma = soma + cnpjdv * 2;
  var cnpjdv2 = 11 - (soma%11);
  if ( cnpjdv2 >= 10 ) { 
    cnpjdv2 = 0;
  }
  cnpjdv += "" + cnpjdv2;
  return cnpjdv;
}     


function CPFdv(CPF) {
  CPF = Limpar(CPF,"0123456789");
  if (CPF.length != 9) { return ""; }
  var soma = 0;
  var checar = CPF.substring(9);
  CPF = CPF.substring(0,9);
  for (var i=0; i<9; i++) { 
    soma = soma + CPF.substring(i,i+1)*(10-i);
  }
  var cpfdv = 11 - (soma % 11);
  if ( cpfdv >= 10 ) { 
    cpfdv = 0;
  }
  soma = 0;
  for (var i=0; i<9; i++) {
    soma = soma + CPF.substring(i,i+1)*(11-i);
  }
  soma = soma + cpfdv * 2;
  var cpfdv2 = 11 - (soma%11);
  if ( cpfdv2 >= 10 ) { 
    cpfdv2 = 0;
  }
  cpfdv += ""+cpfdv2;
  return cpfdv;
}

function piece(str,delim,ind) {
   var aux = str.split(delim);
   if (ind <= aux.length) {
     return aux[ind-1];
   }
}   


// ----- Funções para validação de campos
//@list=chkNum(this)
function chkNum(obj, msg) {
   if (designMode) return;
   if (!obj || obj.value=="") return;
   var ini = obj.value.charAt(0)+obj.value.charAt(obj.value.length-1)
   if (ini=="||") return;
   var n = formataNumero(obj.value);
   if (n=="NaN") {
      if (!msg || msg=="") msg = "Não é um número válido";
      return msgErr (obj, msg);
   } else
   obj.value = n;
}

//@list=chkInteiro(this)
function chkInteiro(obj, msg) {
   if (!obj || obj.value=="") return;
   var n = formataNumero(obj.value);
   if (n=="NaN") {
      if (!msg || msg=="") msg = "Campo deve ser Numérico!";
      obj.value = '';
      return msgErr(obj, msg);
   }
   else {
      obj.value = obj.value;
   }
}



//@list=fmtNum(this)
function fmtNum(obj) {
   if (designMode) return;
   if (!obj || obj.value=="") return;
   obj.value = limpaNumero(obj.value)
}

//@list=chkCep(this)
function chkCep(obj,msg) {
   if (!msg || msg=="") msg = "Não é um número válido";
   if (designMode) return;
   if (!obj) return;
   var val=mTr (obj.value, ",.-/", "");
   if (obj.value=="") return;
   msg = msg +  " Deve conter 8 números"
   if (val.length!=8) return msgErr(obj,msg);
   if (Limpar(val, "0123456789") != val) return msgErr(obj,msg);
   obj.value = FormatarInv(val, "_____-___");
}
//@list=chkData(this,"dd/MM/yyyy")
function chkData(obj, mask, msg) {
   if (designMode) return;
   if (!obj || obj.value=="") return;
   if (!mask || mask== "") mask = "dd/MM/yyyy"; 
   var st = cData(obj.value, mask);
   if (!msg) msg = "";
   if (st == -1) return msgErr(obj, msg + " Deve conter 6 ou 8 números");
   if (st == -2) return msgErr(obj, msg + " Mês inválido");
   if (st == -3) return msgErr(obj, msg + " Dia inválido");
   obj.value =  st;
}

//@list=chkCNPJ(this)
function chkCNPJ(obj, msg) {
   if (!msg) msg = "";
   if (designMode) return;
   if (!obj || obj.value=="") return;
   var CNPJ = obj.value;
  CNPJ = Limpar(CNPJ,"0123456789");
  if (CNPJ.length != 14) { return msgErr(obj, msg + " Deve conter 14 números"); }
  if (CNPJdv(CNPJ.substring(0,12)) == CNPJ.substring(12)) {
    return fmtCNPJ(obj);
  }
  else {
    msgErr(obj, msg + " CNPJ incorreto");
  }
}     

//@list=fmtCNPJ(this)
function fmtCNPJ(obj) {
   if (!obj || obj.value=="") return;
  var CNPJ = obj.value;
  CNPJ = Limpar(CNPJ,"0123456789");
  if (CNPJ.length != 14) { return ""; }
  var parte1 = CNPJ.substring(0,2);
  var parte2 = CNPJ.substring(2,5);
  var parte3 = CNPJ.substring(5,8);
  var parte4 = CNPJ.substring(8,12);
  var parte5 = CNPJ.substring(12,14);
  obj.value = parte1 + "." + parte2 + "." + parte3 + "/" + parte4 + "-" + parte5;
}

//@list=chkCPF(this)
function chkCPF(obj, msg) {
	if (!msg) msg = "";
	if (designMode) return;
	if (!obj || obj.value=="") return;
	var CPF = obj.value;
	CPF = Limpar(CPF,"0123456789");
	if (CPF.length != 11) {
		return msgErr(obj, msg + " deve conter 11 números!")
	}
	if (CPFdv(CPF.substring(0,9)) == CPF.substring(9)) {
		return fmtCPF(obj);
	} else {
		msgErr(obj, msg + " contém um CPF incorreto!");
	}
}

//@list=fmtCPF(this)
function fmtCPF(obj) {
   if (!obj || obj.value=="") return;
   var CPF = obj.value;
  CPF = Limpar(CPF,"0123456789");
  if (CPF.length != 11) { return ""; }
  var parte1 = CPF.substring(0,3);
  var parte2 = CPF.substring(3,6);
  var parte3 = CPF.substring(6,9);
  var parte4 = CPF.substring(9,11);
  obj.value = parte1 + "." + parte2 + "." + parte3 + "-" + parte4;
}

//@list=chkEmail(this)
function chkEmail(obj, msg) {
   if (designMode) return;
   if (obj.value=="") return;
   if (!msg) msg = "";
   var dlm=", ",s="";
   var array = obj.value.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
   if (array)
      for (var i=0; i<array.length; i++) {
         if (i!=0) s+=dlm;
         s+=array[i];
      }
   if (s=="") return msgErr(obj, msg + " Formato inválido do e-mail");
   return "";
}

//@list=chkTime(this)
function chkTime(obj, msg) {
 if (designMode) return;
 var val=obj.value;
 if (val=="") return;
 if (!msg) msg = "";
 val = mTr (val, "h.,", ":::");
 if (Limpar(val, ":0123456789") != val) return msgErr(obj, msg + " Digite somente números");
 if (val.indexOf(":")<0) val = val.substring(0,2) + ":" + val.substring(2,4);
 var H = eval (piece(val, ":", 1) + " + 0");
 var M = eval (piece(val, ":", 2) + " + 0");

 if (H>23) return msgErr(obj,msg+" Hora inválida");
 if (M>59) return msgErr(obj,msg+" Minuto inválido");
 H = "" + H;
 M = "" + M;
 if (H.length==1) H="0" + H;
 if (M.length==0) M="00";
 if (M.length==1) M="0" + M;
 obj.value = FormatarInv("" + H + M, "__:__");
}

// função para substituir o window.open e window.location que não aceita seguran?a ativa
//@list

function wiOpen(url, target, props) {
   if (target) {
      if (target.toLowerCase()=="_blank") {
         target = Date.parse(new Date())+new Date().getMilliseconds();
      }
   } else target = "_self";
   var frm = document.createElement("FORM");
   frm.action = url;
   frm.target = target;
   frm.method = "post";
   document.body.appendChild(frm);
   var wnd;
   if (target!="")  {
      wnd = window.open('',target,props);
   }
   frm.submit();
   document.body.removeChild(frm);
   return wnd;
}

// verifica se algum campo obrigatório de um form deixou de ser preenchido
// exemplo de INPUT: (deve conter a expressão requerid="true")
//   <input type="text" required="true" name="texto2">
// parametro: frm = form a ser submetido
//          :  msg = mensagem de erro
// usar em OnSubmit do form.
//@list=chkRequired(this)
function chkRequired(frm, msg){

   if (!msg || msg=="") msg="Campo obrigatório não preenchido";
   for (var i=0; i<frm.elements.length; i++) {
      if (frm.elements[i].getAttribute("required")=="true"){
         var ok = false;
         if (frm.elements[i].type.toLowerCase()=="radio") {
            for (var j=0; j<frm[frm.elements[i].name].length; j++) {
               if (frm[frm.elements[i].name][j].checked) {
                  ok = true; 
                  break
               }
            }
         }
         else 
             ok = !(frm.elements[i].value=="");
         if (!ok) 
         {
            alert(msg);
            frm.elements[i].focus();
            return false;
         }
      }
  }
  return true;
}

//@list=upperCase(this)
function upperCase(obj)
{
     var maius = obj.value;	
     obj.value = maius.toUpperCase();
     return obj;
}

function fechaJanela() {
	self.close();
}

function abreJanela(url,target,width,height) {
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	if(width==0) {
		width=screen.width;
	}
	if(height==0) {
		width=screen.height;
	}
   	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   //var win = window.open(url, name, winParms);
   //if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
   //return win;
 	var	popupWin;
 	popupWin = window.open(url,target,'nomenubar,notoolbar,nolocation,nodirectories,nostatus,dependent,alwaysRaised=yes,scrollbars=yes'+','+winParms);
//window.open(url,target,'nomenubar,notoolbar,nolocation,nodirectories,nostatus,dependent,alwaysRaised=yes,width='+w+',height='+h);
	popupWin.focus();
}
function abreJanela1(url,target,width,height) {
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
   	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   //var win = window.open(url, name, winParms);
   //if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
   //return win;
   	popupWin = window.open(url,target,'nomenubar,nolocation,nodirectories,nostatus,dependent,alwaysRaised=yes'+','+winParms);
//window.open(url,target,'nomenubar,notoolbar,nolocation,nodirectories,nostatus,dependent,alwaysRaised=yes,width='+w+',height='+h);
	popupWin.focus();
}
function openWin(newURL, newName, newFeatures, orgName) {
	var newWin = open(newURL, newName, newFeatures);
	if(newWin.opener == null)
		newWin.opener = window;
	return newWin;
}

function openCenteredWindow(url, height, width, name, parms) {
   var left = Math.floor( (screen.width - width) / 2);
   var top = Math.floor( (screen.height - height) / 2);
   var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   if (parms) { winParms += "," + parms; }
   var win = window.open(url, name, winParms);
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
   return win;
}

/*function doOpenRemote(aURL, newName, aHEIGHT, aWIDTH, aFeatures, orgName) {
	alert('fazendp');
	if(!aHEIGHT || aHEIGHT == "*") {
		aHEIGHT = (screen,availHeight - 80);
	}
	if(!aWIDTH || aWIDTH == "*") {
		aHEIGHT = (screen,availHeight - 30);
	}
	var newFeatures += "height=" + aHEIGHT + ",innerHeight=" + aHEIGHT;
	newFeatures += ",width=" + aWIDTH + ",innerWidth=" + aWIDTH;
	if(window.screen) {
		var ah = (screen.availHeight - 30);
		var aw = (screen.availWidth - 10);
		var xc = (( aw - aWIDTH / 2);
		var yc = (( aw = aHEIGHT /2);
		newFeatures += ",left=" + xc + ",screenX=" + xc;
		newFeatures += ",top=" + yc + ",screenY=" + yc;
		newFeatures += "," + aFeatures;
	}
	var newWin = openWin(aURL, newName, newFeatures, orgName);
	newWin.focus();
	return newWin;
}*/

function mostra(input,nm) {
      var targetId, objeto, targetElement;
      nome = nm;
      objeto = window.event.srcElement;
      for (i = 0; i < 2; i++) {
         document.forms[0].tipo[i].checked = false;
         targetId = "Out" + i + "div";
         targetElement = document.all(targetId);
         targetElement.style.display = "none"; 
      }
      document.forms[0].tipo[input].checked = true;
      targetId = objeto.id + "div";
      targetElement = document.all(targetId);
      targetElement.style.display = "none";
      if (targetElement.style.display == "none") {
         targetElement.style.display = "true";
      }  
      /*  var targetId, objeto, targetElement;
      nome = nm;
      objeto = window.event.srcElement;
      for (i = 0; i < 4; i++)
      {
         document.forms[0]["tmp.tipo"][i].checked = false;
         targetId = "Out" + i + "div";
         targetElement = document.all(targetId);
         targetElement.style.display = "none"; 
      }      
      document.forms[0]["tmp.tipo"][input].checked = true;

      targetId = objeto.id + "div";
      targetElement = document.all(targetId);
      targetElement.style.display = "none";
      if (targetElement.style.display == "none")
      {
         targetElement.style.display = "";
      }  
      */
}

function submeteLookupDispatchAction(valor) {
	document.forms[0].action.value=valor;
	document.forms[0].submit();
}

function submeteDispatchAction(valor) {
	document.forms[0].method.value=valor;
	document.forms[0].submit();
}
//Retorna o objeto passando por parametro
function getObjeto(nome){
	var objeto = null;
	if (document.all != null){
		//IE
		objeto = document.all[nome];
	} else {
		//Mozilla
		objeto = document.getElementsByName(nome)[0]
	}	
	return objeto;
}

//Seleciona todos itens da combo passado por parametro
function selecionaItemsCombo(combo){
	m1len = combo.length;
    for ( i=0; i<m1len ; i++){            
    	if (combo.options[i].selected == false ) {                
        	combo.options[i].selected = true;
        }            
    }
}

//  -----  AISLAN ------ 
//onKeyDown="formataCampo(this,event,'##/##/####')"

function formataCampo(Campo,teclapres,mascara){ 
  strtext = Campo.value 
  tamtext = strtext.length 
  tammask = mascara.length 
  arrmask = new Array(tammask)     

  for (var i = 0 ; i < tammask; i++){ 
        arrmask[i] = mascara.slice(i,i+1) 
  } 

  if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){ 
      if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){ 
          Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)         
      } 
      else{ 
          Detona_Event(Campo,strtext,teclapres) 
      } 
  }else{//Implementar mascara para numero
      if ((arrmask[tamtext] == "A"))    { 
        charupper = event.valueOf() 
          //charupper = charupper.toUpperCase() 
          Detona_Event(Campo,strtext,teclapres) 
          masktext = strtext + charupper 
          Campo.value = masktext 
      } 
  } 
} 

function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){ 
  if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){ 
      separador = arrpos 
      masktext = strtext + separador 
      Campo.value = masktext 
  } 
} 
function Detona_Event(Campo,strtext,event){ 
  	if (strtext != "") { 
      	Campo.value = strtext 
  	}
  	if (document.all) {
		event.returnValue = false;
		event.keyCode = 0;
	}else{
		event.preventDefault(); 
	} 
}

function getTecla(event) {
	var tecla = null;
	if (document.all) {
		tecla = event.keyCode; 
	} else if (document.layers) {
		tecla = event.which; 
	} else if (document.getElementById) {
		tecla = event.which; 
	}
	return tecla;
}

function capturaEnter(evento){
  if (!evento){
    return false;
  }
  var tecla = getTecla(evento);
  if (tecla == 13){
    submeteDispatchAction('consultarSolicitacoes');
  }
}

function proibeEnter(evento){
  var tecla = getTecla(evento);
  if (tecla == 13){
    return false;
  }
  return true;
}

function soNumero(evento) {
    var tecla = getTecla(evento);
    var msg = 'O campo deve ser numérico!';
    if ((tecla >= 48 && tecla <= 57) || tecla == 13) { // numeros de 0 a 9 ou enter
        return true;
	} else {
        if (tecla != 8) { // backspace
          if (document.all) {
            alert(msg);
            event.keyCode = 0;
          }else{
            alert(msg);
            event.which = 0;
          }  
		} else {
            return true;
		}
	}
}

function mostraOculta(id, condicao){
  if (id != null && id != ""){
	if (condicao != null){
		if(condicao){
			mostra = true;
		}else{
			mostra = false;
		}
	}else{
		if(mostra){
			mostra = false;
		}else{
			mostra = true;
		}
	}
	document.getElementById(id).style.display = mostra ? '' : 'none';
  }
}

//VALIDAÇÃO DE CPF
 function checaCPF (obj) {
 	var CPF = obj.value;
 	var msg = 'CPF inválido!';
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999") {
		alert(msg);
		obj.focus();
		obj.value='';
		return;
	}
		
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9))) {
		alert(msg);
		obj.focus();
		obj.value='';
		return;
	}
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10))) {
		alert(msg);
		obj.focus();
		obj.value='';
		return;
	}
	return;
 }
 
 function reload(){
	window.location.reload();
 }
 
//FIM DE VALIDA??????O DE CPF




/**
 * Fun??o Replace que substitui todas as ocorr?ncias de um determinado 
 * caracter/conjunto de caracteres, por algum outro caracter/conjunto de caracteres.
 * @author Desconhecido.
 */
function xreplace(variavel, aSerSubstituido, substituirPor){
	var temp = variavel;
	var i = temp.indexOf(aSerSubstituido);
	while(i > -1) {
		temp = temp.replace(aSerSubstituido, substituirPor);
		i = temp.indexOf(aSerSubstituido, i + substituirPor.length + 1);
	}
	return temp;
}

/**
 * Verifica se os eventos lan?ados s?o provenientes de um Browser "Internet Explorer".
 * @author Daniel Melo S?.
 */
function isEventoLancadoDoBrowserInternetExplorer() {
	return window.event != null;
}




function executarProcedimentosAposCarregamentoDePagina() {
	addHandlersParaTratarMaxlengthDosTextareas();
}

function addHandlersParaTratarMaxlengthDosTextareas() {
	var elementosTextarea = getElementosTextarea();	
	for (i = 0; i < elementosTextarea.length; i++) {
		document.forms[0][elementosTextarea[i].name].onchange=limitarTamanhoDoTextarea;
		document.forms[0][elementosTextarea[i].name].onkeyup=limitarTamanhoDoTextarea;
	}
}

function limitarTamanhoDoTextarea(evento) {
	var nomeDoCampo = capturarObjetoDoEvento(evento).name;
	var maxlength;
	var textarea;
	
	if (isTextareaValido(nomeDoCampo)) {
		maxlength = getMaxlengthDoCampo(nomeDoCampo);
		if (isMaxlengthValido(maxlength)) {
			textarea = document.forms[0][nomeDoCampo];
			if (textarea.value.length > maxlength) {
				textarea.value = textarea.value.substr(0, maxlength);
			}
		}
	}
}

function isTextareaValido(nomeOuIndiceDoCampo) {
	return document.forms[0][nomeOuIndiceDoCampo] != null && getTipoDoComponente(nomeOuIndiceDoCampo) == "textarea"; 
}

function isMaxlengthValido(maxlength) {
	return maxlength != null && !isNaN(maxlength);
}

function getElementosTextarea() {
	return document.getElementsByTagName("textarea");
}

function getMaxlengthDoCampo(nomeDoCampo) {
	return document.getElementsByName(nomeDoCampo)[0].getAttribute("maxlength");
}

/**
 * Verifica se os eventos lan?ados s?o provenientes de um Browser "Internet Explorer".
 * @author Daniel Melo S?.
 */
function isEventoLancadoDoBrowserInternetExplorer() {
	return window.event != null;
}


function isArray(obj){
	return (typeof(obj.length)=="undefined")? false : true;
}

function isComponenteValido(nomeIndiceOuIdDoComponente) {
	retorno = false;
	if (document.getElementById(nomeIndiceOuIdDoComponente) != null) {
		retorno = true;
	} else if (document.getElementsByName(nomeIndiceOuIdDoComponente)[0] != null) {
		retorno = true;
	} else if (getComponente(nomeIndiceOuIdDoComponente) != null) {
		retorno = true;
	}
	return retorno;
}

function getTipoDoComponente(nomeOuIndiceDoCampo) {
	return getComponente(nomeOuIndiceDoCampo).type;
}

/**
 * Retorna o componente HTML.
 */
function getComponente(nomeOuIndiceDoCampo, formulario) {
	formulario = formulario || document.forms[0];
	return formulario[nomeOuIndiceDoCampo];
}

function setFocoNoCampo(nomeDoCampo) {
	document.forms[0][nomeDoCampo].focus();
}

function selecionarCampo(nomeDoComponenteQueReceberaFoco) {
	if (isComponenteValido(nomeDoComponenteQueReceberaFoco)) {
		document.forms[0][nomeDoComponenteQueReceberaFoco].select();
	}
}

function selecionarItem(nomeDoSelect, valueDoItemASelecionar) {
	var select = getComponente(nomeDoSelect);
	if (select != null && valueDoItemASelecionar != null) {
		for (i = 0; i < select.options.length; i++)  {
			if (select.options[i].value == valueDoItemASelecionar) {
				select.selectedIndex = i;
				break;
			}
		}
	}
}

function mascararData(input, evnt){
	var keyCode = (isBrowserInternetExplorer())? evnt.keyCode : evnt.keyCode;
	//alert(evnt.keyCode);
	if (input.value.length == 2 || input.value.length == 5){
		if(isBrowserInternetExplorer()){
			input.value += "/";
		} else {
			input.value += "/";
		}
	}
	//Chama a fun??o Bloqueia_Caracteres para s? permitir a digita??o de n?meros
	return bloquearCaracteres(evnt);
}

function bloquearCaracteres(evnt){
	var retorno = true;
	if (isBrowserInternetExplorer()){
		if (isCaracterSendoDigitado(evnt) && isTeclasHabilitadasParaCampoTexto(evnt)){
			alert("tem que desabilitar!!!");
			window.event.returnValue = false;
			retorno = false;
		}
	}else{
		if (isCaracterSendoDigitado(evnt) && isTeclasHabilitadasParaCampoTexto(evnt)){
			retorno = false;
			evnt.preventDefault();
		}
	}
	return retorno;
}

function isCaracterSendoDigitado(evnt) {
	//alert(evnt.keyCode);
	return (evnt.charCode < 48 || evnt.charCode > 57);
}

function isTeclaDeExclusaoDeCaracterSendoPressionada(evnt) {
	//alert(evnt.keyCode);
	return (evnt.keyCode == 8 || evnt.keyCode == 46);
}

function isSetasSendoPressionadas(evnt) {
	//alert(evnt.keyCode);
	return (evnt.keyCode == 37 || evnt.keyCode == 38 || evnt.keyCode == 39 || evnt.keyCode == 40);
}

function isTeclasTabShiftOuCtrl(evnt) {
	//alert(evnt.keyCode);
	return (evnt.altKey || evnt.ctrlKey || evnt.keyCode == 9);
}

function isEnterPressionado(evnt) {
	return (evnt.keyCode == 13);
}

function isTeclasHabilitadasParaCampoTexto(evnt) {
	return 	isTeclaDeExclusaoDeCaracterSendoPressionada(evnt) || isSetasSendoPressionadas(evnt) || isTeclasTabShiftOuCtrl(evnt) || isEnterPressionado(evnt);
}
function isElementoImg(html) {
	html = html.trim();
	return (html != null && html.substr(0,4).toUpperCase() == "<IMG")? true : false;
}

var ultimaTr='';
function mudarFundoDeGrid(event) {
	var elemento = capturarObjetoDoEvento(event);
	if(ultimaTr != '') {
		ultimaTr.style.backgroundColor='';
	}
	if(isElementoImg(elemento.parentNode.innerHTML)) {
		ultimaTr = elemento.parentNode.parentNode.parentNode;
		elemento.parentNode.parentNode.parentNode.style.backgroundColor='#CCFFCC';
	} 
	else {
		ultimaTr = elemento.parentNode.parentNode;
		elemento.parentNode.parentNode.style.backgroundColor='#CCFFCC';
	}
}

function capturarObjetoDoEvento(evento) {
	return isEventoLancadoDoBrowserInternetExplorer() ? window.event.srcElement: evento.target;
}

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

function fecharPopUp() {
	window.close();
	window.opener.focus();
}

function configuraTrilha(event, trilha){
	if(!proibeEnter(event)){
		var valorTrilha = trilha.value;
		tamanho = valorTrilha.length;
		if(tamanho > 16 && valorTrilha.substring(0,1) == '%') {
			if(valorTrilha.substring(tamanho-2,tamanho) == '?:') {		
				return false;
			}
			if(tamanho < 35 && valorTrilha.substring(tamanho-1,tamanho) == ':') {
				return false;
			}
		}		
	}
	return true;
}

//window.onresize = onResizeHandler;
//window.onscroll = onScrollHandler;
//Window.prototype.alert = sawAlert;

// Funcaes a executar quando a Tela for redimensionada.
function onResizeHandler() {
	// A Linha abaixo está comentada pois o componente não está em produção.
	//realocarComponenteDeMensgens();
}

// Funcaes a executar quando a Tela for "rolada" (scroll).
function onScrollHandler() {
	// A Linha abaixo está comentada pois o componente não está em produção.
	//realocarComponenteDeMensgens();
}


/**
 * Constante global que define o ID do IFRAME em que o Componente de Mensagens processado.
 * @author Daniel Melo Sa.
 */
var ID_IFRAME_MENSAGENS = "frameDeMensagem";

/**
 * Constante global que define o Nome do Estilo do IFrame em que o Componente de Mensagens ser? diagramado.
 * @author Daniel Melo Sa.
 */
var ESTILO_IFRAME_MENSAGENS = "estiloIFrameComponenteDeMensagens";

/**
 * Constante global que define o Nome do Estilo do DIV em que o Componente de Mensagens ser? diagramado.
 * @author Daniel Melo Sa.
 */
var ESTILO_DIV_MENSAGENS = "estiloDIVDeMensagens";


var mensagensAbertas = new Array();

/**
 * Funcao utilizada para abrir uma Mensagem de Alerta utilizando o Componente de Mensagens.
 * <b>OBS: Para chamar esta funcao, utilize a funcao nativa do browser: window.alert('Mensagem');</b>
 * @author Daniel Melo Sa.
 * @author Tauser Carneiro.
 * @see window.alert().
 */
function sawAlert(string) {
	var chave = criarChaveParaMensagem(string);
	
	registrarAberturaDeMensagem(chave);

	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", ID_IFRAME_MENSAGENS);
	iframe.setAttribute("frameborder", "0");
	iframe.setAttribute("width", "360");
	iframe.setAttribute("height", "160");
	iframe.setAttribute("class", ESTILO_IFRAME_MENSAGENS);
	iframe.setAttribute("src", contexto + "/Mensagem.do?method=alerta&mensagem=" + xreplace(string, "\n", "<br>") + "&chave=" + chave);
	
	var div = document.createElement("div");
	div.setAttribute("id", chave);
	div.setAttribute("class", ESTILO_DIV_MENSAGENS);
	div.appendChild(iframe);

	document.body.appendChild(div);
	document.getElementById(chave).style.visibility = (document.layers)?'show':((document.all)?'visible': ((document.getElementById)?'visible' : ''));
	
	realocarComponenteDeMensgens();
}

/**
 * Cria uma chave de identifica??o ?nica para o componente de mensagem que sera aberto.
 * @param String - String da mensagem que sera diagramada no componente.
 * @author Daniel Melo Sa.
 */
function criarChaveParaMensagem(string) {
	var date = new Date();
	return "Chave" + date.getMilliseconds() + date.getMilliseconds() + "DaMensagem";
}

/**
 * Registra a abertura da Mensagem, adicionando a chave da mensagem na lista de mensagens abertas.
 * @param String - chave da mensagem.
 * @author Daniel Melo Sa.
 */
function registrarAberturaDeMensagem(chave) {
	mensagensAbertas.push(chave);
}

/**
 * Remove a Chave do Componente de Mensagem aberto da lista de Chaves dos Componentes abertos.
 * <b>OBS: Utilizar quando estiver fechando um determinado componente de mensagem.</b>
 * @param String - Chave da Mensagem.
 */
function removerChaveDaMensagemDaListaDeMensagensAberta(chave) {
	var indiceDaChave = null;
	for (i = 0; i < mensagensAbertas.length; i++) {
		if (mensagensAbertas[i] == chave) {
			indiceDeChave = i;
		}
	}
	if (indiceDaChave != null) {
		mensagensAbertas.splice(indiceDaChave, indiceDaChave + 1);
	}
}

/**
 * Registra a abertura da Mensagem, adicionando a chave da mensagem na lista de mensagens abertas.
 * @param String - chave da mensagem.
 * @author Daniel Melo Sa.
 */
function registrarAberturaDeMensagem(chave) {
	mensagensAbertas.push(chave);
}

/**
 * Funcao utilizada para diagramar o Componente de Mensagens de forma central na tela.
 * <b>OBS: Deve ser chamada quando a tela for redimensionada e quando o scroll de tela for exetudado.</b>
 * @author Daniel Melo Sa.
 * @author Tauser Carneiro.
 */
function realocarComponenteDeMensgens() {
	for (i = 0; i < mensagensAbertas.length; i++) {
		document.getElementById("display").innerHTML = document.getElementById(mensagensAbertas[i]).innerHTML + "<br>";
		document.getElementById(mensagensAbertas[i]).style.top = ((((document.body.clientHeight*50)/100)+window.pageYOffset)-(parseInt(document.getElementById(mensagensAbertas[i]).style.height.substr(0,document.getElementById(mensagensAbertas[i]).style.width.length-2))))+'px';
		document.getElementById(mensagensAbertas[i]).style.left = (((document.body.clientWidth*50)/100)-(parseInt(document.getElementById(mensagensAbertas[i]).style.height.substr(0,document.getElementById(mensagensAbertas[i]).style.height.length-2))))+'px';
	}
}

/**
 * Funcao utilizada para fechar uma Mensagem de Alerta.
 * Se necessario, deve-se implementar alguns procedimentos de fechamento de tela.
 * @param String - Chave do componente de mensagens a ser fechado.
 * @author Daniel Melo Sa.
 * @author Tauser Carneiro.
 */
function acaoFecharMensagem(chave) {
	removerChaveDaMensagemDaListaDeMensagensAberta(chave);
	document.getElementById(chave).innerHTML = "";
	document.getElementById(chave).style.visibility = (document.layers)?'hide':((document.all)?'hidden': ((document.getElementById)?'hidden' : ''));
}


/**
 *	Mostra o campo passado como par?metro.
 *  OBS: Ao utilizar a função em uma PopUp o arquivo scriptaculous.js deve ser importado antes do page.js.
 *	@param <b>idDoDiv</b> - ID do DIV a mostrar.
 *	@author Daniel Melo S?.
 */
function mostrarComponente(idDoDiv) {
	if (idDoDiv != null && idDoDiv.length > 0) {
		//Effect.Appear(idDoDiv);
		document.getElementById(idDoDiv).style.display = "inline";
	}
}
/**
 *	Oculta o campo passado como par?metro.
 *  OBS: Ao utilizar a função em uma PopUp o arquivo scriptaculous.js deve ser importado antes do page.js.
 *	@param <b>idDoDiv</b> - ID do DIV a ocultar.
 *	@author Daniel Melo S?.
 */
function ocultarComponente(idDoDiv) {
	if (idDoDiv != null && idDoDiv.length > 0) {
		//Effect.SwitchOff(idDoDiv);
		document.getElementById(idDoDiv).style.display = "none";
	}
}

/**
 *	Habilita o campo passado como par?metro.
 *  OBS: <b>enabled = true</b>.
 *	@param <b>nomeDoComponente</b> - Nome do componente a habilitar.
 *	@author Daniel Melo S?.
 */
function habilitarComponente(nomeDoComponente) {
	if (nomeDoComponente != null) {
		try {
			document.forms[0][nomeDoComponente].disabled = false;
		} catch (E) { }
	}
}
/**
 *	Desabilita o campo passado como par?metro.
 *  OBS: <b>disabled = true</b>.
 *	@param <b>nomeDoComponente</b> - Nome do componente a desabilitar.
 *	@author Daniel Melo Sá.
 */
function desabilitarComponente(indiceOuNomeDoComponente, formulario) {
	formulario = formulario || document.forms[0];
	if (indiceOuNomeDoComponente != null) {
		try {
			formulario[indiceOuNomeDoComponente].disabled = true;
		} catch (E) { alert("erro: page.js.desabilitarComponente()") }
	}
} 

/**
 * Verifica se é um componente que pode receber foco.
 * @param indiceOuNomeDoComponente.
 * @param formulario - Se não for passada a referência do formulario, assume-se que o formulário manipulado é o de índice 0 (document.forms[0]).
 * @author Daniel Melo Sá.
 */
function isComponentePassivelDeFoco(indiceOuNomeDoComponente, formulario) { 
	formulario = formulario || document.forms[0];
	return getTipoDoComponente(indiceOuNomeDoComponente, formulario) != "hidden" && formulario[indiceOuNomeDoComponente].style.display != "none"; 
}

/**
 * Verifica se o componente está habilitado.
 * @param indiceOuNomeDoComponente.
 * @param formulario - Se não for passada a referência do formulario, assume-se que o formulário manipulado é o de índice 0 (document.forms[0]).
 * @author Daniel Melo Sá.
 */
function isComponenteHabilitado(indiceOuNomeDoComponente, formulario) { 
	formulario = formulario || document.forms[0];
	return !formulario[indiceOuNomeDoComponente].disabled; 
}

/**
 * Verifica se é um componente do tipo SELECT ou Radio.
 * @param indiceOuNomeDoComponente.
 * @param formulario - Se não for passada a referência do formulario, assume-se que o formulário manipulado é o de índice 0 (document.forms[0]).
 * @author Daniel Melo Sá.
 */
function isComponenteTipoSelect(indiceOuNomeDoComponente, formulario) {
	formulario = formulario || document.forms[0];
	return (formulario[indiceOuNomeDoComponente].type == 'select-one' || 
			formulario[indiceOuNomeDoComponente].type == 'select-multiple' || 
			formulario[indiceOuNomeDoComponente].type == 'radio');
}

/**
 * Desabilitar todos os Componentes HTML do formulário.
 * @param formulario - Se não for passada a referência do formulario, assume-se que o formulário manipulado é o de índice 0 (document.forms[0]).
 * @author Daniel Melo Sá.
 */
function desabilitarTodosOsCamposDoFormulario(formulario) {
	formulario = formulario || document.forms[0];
	for (componente = 0; componente < formulario.elements.length; componente++) {
		if (isComponenteValido(componente) && isComponentePassivelDeFoco(componente, formulario) && isComponenteHabilitado(componente, formulario)) {
			formulario[componente].disabled = true;
			/*
			if (isComponenteTipoSelect(componente, formulario)) {
				formulario[componente].disabled = true;
			} else {
				formulario[componente].readOnly = true;
			}
			*/
		}
	}
}

/**
 * Habilitar todos os Componentes HTML do formulário.
 * @param formulario - Se não for passada a referência do formulario, assume-se que o formulário manipulado é o de índice 0 (document.forms[0]).
 * @author Daniel Melo Sá.
 */
function habilitarTodosOsCamposDoFormulario(formulario) {
	formulario = formulario || document.forms[0];
	for (componente = 0; componente < formulario.elements.length; componente++) {
		if (isComponenteValido(componente) && isComponentePassivelDeFoco(componente, formulario) && !isComponenteHabilitado(componente, formulario)) {
			formulario[componente].disabled = false;
			/*
			if (isComponenteTipoSelect(componente, formulario)) {
				formulario[componente].disabled = false;
			} else {
				formulario[componente].readOnly = false;
			}
			*/
		}
	}
}


//AISLAN - Função para formatar valor

//Usar campo com size = 20

function formataValor(campo,evento) {
	var tecla = getTecla(evento);
	var comando;
	var vr;
	
	var objCampo = campo;
	vr = objCampo.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( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;
	tam = tam + 1;
	if (tecla == 8 ){ tam = tam - 2 ; }
	if (tam > 15){
		return;
	}
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
			objCampo.value = vr ;
		}
		if ( (tam > 2) && (tam <= 5) ){
			objCampo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}
		if ( (tam >= 6) && (tam <= 8) ){
			objCampo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}
		if ( (tam >= 9) && (tam <= 11) ){
			objCampo.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) ){
			objCampo.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) ){
			objCampo.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 ) ;
		}
	}
}

/**
 * Abrir a janela para exibir os detalhes da guia de acordo com o tipo e chave
 * @param chaveDaGuia - chave da guia
 * @param tipoDaGuia - tipo da guia
 * @author Adriano Borges.
 */
function abreJanelaMaximizadaDaGuia(chaveDaGuia,tipoDaGuia) {
	if (tipoDaGuia == 'CONSULTA ELETIVA'){
		abreJanelaMaximizada('/saw/tiss/SolicitacaoDeConsulta.do?method=consultarGuiaDeConsulta&solicitacaoDeConsulta.chave='+chaveDaGuia);
	} else if (tipoDaGuia == 'SP/SADT') {
		abreJanelaMaximizada('/saw/tiss/SolicitacaoDeSPSADT.do?method=consultarGuiaDeSPSADT&solicitacaoDeSPSADT.chave='+chaveDaGuia);
	} else if (tipoDaGuia == 'INTERNAÇÃO' || tipoDaGuia == 'PRORROGAÇÃO') {
		abreJanelaMaximizada('/saw/tiss/SolicitacaoDeInternacao.do?method=consultarGuiaDeInternacao&solicitacaoDeInternacao.chave='+chaveDaGuia);
	} else if (tipoDaGuia == 'RESUMO DE INTERNAÇÃO') {
		abreJanelaMaximizada('/saw/tiss/SolicitacaoDeConsulta.do?method=consultarGuiaDeConsulta&solicitacaoDeConsulta.chave='+chaveDaGuia);
	} else if(tipoDaGuia == 'HONORÁRIO INDIVIDUAL') {
		abreJanelaMaximizada('/saw/tiss/SolicitacaoDeConsulta.do?method=consultarGuiaDeConsulta&solicitacaoDeConsulta.chave='+chaveDaGuia);
	} else if (tipoDaGuia == 'OUTRAS DESPESAS') {
		abreJanelaMaximizada('/saw/tiss/SolicitacaoDeConsulta.do?method=consultarGuiaDeConsulta&solicitacaoDeConsulta.chave='+chaveDaGuia);
	} 
}

/**
 * Retorna o Unicode do tecla pressionada.
 * @author Daniel Melo Sá.
 */
function getUnicodeDaTeclaPressionada(evento) {
	var unicode = 0;
	if (evento != null) {
		// Verifica se o Browser Cliente é Internet Explorer.
		if (isBrowserInternetExplorer()) {
			var keyCode = evento.keyCode;
			if (keyCode > 0) {
				unicode = keyCode;
			}
		} else { // Se não for IE, considera o padrão DOM Mozilla.
			var charCode = evento.charCode;
			var keyCode = evento.keyCode;
			if (charCode > 0) {
				unicode = charCode;
			} else if (keyCode > 0) {
				unicode = keyCode;
			}
		}
	} else {
		alert("Erro de Sistema: \nO Objeto de evento da Tecla Pressionada não foi enviada corretamente a função referenciada.\nEntre em contato com a Unimed Centro-Oeste e Tocantins e relate o erro.");
	}
	return unicode;
}


/**
 * Verifica se a data é uma data válida.
 * @author Daniel Melo Sá.
 */
function isDataValida(data) {
	return !isNaN(data.replace(/\//g, "")) && data.replace(/\//g, "").length == 8 && data != "DD/MM/YYYY";
}

/**
 * Formata campos de forma genérica, de acordo com o formato estabelecido.
 * @author Desconhecido.
 * @see www.imasters.com.br
 */
function formatarCampo(campo, Mascara, evento) {
	var boleanoMascara;
	
	var Digitato = evento.keyCode;
	exp = /\-|\.|\/|\(|\)| /g
	campoSoNumeros = campo.value.toString().replace( exp, "" );
	
	var posicaoCampo = 0;
	var NovoValorCampo="";
	var TamanhoMascara = campoSoNumeros.length;;
	
	if (Digitato != 8) { // backspace
		for(i=0; i<= TamanhoMascara; i++) {
			boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") || (Mascara.charAt(i) == "/"));
			boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(") || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "));
			if (boleanoMascara) {
				NovoValorCampo += Mascara.charAt(i);
				TamanhoMascara++;
			}else {
				NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
				posicaoCampo++;
			}
		}
		campo.value = NovoValorCampo;
		return true;
	}else {
		return true;
	}
}

/**
 * Retorna os Milisegundos atual
 * @return new Date().getMilliseconds()
 * @author Daniel Melo Sá.
 */
function getMilisegundos() {
	return new Date().getMilliseconds();
}

/**
* Função POG que é melhor que o DEBUG do Eclipse ou qualquer outra IDE.
* Extende implicitamente de Arabtoroman.
* @author Eduardo C. Rangel
*/
function pogDebug(numero) {
	alert("Debug POG: Passou pelo passo nº " + numero + ".");
}