// +----------------------------------------------------+
// | Define como a propriedade display de um bloco (DIV)|
// | tem que ser setada de acordo com o browser utiliza-|
// | do.                                                |
// +----------------------------------------------------+
var browser = navigator.appName;
var	MOSTRAR;
if (browser=="Microsoft Internet Explorer") 
	MOSTRAR = "block";
else
	MOSTRAR = "inherit";

// +--------------------------------------------------------+
// | Function: checkEnter                                   
// | Verifica se a tecla ENTER foi pressioanda.             
// |                                                        
// | Parameters:                                            
// | _oTecla - código da tecla apertada.                      
// |                                                        
// | Returns:                                               
// | Retorna TRUE caso a tecla apertada seja ENTER ou FALSE 
// | caso contrário                                         
// +--------------------------------------------------------+
function checkEnter(_oTecla)
{
	if(typeof(_oTecla) == 'undefined')
		var _oTecla = window.event;
	
	var codigo = (_oTecla.which ? _oTecla.which : _oTecla.keyCode ? _oTecla.keyCode : _oTecla.charCode);
	
	return (codigo == 13);
}

// +-----------------XMLHttpRequest---------------------+
// | Esta funcao cria o objeto XMLHttpRequest de acordo |
// | com o browser usado.                               |
// +----------------------------------------------------+
function getXmlHttpRequest() 
{
	try
  	{
		// Firefox, Opera 8.0+, Safari
		return new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
	    {
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
  		catch (e)
		{
			try
			{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Seu browser não suporta AJAX!");
				return false;
			}
		}
	}
}

// +----------------showErrorXmlHttpRequest-----------------+
// | Essa funcao mostra uma mensagem de erro e seta o pro-  |
// | cesso como inativo, caso o STATUS do XMLHTTPREQUEST    |
// | seja um erro.                                          |
// +--------------------------------------------------------+
function showErrorXmlHttpRequest()
{
	Loader.removeLoader(true);
	criarAviso("erro", "ok", "Erro: " + xmlhttp.status + " - " + xmlhttp.statusText, false, 350, 110);
	ProcessoAtivo = false;
}

// +------------------------controller----------------------+
// | Dispara uma função na camada de controle de acordo com |
// | a URL passada como parâmetro. Caso sXML não seja vazia |
// | prepara o XMLHTTPREQUEST para o seu envio. Usa a função|
// | FUNCAO passada como parâmetro como retorno alterando o |
// | metodo onreadystatechange do objeto HTTPRequest.       | 
// +--------------------------------------------------------+
function controller(_sMetodo, _sXML, _sUrl, _sMsg, _funcao, _sPosicao)
{
	if (!ProcessoAtivo && xmlhttp) 
	{
		if (_sMsg != "")
		{
		    criaDivs();
		    Loader.createLoader("div_carregando", _sMsg, imgLoader.src, 230, _sPosicao);
		}
		ProcessoAtivo = true;
		xmlhttp.open(_sMetodo, _sUrl, true);
		xmlhttp.onreadystatechange = _funcao;
		if (_sXML != '')
		{
			xmlhttp.setRequestHeader("Encoding", "ISO-8859-1");
			xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
			xmlhttp.setRequestHeader("Content-length", _sXML.length);
			xmlhttp.setRequestHeader("Pragma", "no-cache");
			xmlhttp.send(_sXML);
		}
		else
			xmlhttp.send(null);
	}	
}

// +---------------------obterAjuda-------------------------+
// | Esta funcao exibe as mensagens de ajuda que estão no   |
// | vetor sMsgAjuda que é definido no arquivo msgs_ajuda.js|
// | Para que a função funcione corretamente, é necessária  |
// | a criação de um DIV com id igual a 'ajuda' e dentro do |
// | DIV um SPAN com id igual a 'ajuda_texto'.              |
// +--------------------------------------------------------+
function obterAjuda(sNome)
{
	$('#ajuda').show();
	$('#ajuda_texto').html(sMsgAjuda[sNome]);
}

// +------------------checkEnter------------------------+
// | Verifica se a tecla ENTER foi pressioanda.         |
// +----------------------------------------------------+
function checkEnter(tecla)
{
	if(typeof(tecla) == 'undefined')
		var tecla = window.event;
	
	var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);
	
	return (codigo == 13);
}

// +---------------------------error------------------------+
// | Essa função faz cria um tipo abstrado de dados ERROR.  |
// | Essa TAD será usada pra controlar os erros existentes  |
// | no preenchimento do formulário, para que no momento de |
// | submeter os dados, novas verificações não sejam feitas.|
// | As funções que tratam esse TAD são a insereErro e a    |
// | função retiraErro. Tem os atributos:                   |
// | * nome = nome do campo no form onde existe um erro.    |
// | * confirma = recebe 1 quando o erro é encontrado e 0   |
// |              quando o erro é corrigido.                |
// +--------------------------------------------------------+
function error(_sName, _bConfirm)
{
	this.sName = _sName;
	this.bConfirm = _bConfirm;
}



