var winModalWindow;
/**
 * Abre uma janela modal para pesquisa com retorno. 
 * idRecurso - indica o objeto sobre o qual vai ser feita a pesquisa.
 * resultTextBox - referência para o TextBox aonde será colocado o resultado.
 * idFiltro - identificador (ID) dos filtros que devem ser apresentados na tela de PesquisaRetorno.
 */
function OpenModalDialog(idRecurso, resultTextBox, idFiltro, escolha, chamadaAjax)
{ 
	//compativel com o IE
	if(chamadaAjax == null)
		chamadaAjax = false;

	var url = "FormPesquisaRetorno.aspx?idRec=" + idRecurso + "&tipo=" + "&idFiltro=" + idFiltro + "&escolha="+escolha + "&nomeCampoID="+resultTextBox.name;
	
	if (window.showModalDialog) {
		var MyArgs = window.showModalDialog("FormPesquisaRetorno.htm", url, "Fullscreen=no;Scrollbars=no; Menubar=no; Locationbar=no; Resizable=yes; Status=no; dialogWidth=600px; dialogHeight=700px; help=no");
		if(chamadaAjax)
			resultTextBox.focus();
		if (MyArgs == null)
		{
			resultTextBox.value = "-1";
			window.alert("Nenhum item foi selecionado!");
		}
		else
		{
			resultTextBox.value = MyArgs;
		}
		__doPostBack('','');
	}
	else // Non IE or Non ShowModalDialog capable browser
	{
	    window.top.captureEvents (Event.CLICK|Event.FOCUS);
		window.top.onclick=IgnoreEvents;
		window.top.onfocus=HandleFocus;
		winModalWindow = window.open (url,"Win"+idRecurso,"dependent=yes,width=600,height=500,scrollbars=yes");
		winModalWindow.focus();
	}
}

function OpenModalDialogAjax(form, idRecurso, resultTextBox, idFiltro, escolha, chamadaAjax)
{
    //Pesquisa utilizando Recurso: OpenModalDialogAjax(<Form>, <Recurso>, <CampoRetorno>, <OID>   , ''       ,true)
    //Pesquisa utilizando Filtro.: OpenModalDialogAjax(<Form>, ''       , <CampoRetorno>, <Filtro>, 'SIMPLES',true)
	if(chamadaAjax == null)
		chamadaAjax = false;
	if(idFiltro == null)
	    idFiltro = "";
    
    if (escolha != "SIMPLES") //Simples é utilizado somente para pesquisas utilizando Filtros.
        var url = form + "?idRec=" + idRecurso + "&tipo=editar&oideditar=" + idFiltro + "&escolha="+escolha + "&nomeCampoID=" + resultTextBox.name + "&modal=";
    else
	    var url = form + "?idRec=" + idRecurso + "&tipo=" + "&idFiltro=" + idFiltro + "&escolha="+escolha + "&nomeCampoID=" + resultTextBox.name + "&modal=";
   
    returnVal = resultTextBox;
    
	showPopWin(url, 700, 520, retornaValor);
	
	//__doPostBack('','');
}

function OpenModalDialogProgressBar()
{
	//compativel com o IE
		var url = "./Framework/G6Progress.aspx";
	
	if (window.showModalDialog) {
		var MyArgs = window.showModalDialog(url,"winprogress" , "Fullscreen=no;Scrollbars=no; Menubar=no; Locationbar=no; Resizable=yes; Status=no; dialogWidth=350px; dialogHeight=270px; help=no");	
	}
	else // Non IE or Non ShowModalDialog capable browser
	{
	    window.top.captureEvents (Event.CLICK|Event.FOCUS);
		window.top.onclick=IgnoreEvents;
		window.top.onfocus=HandleFocus;
		winModalWindow = window.open (url,"winprogress","dependent=yes,width=350,height=270,scrollbars=yes");
		winModalWindow.focus();
	}
}

function OpenCadastroModalDialog(formulario, idRecurso, chave, valorChave)
{
	var url = formulario+"?idRec=" + idRecurso + "&"+chave+"=" + valorChave;
	
	if (window.showModalDialog) {
		var MyArgs = window.showModalDialog("FormPesquisaRetorno.htm", url, "Fullscreen=no;Scrollbars=no; Menubar=no; Locationbar=no; Resizable=yes; Status=no; dialogWidth=600px; dialogHeight=700px; help=no");
		if (MyArgs == null)
		{
			resultTextBox.value = "-1";
			window.alert("Nenhum item foi selecionado!");
		}
		else
		{
			resultTextBox.value = MyArgs;
		}
		__doPostBack('','');
	}
	else
	{
		window.top.captureEvents (Event.CLICK|Event.FOCUS);
		window.top.onclick=IgnoreEvents;
		window.top.onfocus=HandleFocus;
		winModalWindow = window.open (url,"Win"+idRecurso,"dependent=yes,width=600,height=500",scrollbars=yes);
		winModalWindow.focus();
	}
}

/* Alterado por Jackson */
function LimitaFaixaValorAliquota(obj)
{
    var valor = obj.value;
    valor = valor.replace(/ /gi, "");
    valor = valor.replace(",", ".");
    
    if (valor == "") 
    {
        obj.value = '';
        alert("Aliquota deve estar na faixa entre 2% e 5%.");
        obj.focus();
        return false;
    }
    
    if (isNaN(valor)) // Testa se é um número ou qquer outra coisa. Retorna true se não for número
    {
        obj.value = '';
        alert("Aliquota deve estar na faixa entre 2% e 5%.");
        obj.focus();
        return false;
    }
    else
    {
        valor = new Number(valor);

        if (valor > 5) 
        {
            obj.value = '5,00';
            alert("Aliquota deve estar na faixa entre 2% e 5%.");
            obj.focus();
            return false;
        };
        if (valor < 2) 
        {
            obj.value = '2,00';
            alert("Aliquota deve estar na faixa entre 2% e 5%.");
            obj.focus();
            return false;
        };
    }
    
    obj.value = valor.toString().replace(".", ",");
    
    return true;
}

