/****************************************************************************************
* 
* @desc Javascript onde estão as funções responsáveis em validar os campos dos formulários
* 		e funções auxiliares para o sistema.
*
* @author       Cláudia	Santos  <claudia@compos.com.br>
*				Joel Tadeu 		<joel@compos.com.br>
*				      
* @copyright    Compos 26/01/2005
* @version		1.0
* @access		public 
*
****************************************************************************************/

//--------------------------------------
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function
//--------------------------------------
function validarNome(nome) 
{
	validos = 'qazwsxedcrfvtgbyhnujmikolp1234567890_-';
	pos = 0;
	
	nome = nome.toLowerCase();                         
	if (trim(nome) == '') 
	{
		return false;
	}
	
	for (var indice = 0; indice < nome.length; indice++) 
	{
		pos = 0;
		for (var indiceI = 0; indiceI < validos.length; indiceI++) 
		{
			if (nome.charAt(indice) == validos.charAt(indiceI)) 
			{
				pos++;
			}
		}
		if (pos == 0) 
		{
		  return false;
		}
	}
	return true;
}
//--------------------------------------
// Função para validar Email
function validarEmailDominio(text)
{ 
  var    arroba = "@", 
		 ponto = ".", 
		 virgula = ",",
		 posponto = 0, 
		 posarroba = 0; 
  
  // testa se está vazio
  if (text =="") 
	 return false; 

  // Verifica se existe o simbolo '@' e sua posição
  for (var indice = 0; indice < text.length; indice++)
  { 
	 if (text.charAt(indice) == arroba) 
	 { 
		posarroba = indice; 
		break; 
	 } 
  } 

  // Verifica se existe o simbolo '.' e sua posição
  for (var indice = posarroba; indice < text.length; indice++)
  { 
	 if (text.charAt(indice) == ponto) 
	 { 
		posponto = indice; 
		break; 
	 } 
  } 
  
  // Verifica se existe o simbolo ',' e sua posição
  for (var indice = 0; indice < text.length; indice++)
  { 
	 if (text.charAt(indice) == virgula) 
	 { 
		return false;
		break; 
	 } 
  }
  
  // Verifica a posicão do simbolo '@' em relação  ao simbolo '.'
  if (posponto == 0) 
	 return false; 
  if (posponto == (posarroba + 1)) 
	 return false; 
  if ((posponto + 1) == text.length) 
	 return false; 
  
  return true; 
}
//--------------------------------------
function validarData(Data)
{
	var err = 0;
	var string = Data;
	var valid = "0123456789/";
	var ok = "yes";

	for (var i=0; i<string.length; i++)
	{
		var temp = "" + string.substring(i, i+1);

		if (valid.indexOf(temp) == "-1")
			err = 1;
	}

	if (string.length != 10)
		err = 1;

	dia = string.substring(0, 2);
	barra1 = string.substring(2, 3);
	mes = string.substring(3, 5);
	barra2 = string.substring(5, 6);
	ano = string.substring(6, 10);
	
	if ((dia < 1) || (dia > 31))
		err = 1;
	if (barra1 != '/')
		err = 1;
	
	if ((mes < 1) || (mes > 12))
		err = 1;
	
	if (barra2 != '/')
		err = 1;
	
	if (ano < 0)
		err = 1;
	
	if (mes == 4 || mes == 6 || mes == 9 || mes == 11)
	{
		if (dia == 31)
			err = 1;
	}
	
	if (mes == 2)
	{
		var g = parseInt(ano/4);

		if (isNaN(g))
			err = 1;

		if (dia > 29)
			err = 1;

		if ((dia == 29) && (((ano/4) != parseInt(ano/4))))
			err = 1;
	}

	if (err == 1)
		return(false);
	else
		return(true);
}
//--------------------------------------
function validarEmail(email) { 
	var arroba = "@", 
	ponto = ".", 
	posponto = 0, 
	posarroba = 0; 
  
  	// testa se está vazio
	if (email =="") return false; 

 	validos = 'qazwsxedcrfvtgbyhnujmikolp1234567890@._-';
	pos = 0;
	
	email = email.toLowerCase();                         
	for (var i = 0; i < email.length; i++) 
	{
		pos = 0;
		for (var j = 0; j < validos.length; j++) 
		{
			if (email.charAt(i) == validos.charAt(j)) 
			{
				pos++;
			}
		}
		if (pos == 0) 
		{
		  return false;
		}
	}
	
  	// Verifica se existe o simbolo '@' e sua posição
  	for (var indice = 0; indice < email.length; indice++)
  	{ 
	 	if (email.charAt(indice) == arroba) 
	 	{ 
			posarroba = indice; 
			break; 
	 	} 
  	} 

  	// Verifica se existe o simbolo '.' e sua posição
  	for (var indice = posarroba; indice < email.length; indice++)
  	{ 
		if (email.charAt(indice) == ponto) 
	 	{ 
			posponto = indice; 
			break; 
	 	} 
  	} 
 	// Verifica a posicão do simbolo '@' em relação  ao simbolo '.'
  	if (posponto == 0 || posarroba == 0) 	return false; 
  	if (posponto == (posarroba + 1)) 	return false; 
  	if ((posponto + 1) == email.length) 	return false; 
    
  	return true; 
}
//--------------------------------------
function validarIP1(ip) {

  	validos = '01234567890.';
	
	contPonto = 0;
	
	ip = trim(ip.toLowerCase());                         
	
	for (var i = 0; i < ip.length; i++) 
	{
		pos = 0;

		if (ip.charAt(i) == '.') {
			contPonto++;
		}

		for (var j = 0; j < validos.length; j++) 
		{
			if (ip.charAt(i) == validos.charAt(j)) 
			{
				pos++;
			}
		}
		if (pos == 0) 
		{
		  return false;
		}
	}
	
	if (contPonto != 3) {
		return false;
	}
	
	reIP = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;


	if (!reIP.test(ip)) {
		return false;
	}
	
	return true;
}
//--------------------------------------
function validarIP(IPvalue) {
	errorString = ""; 
	theName = "IPaddress"; 

	var ipArray=IPvalue.split(".");

	if (IPvalue == "0.0.0.0") 
  		//errorString = erroralert('rere');
  		return true;
		
	else if (IPvalue == "255.255.255.255") 
  		//errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.(5)'; 
		return false;
	if (!ipArray||!ipArray[0]||!ipArray[1]||!ipArray[2]||!ipArray[3]||ipArray.length>4) 
  		//errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.(1)'; 
		return false;
	else { 
		for (i = 0; i < 4; i++) { 
    		thisSegment = ipArray[i]; 
    		if (thisSegment > 255) { 
      			//errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.(2)'; 
				return false;
      			i = 4; 
    		} 
    		if ((i == 0) && (thisSegment > 255)) { 
      			//errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.(3)'; 
				return false;
      			i = 4; 
    		} 
  		} 
	} 
	extensionLength = 3; 
 	return true; 
} 
//--------------------------------------
function validarPorta(porta) {
	
	porta = trim(porta.toLowerCase());
	
	validos = '1234567890';
	
	for (var i = 0; i < porta.length; i++) 
	{
		pos = 0;

		for (var j = 0; j < validos.length; j++) 
		{
			if (porta.charAt(i) == validos.charAt(j)) 
			{
				pos++;
			}
		}
		if (pos == 0) 
		{
		  return false;
		}
	}
	
	return true;
}
//--------------------------------------
function sairSistema() {
	document.forms[0].acao.value = 'SAIR';
	document.forms[0].submit();
}
//--------------------------------------
function mensagem(texto) {
	
	browsername = navigator.appName;
	
	if (browsername == 'Microsoft Internet Explorer') {
		window.open("../home/mensagem.php?mensagem=" + texto + "","Mensagem","scrollbars=no,left=300,top=300,width=300,height=122");
	} else {
		window.open("../home/mensagem.php?mensagem=" + texto + "","Mensagem","scrollbars=no,screenX=300,screenY=300,width=300,height=122");
	}
}
//--------------------------------------
function validarCamposDominio(campo) {

	campo = trim(campo.toLowerCase());	
	
	if (campo == '-1') {
		
		return true;
	}

	if ((campo.charAt(0) == '0') && (campo.length > 1)) {
	
		return false;
	}
	
	validos = '0123456789';
	
	for (var i = 0; i < campo.length; i++) 
	{
		pos = 0;

		for (var j = 0; j < validos.length; j++) 
		{
			if (campo.charAt(i) == validos.charAt(j)) 
			{
				pos++;
			}
		}
		if (pos == 0) 
		{
		  return false;
		} 
	}
	
	if (pos != 0)
		return true;
		
	return false;
}
//--------------------------------------
function validarNumero(campo) {

	campo = trim(campo);
	
	validos = '0123456789';
	
	for (var i = 0; i < campo.length; i++) 
	{
		pos = 0;

		for (var j = 0; j < validos.length; j++) 
		{
			if (campo.charAt(i) == validos.charAt(j)) 
			{
				pos++;
			}
		}
		if (pos == 0) 
		{
		  return false;
		} 
	}
	
	if (pos != 0)
		return true;
		
	return false;
}
//--------------------------------------
function validarHora(campo) {

	if (validarNumero(campo)) {
		
		if (campo<0 || campo>23) {
			return false;
		} 
		
	} else {
		return false;
	}
	
	return true;

}
//--------------------------------------
function validarMinuto(campo) {

	if (validarNumero(campo)) {
		
		if (campo<0 || campo>59) {
			return false;
		} 
		
	} else {
		return false;
	}
	return true;
}
//--------------------------------------
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|co|uk|es)$/;
//--------------------------------------
function validarDominio(FormField,NoWWW,CheckTLD) {
	// NoWWW y CheckTLD son opcionales, ambos aceptan los valores true, false, y null.
	// NoWWW se utiliza para verificar que un nombre de dominio no comience con 'www.', ejem. para WHOIS.
	DomainName=FormField.value.toLowerCase();
	if (CheckTLD==null) {CheckTLD=true}
	var specialChars="/\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=DomainName.split(".");
	var len=domArr.length;
	if (len==1) { FormField.focus(); return false}
	for (i=0;i<len;i++) {if (domArr[i].search(atomPat)==-1) { FormField.focus(); return false}}
	if ((CheckTLD) && (domArr[domArr.length-1].length!=2) && (domArr[domArr.length-1].search(knownDomsPat)==-1)) { FormField.focus(); return false}
	if ((NoWWW) && (DomainName.substring(0,4).toLowerCase()=="www.")) { FormField.focus(); return false}
	return true;
}
//--------------------------------------
function FSfncValidateEmailAddress (FormField,CheckTLD) {
	// CheckTLD es opcionalis optional, acepta los valores true, false, y null.
	emailStr = FormField.value.toLowerCase()
	if (CheckTLD==null) {CheckTLD=true}
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {alert(FormField.title + " parece ser incorrecta (Compruebe arroba (@) y puntos (.))"); FormField.focus(); FormField.focus(); return false}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {if (user.charCodeAt(i)>127) {alert(FormField.title + ": nombre de usuario contiene caracteres inválidos"); return false}}
	for (i=0; i<domain.length; i++) {if (domain.charCodeAt(i)>127) {alert(FormField.title + ": nombre de dominio contiene caracteres inválidos"); FormField.focus(); return false}}
	if (user.match(userPat)==null) {alert(FormField.title + ": nombre de usuario no es válido."); FormField.focus(); return false}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {for (var i=1;i<=4;i++) {if (IPArray[i]>255) {alert(FormField.title + ": dirección IP no es válida"); FormField.focus(); return false}}; return true}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {if (domArr[i].search(atomPat)==-1) {alert(FormField.title + ": nombre de dominio no es válido."); FormField.focus(); return false}}
	if ((CheckTLD) && (domArr[domArr.length-1].length!=2) && (domArr[domArr.length-1].search(knownDomsPat)==-1)) {alert(FormField.title + ": debe terminar en dominio bien conocido o país de dos letras."); FormField.focus(); return false}
	if (len<2) {alert(FormField.title + ": le falta un nombre de anfitrión"); FormField.focus(); return false}
	return true;
}
//--------------------------------------
function marcarLista(objeto) {

	srcLen = objeto.options.length;
	if (srcLen != 0) {
		for (var x=0; x<srcLen; x++) 
		{
			objeto.options[x].selected="true";
		}
	}
}
//--------------------------------------
function desmarcarLista(objeto) {

	srcLen = objeto.options.length;
	if (srcLen != 0) {
		for (var x=0; x<srcLen; x++) 
		{
			objeto.options[x].selected="false";
		}
	}
}
//--------------------------------------
function retornaExtensao(imagem) 
{
	tam = imagem.length;
	imagem = imagem.toLowerCase();
	extensao = imagem.substring(tam-3,tam);

	return extensao;   
}
//--------------------------------------
// Retorna se a extensao é valida ou não para ser inserido no banco
function validarImagem(imagem) 
{

	varExt = new Array();
	varExt [0] = "gif";
	varExt [1] = "png";
	varExt [2] = "jpg";
	varExt [3] = "jpeg";
	
	extensao = retornaExtensao(imagem);
	for (k=0; k < 5; k++) {
	   if (extensao == varExt[k]) {
		  return true;
	   }
	}
	return false;
}
//--------------------------------------
function textCounter(field,maxlimit)
{
  if (field.value.length > maxlimit) // if too long...trim it! 
  { field.value = field.value.substring(0, maxlimit); }
}
//--------------------------------
function validaTecla(event)	{
	var BACKSPACE= 8;
	var key;
	var tecla;

	CheckTAB=true;
	if(navigator.appName.indexOf("Netscape")!= -1) 
	  tecla= event.which; 
	else
	  tecla= event.keyCode;
	  
	key = String.fromCharCode(tecla);
	if ( tecla == 39 ) return (false);
	if ( tecla == BACKSPACE ) return (true);
	return (true);
} 
//---------------------------
function isNum( caractere,charFormat ){
  var charlib="";
  if (charFormat==-1)  // Moeda - com valores negativos
    { charlib="-,"; }
  else if (charFormat==0)  // Moeda
    { charlib=","; }
  else if (charFormat==1)  // CEP/Telefone
    { charlib="-"; }
  else if (charFormat==2)  // Hora
    { charlib=":"; }
  else if (charFormat==3)  // Data
    { /* charlib="/"; */ }
  if (charFormat==4)  // Número entre 0 e 9
    { charlib=""; }
  if (charFormat==5)  // Quant
    { charlib=","; }
  if (charFormat.length>1)  // Definiu a limitação
    { charlib=charFormat; }

  var strValidos = charlib+"0123456789"
  if ( strValidos.indexOf( caractere ) == -1 ) return false;
  return true;
}
//--------------------------
function validaNum(campo, event,charFormat){
  var BACKSPACE= 8;
  var key;
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla= event.which;
  else
    tecla= event.keyCode;
  if ( tecla == 46 && charFormat==5 )  {
    if(navigator.appName.indexOf("Netscape")!= -1)
      event.which=44;
    else
      event.keyCode=44;
    tecla=44;
  }
  key = String.fromCharCode( tecla);
  if ( tecla == 13 ) { return false; }
  if ( tecla == BACKSPACE ) return true;
  return ( isNum(key,charFormat));
}
//--------------------------
var AgntUsr=navigator.userAgent.toLowerCase();
//---------------------------
/*
function CarregaCombo(campo,consulta,combo,consulta2,campo2) {
  inicializaSplash();
	remove_tudo(combo);
	var NavYes=AgntUsr.indexOf('mozilla')!=-1&&AgntUsr.indexOf('compatible')==-1?1:0;
	c_iframe=NavYes? document.getElementById("sframe") : document.all.sframe
	c_iframe.src="utcombo.php?nomecampo="+campo.name+"&id="+campo.value+"&id2="+campo2+"&consulta="+consulta+"&combo="+combo+"&cons2="+consulta2;
}
*/
//---------------------------
//CarregaCombo(document.forms[0].sbgrupo,'".$consprod."','produto','',this.value
function CarregaCombo() {
  inicializaSplash();

	var indice=0, cont=0;
	var vetor= new Array();
	while(cont < arguments.length) {		
		vetor[indice]=new Array();
		vetor[indice]['campo']=arguments[cont];
		cont++;
		vetor[indice]['consulta']=arguments[cont];
		cont++;
		vetor[indice]['combo']=arguments[cont];
  	remove_tudo(arguments[cont]);
		cont++;
		vetor[indice]['consulta2']=arguments[cont];
		cont++;
		vetor[indice]['campo2']=arguments[cont];
		cont++;
		indice++;
	}
	var NavYes=AgntUsr.indexOf('mozilla')!=-1&&AgntUsr.indexOf('compatible')==-1?1:0;
	c_iframe=NavYes?document.getElementById("sframe") : document.all.sframe
	var aux="utcombo.php?";
	for (var i = 0; i < vetor.length; i++){
		aux=aux+
		"nomecampo["+i+"]="+vetor[i]['campo'].name+
		"&id["+i+"]="+vetor[i]['campo'].value+
		"&consulta["+i+"]="+vetor[i]['consulta']+
		"&combo["+i+"]="+vetor[i]['combo']+
		"&cons2["+i+"]="+vetor[i]['consulta2']+
		"&id2["+i+"]="+vetor[i]['campo2']+"&";
	}
	c_iframe.src=aux;	
}
//---------------------------
function adiciona(texto,valor,objeto) {
	linha = document.createElement("OPTION");
	linha.text = texto;
	linha.value = valor;
	document.forms[0].elements[objeto].options.add(linha);
}
//---------------------------
function remove_tudo(objeto) { //Limpa a combo
	var tam = document.forms[0].elements[objeto].length;
	while( tam > 0 ) { document.forms[0].elements[objeto].remove(tam-1); 	tam--;	}
}
//---------------------------
/*function PegaValor(campo,consulta,objeto,valordefault,campo2,consulta2,objeto2,valordefault2,campo3,consulta3,objeto3,valordefault3) {
  inicializaSplash();
	var NavYes=AgntUsr.indexOf('mozilla')!=-1&&AgntUsr.indexOf('compatible')==-1?1:0;
	c_iframe=NavYes? document.getElementById("sframe") : document.all.sframe
	c_iframe.src="utbusca.php?id="+campo+"&consulta="+consulta+"&objeto="+objeto+"&valordefault="+valordefault+"&id2="+campo2+"&consulta2="+consulta2+"&objeto2="+objeto2+"&valordefault2="+valordefault2+
	"&id3="+campo3+"&consulta3="+consulta3+"&objeto3="+objeto3+"&valordefault3="+valordefault3;
}*/
function PegaValor() {
	inicializaSplash();
	var indice=0;
	var cont=0;
	var vetor= new Array();
	while(cont < arguments.length) {		
		vetor[indice]=new Array();
		vetor[indice]['campo']=arguments[cont];
		cont++;
		vetor[indice]['consulta']=arguments[cont];
		cont++;
		vetor[indice]['objeto']=arguments[cont];
		cont++;
		vetor[indice]['default']=arguments[cont];
		cont++;
		vetor[indice]['campo2']=arguments[cont];
		cont++;
		indice++;
	}
	var NavYes=AgntUsr.indexOf('mozilla')!=-1&&AgntUsr.indexOf('compatible')==-1?1:0;
	c_iframe=NavYes?document.getElementById("sframe") : document.all.sframe
	var aux="utbusca.php?";
	for (var i = 0; i < vetor.length; i++){
		aux=aux+"id["+i+"]="+vetor[i]['campo']+
		"&consulta["+i+"]="+vetor[i]['consulta']+
		"&objeto["+i+"]="+vetor[i]['objeto']+
		"&default["+i+"]="+vetor[i]['default']+
		"&id2["+i+"]="+vetor[i]['campo2']+"&";
	}
	c_iframe.src=aux;	
}
//---------------------------
function SetaCampo(valor,objeto) {
	while(valor.indexOf('<br>')!=-1)
	{ valor=valor.replace( "<br>", "\n" ); }
  document.forms[0].elements[objeto].value=valor; 

	if(objeto=="tipotabela") { EnabledTipo(); }
}
//---------------------------
function ValidaHora(CHora) {
  //--CHora em formato HH:MM:SS
  if (CHora.value!="") {
		hr = (CHora.value.substring(0,2));
		min = (CHora.value.substring(3,5));
		//seg = (CHora.value.substring(6,10));
		
		situacao = 1;
		// verifica se a hora é válida
		if (hr < 00 || hr > 23)
		  { situacao = 0; }

		// verifica se o min e válido
		if (min < 00 || min > 59 )
		  { situacao = 0; }

		// verifica se e o segundo é válido
		//if (seg< 00 || seg > 59)
		//  { situacao = 0; }
		
		if (CHora.value == "")  { situacao = 0; }

		if (situacao == 0)
		{
		  alert("Hora inválida! Entre Hora no formato hh:mm"); //hh:mm:ss
		  CHora.focus();
		}
	}	
}
//-----------------------------------------
function ValidaCpfCnpj(CThis)
{
  var soma=0
  var Resto=0
  var x=0
  var st=CThis.value
  if (st.length==0)       // Vazio
    { return (true); }
  else if (st.length==11) // CPF
  {
    for (x = 1 ; x < 10 ; x++)
      { soma=soma+parseInt(st.substring(x-1,x)) * (11 - x) }
    Resto = 11 - (soma - (parseInt(soma / 11) * 11))
    if (Resto==10 || Resto==11) {Resto=0}
    if (parseInt(Resto)!=parseInt(st.substring(9, 10)))
    {
      alert("Formato inválido para \"CPF\". ");
      CThis.value=""
      CThis.focus();
      return (false);
    }
    soma = 0
    for (x = 1 ; x < 11 ; x++)
      { soma=soma+parseInt(st.substring(x-1,x)) * (12 - x) }
    Resto = 11 - (soma - (parseInt(soma / 11) * 11))
    if (Resto == 10 || Resto == 11) {Resto = 0}
    if (parseInt(Resto)!= parseInt(st.substring(10,11)))
    {
      alert("Formato inválido para \"CPF\". ");
      CThis.value=""
      CThis.focus();
      return (false);
    }
    return (true);
  }

  else if (st.length==14) // CNPJ
  {
    var Retorno=0
    var A=0
    var j=5
    var i=0
    var d1=0
    var d2=0
		
   for (x = 1; x < 13 ; x++)
   {
     A = A + (parseInt(st.substring(x-1,x)) * j)
     if (j>2) {j = j - 1} else {j= 9}
   }
   A = A%11

   if (A>1) {d1 = 11 - A} else {d1 = 0}
   A = 0
   i = 0
   j = 6
    for (x = 1; x < 14 ; x++)
      {
      A = A + (parseInt(st.substring(x-1,x)) * j)
      if (j>2) {j = j - 1} else  {j= 9}
      }
    A = A % 11

    if(A >1 ) 
		{ d2=11-A; }
		else
		{ d2=0; }
		
    if (d1 == parseInt(st.substring(12, 13)) && d2 == parseInt(st.substring(13, 14)))
    { return (true); }
		else
		{
      alert("Formato inválido para \"CNPJ\". ");
      CThis.value=""
      CThis.focus();
      return (false);
		}
  }

  alert("Número de caracteres inválidos para \"CPF-CNPJ\". ");
  CThis.focus();
  return (false);
}
//--------------------------
/**
* @desc Função responsável em formatar o objeto passado como parametro
*		para o padrao desejado (Mascara para o campos).
*
* @param Object  objeto		- Objeto do formulario HTML
* @param Integer tipo		- Tipo de Formatação desejada
* @param Char  teclapres	- tecla pressionada
* @return void
* @example 					0 - Formata campo para Data Completa  	(dd/mm/yyyy)
*							1 - Formata campo para Telefone 		(xx)3674738
*							2 - Formata campo para horário  		(hh:mm)
*							3 - Formata campo para Data simples		(mm/yyyy)
*
*/
function FormataDado(objeto,tipo,teclapres){
	var tecla = teclapres.keyCode;
	vr = objeto.value;
	tam = vr.length;
	if (tipo==0){
		if(tam==3 && vr.charAt(2)!='/'){/*Adicionando uma '/' quando ela foi apagada*/
			aux=vr.charAt(2);
			objeto.value = vr.substring(0,2)+'/'+aux;
		}
		if(tam==6 && vr.charAt(5)!='/'){/*Adicionando uma '/' quando ela foi apagada*/
			aux=vr.charAt(5);
			objeto.value = vr.substring(0,5)+'/'+aux;
		}
		if (tam!=3) vr = vr.replace( "/", "" );
		if (tam>6) vr = vr.replace( "/", "" );
		tam = vr.length;
		if (tecla!=8){	
			 if (tam==2) {
				objeto.value = objeto.value+ '/';
			 }
			else if (tam==4) {
				objeto.value = objeto.value+ '/';
			}
		}
	}
	else if (tipo==1){
		if (tam!=3) vr = vr.replace( ")", "" );
		tam = vr.length;
		if (tecla!=8){	
			 if (tam==2) {
				objeto.value="("+objeto.value+")";
			 }
		}
	} else if (tipo==2) {
		if (tam!=3) vr = vr.replace( ":", "" );
		tam = vr.length;
		if (tecla!=8){	
			 if (tam==2) {
				objeto.value = objeto.value+ ':';
			 }
		}
	}else if (tipo==3){
		if (tam!=3) vr = vr.replace( "/", "" );
		tam = vr.length;
		if (tecla!=8){	
			 if (tam==2) {
				objeto.value = objeto.value+ '/';
			 }
		}
	} 
}