// +------------------------zerarCampo----------------------+
// | Função que recebe um campo de um formulário e altera   |
// | suas propriedades de fundo e de cor da fonte. Utilizada|
// | para zerar campos com erros após tentativa de submissão|
// | dos valores.                                           |
// +--------------------------------------------------------+
function zerarCampo(oObj)
{
	oObj.style.background = '#FFFFFF';
	oObj.style.color = 'black';
}

// +----------------------prepararForm----------------------+
// | Define os eventos dos campos de acordo com as proprie- |
// | dades: datatype, allownull e help;
// +--------------------------------------------------------+
function prepararForm()
{
	$("select[allownull='false']").focus( function ()
		{
			zerarCampo(this);
		});

	$("textarea[allownull='false']").focus( function ()
		{
			zerarCampo(this);
		});

	oInput = $("input[allownull='false']");
	oInput.keypress( function (e)
		{
			zerarCampo(this);
		});

	var oInput = $("input[datatype='data']");
	if (oInput.length > 0)
	{	
	    oInput.keypress( function (e)
		    {
			    InputMascaraData(this, 8, e);
			    return InputSomenteNum(e);
		    });
	    oInput.keydown( function (e)
		    {
			    return InputSomenteNum(e);
		    });
	    oInput.change( function (e)
		    {
			    InputMascaraData(this, 8, e);
		    });
	    oInput.blur( function ()
		    {
			    verificaData(this.value);
		    });	
	}
	
	oInput = $("input[datatype='number']");
	if (oInput.length > 0)
	{		
	    oInput.keypress( function (e)
		    {
			    return InputSomenteNum(e);
		    });
	    oInput.keydown( function (e)
		    {
			    return InputSomenteNum(e);
		    });
    }
    
	oInput = $("input[datatype='cpf']");
	if (oInput.length > 0)
	{		
	    oInput.keypress( function (e)
		    {
			    InputMascaraCPF(this, 11);
			    return InputSomenteNum(e);
		    });
	    oInput.keydown( function (e)
		    {
			    return InputSomenteNum(e);
		    });
	    oInput.change( function (e)
		    {
			    InputMascaraCPF(this, 11);
		    });
		// ESSA FUNCAO NAO DEVE FICAR AQUI -> ACESSA A SEGUNDA CAMADA E 
		// A FUNCAO verificaCPF NAO FAZ PARTE DESSE ARQUIVO (quatre_lib.js)    
	    oInput.blur( function ()
		    {
			    verificaCPF(this.value);
		    });	
    }

	oInput = $("input[datatype='cnpj']");
	if (oInput.length > 0)
	{		
	    oInput.keypress( function (e)
		    {
			    InputMascaraCNPJ(this, 14);
			    return InputSomenteNum(e);
		    });
	    oInput.keydown( function (e)
		    {
			    return InputSomenteNum(e);
		    });
	    oInput.change( function (e)
		    {
			    InputMascaraCNPJ(this, 14);
		    });
    }
    
	oInput = $("input[datatype='cep']");
	if (oInput.length > 0)
	{		
	    oInput.keypress( function (e)
		    {
			    InputMascaraCEP(this, 8);
			    return InputSomenteNum(e);
		    });
	    oInput.keydown( function (e)
		    {
			    return InputSomenteNum(e);
		    });
	    oInput.change( function (e)
		    {
			    InputMascaraCEP(this, 8);
		    });
	    oInput.blur( function ()
		    {
			    verificaCEP(this.value);
		    });	
	}
	
	oInput = $("input[help='true']");
	if (oInput.length > 0)
	{
	    oInput.focus ( function ()
		    {
			    obterAjuda(this.name);
		    });	
    }
    
	oInput = $("input[help='false']");
	if (oInput.length > 0)
	{
	    oInput.focus ( function ()
		    {
			    $('#ajuda').hide();
		    });	
    }	
}

// +-----------------------pegaCidades----------------------+
// | Dispara uma função na segunda camada que buscará uma   |
// | lista contendo as cidades do estado passado como para- |
// | mêtro. Usa a função handleHttpRespCidades como retorno |
// | alterando o método onreadystatechange do objeto        |
// | HTTPRequest.                                           | 
// +--------------------------------------------------------+
function pegaCidades(sEstado)
{
	if (sEstado != "")
	{
		$("#selectCidades").hide();
		$("#carregando").show();
		controller("GET", "", "../cidades.asp?sEstado=" + sEstado, "", handleHttpRespCidades,"center");
	}
	else
	{
		$("#selectCidades").html("<select name='cidade' id='cidade' help='false' xml='true'><option value=''>-------------------------</option></select>");
		$("#selectCidades").show();
	}
}