function LimitaFaixaValorCampo(obj, minValue, maxValue) {
    var valor = obj.value;
    FormatMoney(valor);
    if (valor == "") {
        obj.value = '';
        alert("O valor deve estar na faixa entre " + minValue + " e " + maxValue + ".");
        obj.focus();
        return false;
    }

    if (isNaN(valor)) // Testa se é um número ou qquer outra coisa. Retorna true se não for número
    {
        //obj.value = '';
        //alert("Aliquota deve estar na faixa entre " + minValue + " e " + maxValue + ".");
        //obj.focus();
        //return false;
    }
    else {
        valor = new Number(valor);

        if (valor > maxValue) {
            obj.value = maxValue;
            alert("O valor deve estar na faixa entre " + minValue + " e " + maxValue + ".");
            obj.focus();
            return false;
        };
        if (valor < minValue) {
            obj.value = minValue;
            alert("O valor deve estar na faixa entre " + minValue + " e " + maxValue + ".");
            obj.focus();
            return false;
        };
    }

    obj.value = valor.toString().replace(".", ",");
    return true;
}

/*
 * Coletor: Marcelo R.S.
 * Coloca Mascara no campo numérico
 * Ex: onkeyup="numberMask(this, event, '9999-9999')"
 */
function numberMask(objSender, objEvent, strMask) { 
      key = (objEvent.which) ? objEvent.which : objEvent.keyCode; 

      if(key == 37 || key == 39) 
        return true; 
      strValue = ''; 
      for(i = 0; i < objSender.value.length; i++) { 
        chrValue = objSender.value.charAt(i); 
        strValue += !isNaN(chrValue) ? chrValue : ''; 
      } 
      countChr = 0; 
      for(i = 0; i < strMask.length; i++) { 
        countChr += strMask.charAt(i) == '9' ? 1 : 0; 
      } 
      strFormated = ''; 
      j = 0, i = 0; 
      while(j < strValue.length && j < countChr) { 
        chrMask = strMask.charAt(i); 
        if(chrMask == '9') { 
          strFormated += strValue.charAt(j); 
          j++; 
        } 
        else { 
          strFormated += chrMask; 
        } 
        i++; 
      } 
      objSender.value = strFormated; 
      return true;      
} 

//Teste de melhorias - Status: parado
function numberMask2(objSender, objEvent, strMask) { 
      key = (objEvent.which) ? objEvent.which : objEvent.keyCode; 

      if(key == 37 || key == 39) 
        return true; 
      strValue = ''; 
      for(i = 0; i < objSender.value.length; i++) { 
        chrValue = objSender.value.charAt(i); 
        strValue += !isNaN(chrValue) ? chrValue : ''; 
      } 
      countChr = 0; 
      for(i = 0; i < strMask.length; i++) { 
        countChr += strMask.charAt(i) == '9' ? 1 : 0; 
      } 
      strFormated = ''; 
      j = 0, i = 0; 
      while(j < strValue.length && j < countChr) { 
        chrMask = strMask.charAt(i); 
        if(chrMask == '9') { 
          strFormated += strValue.charAt(j); 
          j++; 
        } 
        else { 
          strFormated += chrMask; 
        } 
        i++; 
      } 
      objSender.value = strFormated; 
      return true;         
} 

// ==============================================================
// Non IE or Non ShowModalDialog capable browser FUNCTIONS

function IgnoreEvents(e) {
  return false;
  } // end of function IgnoreEvents

  
function HandleFocus() {

  if (winModalWindow) {
    if (!winModalWindow.closed) {
        winModalWindow.focus();
       }
	else {
      window.top.releaseEvents (Event.CLICK|Event.FOCUS);
      window.top.onclick = "";
     }
  }
  return false;
} // end of function HandleFocus



/**
 * Esse método formata o string passado no parâmetro info, para o formato de money (xxx.xxx.xxx,xx).
 * Se não for colocada a vírgula, a função acrescenta a vírgula seguida de dois dígitos '0'. 
 * Se tiver menos de 2 dígitos à direita da vírgula, completa com dígitos '0' até que tenha 2 dígitos.
 * Se tiver mais de 2 dígitos à dirita da vírgula, move a vírgula para a direita até que fiquem 2 dígitos à direita.
 */
function FormatMoney(info)
{
	if(info == "")
		return "0,00";
	info = VerificaVirgulaDecimal(info);
	var numero = unformatNumber(info);
	if(numero == "")
		numero = "000";
	var maxDigitos = 11;
	if(numero.length <= 5)
		maxDigitos = 5;
	else if(numero.length <= 8)
		maxDigitos = 8;
	else if(numero.length <= 11)
		maxDigitos = 11;
	
	if(numero.length < 3)
		numero = numero.lpad(3, '0');
	numero = numero.lpad(maxDigitos, ' ');

	switch(maxDigitos)
	{
	case 5:
		reNumero = /([0-9 ]{3})([0-9]{2})$/;
		numero = numero.replace(reNumero, "$1,$2");
		break;
	case 8:
		reNumero = /([0-9 ]{3})([0-9 ]{3})([0-9]{2})$/;
		numero = numero.replace(reNumero, "$1.$2,$3");
		break;
	case 11:
		reNumero = /([0-9 ]{3})([0-9 ]{3})([0-9 ]{3})([0-9]{2})$/;
		numero = numero.replace(reNumero, "$1.$2.$3,$4");
		break;
	}
	return numero.trim();
}

function VerificaVirgulaDecimal(info)
{
	if(info.charAt(info.length - 1) == ',')
		info += "00";
	else if(info.charAt(info.length - 2) == ',')
		info += "0";
	else
	{
		var achei = false;
		var i = 0;
		for(i = 0; i < info.length; i++)
			if(info.charAt(i) == ",")
			{
				achei = true;
				break;
			}
		if(achei == false)
			info += ",00";
		else
			info = info.substring(0, i + 3);
	}
	return info;
}

function RemoveBarraDivisao(info)
{
	//info = info.replace('/', '');
	var resultado = "";
	for(i = 0; i < info.length; i++)
	{
		if(info.charAt(i) != '/' && info.charAt(i) != '-' && info.charAt(i) != '.')
			resultado += info.charAt(i);
	}
	return resultado;
}

function FormatDate(info)
{
	if(info == "")
		return "";
	tmp = RemoveBarraDivisao(info);
	var res = "";
	if(tmp.length < 6 || tmp.length > 8 || !isDataValida(tmp))
	{
		alert("Data incorreta! \n" +
		      "- A data deve estar em um dos seguintes formatos: \n" + 
		      "  01/01/2004, 01/01/04, 01012004 ou 010104.");
		return info;
	}
	if(tmp.length == 6)
	{
		res = tmp.substring(0,4);
		res += "20";
		res += tmp.substring(4, 6);
	}
	else
		res = tmp;

	return Format(res, "99/99/9999");
}

