// JavaScript Document
	/* Atribui a sua regex a uma vari?vel comum
 * dentro dos [], voc? coloca os caracteres 
 * ou sequ?ncia de caracteres que vai permitir
 */
var regexTexto = /^[a-z' 'A-Z????????????????????????????????]+$/;

/* aqui come?a a fun??o que recebe o campo que ser? 
 * validado no final do artigo vou mostrar como 
 * passar o campo como par?metro 
 */
function soCaracter( campo ){
campo.value = replaceAll(campo.value,"  "," ");
     /* aqui faz o teste usando o m?todo test que 
      *  compara a sua regex com o value do campo
      */
     if ( regexTexto.test( campo.value )) {
          //caso ok retorna true
          return true; 
     }
     else{
          /* aqui voc? pode retornar falso, colocar uma 
           * mensagem, limpar o campo, setar o foco no campo...
           */
          campo.value = '';
          campo.focus();
          return false;
    }
}


function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}

function ajaxProcess(myForm,field,actionMethod){
 	
   var xmlHttp;
 
   try{      
   		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
   	  }
   	  catch (e){      
    	       try{        
    		     xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");        
    	   	     }
    	   	     catch (e){        
    	   	       alert("Your browser does not support AJAX!");        
    	   	       return false;        
    	   	     }
        	  }
    
    xmlHttp.onreadystatechange=function(){   
      if(xmlHttp.readyState==1)
        document.forms[0].status.value="processando..";      
      if(xmlHttp.readyState==4)
        document.forms[0].status.value="pronto"; 
    }
     
    myForm.acao.value = actionMethod;
    var strAction = "";
    strAction += myForm.action+"?acao="+myForm.acao.value;
    var element = document.getElementById("frame");
    element.src = strAction;
    xmlHttp.open("GET",strAction,true);
    xmlHttp.send(null);    	    	  
 }


	function validaCNPJ(cnpj){
	    if(cnpj!=null && cnpj!=""){
	       submeter('validaCnpjCadastrado')  
	    }
	}
	
	function validaCNPJSuperior(cnpj){
	    if(cnpj!=null && cnpj!=""){
	       submeter('validaCnpjSuperiorCadastrado')  
	    }
	}
	
	function validaCNPJUnidade(cnpj){
	    if(cnpj!=null && cnpj!=""){
	       submeter('validaCnpjCadastradoUnidade')
	    }
	}
	
	function validaCNPJSuperiorUnidade(cnpj){
	    if(cnpj!=null && cnpj!=""){
	       submeter('validaCnpjSuperiorCadastradoUnidade')  
	    }
	}
	
	function mascara_cep(cep,cepform,e){
         var tecla;
         var tam = cep.length;
   
         if (document.all) {
            var tecla=event.keyCode;
         } else {
            var tecla = e.which;
         } 

         if (tecla != 8) { 
         	
            if (tam == 5) {
               cep = cep + '-';
               cepform.value = cep;
            }
         } 
      }
      function mascara_telefone(telefone,telefoneform,e){
         var tecla;
         var tam = telefone.length;
   
         if (document.all) {
            var tecla=event.keyCode;
         } else {
            var tecla = e.which;
         } 

         if (tecla != 8) { 
         	
            if (tam == 2) {
               telefone = telefone + '-';
               telefoneform.value = telefone;
            }
         } 
      }
	
	function mascara_cnpj(cnpj,cnpjform,e){

   var tecla;
   var tam = cnpj.length;
   
   if (document.all){
   var tecla=event.keyCode;
   } 
   else{
   var tecla = e.which;
   } 


  if(tecla != 8){ 
     
    if (tam == 2) {
        cnpj = cnpj + '.';
        cnpjform.value = cnpj;
    }
    if (tam == 6) {
        cnpj = cnpj + '.';
        cnpjform.value = cnpj;
    }
    if (tam == 10) {
        cnpj = cnpj + '/';
        cnpjform.value = cnpj;
    }
    if (tam == 15) {
       cnpj = cnpj + '-';
      cnpjform.value = cnpj;
    }
   } 
}

  function exibirdiv(id){
 	 obj = document.getElementById(id);
	 obj.style.display  = "block";
  }

 function ocultardiv(id){
    obj = document.getElementById(id);
    obj.style.display  = "none";  
  }
  