function pegaCidades2(sEstado, sCidade)
{
	if (sEstado != "")
	{
		$("#selectCidades").hide();
		$("#carregando").show();
		controller("GET", "", "../cidades2.asp?sEstado=" + sEstado + "&sCidade="+ sCidade, "", handleHttpRespCidades,"center");
	}
	else
	{
		$("#selectCidades").html("<select name='cidade' id='cidade' help='false' xml='true'><option value=''>-------------------------</option></select>");
		$("#selectCidades").show();
	}
}
// +-------------------handleHttpRespCidades----------------+
// | Esta função é colocada no método onreadystatechange do |
// | objeto HTTPRequest quando a função pegaCidades é dispa-|
// | rada. Recebe o HTML ou XML impresso pelo objeto e faz  |
// | o tratamento dessa saída.                              |
// +--------------------------------------------------------+
function handleHttpRespCidades()
{
	if (xmlhttp.readyState == 4) 
	{
		if (xmlhttp.status == 200) 
		{
			if (xmlhttp.responseText.indexOf('invalid') == -1) 
			{		        
		        $("#selectCidades").html(xmlhttp.responseText);
		        $("#carregando").hide();		        
		        $("#selectCidades").show();
				ProcessoAtivo = false;
			}
		}
		else
		    showErrorXmlHttpRequest();
	}
}

// +----------------------verificaFaixa---------------------+
// | Verifica se o valor digitado no campo faixa_salarial_2 |
// | é menor ou igual ao valor do campo faixa_salarial. In- |
// | sere um erro caso positivo, e retira o erro caso nega- |
// | tivo. Utiliza a função formataNumero da biblioteca     |
// | quatre_lib.js.                                         |
// +--------------------------------------------------------+
function verificaFaixaSalarial()
{
	var fValor  = parseFloat(formataNumero(document.getElementById('faixa_salarial')));
	var fValor2 = parseFloat(formataNumero(document.getElementById('faixa_salarial_2')));
	if ( (fValor2 <= fValor) && (fValor2 != 0 || fValor != 0) )
	{
		mostrarErro(document.getElementById('faixa_salarial'), "O limite superior não pode ser menor ou igual ao limite inferior.");
		return false;
	}	
	else
	{
		limparErro(document.getElementById('faixa_salarial'));
		return true;
	}
}

// +---------------------verificaMoeda----------------------+
// | Utiliza a função checkMoeda da biblioteca quatre_lib.js|
// | para validar o campo de faixa salarial. É utilizada nos|
// | campos faixa_salarial e faixa_salarial_2.              |
// +--------------------------------------------------------+
function verificaMoeda(oObj)
{	
	if (StrTrim(oObj.value) != "")
	{
		
		if (checkMoeda(oObj.value))
		{
			oObj.style.color = "black";
			retiraErro(oObj.name);
		}
		else
		{
			mostrarErro(oObj, "O limite superior não pode ser menor que o limite inferior.");
			return false;
		}
	}
}

// +----------------------alterarEstado---------------------+
// | Função recursiva que altera o estado (disabled) de to- |
// | dos os elementos HTML (nodos).                         | 
// +--------------------------------------------------------+ 
function alterarEstado(oObj) 
{
	try 
	{
		oObj.disabled = oObj.disabled ? false : true;
	}
	catch(E){}
	
	if (oObj.childNodes && oObj.childNodes.length > 0) 
	{
		for (var x = 0; x < oObj.childNodes.length; x++) 
		{
			alterarEstado(oObj.childNodes[x]);
		}
	}
}

// +----------------------formataNumero---------------------+
// | Essa função formata o campo numérico passado como para-|
// | metro para o padrão em inglês. Exemplo:                |
// | Entrada: 1.000,00                                      |
// | Saída: 1000.00                                         |
// +--------------------------------------------------------+
function formataNumero(oObj)
{
	var iPosVirgula;
	var iPosPonto;
	var i;
	var sSaida = '';
	
	if (oObj.value.length > 0 )
	{	
		iPosVirgula = oObj.value.indexOf(",",1);
		iPosPonto = oObj.value.indexOf(".",1);
		if (iPosVirgula != -1 || iPosPonto != -1 )
		{
			for (i=0; i < oObj.value.length; i++)
			{
				if(i != iPosPonto && i != iPosVirgula)
					sSaida = sSaida +  oObj.value.charAt(i);	
				else
				{
					if(i == iPosVirgula)
						sSaida = sSaida +  '.';
				}
			}
		}
	}
	if (sSaida == "")
		return oObj.value;
	else
		return sSaida;
}




function getText(oNode)
{
	if (window.ActiveXObject)
	{	
		return oNode.text;
	}
	else
	{
		return oNode.textContent;	
	}
}