/**
* @desc Função responsável em formatar valores monetários (1.456,92)
*
* @param Object  objeto		- Objeto do formulario HTML
* @param Integer tammax		- Tamanho máximo do campo
* @param Char  teclapres	- tecla pressionada
* @return void
*
*/
function FormataValor(objeto,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = objeto.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		objeto.value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		objeto.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		objeto.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		objeto.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) ){
	 		objeto.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) ){
	 		objeto.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 ) ;}
	}
}

//--------------------------
//** Formata no padrão brasileiro para moeda. ex:  1.200,00 ou 1200,00 => 1.200,00
function formata_numero(numero){
  numero = numero.toString();
  if ((numero==null) || (numero==''))  { return "0,00"; }
	numero = numero.replace("." , "_");
	numero = numero.replace("," , ".");
	numero = numero.replace("_" , ",");

  if(numero.indexOf(",")==-1) { numero = numero+",00"; }
	div=numero.split(",");
	inteiro=div[0];
	decimal=div[1];
	if(decimal.length<2) { numero = numero+"0";	}
	
	if(numero.length>6 && numero.indexOf(".")==-1) {
		divmil=((inteiro.length/4)+1);
		numero="";
    for(i=0;i<divmil;i++) {
		  posfim=(inteiro.length-(3*i));
			posini=(posfim-3);
			if(posini<0){posini=0;}
			num=inteiro.substring(posini,posfim);
			if(numero!="" && num!="") { numero="."+numero; }
		  numero=num+numero;
		}
		inteiro=numero;
	}
	if(decimal.length<2) { decimal=decimal+"0";	}
	if(decimal.length>2) { decimal=decimal.substring(0,2)	}
  numero=inteiro+","+decimal;
  return numero;
}
//--------------------------
//** Converte no padrão americao para moeda. ex: 1.200,00 => 1200.00
function converte_numero(numero){
  if ((numero==null) || (numero=='') || (numero==0))  { return "0.00"; }
  string_ponto = numero.toString();
  numero = numero.toString();
  posicao_ponto = string_ponto.indexOf(",");
  if (posicao_ponto!= -1) {
    numero = numero.replace("." , "");
    numero = numero.replace("," , ".");
  }
  return numero;
}
//===========================
//** Autosearch combobox / Java Script to Handle AutoSearch
//** Funções para pesquisa no combo, ao digitar texto
//===========================
document.write("<INPUT type=hidden name=keys size=0>");
function selectKeyDown(){
    // Delete Key or ESC resets previous search keys
    if(window.event.keyCode == 46 || window.event.keyCode == 27)
    { clr(); }
}
//---------------------------
function selectKeyPress(){
    // Notes:
    //    1) previous keys are cleared onBlur/onFocus and with Delete key
    //    2) if the search doesn't find a match, this returns to normal 1 key 
    //       search setting returnValue = false below for ALL cases will 
    //       prevent default behavior
    
    //TODO:
    //    1) add Netscape handling

    var sndr = window.event.srcElement;
    var pre = this.document.all["keys"].value;
    var key = window.event.keyCode;
    var charto = String.fromCharCode(key);
    // "i" -> ignoreCase
    var re = new RegExp("^" + pre + charto, "i"); 
    for(var i=0; i<sndr.options.length; i++) {
        if(re.test(sndr.options[i].text)) {
          sndr.options[i].selected=true;
          document.all["keys"].value += charto;
          window.event.returnValue = false;
          break;
        }
    }
		
}
//---------------------------
function clr()
{ document.all["keys"].value = ""; }
//===========================
function posicionarCursor(){
 	if(document.forms.length>0) {
		for (i=0;i<document.forms[0].elements.length;i++) {
			if(document.forms[0].elements[i].type=="text" || document.forms[0].elements[i].type=="select-one" || document.forms[0].elements[i].type=="select" || document.forms[0].elements[i].type=="textarea"){
			  if(document.forms[0].elements[i].disabled==false){
      		document.forms[0].elements[i].focus(); 
  				break;
				}	
			}	
		}	
	}
}
//---------------------------
// ScriptX.cab
//--------------------------
function getSettings(){
  with ( factory.printing )  {
    idHeader.value = header;
    idFooter.value = footer;
    idPortrait.checked = portrait;
	  idSize.value = size;
    idLeft.value = leftMargin;
    idTop.value = topMargin;
    idRight.value = rightMargin;
    idBottom.value = bottomMargin;
  }
}
//----------------------------
function doPrint(frame){
  window.status = "Definindo Margens";
  DefineMargens()      // set settings - print and get settings when done
  window.status = "Enviando Impressão";
  factory.printing.Print(false, frame);
  window.status = "";
}
//----------------------------
function doPrint2(frame){
  window.status = "Definindo Margens";
  DefineMargens()      // set settings - print and get settings when done
  window.status = "Enviando Impressão";
  factory.printing.Print(true, frame);
  window.status = "";
}
//----------------------------
function abrirJanela(url){
  win=window.open(url,"Ambiente","toobar=no,location=no,directories=no,status=1,menubar=no,resizable=yes,scrollbars=yes,left=0,top=0,width=800,height=600")
//  win=window.open(url,"Ambiente","toolbar=no,location=no,directories=no,status=no,menubar=yes,resizable=yes,scrollbars=yes,left=0,top=0,width=800,height=600")
	win.focus();
}
//---------------------------
function abrirJanela2(url){
//  win=window.open(url,"Ambiente","toobar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes,left=0,top=0,width=800,height=600")
  win=window.open(url,"Ambiente","toolbar=yes,location=no,directories=no,status=1,menubar=yes,resizable=yes,scrollbars=yes,left=0,top=0,width=800,height=600")
	win.focus();
}
//---------------------------
function enviar(idioma){
  
	var ret=validarFormulario(form,idioma);
	if(ret){
		document.forms[0].act.value='enviar';
		document.forms[0].submit();
	}else{
	  return false;
	}
}