//Novo FormatDate: Usado em Novo CeC. Autor: Marcelo R. Scandolara
function FormatDateN(info)
{
	if(info == "")
		return "";
	tmp = RemoveBarraDivisao(info.value);
	var res = "";
	if(tmp.length < 8 || !isDataValida(tmp))
	{
	    if (tmp.length != 0)
	    {
		    alert("Data incorreta! \n" +
		      "- A data deve estar no formato ddmmaaaa. Ex: 01012010.");
		    info.value = "";
		    info.focus();
		}   
		return "";
	}
	if(tmp.length == 6)
	{
		res = tmp.substring(0,4);
		res += "20";
		res += tmp.substring(4, 6);
	}
	else
		res = tmp;

	return Format(res, "99/99/9999");
}


/*
 * Autor: Marcelo R.S.
 * Verifica se a Data é Menor que a data atual.
 */
function isDataMenor(info)
{
	if(info.value == "")
		return true;
		
	tmp = RemoveBarraDivisao(info.value);
	var data = new Date();
	var dia = unformatNumber(data.getDate()); 
	var mes = unformatNumber(data.getMonth()+1);  
	var ano = unformatNumber(data.getFullYear());
	var hoje =  dia.lpad(2,'0') + "/" + mes.lpad(2,'0') + "/" + ano;

	var data1 = hoje; 
    var data2 = info.value; 
    
	if (parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) > parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) )
    {
        if (isDataValida(tmp))
        {
            alert("A data nao pode ser maior do que a data atual.");
	        info.value = "";
	        info.focus();
	        return false;
        }
    }
    else
        return true;        
}

/*
 * Autor: Marcelo R.S.
 * Verifica se o Telefone esta em formato valido, usado junto com o numberMask
 */
function isFone(campo)
{
	if(campo.value == "")
		return true;
		
	campo.value = campo.value.trim();	
	
    if (campo.value.length < 13)
    {
        alert("Telefone incorreto.");
        campo.value = "";
        campo.focus();
        return false;
    }
    return true;
}

/*
 * Verifica se a Data é Valida.
 *  -> Testa se é bisexto. Se Não for bisexto e for colocada a data de 29/02, retorna erro.
 *     Tem que ser múltiplo de 4, mas não pode ser múltiplo de 100 a não ser que seja múltiplo de 400.
 *      Ex:
 *      2008 é bisexto
 *      1900 não é ( é múltiplo de 100 mas não de 400 ).
 *      2000 é ( múltiplo de 100 E 400 ).
 *  -> Testa se o mes e o ano são válidos. Inclusive testando se a quantidade de dias é válido para o mes. 
 *        Ex: o mes tem 30 dias ou 31.
*/
function isDataValida(data)
{
    //data = RemoveBarraDivisao(data);
    
    var dia = data.substring(0,2);
    var mes = data.substring(2,4);
    var ano = data.substring(4,8);
    
    if (mes < "01" || mes > "12")
        return false;
        
    if(ano.length != 2 && (ano < "1901" || ano > "2120"))
        return false;
    
    if (dia < "01")
        return false;
    
    if((mes == "01") || (mes == "03") || (mes == "05") || (mes == "07") || (mes == "08") || (mes == "10") || (mes == "12"))
    {
        if (dia > "31")
            return false;
    }
    
    if((mes == "04") || (mes == "06") || (mes == "09") || (mes == "11"))  
    {
        if (dia > "30")
            return false;
    }
    
    if((ano % 4 == 0) && ((ano % 100 != 0) || (ano % 400 == 0)))
    {
        if (mes == "02")
        {
            if (dia > "29")
                return false;
        }
    }
    else
    {
        if (mes == "02")
        {
            if (dia > "28")
                return false;
        }
    }
    return true;
}

/**
 * Esse método formata o string passado no parâmetro info, de acordo com a máscara informada no parâmetro mascara.
 * Na máscara, o dígito 9 representa um número e a letra X representa um caracter alfanumérico. 
 * Exemplos: CEP: 99-999-99    CPF: 999.999.999-99   Placa de carro: XXX-9999
 * Exemplo de utilização: Em um objeto TextBox, colocar no modo html: onkeyup="this.value = Format(this.value, '99/99/9999');"
 */