function LoadParseXML(sXMLIn)
{
	if (window.ActiveXObject)
	{
		var XML = new ActiveXObject("Microsoft.XMLDOM");
		XML.async = "false";
		XML.loadXML(sXMLIn);
	}
	else
	{
		var parser = new DOMParser();
		var XML = parser.parseFromString(sXMLIn, "text/xml");
	}
	var oDoc = XML.documentElement;	
	return oDoc;
}

// +---------------------------validaSenha---------------------------+
// | Esta função é responsável por validar a senha do usuário.       |
// | Recebe como paramêtro o tamanho mínimo permitido (iTamMin) e    |
// | um objeto contendo a senha digitada.                            |
// +-----------------------------------------------------------------+
function validaSenha(iTamMin, oSenha) 
{
	var sInvalido = " ";
	
	if (oSenha.value.length < iTamMin) 
	{
		return "A senha deve ter pelo menos " + iTamMin + " caracteres.";
	}

	if (oSenha.value.indexOf(sInvalido) > -1) 
	{
		return "Espaços em branco não são permitidos.";
	}
	else 
	{
		return "OK";
	}
}

// +---------------------------validaLogin---------------------------+
// | Esta função é responsável por validar o login do usuário.       |
// | Recebe como paramêtro o tamanho mínimo permitido (iTamMin) e    |
// | um objeto contendo o login digitado.                            |
// +-----------------------------------------------------------------+
function validaLogin(iTamMin, sLogin) 
{
	var sInvalido = " ";
		
	if (sLogin.length < iTamMin) 
	{
		return "O login deve ter pelo menos " + iTamMin + " caracteres.";
	}

	if (sLogin.indexOf(sInvalido) > -1) 
	{
		return "Espaços em branco não são permitidos.";
	}
	
	var verif = false;
	for (var i=0; i < sLogin.length; i++)
	{
		if ( ( (sLogin.charCodeAt(i) >= 48) && (sLogin.charCodeAt(i) <= 57) ) ||
		     ( (sLogin.charCodeAt(i) >= 97) && (sLogin.charCodeAt(i) <= 122) ) ||
		     ( (sLogin.charCodeAt(i) == 45) || (sLogin.charCodeAt(i) == 46) || (sLogin.charCodeAt(i) == 95) ) )
			verif = true;
		else
		{
			verif = false;
			break;
		}
	}
	
	if (!verif)
		return "Somente dígitos e letras minúsculas<BR /> são permitidos.";
	
	return "OK";
}

// +---------------------------InputSomenteNum---------------------------+
// | Esta funcao verifica se o usuario digitou somente numeros.          |
// +---------------------------------------------------------------------+
function InputSomenteNum(tecla)
{
	if(typeof(tecla) == 'undefined')
		var tecla = window.event;
	
	var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);
	
	// permite números, 8=backspace, 46=del e 9=tab
	if ( (codigo >= 48 && codigo <= 57) || (codigo >= 96 && codigo <= 105) || codigo == 8 || codigo == 46 || codigo == 9 )
	{ 
		return true; 
	}
	else
	{ 
		return false; 
	}
}

function InputMascaraDinheiro(fld, milSep, decSep) 
{
	var blnNegativo = (fld.value < 0);
	var sep = 0;
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	
	len = aux.length;
	if (len == 0) 
		fld.value = '0'+ decSep + '00';
	if (len == 1) 
		fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) 
		fld.value = '0'+ decSep + aux;
	if (len > 2)
	{
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--)
		{
			if (j == 3)
			{
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	if (blnNegativo)
	{
		fld.value = "-" + fld.value;
	}
	return fld.value;
}

// +------------------InputMascaraCNPJ----------------------+
// | Funcao que aplica mascara para o campo CNPJ.           |
// +--------------------------------------------------------+
function InputMascaraCNPJ(campo, tammax) 
{
	var vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	var tam = vr.length;
	if (tam < tammax) 
	{ 
		tam = vr.length + 1 ; 
	}
	tam = tam - 1;
	if ( (tam > 2) && (tam <= 5) ) 
	{
		vr = vr.substr( 0, tam - 1 ) + '-' + vr.substr( tam - 1, tam ) ; 
	}
	if ( (tam >= 6) && (tam <= 8) ) 
	{
		vr = vr.substr( 0, tam - 5 ) + '/' + vr.substr( tam - 5, 4 ) + '-' + vr.substr( tam - 1, tam ) ; 
	}
	if ( (tam >= 9) && (tam <= 11) ) 
	{
		vr = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '/' + vr.substr( tam - 5, 4 ) + '-' + vr.substr( tam - 1, tam ) ; 
	}
	if ( (tam >= 12) && (tam < 14) ) 
	{
		vr = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '/' + vr.substr( tam - 5, 4 ) + '-' + vr.substr( tam - 1, tam ) ; 
	}
	campo.value = vr;
}

// +------------------InputMascaraCPF----------------------+
// | Funcao que aplica mascara para o campo CPF.           |
// +-------------------------------------------------------+
function InputMascaraCPF(campo, tammax) 
{
	var vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	var tam = vr.length;
	if (tam < tammax)
	{ 
		tam = vr.length + 1; 
	}
	tam = tam - 1;
	if ( (tam > 2) && (tam <= 11) ) 
	{
		vr = vr.substr( 0, tam - 1 ) + '-' + vr.substr( tam - 1, tam ); 
	}
	if ( (tam == 10) ) 
	{
		vr = vr.substr( 0, tam - 7 ) + '.' + vr.substr( tam - 7, 3 ) + '.' + vr.substr( tam - 4, tam ); 
	}
	campo.value = vr;
}

// +------------------InputMascaraCEP----------------------+
// | Funcao que aplica mascara para o campo CEP.           |
// +-------------------------------------------------------+
function InputMascaraCEP(campo, tammax) 
{
	var vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( ".", "" );
	var tam = vr.length;
	if (tam < tammax) 
	{ 
		tam = vr.length + 1; 
	}
	tam = tam - 1;
	if ( (tam > 2) && (tam <= 8) ) 
	{
		vr = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ); 
	}
	if ( (tam == 7) ) 
	{
		vr = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, tam ); 
	}
	campo.value = vr;
}