function executar(opcao) {
          document.forms[0].acao.value = opcao;
          document.forms[0].submit();
        }
        
function submeter( acao){
	document.forms[0].acao.value = acao;
	if(document.forms[0].btnEnviar!= null){
	   document.forms[0].btnEnviar.disabled=true;
	}
	 document.forms[0].submit();
 }

 function alterar( id ){ 
    document.forms[0].acao.value = "alterar";
    document.forms[0].id.value = id;
	if(document.forms[0].btnEnviar!= null){
	   document.forms[0].btnEnviar.disabled=true;
	}
	 document.forms[0].submit();
 }
 
  function soNums(e,punct) 
    {       
        if (document.all){var evt=event.keyCode;} 
        else{var evt = e.charCode;} 
        var min_key = (punct?43:47); 
        if (evt <20 || (evt >min_key && evt<58)){return true;} 
        return false; 
    } 

function ler_imagens() { //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=ler_imagens.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 img_restore() { //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_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 img_troca() { //v3.0
  var i,j=0,x,a=img_troca.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 showdiv()
{
	document.getElementById('excluir').style.visibility = "visible";
}


function popup(vURL, vNomeJanela, vAltura, vLargura){
	var vPropriedades = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,menubar=no,width='+vLargura+',height='+vAltura;
	
	window.open(vURL,vNomeJanela,vPropriedades);	
}

//IN?CIO DA ROTINA DO MENU

var persistmenu="no";
var persisttype="sitewide";

/*if (document.getElementById){ 
document.write('<style type="text/css">\n')
document.write('.submenu{display: none;}\n')
document.write('</style>\n')
}*/

function SwitchMenu(obj){
 if(document.getElementById){
 var el = document.getElementById(obj);
 var ar = document.getElementById("masterdiv").getElementsByTagName("div"); 
  if(el.style.display != "block"){ 
   for (var i=0; i<ar.length; i++){
    if (ar[i].className=="submenuO") 
    ar[i].style.display = "none";
    if (ar[i].className=="submenu") 
    ar[i].style.display = "none";
   }
   el.style.display = "block";
  }else{
   el.style.display = "none";
  }
 }
}

function get_cookie(Name) { 
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { 
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
if (persistmenu=="yes"){
var cookiename=(persisttype=="sitewide")? "switchmenu" : window.location.pathname
var cookievalue=get_cookie(cookiename)
if (cookievalue!="")
document.getElementById(cookievalue).style.display="block"
}
}

function savemenustate(){
var inc=1, blockid=""
while (document.getElementById("sub"+inc)){
if (document.getElementById("sub"+inc).style.display=="block"){
blockid="sub"+inc
break
}
inc++
}
var cookiename=(persisttype=="sitewide")? "switchmenu" : window.location.pathname
var cookievalue=(persisttype=="sitewide")? blockid+";path=/" : blockid
document.cookie=cookiename+"="+cookievalue
}


function geraMenu(path){
	var vHtml = '<div id="masterdiv">'+
			
			  '<div class="menutitle" onClick="SwitchMenu(\'sub1\')">Manter Dados Operacionais</div>'+
			  '<div class="submenu" id="sub1"><a href="'+path+'manterDados/servicos.html">Servi?os</a><br>'+
			  '<a href="'+path+'manterDados/subServicos.html">SubServi?os</a><br>'+
			  '<a href="'+path+'manterDados/produtos.html">Produto</a><br>'+
			  '<a href="'+path+'manterDados/setorEconomico.html">Setor Econ?mico</a><br>'+
			  '<a href="'+path+'manterDados/acreditacao.html">Acredita??o</a><br>'+
			  '<a href="'+path+'manterDados/tipoInstituicao.html">Tipo Institui??o</a><br>'+
			  '<a href="'+path+'manterDados/naturezaJuridica.html">Natureza Jur?dica</a><br>'+
			  '<a href="'+path+'manterDados/normas.html">Normas</a></div>'+
			  

			 
			  '<div class="menutitle" onClick="SwitchMenu(\'sub2\')">Usu?rios</div>'+
			  '<div class="submenu" id="sub2">' +
			  '<a href="'+path+'manterDados/manterUsuarios.html">Manter Usu?rios</a></div>' +
			  
			  '<div class="menutitle" onClick="SwitchMenu(\'sub3\')">Enviar Comunicados</div>'+
			  '<div class="submenu" id="sub3">' +
			  '<a href="'+path+'manterDados/enviarComunicados.html">Enviar Comunicados</a></div>' +
		      '<br><br></div>'+ 
			  
			  '<div class="textomenulat">Administrador da Unidade</div><br>'+
			  
			  '<div class="menutitle" onClick="SwitchMenu(\'sub10\')">Alterar Registros</div>'+
			  '<div class="submenu" id="sub10"><br>'+
			  '<a href="#">Dados Cadastrais</a><br>'+
			  '<a href="#">Servi?os</a><br>'+
			  '<a href="#">Produtos</a><br>'+
			  '<a href="#">Setores</a><br>'+
			  '<a href="#">Credenciamento</a><br>'+
			  
			  '</div>'+
			  '</div>';			  
	return vHtml;	
}

//  FUN?OES AJAX DWR

   function atualizaCombo(lista){
	      DWRUtil.removeAllOptions(idObj);
	      DWRUtil.addOptions(idObj,{0:'Selecione'});
		  DWRUtil.addOptions(idObj, lista,"id","descricao");
  }
     function atualizaLista(lista){
	      DWRUtil.removeAllOptions(idObj);
	      DWRUtil.addOptions(idObj,{0:'Outra'});
		  DWRUtil.addOptions(idObj, lista,"id","descricao");
  }
     function limpaCombo(){
	      DWRUtil.removeAllOptions(idObj);
	      DWRUtil.addOptions(idObj,{0:'Selecione'});
  }

 function exibeMensagem(msg) {
  	var loadingMessage;
  	loadingMessage = msg;
  	DWREngine.setPreHook(function() {
    var disabledZone = $('disabledZone');
    if (!disabledZone) {
      disabledZone = document.createElement('div');
      disabledZone.setAttribute('id', 'disabledZone');
      disabledZone.style.position = "absolute";
      disabledZone.style.zIndex = "1000";
      disabledZone.style.left = "-50px";
      disabledZone.style.top = "80px";
      disabledZone.style.width = "100%";
      disabledZone.style.height = "100%";
      document.body.appendChild(disabledZone);
      var messageZone = document.createElement('div');
      messageZone.setAttribute('id', 'messageZone');
      messageZone.style.position = "absolute";
      messageZone.style.top = "0px";
      messageZone.style.right = "0px";
      messageZone.style.background = "#800000";
      messageZone.style.color = "white";
      messageZone.style.fontFamily = "Arial,Helvetica,sans-serif";
      messageZone.style.padding = "4px";
      disabledZone.appendChild(messageZone);
      var text = document.createTextNode(loadingMessage);
      messageZone.appendChild(text);
    }
    else {
      $('messageZone').innerHTML = loadingMessage;
      disabledZone.style.visibility = 'visible';
    }
  });

  DWREngine.setPostHook(function() {
    $('disabledZone').style.visibility = 'hidden';
  });
}
/** M?todo de aumentar e diminuir tamanho da fonte do HTML<br>
	idAlvo = local que o texto se encontra<br>
	acao = n?mero inicial do array do tamanho<br>
*/
//pega todas as tags p//
var tagAlvo = new Array('p'); 
// Especificando os poss?veis tamanhos de fontes, poderia ser: x-small, small...
var tamanhos = new Array( '9px','10px','11px','12px','13px','14px','15px' );
var tamanhoInicial = 2;
 
function changeSize(listaNodes, pos)
{
	if(listaNodes != null && pos > (listaNodes.length -1))
		return;
	if(listaNodes[pos].childNodes.length > 0)
	{
		changeSize(listaNodes[pos].childNodes, 0);
	}
	if(listaNodes[pos].style!=null)
		listaNodes[pos].style.fontSize = tamanhos[tamanhoInicial];
	changeSize(listaNodes, pos+1);

} 
 
function mudaTamanho( idAlvo,acao ){
  if (!document.getElementById) 
  	return
  var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
  tamanho += acao;
  if ( tamanho < 0 ) 
  	tamanho = 0;
  if ( tamanho > 6 ) 
  	tamanho = 6;
  tamanhoInicial = tamanho;
  if ( !( selecionados = document.getElementById( idAlvo ) ) ) 
  	selecionados = document.getElementsByTagName( idAlvo )[ 0 ];
  //selecionados.style.fontSize = tamanhos[ tamanho ];
  changeSize(selecionados.childNodes,0);
  /*
  for ( i = 0; i < tagAlvo.length; i++ ){
    tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
	for ( j = 0; j < tagsAlvo.length; j++ ) 
		tagsAlvo[ j ].style.fontSize = tamanhos[ tamanho ];
		
 	}*/
}

/** M?todo retorna o tamanho da fonte do HTML ao original - 11px<br>
	idAlvo = local que o texto se encontra<br>
*/
function tamanhoOriginal(idAlvo){
  if (!document.getElementById) return
 	   var selecionados = null,tamanho = 2,i,j,tagsAlvo;
	   tamanhoInicial = tamanho;
 	if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];
	   	selecionados.style.fontSize = '11px';
	   	/*
  	for ( i = 0; i < tagAlvo.length; i++ ){
      tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
    for ( j = 0; j < tagsAlvo.length; j++ ) tagsAlvo[ j ].style.fontSize = '11px';
  	}*/
  	 changeSize(selecionados.childNodes,0);
}


function ConfirmaDesativar() {
	var pergunta = "Voc? tem certeza que deseja desativar este registro?";
	if (confirm(pergunta)) {
		return true;
	} else {
		alert("Registro N?o desativado.")
		return false;
	}	
}

function ConfirmaExclusao() {
	var pergunta = "Voc? tem certeza que deseja excluir este registro?";
	if (confirm(pergunta)) {
		return true;
	} else {
		alert("Registro n?o exclu?do.")
		return false;
	}	
}

var emails;
function validar(acao){
 if (acao == 'cnpj'){
  	validaCnpj();
  } else {
		emails = acao;
		validaEmail();
  }
}

function validaCnpj() {
                 CNPJ = document.getElementById("cnpj").value;
                 erro = new String;
                 if (CNPJ.length < 18) erro += "? necessario preencher corretamente o n?mero do CNPJ! \n\n"; 
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                 if (erro.length == 0) erro += "? necess?rio preencher corretamente o n?mero do CNPJ! \n\n";
                 }
                 //substituir os caracteres que n?o s?o n?meros
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x; 
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
              }
               var nonNumbers = /\D/;
              if (nonNumbers.test(CNPJ)) erro += "A verifica??o de CNPJ suporta apenas n?meros! \n\n"; 
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
 			}
              if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]); 
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +="D?gito verificador com problema!";
               }
              if (erro.length > 0){
                       alert(erro);
                       document.getElementById("cnpj").value = "";
                       return false;
               } 
               return true;
 }
 
function validaEmail(){
	var txt = document.getElementById(emails).value;
	if (txt.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) {
		alert("Email incorreto.");
		document.getElementById(emails).value = "";
		return false;
	}
	return true;
}

function validarEmail(email){
	var txt = document.getElementById(email).value;
	if (txt.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) {
		alert("Email incorreto.");
		document.getElementById(emails).value = "";
		return false;
	}
	return true;
}

function fieldToUpperByName(e){
	e.currentTarget.value += String.fromCharCode(e.keyCode).toString().toUpperCase();
}