function Format(info, mascara)
{
	function IsDigit(info)
	{
		if(info.length == 1 && info >= '0' && info <='9')
			return true;
		return false;
	}
	var resultado = "";
	var j = 0;
	var i = 0;
	for(i = 0; i < mascara.length && j < info.length; i++)
	{
		switch(mascara.charAt(i))
		{
			case '9':
				if(IsDigit(info.charAt(j)))
					resultado += info.charAt(j);
				j++;
				break;
			case 'X':
				resultado += info.charAt(j);
				j++;
				break;
			default:
				resultado += mascara.charAt(i);
				if(info.charAt(j) == mascara.charAt(i))
					j++;
				break;
		}
	}
	return resultado;
}		
function FormatCEP(info)
{
	return Format(info, '99999-999');
}
//AtivaFocoSelecao()
function DoBlur(fld) 
{
    fld.className = 'form_caixadetexto';
}
function DoFocus(fld) 
{
    fld.className = 'form_caixadetexto_focus';
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Verificação de CPF e CNPJ

var NUM_DIGITOS_CNPJ = 14;
var NUM_DIGITOS_CPF  = 11;


/**
 * Adiciona método lpad() à classe String.
 * Preenche a String à esquerda com o caractere fornecido,
 * até que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona método trim() à classe String.
 * Elimina brancos no início e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formatação e zeros à esquerda da string
 * de número fornecida.
 * @param String pNum
 *      String de número fornecida para ser desformatada.
 * @return String de número desformatada.
 */
function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


function unformatNumberCpfCPJ(pNum)
{
	return String(pNum).replace(/\D/g, "");
} //unformatNumber

function unformatNumDocReceita(pNum)
{
	return String(pNum).replace(/\D/g, "");
} //unformatNumDocReceita

/**
 * Calcula os 2 dígitos verificadores para o número-base pBase de
 * CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
 * informa se o número-base fornecido é CNPJ (default = false).
 * @param String pBase
 *      String do número-base (SEM dígitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 *      Indica se a string fornecida é de um CNPJ.
 *      Caso contrário, é CPF. Default = false (CPF).
 * @return String com os dois dígitos verificadores.
 */
function dvCpfCnpj(pBase, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? 8: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pBase, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for(j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida é um CPF válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpf
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF válido.
 */
function isCpf(pCpf)
{
	var numero = unformatNumDocReceita(pCpf) //formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != base + digitos) 
	{
    	return false;
	}

	/* Não serão considerados válidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf

function showMsgAndClearField(field, msg)
{
    if(field != null && msg != null)
    {
        field.value = "";
        alert(msg);
    }
}
/*Novo Código: EM TESTE*/
/*function isCpf(cpf)
{
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    digitos_iguais = 1;
    if (cpf.length < 11)
        return false;
    for (i = 0; i < cpf.length - 1; i++)
        if (cpf.charAt(i) != cpf.charAt(i + 1))
              {
              digitos_iguais = 0;
              break;
              }
    if (!digitos_iguais)
        {
        numeros = cpf.substring(0,9);
        digitos = cpf.substring(9);
        soma = 0;
        for (i = 10; i > 1; i--)
              soma += numeros.charAt(10 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
              return false;
        numeros = cpf.substring(0,10);
        soma = 0;
        for (i = 11; i > 1; i--)
              soma += numeros.charAt(11 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
              return false;
        return true;
        }
    else
        return false;
}
*/
/**
 * Testa se a String pCnpj fornecida é um CNPJ válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ válido.
 */
function isCnpj(pCnpj)
{
	var numero = unformatNumDocReceita(pCnpj);//formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, 8);
	var ordem = numero.substring(8, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos) 
	{
	    return false;
	}

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; i<8; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	
	if (algUnico)
	{
	    return false;
	}

	/* Não será considerado válido CNPJ com número de ORDEM igual a 0000.
	 * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
	 * e com as três primeiras posições do número BÁSICO com 000 (zeros).
	 * Esta crítica não será feita quando o no BÁSICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") 
	{
	    return false;
	}
	
	
	return (base == "00000000"	|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj


/*Novo Código: Em Teste*/
/*function isCnpj(cnpj)
{
    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    digitos_iguais = 1;
    if (cnpj.length < 14 && cnpj.length < 15)
        return false;
    for (i = 0; i < cnpj.length - 1; i++)
        if (cnpj.charAt(i) != cnpj.charAt(i + 1))
              {
              digitos_iguais = 0;
              break;
              }
    if (!digitos_iguais)
        {
        tamanho = cnpj.length - 2
        numeros = cnpj.substring(0,tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--)
              {
              soma += numeros.charAt(tamanho - i) * pos--;
              if (pos < 2)
                    pos = 9;
              }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
              return false;
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0,tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--)
              {
              soma += numeros.charAt(tamanho - i) * pos--;
              if (pos < 2)
                    pos = 9;
              }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
              return false;
        return true;
        }
    else
        return false;
}*/

/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * à esquerda se necessário e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 *      String fornecida para ser formatada.
 * @param boolean pUseSepar
 *      Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 *      Indica se a string fornecida é um CNPJ.
 *      Caso contrário, é CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj == null) 
	    pIsCnpj = isCnpj(pCpfCnpj)
	    
	//pIsCnpj = isCnpj(unformatNumDocReceita(pCpfCnpj))
	    
	if (pUseSepar == null) 
	    pUseSepar = true;
	
	var maxDigitos = pIsCnpj ? NUM_DIGITOS_CNPJ : NUM_DIGITOS_CPF;
	var numero = unformatNumDocReceita(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj

/**
 * Testa se a String pCpfCnpj fornecida é um CPF ou CNPJ válido.
 * Se a String tiver uma quantidade de dígitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpfCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ válido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var resultado;
	var valor = pCpfCnpj.value;
	if(valor.indexOf(" ") >= 0)
	{
		alert("CPF/CNPJ Incorreto! Remova os caracteres em branco.");
		pCpfCnpj.value = "";
		pCpfCnpj.select();
		return false;	    
	}
	
	if(valor == "")
		return true;
		
	var numero = valor.replace(/\D/g, "");
	
	if (numero.length > NUM_DIGITOS_CPF)
	{
	    if (numero.length > 14)
		{		    
			alert("CNPJ Incorreto!");
			pCpfCnpj.value = "";
			//pCpfCnpj.select();
			return false;
		}
		
		resultado = isCnpj(valor)
		if(!resultado)
		{
			alert("CNPJ Incorreto!");
			pCpfCnpj.value = "";
			//pCpfCnpj.select();
		}
		else
		{
			reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		    pCpfCnpj.value = valor.replace(reCnpj, "$1.$2.$3/$4-$5");
		}
	}
	else
	{
		resultado = isCpf(valor);
		if(!resultado)
		{
			alert("CPF Incorreto!");
			pCpfCnpj.value = "";
			//pCpfCnpj.select();
		}
		else
		{
		    reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		    pCpfCnpj.value = valor.replace(reCpf, "$1.$2.$3-$4");
		}
	}
	return resultado;
} //isCpfCnpj
////////////////////////////////////////////////////////////////////////////////////////////////////

function setFocus(object) {
    if (document.getElementById && document.getElementById(object) != null)
         node = document.getElementById(object).focus();
    else if (document.layers && document.layers[object] != null)
        document.layers[object].focus();
    else if (document.all && document.all[object])
        document.all[object].focus();
}

function show(object) {
    if (document.getElementById && document.getElementById(object) != null)
         node = document.getElementById(object).style.visibility='visible';
    else if (document.layers && document.layers[object] != null)
        document.layers[object].visibility = 'visible';
    /*else if (document.all)
        document.all[object].style.visibility = 'visible';*/
}

function hide(object) {
    if (document.getElementById && document.getElementById(object) != null)
         node = document.getElementById(object).style.visibility='hidden';
    else if (document.layers && document.layers[object] != null)
        document.layers[object].visibility = 'hidden';
    /*else if (document.all)
         document.all[object].style.visibility = 'hidden';*/
}

function isShown(object) {
    if (document.getElementById && document.getElementById(object) != null)
        if(document.getElementById(object).style.visibility=='visible')
			return true
		else
			return false;
    else if (document.layers && document.layers[object] != null)
        if(document.layers[object].visibility == 'visible')
			return true;
		else
			return false;
    else if (document.all)
		if(document.all[object].style.visibility == 'visible')
			return true;
		else
			return false;
}

function GetObjectByName(objectName) {
    if (document.getElementById && document.getElementById(objectName) != null)
         return document.getElementById(objectName);
    else if (document.layers && document.layers[objectName] != null)
        return document.layers[objectName];
    else if (document.all)
        return document.all[objectName];
}

//funcao utilizada para netscape, firefox
function GetOpenerObjectByName(objectName) {
    if (window.opener.document.getElementById && window.opener.document.getElementById(objectName) != null)
         return window.opener.document.getElementById(objectName);
    else if (window.opener.document.layers && window.opener.document.layers[objectName] != null)
        return window.opener.document.layers[objectName];
    else if (document.all)
        return window.opener.document.all[objectName];
}

function UsuarioPressionouEnter()
{
	if(window.event && window.event.keyCode == 13)
	{
		event.keyCode=9;
		return true;
		//setFocus(controlToSetFocus);
	}
	return false;
}

function isDecimal(pValor)
{
	var reDecimalPt = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
	if(pValor.value != "")
	{
		if(reDecimalPt.test(pValor.value))
			return true;
		else
		{
			alert("Valor incorreto!");
			pValor.value = "";
			pValor.focus();
			return false;
		}
	}
}

function isEmail(pValor)
{
	var  reEmail1 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
    pValor.value = pValor.value.trim(); //retira espacos
	if(reEmail1.test(pValor.value))
		return true;
	else
	{
	    if(pValor.value.length > 0) //se deixar em branco não mostra mensagem
	    {
	        alert("E-mail incorreto!");
		    pValor.focus();
		    return false;
		} else
		    return true;
	}
}

/**
 * Autor: Marcelo R. Scandolara - 08/01/2010
 * Compara o E-mail de Confirmação é igual ao previamente digitado.
 * @param Object valor1
 *      Confirmação do E-mail
 * @param Object valor2
 *      E-mail a ser confirmado
 * @return <code>true</code> se os E-mail forem identicos, ou se não forem informados.
 * @return <code>false</code> case os e-mail não sejam iguais.
 */
function isConfirmaEmail(valor1, valor2)
{
	var  reEmail1 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
    valor1.value = valor1.value.trim();
    
    if (valor1.value == valor2.value) //Email conferem
        return true;
    else
    {
        if (reEmail1.test(valor1.value)) //se email confirmacao for EMAIL
        {
            if (valor1.value.length > 0) //se não forem iguais
            {
                alert("E-mail diferente do informado.");
                valor1.value = "";
                valor1.focus();
                return false;
            }
        }
        
        if (reEmail1.test(valor2.value) && valor1.value.length == 0) //Se Email estiver ok mas confirmacao vazio
        {
            valor2.focus();
            return false;
        }
        valor1.value = "";
        return false;
    }
    return false;
}

/**
 * Autor: Marcelo R. Scandolara - 20/01/2010
 * Compara dois campos.
 * @param Object valor1
 *      Confirmação do Campo1
 * @param Object valor2
 *      Campo2 a ser confirmado
 * @param Object nomeCampo
 *      Nome do Campo a ser usado em mensagem
  * @param Object tamanho
 *      Tamanho mínimo do campo (usado para verificação de senha, por exemplo!)
 * @return <code>true</code> se os Campos forem identicos, ou se não forem informados.
 * @return <code>false</code> caso os Campos não sejam iguais.
 */
function isConfirma(valor1, valor2, nomeCampo, tamanho)
{
    valor1.value = valor1.value.trim();
    valor2.value = valor2.value.trim();
    if (tamanho != null)
    {
        if (valor1.value.length < tamanho || valor2.value.length < tamanho)
        {
            alert("Minimo de " + tamanho + " caracteres.");
            return false;
        }
    }
    
    if (valor1.value == valor2.value) //Campos conferem
        return true;
    else
    {
        if (valor1.value.length > 0) //se não forem iguais
        {
            alert(nomeCampo);
            valor1.value = "";
            valor1.focus();
            return false;
        }
        
        if (valor1.value.length == 0) //Se estiver ok mas confirmacao vazio
        {
            valor2.focus();
            return false;
        }
        valor1.value = "";
        return false;
    }
    return false;
}

/*function tamanhoMinimo(campo, tamanho)
{
    if (campo.value.length < tamanho)
    {
        alert("Favor preencher pelo menos com " + tamanho + " caracteres.");
        return false;
    }
    else
        return true;
}*/

//Ex: onKeyUp='restringeCaracteresValidos(this,"0123456789.-/)");'
function restringeCaracteresValidos(campo, caracteresValidos)
{ 
	var valorAuxiliar = '';  
    var valor;  
    var digitosValidos;  
    valor = campo.value; 
    for (i=0;i<valor.length;i++)
    {  
		if(caracteresValidos.indexOf(valor.charAt(i)) >= 0) 
		{ 
			valorAuxiliar += valor.charAt(i); 
        }
    } 
    if(campo.value != valorAuxiliar)
		campo.value=valorAuxiliar; 
}

function removeCaracteresInvalidos(campo, caracteresInvalidos)
{
    var valorAuxiliar = '';  
    var valor;  
    var digitosValidos;  
    valor = campo.value; 
    for (i=0;i<valor.length;i++)
    {  
		if(!(caracteresInvalidos.indexOf(valor.charAt(i)) >= 0)) 
		{ 
			valorAuxiliar += valor.charAt(i); 
        }
    } 
    
    if(campo.value != valorAuxiliar)
		campo.value=valorAuxiliar; 
}

function encodeHtml(toEncode)
{
	encodedHtml = escape(toEncode);
	encodedHtml = encodedHtml.replace("/\//g","%2F");
	encodedHtml = encodedHtml.replace("/\?/g","%3F");
	encodedHtml = encodedHtml.replace("/=/g","%3D");
	encodedHtml = encodedHtml.replace("/&/g","%26");
	encodedHtml = encodedHtml.replace("/@/g","%40");
	return encodedHtml;
}

function getXMLHttp(){
	try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {}
    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {}
    try { return new XMLHttpRequest(); } catch(e) {}
    alert('XMLHttpRequest not supported');
	return null;
}

/*function atualizarEditBoxPorAjax(idObjetoAAtualizar, url, variaveis, idObjetoMensagemAguarde)
{
	xmlhttp = new getXMLHttp();
	xmlhttp.open('POST', url, true);
	document.body.style.cursor = 'wait';
	if(idObjetoMensagemAguarde != null && idObjetoMensagemAguarde != '')
		GetObjectByName(idObjetoMensagemAguarde).value = 'Aguarde... Consultando.';
	else
		GetObjectByName(idObjetoAAtualizar).value = 'Aguarde... Consultando.';
	xmlhttp.onreadystatechange = function()
				{
					if ( xmlhttp.readyState == 4 )
					{
						if(idObjetoMensagemAguarde != null && idObjetoMensagemAguarde != '')
							GetObjectByName(idObjetoMensagemAguarde).value = '';
						document.body.style.cursor = 'default';
						if( xmlhttp.status == 200 )
							GetObjectByName(idObjetoAAtualizar).value = xmlhttp.responseText;
						else
						{
							GetObjectByName(idObjetoAAtualizar).value = '';
							alert(xmlhttp.statusText);
						}
					}
				}		
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(variaveis); 	
}

function atualizarComponentePorAjax(idObjetoAAtualizar, url, variaveis, idObjetoMensagemAguarde)
{
	xmlhttp = new getXMLHttp();
	xmlhttp.open('POST', url, true);
	document.body.style.cursor = 'wait';
	if(idObjetoMensagemAguarde != null && idObjetoMensagemAguarde != '')
		GetObjectByName(idObjetoMensagemAguarde).value = 'Aguarde... Consultando.';
	xmlhttp.onreadystatechange = function()
				{
					if ( xmlhttp.readyState == 4 )
					{
						if(idObjetoMensagemAguarde != null && idObjetoMensagemAguarde != '')
							GetObjectByName(idObjetoMensagemAguarde).value = '';
						document.body.style.cursor = 'default';
						if( xmlhttp.status == 200 )
							GetObjectByName(idObjetoAAtualizar).outerHTML = xmlhttp.responseText;
						else
						{
							GetObjectByName(idObjetoAAtualizar).outerHTML = '';
							alert(xmlhttp.statusText);
						}
					}
				}		
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(variaveis); 	
}*/

function tempOnSubmit()
{
	alert('Aguardando resposta dinamica do Servidor. Tente novamente.');
	return false;
}
function getPageSize() {
    return [
        document.body.offsetWidth,
        document.body.offsetHeight
    ];
}

function atualizarComponentesPorAjax(url, variaveis, idObjetoMensagemAguarde)
{
	xmlhttp = new getXMLHttp();
	xmlhttp.open('POST', url, true);
	///document.body.style.cursor = 'wait';
	if(idObjetoMensagemAguarde != null && idObjetoMensagemAguarde != '')
	{
		if(GetObjectByName(idObjetoMensagemAguarde).type == 'text')
			GetObjectByName(idObjetoMensagemAguarde).value = 'Aguarde... Consultando.';
		else
			GetObjectByName(idObjetoMensagemAguarde).style.visibility='visible';
	}
	if(oldOnSubmit == null)
		var oldOnSubmit = GetObjectByName('Form1').onsubmit;
	
	GetObjectByName('Form1').onsubmit = tempOnSubmit;
	xmlhttp.onreadystatechange = function()
				{
					if ( xmlhttp.readyState == 4 )
					{
						if(idObjetoMensagemAguarde != null && idObjetoMensagemAguarde != '')
						{
							GetObjectByName(idObjetoMensagemAguarde).value = '';
							if(idObjetoMensagemAguarde == 'divmsg' && GetObjectByName(idObjetoMensagemAguarde) != null)
								GetObjectByName(idObjetoMensagemAguarde).style.visibility='hidden';
						}
						//document.body.style.cursor = 'default';
						GetObjectByName('Form1').onsubmit = oldOnSubmit;
						oldOnSubmit = null;
						if( xmlhttp.status == 200 )
						{
							var res = xmlhttp.responseText;
							do
							{
								var divideCampos = res.indexOf("<<|>>")
								if(divideCampos == -1)
									divideCampos = res.length;
								var parte1 = res.substr(0, divideCampos);
								var i = parte1.indexOf("<<=>>");
								if(i < 0)
								{
									alert("Nao veio o nome da variavel a atualizar na resposta do Ajax. Resposta Recebida: " + parte1);
									break;
								}
								var campo = parte1.substr(0, i);
								var valor = parte1.substr(i + 5, parte1.length - i - 5);

								if(campo == "<<script>>")
									eval(valor);
								//else if(campo == "<<appendtohtml>>")
								//	document.write(valor);
								else
								{
									/*if(GetObjectByName(campo).type == 'checkbox')
										GetObjectByName(campo).checked = (valor == 'true') ? true : false;
									else
									{
										if(valor.indexOf("<<OUTER>>") > -1)
										{
											valor = valor.replace("<<OUTER>>", "");
											GetObjectByName(campo).outerHTML = valor;
										}
										else
											GetObjectByName(campo).innerHTML = valor;
									}
										//GetObjectByName(campo).innerHTML = valor;
										//GetObjectByName(campo).outerHTML = valor;
										*/									
									replaceOuterHTML(GetObjectByName(campo), valor);
								}
								res = res.substr(divideCampos + 5, res.length - divideCampos - 5);
							} while(res.length > 0)
						}
						else
							alert("Ocorreu um problema: " + xmlhttp.statusText);
					}
				}		
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	var strPost = ''; 
	var formRef = GetObjectByName('Form1');
	for(var i = 0; i < formRef.elements.length; i++) 
	{
		if(formRef.elements[i].name != '__VIEWSTATE' && formRef.elements[i].name != '')
		{
			var temp = '';
			if(formRef.elements[i].type == 'checkbox' || formRef.elements[i].type == 'radio')
				temp = formRef.elements[i].name + '=' + (formRef.elements[i].checked ? 'true':'false') + '&'; 
			else
				temp = formRef.elements[i].name + '=' + formRef.elements[i].value + '&'; 
			strPost += temp; 
		}
	}
	if(variaveis != null)
		strPost += variaveis;
	var isIE = document.all?true:false;
	if(isIE)
		strPost += "&UserBrowser=IE";
	else
		strPost += "&UserBrowser=Outro";
	xmlhttp.send(strPost); 	
}

function replaceOuterHTML(elm,outerHTML)
{
	if(elm)
	{
		if(elm.outerHTML)
		{
			//ie5+
			elm.outerHTML = outerHTML;
			return;
		}
		else if(elm.innerHTML != undefined)
		{
			//what is the tag we are trying to replace?
			var innerHTML = '';
			var endtagname = outerHTML.indexOf(' ');
			var tag = outerHTML.substr(1,(endtagname-1));
			var newNode = document.createElement(tag);
			var firstCloseTag = outerHTML.indexOf('>');
			//put the new tag out there
			elm.parentNode.replaceChild(newNode,elm);
			//set the attributes
			var strParse = outerHTML.substr(endtagname+1,firstCloseTag-(endtagname+1));
			//alert('parsing:' + strParse + '.');
			while(strParse.length > 0)
			{
				if(strParse.substr(0,1) == ' ')
				{
					strParse = strParse.substr(1,strParse.length);
				}
				else
				{
					var start = strParse.indexOf('="');
					var attributeName = strParse.substr(0,start);
					var end = (strParse.indexOf('"',(start + 2))) - (start + 2);
					var attributeValue = strParse.substr(start + 2, end);
					if(attributeName != null && attributeName != '')
						newNode.setAttribute(attributeName,attributeValue);
					strParse = strParse.substr(start + end + 4, strParse.length);
				}
			}
			//set the innerHTML
			if(outerHTML.substr(firstCloseTag-1,1) == '/')
			{
				innerHTML = outerHTML.substr(firstCloseTag +1, outerHTML.length);
			}
			else
			{
				var i = outerHTML.length - 2;
				var strStartClose = '';
				while(strStartClose != "<" && i>0)
				{
					strStartClose = outerHTML.substr(i,1);
					i--;
				}
				innerHTML = outerHTML.substr(firstCloseTag +1,i - firstCloseTag);
			}
			//alert('innerHTML=' + innerHTML + '.');
			newNode.innerHTML = innerHTML;
			return;
		}
	}
}











/*--------------------------------------------- BIBLIOTECAS EXTERNAS -----------------------------------------
 * Inicio: Nova Windows ShowModal DHTML 
 *
 * SUBMODAL v1.6
 * Used for displaying DHTML only popups instead of using buggy modal windows.
 *
 * By Subimage LLC
 * http://www.subimage.com
 *
 * Contributions by:
 * 	Eric Angel - tab index code
 * 	Scott - hiding/showing selects for IE users
 *	Todd Huss - inserting modal dynamically and anchor classes
 *
 * Up to date code can be found at http://submodal.googlecode.com
 *-------------------------------------------------------------------------------------------------------------*/

// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gReturnFunc;
var gPopupIsShown = false;
var gDefaultPage = "carregando.html";
var gHideSelects = false;
var gReturnVal = null;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = keyDownHandler;
}

/**
 * Initializes popup code on load.	
 */
function initPopUp() {
	// Add the HTML to the body
	theBody = document.getElementsByTagName('BODY')[0];
	popmask = document.createElement('div');
	popmask.id = 'popupMask';
	popcont = document.createElement('div');
	popcont.id = 'popupContainer';
	popcont.innerHTML = '' +
		'<div id="popupInner">' +
			'<div id="popupTitleBar">' +
				'<div id="popupTitle"></div>' +
			'</div>' +
			'<iframe src="'+ gDefaultPage +'" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>' +
			'<div id="popupFooterBar">' +
				'<div id="popupFooter" align="center">' + 
				    '<INPUT id="popCloseBox" type="button" value="Fechar" name="button1" class="form_botaoFechar" align="right" onclick="hidePopWin(true,\'-1\');">' +
				'</div>' +
			'</div>' +
		'</div>';
		
		/* align="center"
		popcont.innerHTML = '' +
		'<div id="popupInner">' +
			'<div id="popupTitleBar">' +
				'<div id="popupTitle"></div>' +
				'<div id="popupControls">' +
					'<img src="close.gif" onclick="hidePopWin(true);" id="popCloseBox" />' +
				'</div>' +
			'</div>' +
			'<iframe src="'+ gDefaultPage +'" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>' +
		'</div>';*/
		
		
		/*	popcont.innerHTML = '' +
		'<div id="popupInner">' +
			'<div id="popupTitleBar">' +
				'<div id="popupTitle"></div>' +
			'</div>' +
			'<iframe src="'+ gDefaultPage +'" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>' +
			'<div id="popupFooterBar">' +
				'<div id="popupFooter"></div>' +
				'<div id="popupButtons" align="center">' +
					'<img src="fechar.gif" onclick="hidePopWin(true);" id="popCloseBox"/>' +
				'</div>' +
			'</div>' +
		'</div>';*/
	theBody.appendChild(popmask);
	theBody.appendChild(popcont);
	
	gPopupMask = document.getElementById("popupMask");
	gPopupContainer = document.getElementById("popupContainer");
	gPopFrame = document.getElementById("popupFrame");	
	
	// check to see if this is IE version 6 or lower. hide select boxes if so
	// maybe they'll fix this in version 7?
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
		gHideSelects = true;
	}
	
	// Add onclick handlers to 'a' elements of class submodal or submodal-width-height
	var elms = document.getElementsByTagName('a');
	for (i = 0; i < elms.length; i++) {
		if (elms[i].className.indexOf("submodal") == 0) { 
			// var onclick = 'function (){showPopWin(\''+elms[i].href+'\','+width+', '+height+', null);return false;};';
			// elms[i].onclick = eval(onclick);
			elms[i].onclick = function(){
				// default width and height
				var width = 400;
				var height = 200;
				// Parse out optional width and height from className
				params = this.className.split('-');
				if (params.length == 3) {
					width = parseInt(params[1]);
					height = parseInt(params[2]);
				}
				showPopWin(this.href,width,height,null); return false;
			}
		}
	}
}
addEvent(window, "load", initPopUp);

 /**
	* @argument width - int in pixels
	* @argument height - int in pixels
	* @argument url - url to display
	* @argument returnFunc - function to call when returning true from the window.
	* @argument showCloseBox - show the close box - default true
	*/
function showPopWin(url, width, height, returnFunc, showCloseBox) {
	// show or hide the window close widget
	if (showCloseBox == null || showCloseBox == true) {
		document.getElementById("popCloseBox").style.display = "block";
	} else {
		document.getElementById("popCloseBox").style.display = "none";
	}
	gPopupIsShown = true;
	disableTabIndexes();
	gPopupMask.style.display = "block";
	gPopupContainer.style.display = "block";
	// calculate where to place the window on screen
	centerPopWin(width, height);
	
	var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);

	gPopupContainer.style.width = width + "px";
	gPopupContainer.style.height = (height+titleBarHeight) + "px";
	
	setMaskSize();

	// need to set the width of the iframe to the title bar width because of the dropshadow
	// some oddness was occuring and causing the frame to poke outside the border in IE6
	gPopFrame.style.width = parseInt(document.getElementById("popupTitleBar").offsetWidth, 10) + "px";
	gPopFrame.style.height = (height) + "px";
	
	// set the url
	gPopFrame.src = url;
	
	gReturnFunc = returnFunc;
	// for IE
	if (gHideSelects == true) {
		hideSelectBoxes();
	}
	
	window.setTimeout("setPopTitle();", 600);
}

//
var gi = 0;
function centerPopWin(width, height) {
	if (gPopupIsShown == true) {
		if (width == null || isNaN(width)) {
			width = gPopupContainer.offsetWidth;
		}
		if (height == null) {
			height = gPopupContainer.offsetHeight;
		}
		
		//var theBody = document.documentElement;
		var theBody = document.getElementsByTagName("BODY")[0];
		//theBody.style.overflow = "hidden";
		var scTop = parseInt(getScrollTop(),10);
		var scLeft = parseInt(theBody.scrollLeft,10);
	
		setMaskSize();
		
		//window.status = gPopupMask.style.top + " " + gPopupMask.style.left + " " + gi++;
		
		var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);
		
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		
		gPopupContainer.style.top = (scTop + ((fullHeight - (height+titleBarHeight)) / 2)) + "px";
		gPopupContainer.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
		//alert(fullWidth + " " + width + " " + gPopupContainer.style.left);
	}
}
addEvent(window, "resize", centerPopWin);
addEvent(window, "scroll", centerPopWin);
window.onscroll = centerPopWin;