// +------------------InputMascaraData---------------------+
// | Funcao que aplica mascara para o campo DATA.          |
// +-------------------------------------------------------+
function InputMascaraData(campo, tammax, tecla) 
{
	if(typeof(tecla) == 'undefined')
	var tecla = window.event;
	var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);
	var vr = campo.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	var tam = vr.length;
	if (tam < tammax) 
	{ 
		tam = vr.length + 1; 
	}
	if (codigo == 8) 
	{ 
		tam = tam - 1; 
	}
	tam = tam - 1;
	if ( (tam >= 2) && (tam < 3) ) 
	{
		vr = vr.substr( 0, tam - 0 ) + '/' + vr.substr( tam - 0, 2 ); 
	}
	if ( (tam >= 3) && (tam < 4) ) 
	{
		vr = vr.substr( 0, tam - 1 ) + '/' + vr.substr( tam - 1, 2 ); 
	}
	if (tam == 4) 
	{
		vr = vr.substr( 0, tam - 2 ) + '/' + vr.substr( tam - 2, 2 ) + '/' + vr.substr( tam - 0, 5 ); 
	}
	if (tam == 5) 
	{
		vr = vr.substr( 0, tam - 3 ) + '/' + vr.substr( tam - 3, 2 ) + '/' + vr.substr( tam - 1, 6 ); 
	}
	if (tam == 6) 
	{
		vr = vr.substr( 0, tam - 4 ) + '/' + vr.substr( tam - 4, 2 ) + '/' + vr.substr( tam - 2, 7 ); 
	}
	if (tam == 7) 
	{
		vr = vr.substr( 0, tam - 5 ) + '/' + vr.substr( tam - 5, 2 ) + '/' + vr.substr( tam - 3, 8 ); 
	}
	campo.value = vr;
}

// +-------------------------StrTrim-----------------------+
// | Funcao que retira os espacos vazios da string.        |
// +-------------------------------------------------------+
function StrTrim(str)
{
	if (isEmpty(str))
	{
		return '';
	}
	str=String(str);
	var iIni,iEnd;
	iIni=0;
	iEnd=str.length;
	while (isSpace(str.charAt(iIni)))
	{
		iIni++;
		if (iIni==iEnd)
		{
		  return '';
		}
	}
	iEnd--;
	while (isSpace(str.charAt(iEnd)))
	{
		iEnd--;
	}
	return str.slice(iIni,iEnd+1);
}

// +---------------------------------------checkCPF-------------------------------------------+
// | Funcao que monta um vetor com os digitos do CPF, para que a verificacao possa ser feita  |
// | na funcao CPFCheck.                                                                      |
// +------------------------------------------------------------------------------------------+
function checkCPF(cpf)
{
  cpf=StrTrim(cpf);
  if (isEmpty(cpf))
  {
    return true;
  }
  if (cpf.length!=14)
  {
    return false;
  }
  if ((cpf.charAt(3)!='.')||(cpf.charAt(7)!='.')||(cpf.charAt(11)!='-'))
  {
    return false;
  }
  if (
       (!isDigit(cpf.charAt(0 ))) ||
       (!isDigit(cpf.charAt(1 ))) ||
       (!isDigit(cpf.charAt(2 ))) ||
       (!isDigit(cpf.charAt(4 ))) ||
       (!isDigit(cpf.charAt(5 ))) ||
       (!isDigit(cpf.charAt(6 ))) ||
       (!isDigit(cpf.charAt(8 ))) ||
       (!isDigit(cpf.charAt(9 ))) ||
       (!isDigit(cpf.charAt(10))) ||
       (!isDigit(cpf.charAt(12))) ||
       (!isDigit(cpf.charAt(13)))
     )
  {
    return false;
  }
  var d=new Array();
  d[0] =parseInt(cpf.charAt(0 ),10);
  d[1] =parseInt(cpf.charAt(1 ),10);
  d[2] =parseInt(cpf.charAt(2 ),10);
  d[3] =parseInt(cpf.charAt(4 ),10);
  d[4] =parseInt(cpf.charAt(5 ),10);
  d[5] =parseInt(cpf.charAt(6 ),10);
  d[6] =parseInt(cpf.charAt(8 ),10);
  d[7] =parseInt(cpf.charAt(9 ),10);
  d[8] =parseInt(cpf.charAt(10),10);
  d[9] =parseInt(cpf.charAt(12),10);
  d[10]=parseInt(cpf.charAt(13),10);
  return true;
}

// +---------------------------------------checkCNPJ-------------------------------------------+
// | Funcao que monta um vetor com os digitos do CNPJ, para que a verificacao possa ser feita  |
// | na funcao CNPJCheck.                                                                      |
// +-------------------------------------------------------------------------------------------+
function checkCNPJ(cnpj)
{
  cnpj=StrTrim(cnpj);
  if (isEmpty(cnpj))
  {
    return true;
  }
  if (cnpj.length!=18)
  {
    return false;
  }
  if ((cnpj.charAt(2)!='.')||(cnpj.charAt(6)!='.')||(cnpj.charAt(10)!='/')||(cnpj.charAt(15)!='-'))
  {
    return false;
  }
  if (
       (!isDigit(cnpj.charAt(0 ))) ||
       (!isDigit(cnpj.charAt(1 ))) ||
       (!isDigit(cnpj.charAt(3 ))) ||
       (!isDigit(cnpj.charAt(4 ))) ||
       (!isDigit(cnpj.charAt(5 ))) ||
       (!isDigit(cnpj.charAt(7 ))) ||
       (!isDigit(cnpj.charAt(8 ))) ||
       (!isDigit(cnpj.charAt(9 ))) ||
       (!isDigit(cnpj.charAt(11))) ||
       (!isDigit(cnpj.charAt(12))) ||
       (!isDigit(cnpj.charAt(13))) ||
       (!isDigit(cnpj.charAt(14))) ||
       (!isDigit(cnpj.charAt(16))) ||
       (!isDigit(cnpj.charAt(17)))
     )
  {
    return false;
  }
  var d=new Array();
  d[0] =parseInt(cnpj.charAt(0),10);
  d[1] =parseInt(cnpj.charAt(1),10);
  d[2] =parseInt(cnpj.charAt(3),10);
  d[3] =parseInt(cnpj.charAt(4),10);
  d[4] =parseInt(cnpj.charAt(5),10);
  d[5] =parseInt(cnpj.charAt(7),10);
  d[6] =parseInt(cnpj.charAt(8),10);
  d[7] =parseInt(cnpj.charAt(9),10);
  d[8] =parseInt(cnpj.charAt(11),10);
  d[9] =parseInt(cnpj.charAt(12),10);
  d[10]=parseInt(cnpj.charAt(13),10);
  d[11]=parseInt(cnpj.charAt(14),10);
  d[12]=parseInt(cnpj.charAt(16),10);
  d[13]=parseInt(cnpj.charAt(17),10);
  return CNPJCheck(d);
}

// +----------------- ----checkMoeda-----------------------+
// | Funcao que verifica se o valor passado como parametro |
// | esta no formato correto da moeda corrente.            |
// +-------------------------------------------------------+
function checkMoeda(sValor)
{
	var reMoeda = /^\d{1,3}(\.\d{3})*\,\d{2}$/;
	if (reMoeda.test(sValor)) 
	{
		return true;
	} 
	else if (sValor != null && sValor != "") 
	{
		return false;
	}	
}

// +------------------------CPFCheck-----------------------+
// | Funcao que verifica a validade do CPF                 |
// +-------------------------------------------------------+
function CPFCheck(d)
{
	if (d.length!=11)
	{
		return false;
	}
	if ((d[0]==0)&&(d[1]==0)&&(d[2]==0)&&(d[3]==0)&&(d[4]==0)&&(d[5]==0)&&(d[6]==0)&&(d[7]==0)&&(d[8]==0))
	{
		return false;
	}
	var c1,c2;
	c1=d[8]*2+d[7]*3+d[6]*4+d[5]*5+d[4]*6+d[3]*7+d[2]*8+d[1]*9+d[0]*10;
	c1=11-(c1%11);
	if (c1>=10)
	{
		c1=0;
	}
	c2=c1*2+d[8]*3+d[7]*4+d[6]*5+d[5]*6+d[4]*7+d[3]*8+d[2]*9+d[1]*10+d[0]*11;
	c2=11-(c2%11);
	if (c2>=10)
	{
		c2=0;
	}
	if ((c1==d[9])&&(c2==d[10]))
	{
		return true;
	}
	else
	{
		return false;
	}
}