/**
 * Sets the size of the popup mask.
 *
 */
function setMaskSize() {
	var theBody = document.getElementsByTagName("BODY")[0];
			
	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();
	
	// Determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) {
		popHeight = fullHeight;
	} else {
		popHeight = theBody.scrollHeight;
	}
	
	if (fullWidth > theBody.scrollWidth) {
		popWidth = fullWidth;
	} else {
		popWidth = theBody.scrollWidth;
	}
	
	gPopupMask.style.height = popHeight + "px";
	gPopupMask.style.width = popWidth + "px";
}


function retornaValor(val){
        //window.alert("Return value is..." + val);
        //if (val == "-1")
        //    window.alert("Nenhum item foi selecionado!");
        returnVal.value = val;
    }

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function hidePopWin(callReturnFunc, returnVal) {
	gPopupIsShown = false;
	var theBody = document.getElementsByTagName("BODY")[0];
	theBody.style.overflow = "";
	restoreTabIndexes();
	if (gPopupMask == null) {
		return;
	}
	gPopupMask.style.display = "none";
	gPopupContainer.style.display = "none";
	if (callReturnFunc == true && gReturnFunc != null) {
		// Set the return code to run in a timeout.
		// Was having issues using with an Ajax.Request();
		//gReturnVal = window.frames["popupFrame"].returnVal;
		//window.setTimeout('gReturnFunc(gReturnVal);', 1);
		
		gReturnFunc(returnVal);
	}
	gPopFrame.src = gDefaultPage;
	// display all select boxes
	if (gHideSelects == true) {
		displaySelectBoxes();
	}
	__doPostBack('','');
}