// +------------------------CNPJCheck----------------------+
// | Funcao que verifica a validade do CNPJ                |
// +-------------------------------------------------------+
function CNPJCheck(d)
{
	if (d.length!=14)
	{
		return false;
	}
	if ((d[0]==0)&&(d[1]==0)&&(d[2]==0)&&(d[3]==0)&&(d[4]==0)&&(d[5]==0)&&(d[6]==0)&&(d[7]==0)&&(d[8]==0)&&(d[9]==0)&&(d[10]==0)&&(d[11]==0))
	{
		return false;
	}
	var c1,c2;
	c1=d[11]*2+d[10]*3+d[9]*4+d[8]*5+d[7]*6+d[6]*7+d[5]*8+d[4]*9+d[3]*2+d[2]*3+d[1]*4+d[0]*5;
	c1=11-(c1%11);
	if (c1>=10)
	{
		c1=0;
	}
	c2=c1*2+d[11]*3+d[10]*4+d[9]*5+d[8]*6+d[7]*7+d[6]*8+d[5]*9+d[4]*2+d[3]*3+d[2]*4+d[1]*5+d[0]*6;
	c2=11-(c2%11);
	if (c2>=10)
	{
		c2=0;
	}
	if ((c1==d[12])&&(c2==d[13]))
	{
		return true;
	}
	else
	{
		return false;
	}
}

// +------------------------checkEMail----------------------+
// | Funcao que verifica a validade do e-mai.               |
// +--------------------------------------------------------+
function checkEMail(mail)
{
	mail=StrTrim(mail);
	if (isEmpty(mail))
	{
		return true;
	}
	var i,flag=false,count=0,sz=mail.length;
	for (i=0;i<sz;i++)
	{
		if (!isEMail(mail.charAt(i)))
		{
			return false;
		}
		if (mail.charAt(i)=='@')
		{
			if (flag==false)
			{
				flag=true;
			}
			else
			{
				return false;
			}
			if ((i==0)||(i==(sz-1)))
			{
				return false;
			}
			if ((!isLetterDigit(mail.charAt(i-1)))||(!isLetterDigit(mail.charAt(i+1))))
			{
				return false;
			}
		}
		if (mail.charAt(i)=='.')
		{
			if (flag==true)
			{
				count++;
			}
			if ((i==0)||(i==(sz-1)))
			{
				return false;
			}
			if ((!isLetterDigit(mail.charAt(i-1)))||(!isLetterDigit(mail.charAt(i+1))))
			{
				return false;
			}
		}
	}
	if ((flag==false)||(count==0))
	{
		return false;
	}
	return true;
}

// +---------------substituirCaracterEspecial---------------+
// | Funcao para substituir caracteres especiais por seus   |
// | códigos.                                               |
// +--------------------------------------------------------+
function substituirCaracterEspecial(str)
{
  str = str.replace(/</gi,"&lt;");
  str = str.replace(/>/gi,"&gt;");
  str = str.replace(/&/gi,"&amp;");
  return str;
}

// +-----------------retirarCaracterEspecial----------------+
// | Funcao para retirar caracteres especiais.              |
// +--------------------------------------------------------+
function retirarCaracterEspecial(str)
{
  str = str.replace(/</gi,"");
  str = str.replace(/>/gi,"");
  str = str.replace(/&/gi,"");
  return str;
}

function isEmpty(str)
{
  return ((str==null)||(str.length==0));
}

function isLetter(c)
{
  return (((c>='a')&&(c<='z'))||((c>='A')&&(c<='Z')));
}

function isDigit(c)
{
  return ((c>='0')&&(c<='9'));
}

function isLetterDigit(c)
{
  return (isLetter(c)||isDigit(c));
}

function isSign(c)
{
  return ((c=='-')||(c=='+'));
}

function isDecimalSeparator(c)
{
  return ((c=='.')||(c==','));
}

function isSpace(c)
{
  return ((c==' ')||(c=='\t')||(c=='\n')||(c=='\r'));
}

function istelefone(c)
{
  return (isDigit(c)||(c==' ')||(c=='-')||(c=='+')||(c=='(')||(c==')')||(c=='.'));
}

function isEMail(c)
{
  return (isLetterDigit(c)||(c=='@')||(c=='.')||(c=='-')||(c=='_'));
}

function isCPFCNPJ(c)
{
  return (isDigit(c)||(c=='.')||(c=='-')||(c=='/'));
}

// +--------------------------------------------------------+
// | Function: criaDivs                       
// | Essa função é responsável por preparar a página para a exibição
// | das janelas de acordo com o browser do cliente. Altera 
// | configurações do HTML e do BODY e cria os DIV necessários.                                                  
// +--------------------------------------------------------+
function criaDivs()
{
	if (typeof document.body.style.maxHeight === "undefined")
	{
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css("overflow","hidden");
		if (document.getElementById("iframe_selects") === null) 
			$("body").append("<iframe id='iframe_selects'></iframe><div id='div_background'></div><div id='div_janela'></div>");
	}
	else
	{
		if(document.getElementById("div_background") === null)
			$("body").append("<div id='div_background'></div><div id='div_janela'></div>");
	}
}

// +--------------------------------------------------------+
// | Function: criarAviso
// | Essa função é responsável pela criação de uma janela com dimensões
// | 350 X 110 exibindo a mensagem definida de acordo com os parâmetros.
// |                                                        
// | Parameters:   
// | _sTipo - define qual ícone será exibido:
// | - alerta
// | - erro
// | - info (default)
// | - ok      
// | _sButtons - define quais botões serão exibidos, opções:
// | - Sim e Não [sim_nao]
// | - Ok e Cancelar [ok_cancelar]
// | - Ok [ok] (default)
// | _sTexto - texto que será exibido na janela
// | _bFunction - define se uma função será definida para o o clique do 
// |  botão ou será usada a função padrão [opcional]
// | _iWidth - largura da janela [opcional]
// | _iHeight - altura da janela [opcional]
// |
// | See Also:
// | <classWindow>
// +--------------------------------------------------------+
function criarAviso(_sTipo, _sButtons, _sTexto, _bFunction, _iWidth, _iHeight)
{
	if ( (_iWidth != "") && (_iWidth != undefined) )
		iWidth = _iWidth;
	else
	    iWidth = 350;
	    
	if ( (_iHeight != "") && (_iWidth != undefined) )
		iHeight = _iHeight;	
	else
	    iHeight = 110;	 
	
	if ( (_bFunction == false) || (_bFunction == undefined) )
		sFunction = "onclick='Window.removeWindow(true);'";	
	else
		sFunction = "";
	    	   
    switch (_sTipo)
    {
    	case 'alerta':
		case 'erro':
		case 'info':
		case 'ok':
			var sImg = _sTipo + '.gif';
    		break;
    	default:
    		var sImg = 'info.gif';
    }    
    switch (_sButtons)
    {
    	case 'sim_nao':
    		var sButton = "<input id='button_criaraviso_sim' type='button' value='Sim' " + sFunction + "/>";
    		sButton = sButton + "&nbsp;&nbsp;<input id='button_criaraviso_nao' type='button' value='N&atilde;o' " + sFunction + "/>";
    		var sFocus = "button_criaraviso_sim";
    		break;
    	case 'ok_cancelar':
    		var sButton = "<input id='button_criaraviso_ok' type='button' value='Ok' " + sFunction + "/>";
    		sButton = sButton + "&nbsp;&nbsp;<input id='button_criaraviso_cancelar' type='button' value='Cancelar' " + sFunction + "/>";
    		var sFocus = "button_criaraviso_ok";
    		break;
    	default:
    		var sButton = "<input id='button_criaraviso_ok' type='button' value='Ok' " + sFunction + "/>";
    		var sFocus = "button_criaraviso_ok";
    		break;    	
    }   
    var sHTML = "<table border='0' width='100%'>";
    sHTML = sHTML + "<tr><td rowspan='3' align='center' valign='middle'><img src='img/" + sImg + "' /></td>";
    sHTML = sHTML + "<td align='center'>" + _sTexto + "</td></tr>";
    sHTML = sHTML + "<tr><td><img src='img/spacer.gif' width='10px' height='5px' /></td></tr>";
    sHTML = sHTML + "<tr><td align='center'>" + sButton + "</td></tr>";
    sHTML = sHTML + "</table>";
    Window.createWindow(false, "", iWidth, iHeight);
    Window.showWindow();
    Window.insertContent(sHTML);
    $("#" + sFocus).focus();
}

function FloatTopLeft(startX, startY)
{
	var ns = (navigator.appName.indexOf("Netscape") != -1);
	var px = document.layers ? "" : "px";
	function ml(id)
	{
		var el = document.getElementById(id);
		el.sP = function (x,y)
			{
				this.style.left = x + px;
				this.style.top = y + 50 + px;
			};
		el.x = startX; 
		el.y = startY;
		return el;
	}
	window.stayTopLeft=function()
	{
		var pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
		var dY = (pY > startY) ? pY : startY;
		ftlObj.y += (dY - ftlObj.y)/8;
		ftlObj.sP(ftlObj.x, ftlObj.y);
		setTimeout("stayTopLeft()", 20);
	}
	ftlObj = ml("ajuda");
	stayTopLeft();
}