/**
 * Sets the popup title based on the title of the html document it contains.
 * Uses a timeout to keep checking until the title is valid.
 */
function setPopTitle() {
	return;
	if (window.frames["popupFrame"].document.title == null) {
		window.setTimeout("setPopTitle();", 10);
	} else {
		document.getElementById("popupTitle").innerHTML = window.frames["popupFrame"].document.title;
	}
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}


/**
 * Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
 * IE has a problem with wanted select form tags to always be the topmost z-index or layer
 *
 * Thanks for the code Scott!
 */
function hideSelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++) {
    x[i].style.visibility = "hidden";
  }
}

/**
 * Makes all drop down form select boxes on the screen visible so they do not 
 * reappear after the dialog is closed.
 * 
 * IE has a problem with wanting select form tags to always be the 
 * topmost z-index or layer.
 */
function displaySelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++){
    x[i].style.visibility = "visible";
  }
}

/**
 * COMMON DHTML FUNCTIONS
 * These are handy functions I use all the time.
 *
 * By Seth Banks (webmaster at subimage dot com)
 * http://www.subimage.com/
 *
 * Up to date code can be found at http://www.subimage.com/dhtml/
 *
 * This code is free for you to use anywhere, just keep this comment block.
 */

/**
 * X-browser event handler attachment and detachment
 * TH: Switched first true to false per http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html
 *
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}
function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/
 *
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 *
 * Gets the full width/height because it's different for most browsers.
 */
function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 

	return window.undefined; 
}
function getViewportWidth() {
	var offset = 17;
	var width = null;
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
}

/**
 * Gets the real scroll top
 */
function getScrollTop() {
	if (self.pageYOffset) // all except Explorer
	{
		return self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollTop;
	}
}
function getScrollLeft() {
	if (self.pageXOffset) // all except Explorer
	{
		return self.pageXOffset;
	}
	else if (document.documentElement && document.documentElement.scrollLeft)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollLeft;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollLeft;
	}
}

function checkAll_jQuery(painelId){
    if(!jQuery)
        alert("falta carregar a biblioteca jQuery");
    
    $(document).ready(function(){
        var objChk = $('#'+painelId+' input:enabled[type=checkbox]');
        objChk.attr('checked', true);
    });
}

function uncheckAll_jQuery(painelId){
    if(!jQuery)
        alert("falta carregar a biblioteca jQuery");
        
    $(document).ready(function(){
        var objChk = $('#'+painelId+' input:enabled[type=checkbox]');
        objChk.attr('checked', false);
    });
}

/* FIM:    Testes com Nova Windows ShowModal DHTML */


