/**
 *
 * Esse arquivo é responsável por definir funções javascript comuns do site
 * @author Joubert Alexandrino
 * @package Agência Virtual
 */
 
 


/**
 * Função responsável por expandir ou comprimir itens de menu
 * @param obj 
 * @param tipo 
 */
function mostraspan(obj,tipo){
	
	if (tipo == 'cap')
		limite = 2;
	if (tipo == 'sub')
		limite = 0;
		
	for (x=1;x<=limite;x++){

		if (x == obj){
			if (eval(tipo+x+".style.display == 'none'")){
				eval(tipo+x+".style.display = ''") ;				
			}
			else{
				eval(tipo+x+".style.display = 'none'") ;				
			}
		}else{
			eval(tipo+x+".style.display = 'none'") ;			
		}
	}
}



/*
================================================================================
Formata datas digitadas em um campo texto colocando as barras separadoras
================================================================================
*/
function formatadata(objTexto)
{
strDataO = new String(objTexto.value);
intTamDataO = strDataO.length;
re = new RegExp("[/_]","gi");
strDataL = strDataO.replace(re,"");
intTamDataL = strDataL.length;
if (event.keyCode != 8)
    {
    if ((strDataO.charCodeAt(intTamDataO - 1) >= 48) && 
        (strDataO.charCodeAt(intTamDataO - 1) <= 57))
        {
        switch (intTamDataL)
            {
            case 1:
                if (eval(strDataL) <= 3)
                    {strDataF = strDataL + "_/__/____";}
                else
                    {strDataF = strDataO.substr(0, intTamDataO - 1);};
                break;
            case 2:
                if (eval(strDataL) <= 31)
                    {strDataF = strDataL + "/__/____";}
                else
                    {strDataF = strDataO.substr(0, intTamDataO - 1);};
                break;
            case 3:
                if (eval(strDataL.substr(2,1)) <= 1)
                    {strDataF = strDataL.substr(0,2) + "/" + strDataL.substr(2,1) + "_/____";}
                else
                    {strDataF = strDataO.substr(0, intTamDataO - 1);};
                break;
            case 4:
                if (eval(strDataL.substr(2,2)) <= 12)
                    {strDataF = strDataL.substr(0,2) + "/" + strDataL.substr(2,2) + "/____";}
                else
                    {strDataF = strDataO.substr(0, intTamDataO - 1);};
                break;
            case 5:
                strDataF = strDataL.substr(0,2) + "/" + strDataL.substr(2,2) + "/" + strDataL.substr(4,1) + "___";
                break;
            case 6:
                strDataF = strDataL.substr(0,2) + "/" + strDataL.substr(2,2) + "/" + strDataL.substr(4,2) + "__";
                break;
            case 7:
                strDataF = strDataL.substr(0,2) + "/" + strDataL.substr(2,2) + "/" + strDataL.substr(4,3) + "_";
                break;
            case 8:
                strDataF = strDataL.substr(0,2) + "/" + strDataL.substr(2,2) + "/" + strDataL.substr(4,4);
                break;
            };
        
        objTexto.value = strDataF;
        }
    else
        {objTexto.value = strDataO.substr(0, intTamDataO - 1);};
    };
};

function expandingWindow(website) {
var heightspeed = 10; // velocidade vertical
var widthspeed = 12;  // velocidade horizontal
var leftdist = 100;    // distância da margem esquerda
var topdist = 30;     // distância do topo
if (document.all) {
var winwidth = window.screen.availWidth - leftdist;
var winheight = window.screen.availHeight - topdist;
var sizer = window.open("","","left=" + leftdist + ",top=" + topdist + ",width=1,height=1,scrollbars=yes");
for (sizeheight = 1; sizeheight < winheight; sizeheight += heightspeed) {
sizer.resizeTo("1", sizeheight);
}
for (sizewidth = 1; sizewidth < winwidth; sizewidth += widthspeed) {
sizer.resizeTo(sizewidth, sizeheight);
}
sizer.location = website;
}
else
window.location = website;
}

function EnviaForm(intCodAsc, objForm)
{
 if (intCodAsc == 13)
     {
    if ((objForm.login.value == "") || 
        (objForm.senha.value == ""))
       {alert("Os campos Login e Senha não foram preenchidos corretamente!");}
    else
       {objForm.submit();};
    };
}

function alterar_senha(formulario){

if (formulario.txtNovaSenha.value != formulario.txtConfirmeNovaSenha.value)
    {
    alert("As senhas digitadas não são iguais! Digite-as novamente.");
    formulario.txtNovaSenha.value = "";
    formulario.txtConfirmeNovaSenha.value = "";
    }
else
    {
    strNovaSenha = formulario.txtNovaSenha.value
    if (strNovaSenha.length < 4 && strNovaSenha.length > 0)
        {
        alert("ERRO: Sua nova senha deve possuir, no mínimo, 4 caracteres (letras e/ou números).");
        formulario.txtNovaSenha.value = "";
        formulario.txtConfirmeNovaSenha.value = "";
        }
    else
        {testaformulario(formulario)}
    };
}

//função para abrir janela pop-up
function popup(strURL, intLargura, intAltura){

    window.open (strURL,"","directories=no,height=" + intAltura + ",width=" + intLargura + ",menubar=yes,resizable=no,status=yes,titlebar=no,scrollbars=yes,toolbar=no");

}

//função para abrir janela pop-up sem scrollbars
function popup2(strURL, intLargura, intAltura){

    window.open (strURL,"","directories=no,height=" + intAltura + ",width=" + intLargura + ",menubar=no,resizable=no,status=no,titlebar=no,scrollbars=no,toolbar=no");
}

//função para abrir janela pop-up sem nada
function cleanpop(strURL, intLargura, intAltura){

    window.open (strURL,"","directories=no,height=" + intAltura + ",width=" + intLargura + ",menubar=no,resizable=no,statusbar=no,titlebar=no,scrollbars=no,toolbar=no")

}

function popcentro(strURL, intLargura, intAltura){

		w = intLargura;
		h = intAltura;
		l = (screen.availWidth-10 - w) / 2;
		t = (screen.availHeight-20 - h) / 2;
		features = "width="+w+",height="+h+",left="+l+",top="+t;
		features += ",screenX="+l+",screenY="+t;
		features += ",scrollbars=no,resizable=no,location=no";
		features += ",menubar=no,toolbar=no,status=no";

		window.open(strURL,"popup",features);
}

//função para abrir janela pop-up com barra de menu
function popupmenu(strURL, intLargura, intAltura){

    window.open (strURL,"","directories=no,height=" + intAltura + ",width=" + intLargura + ",menubar=yes,resizable=no,status=no,titlebar=no,scrollbars=yes,toolbar=no")

}

//função para testar se o número de caracteres utilizado na busca é no mínimo 3
function testabusca(formulario){
    
    var strTexto = formulario.txt_busca.value
    
    if (strTexto.length < 3)
        {alert("A palavra chave para a busca deve conter no mínimo 3 caracteres!")}
    else
        {formulario.submit()};

}

//função para decidir e enviar o usuário à etapa desejada de atualização de cadastro do site
function decide_etapa(objRadio){

if (objRadio[0].checked)
    {history.go(-2)}
else
    {history.go(-1)};

}

function abre_janela(endereco, largura, altura) {

var janela, strCaracteristicas 

strCaracteristicas = "width=" + largura + ", height=" + altura + ", location=no, menubar=no, resizable=no, scrollbars=no, dependent=yes"

janela=window.open(endereco, "", strCaracteristicas)

}

function muda_volta_menu(categoria) {
    
    javascript:parent.frames["men"].location.href='pag_men.cfm?codigo_categoria=' + categoria + '&muda_volta=1'
}

function imprime_frame() {
window.parent.con.focus();
window.print();
}

function surfto(form)
{
var myindex=form.dest.selectedIndex
window.open(form.dest.options[myindex].value, target="_top", "toolbar=yes,scrollbars=yes,location=yes,status=yes,menubar=yes"); //change these both to "yes" to get the toolbar
form.dest.selectedIndex="0"
}

function inserelista(elemento)
{
    
    document.cookie = "L" + elemento + ";";
    alert(document.cookie);
}
function checacampos()
{
    var calculo = 0;
    var indice = 0;
    for (var i = 0; i < 60; i++)
    {
        if (quest.elements[i].checked == 1) 
        {
            indice++;
            calculo = calculo - (-quest.elements[i].value);
        }
    }
    if (indice == 20)
    {
        quest.method = "post"
        quest.action = "scr_tes_per_emp.cfm?calculo="+calculo
        quest.submit()
    }
    else
    {
        alert("Você deve preencher todos os campos")
    }
    
}

function fun_abr_jan(janela,alvo)
{
    window.open(janela,alvo,"toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=no,menubar=yes,width=400,height=400");
}

function mostra_hint(nome_div, mostra_esconde)
{
    if (mostra_esconde == "mostra")
        {document.all(nome_div).className = "hintShow";}
    else
        {document.all(nome_div).className = "hintHide";}
}    

function fun_nav(cat_nav){
    parent.frames["nav"].location = "pag_nav.cfm?codigo_categoria=" + cat_nav;
}

function fun_men(cat_nav){
    parent.frames["men"].location = "pag_men.cfm?codigo_categoria=" + cat_nav;
}

function fun_des(cat_nav){
    parent.frames["des"].location = "pag_des.cfm?codigo_categoria=" + cat_nav;
}

function verifica_recarga() {
var strRef = document.referrer

    if (strRef.substring(0,38) != "http://www.sebraees.com.br/pag_ent.htm")
    {
        fun_nav(1);
        fun_men(1);
        fun_des(1);
    };
}

function verifica_popup() {
var strRef = document.referrer

    if (strRef.substring(0,26) != "http://www.sebraees.com.br")
    {abre_janela('pop_psqt.cfm', '280', '260')};
}

/*function vai_para(my_select, frame_alvo)
{
    var index = my_select.selectedIndex;
    parent.frames[frame_alvo].location = my_select.options[index].value;
    my_select.selectedIndex = 0;
}*/

function vai_para(my_select, frame_alvo)
{
    var alvo
    var index = my_select.selectedIndex;
    var pagina = my_select.options[index].value;
    
    if (pagina.substr(0,4) == "http")
        {alvo = "_blank";}
    else
        {alvo = frame_alvo;}
    if (alvo == "_blank")
        window.open(pagina, "_blank")
    else
        parent.frames[alvo].location = pagina;
}

function menu(url)
{
    parent.frames["men"].location = url;
}

//-- Cria links dentro do texto --
    function linka(url)
    {
        var tr;
        var txt_sel;
        
        if (url == "")
            alert("Nenhum nome de arquivo foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                txt_sel = tr.text;
                tr.text = "<a href='"+ url +"'>" + txt_sel + "</a>";
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }
    
//-- Cria items de lista dentro do texto --    

function listitem()
{
    var tr, trecho, novo_trecho1, novo_trecho2, txt_sel;
    
    start_tag = "<li>";
    end_tag = "</li>";
    
    tr = document.selection.createRange();
        
    if (tr.text != "")
        {
        trecho = new String(tr);
        
        if (trecho.search(start_tag) == -1)
            {
            txt_sel = tr.text;
            tr.text = "<li>"+ txt_sel +"</li><br>";
            }
        else
            {
            novo_trecho1 = trecho.replace(start_tag, "");
            novo_trecho2 = novo_trecho1.replace(end_tag, "");
            tr.text = novo_trecho2
            }
        }
    else
        alert("Nenhum texto foi selecionado!");
}

//-- Formata texto --
function formata(efeito)
{
    var tr, trecho, novo_trecho1, novo_trecho2;
    var txt_sel;
    var start_tag, end_tag;
    if (efeito == "negrito"){
        start_tag = "<b>";
        end_tag = "</b>";}
    else {
        if (efeito == "italico"){
            start_tag = "<i>";
            end_tag = "</i>";}
        else {
            if (efeito == "sublinhado"){
                start_tag = "<u>";
                end_tag = "</u>";}
             }
         }
    
    tr = document.selection.createRange();
    
    if (tr.text != "")
        {
        trecho = new String(tr)
        
        if (trecho.search(start_tag) == -1)
            {
            txt_sel = tr.text;
            tr.text = start_tag + txt_sel + end_tag;
            }
        else
            {
            novo_trecho1 = trecho.replace(start_tag, "");
            novo_trecho2 = novo_trecho1.replace(end_tag, "");
            tr.text = novo_trecho2
            }
        }
    else
        alert("Nenhum texto foi selecionado!");    
}


function verifica(){
        
        if (form.titulo_categoria.options[form.titulo_categoria.selectedIndex].value == "nenhuma")
            {alert("Você deve escolher a categoria antes.")}
        else
            {form.submit();}
    }

//-- insere imagens dentro do texto --
    function ins_img(url)
    {
        var tr;
        var txt_sel;
        
        if (url == "")
            alert("Nenhum nome de arquivo foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                
                txt_sel = tr.text;
                tr.text = "<img src='imagens/"+ url +"'>" + txt_sel;
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }

//-- Cria links para imagens dentro do texto --
    function linka_img(imagem)
    {
        var tr, txt_sel, trecho, trecho_final, inicio_start_tag, fim_start_tag, end_tag, inicio, fim, tag_inteira;
        
        if (imagem == "")
            alert("Nenhuma imagem foi selecionada!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                trecho              = new String(tr.text);
                inicio_start_tag = new RegExp("<");
                fim_start_tag      = new RegExp(">");
                end_tag          = new RegExp("</a>");
                
                if (trecho.search(inicio_start_tag) == -1)
                    {
                    txt_sel = tr.text;
                    tr.text = "<a href='imagens/"+ imagem +"'>" + txt_sel + "</a>";
                    }
                else
                    {
                    trecho = trecho.replace(end_tag, "");
                    inicio = trecho.search(inicio_start_tag);
                    fim    = trecho.search(fim_start_tag);
                    tag_inteira = trecho.substring(inicio, fim+1);
                    trecho_final = trecho.replace(tag_inteira, "");
                    tr.text = trecho_final;
                    }
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }

//-- Cria links para bookmarks dentro do texto --
    function cria_bookmark(book)
    {
        var tr, txt_sel, trecho, trecho_final, inicio_start_tag, fim_start_tag, end_tag, inicio, fim, tag_inteira;
        
        if (book == "")
            alert("Nenhum nome para o bookmark foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                trecho              = new String(tr.text);
                inicio_start_tag = new RegExp("<");
                fim_start_tag      = new RegExp(">");
                end_tag          = new RegExp("</a>");
                
                if (trecho.search(inicio_start_tag) == -1)
                    {
                    txt_sel = tr.text;
                    tr.text = "<a name='"+ book +"'>" + txt_sel + "</a>";
                    }
                else
                    {
                    trecho = trecho.replace(end_tag, "");
                    inicio = trecho.search(inicio_start_tag);
                    fim    = trecho.search(fim_start_tag);
                    tag_inteira = trecho.substring(inicio, fim+1);
                    trecho_final = trecho.replace(tag_inteira, "");
                    tr.text = trecho_final;
                    }
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }
    
//-- Cria links dentro do texto --
    function linka(url)
    {
        var tr, txt_sel, trecho, trecho_final, inicio_start_tag, fim_start_tag, end_tag, inicio, fim, tag_inteira;
        
        if (url == "")
            alert("Nenhum endereço foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                trecho              = new String(tr.text);
                inicio_start_tag = new RegExp("<");
                fim_start_tag      = new RegExp(">");
                end_tag          = new RegExp("</a>");
                
                if (trecho.search(inicio_start_tag) == -1)
                    {
                    txt_sel = tr.text;
                    if (document.form.alvo.checked)
                        tr.text = "<a href='"+ url +"' target='_blank'>" + txt_sel + "</a>";
                    else
                        tr.text = "<a href='"+ url +"'>" + txt_sel + "</a>";
                    }
                else
                    {
                    trecho = trecho.replace(end_tag, "");
                    inicio = trecho.search(inicio_start_tag);
                    fim    = trecho.search(fim_start_tag);
                    tag_inteira = trecho.substring(inicio, fim+1);
                    trecho_final = trecho.replace(tag_inteira, "");
                    tr.text = trecho_final;
                    }
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }

//-- Cria links para arquivo dentro do texto --
    function linka_arq(arq)
    {
        var tr, txt_sel, trecho, trecho_final, inicio_start_tag, fim_start_tag, end_tag, inicio, fim, tag_inteira;
        
        if (arq == "")
            alert("Nenhum nome de arquivo foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                trecho              = new String(tr.text);
                inicio_start_tag = new RegExp("<");
                fim_start_tag      = new RegExp(">");
                end_tag          = new RegExp("</a>");
                
                if (trecho.search(inicio_start_tag) == -1)
                    {
                    txt_sel = tr.text;
                    tr.text = "<a href='arquivos/"+ arq +"' target='_blank'>" + txt_sel + "</a>";
                    }
                else
                    {
                    trecho = trecho.replace(end_tag, "");
                    inicio = trecho.search(inicio_start_tag);
                    fim    = trecho.search(fim_start_tag);
                    tag_inteira = trecho.substring(inicio, fim+1);
                    trecho_final = trecho.replace(tag_inteira, "");
                    tr.text = trecho_final;
                    }
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }

//-- Cria links para categorias dentro do texto --
    function linka_cat(url)
    {
        var tr, txt_sel, trecho, trecho_final, inicio_start_tag, fim_start_tag, end_tag, inicio, fim, tag_inteira;
        
        if (url == "")
            alert("Nenhum nome de arquivo foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                trecho              = new String(tr.text);
                inicio_start_tag = new RegExp("<");
                fim_start_tag      = new RegExp(">");
                end_tag          = new RegExp("</a>");
                
                if (trecho.search(inicio_start_tag) == -1)
                    {
                    txt_sel = tr.text;
                    tr.text = "<a href='"+ url +"' target='con'>" + txt_sel + "</a>";
                    }
                else
                    {
                    trecho = trecho.replace(end_tag, "");
                    inicio = trecho.search(inicio_start_tag);
                    fim    = trecho.search(fim_start_tag);
                    tag_inteira = trecho.substring(inicio, fim+1);
                    trecho_final = trecho.replace(tag_inteira, "");
                    tr.text = trecho_final;
                    }
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }

//-- Cria links de e-mail dentro do texto --
    function linka_email(email)
    {
        var tr, txt_sel, trecho, trecho_final, inicio_start_tag, fim_start_tag, end_tag, inicio, fim, tag_inteira;
        
        if (email == "")
            alert("Nenhum endereço de e-mail foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                trecho              = new String(tr.text);
                inicio_start_tag = new RegExp("<");
                fim_start_tag      = new RegExp(">");
                end_tag          = new RegExp("</a>");
                
                if (trecho.search(inicio_start_tag) == -1)
                    {
                    txt_sel = tr.text;
                    tr.text = "<a href='mailto:"+ email +"'>" + txt_sel + "</a>";
                    }
                else
                    {
                    trecho = trecho.replace(end_tag, "");
                    inicio = trecho.search(inicio_start_tag);
                    fim    = trecho.search(fim_start_tag);
                    tag_inteira = trecho.substring(inicio, fim+1);
                    trecho_final = trecho.replace(tag_inteira, "");
                    tr.text = trecho_final;
                    }
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }    

function MudaChkBox(tipo)
{
    var tam = form_val_ass.validados.length;
    if(tipo == 'valida')
    {
        for(i = 0; i < tam; i++)
        {
        form_val_ass.validados[i].checked = true;
        }
    }
    else
    {
        for(i = 0; i < tam; i++)
        {
        form_val_ass.validados[i].checked = false;
        }
    }
}

function menu(url)
{
    parent.frames["men"].location = url;
}

function muda_mensagem(msg)
{
    top.frames["mensagem"].location = 'bar_men.cfm?mensagem=' + msg;
}

//-- Cria links para arquivos dentro do texto --
    function linka_arquivo(arq)
    {
        var tr;
        var txt_sel;
        var caminho = "http://www.sebraees.com.br/inf_emp/resumo/arquivos/"
        
        if (arq == "")
            alert("Nenhum nome de arquivo foi digitado!");
        else
            {
            tr = document.selection.createRange();
            if (tr.text != "")
                {
                txt_sel = tr.text;
                tr.text = "<a href=" + caminho + arq +" target='_blank'>" + txt_sel + "</a>";
                }
            else
                alert("Nenhum texto foi selecionado!");
            }
    }
    
    
//-- Formata texto --
function formata(efeito)
{
    var tr, res, ree;
    var txt_sel;
    var start_tag, end_tag;
    if (efeito == "negrito")
    {
        start_tag = "<b>";
        end_tag = "</b>";
    }
    else 
    {
        if (efeito == "italico")
        {
            start_tag = "<i>";
            end_tag = "</i>";
        }
        else
        {
            if (efeito == "sublinhado")
            {
                start_tag = "<u>";
                end_tag = "</u>";
             }
         }
    }
    
    tr = document.selection.createRange();
    res = new RegExp(start_tag);
    ree = new RegExp(end_tag);

        if (tr.text != "")
        {
            if (tr.text.search(res) == -1)
            {
                txt_sel = tr.text;
                tr.text = start_tag + txt_sel + end_tag;
            }
            else
            {
                txt_sel = tr.text;
                my_string = txt_sel.replace(res, "");
                my_string = my_string.replace(ree, "");
                tr.text = my_string;
            }
        }
        else
            alert("Nenhum texto foi selecionado!");
}    
    
//-- Cria items de lista dentro do texto --    

function listitem()
{
    var tr, trecho, novo_trecho, txt_sel, start_tag, end_tag;
    
    tr = document.selection.createRange();
    start_tag = new RegExp("<li>");
    end_tag = new RegExp("</li>");
    
    if (tr.text != "")
        {
        trecho = new String(tr.text)
        
        if (trecho.search(start_tag) == -1)
            {
            txt_sel = tr.text;
            tr.text = "<li>"+ txt_sel +"</li>";
            }
        else
            {
            novo_trecho = trecho.replace(start_tag, "");
            novo_trecho = novo_trecho.replace(end_tag, "");
            tr.text = novo_trecho;
            }
        }
    else
        alert("Nenhum texto foi selecionado!");
}

//-- Limpa a área de conteúdo --

function limpa_conteudo(){

    top.frames["conteudo"].location.href="branco.htm";

}

//-- Limpa a barra de ferramentas --

function limpa_ferramentas(){

    top.frames["ferramentas"].location.href="bar_fer.cfm";

}






// função irada para checar campos - by Juliano Careca

function testaformulario(formulario)
{
/* 
ESSA FUNÇÃO ANALISA OS CAMPOS DE UM FORMULÁRIO E, SE TODOS OS CAMPOS REQUERIDOS ESTIVEREM 
PREENCHIDOS, ENVIA O FORMULÁRIO. OS CAMPOS QUE FOREM REQUERIDOS DEVEM TER SEUS NOMES
PRECEDIDOS DE "req_". É NECESSÁRIO TAMBÉM QUE, PARA CADA CAMPO REQUERIDO, SEJA COLOCADO 
EM SUA TAG O PARÂMETRO "id=<descrição_do_campo>". Exemplo:
    <input type="text" name="req_texto" id="Observações">
*/ 

var numero_elementos = formulario.length, contador = 0; 
var contador_elementos, valido, nome_elemento, id_elemento_vazio="nenhum", numero_elemento_vazio;
var con_num_rad, contador_radios, radio_valido, numero_radios, nome_radio_atual, numero_radio;
var aRadio = new Array(), aElementosRadio = new Array(), grupo_novo = 0, aContador;

// PREDEFINE O FORMULÁRIO COMO PREENCHIDO CORRETAMENTE
valido = 1;

// VERIFICA SE O FORMULARIO NÃO ESTÁ VAZIO
if (numero_elementos == 0)
    {
    alert("O formulário não possui nenhum campo a ser validado!");
    }
else
    {
    // INÍCIO DO LOOP DE VERIFICAÇÃO DOS CAMPOS DO FORMULÁRIO
    for (contador = numero_elementos-1; contador >= 0; contador--)
        {
        nome_elemento = formulario.elements[contador].name
        // VERIFICA SE O CAMPO ATUAL É REQUERIDO
        //if (nome_elemento.substr(0,4) == "req_")
        if (formulario.elements[contador].requerido == 1)
            {
            // DECIDE QUAL É O TIPO DE CAMPO A SER VERIFICADO
            switch (formulario.elements[contador].type)
                {
                    case "text" : // SE FOR CAMPO TEXTO, VERIFICA SE NÃO ESTÁ VAZIO
                        if (formulario.elements[contador].value == "")
                            {
                            valido = 0;
                            numero_elemento_vazio = contador;
                            id_elemento_vazio = formulario.elements[contador].id;
                            }
                        break;
                    case "password" : // SE FOR CAMPO TEXTO, VERIFICA SE NÃO ESTÁ VAZIO
                        if (formulario.elements[contador].value == "")
                            {
                            valido = 0;
                            numero_elemento_vazio = contador;
                            id_elemento_vazio = formulario.elements[contador].id;
                            }
                        break;
                    case "radio" : // SE FOR TIPO RADIO BUTTON
                        
                        //VERIFICA SE É UM GRUPO NOVO DE RADIO BUTTONS
                        nome_radio_atual = formulario.elements[contador].name;
                        grupo_novo = 1;
                        
                        if (aRadio.length != 0)
                            {
                            for (aContador = 0; aContador <= aRadio.length; aContador++)
                                {
                                if (nome_radio_atual == aRadio[aContador])
                                    {grupo_novo = 0;}
                                }
                            }
                        else
                            {grupo_novo = 1;};
                            
                        if (grupo_novo == 1) // SE FOR UM GRUPO NOVO
                        {
                            // GUARDA O NOME DESSE RADIO NO ARRAY DE RADIOS ANALISADOS:
                            aRadio[aRadio.length + 1] = formulario.elements[contador].name; 
                            
                            // GUARDA NUM ARRAY OS NÚMEROS DE ELEMENTOS DOS RADIO BUTTONS DO GRUPO A SEREM ANALISADOS
                            for (con_num_rad = 0; con_num_rad <= numero_elementos - 1; con_num_rad++)
                            {
                                if (formulario.elements[con_num_rad].name == formulario.elements[contador].name)
                                {
                                    aElementosRadio[aElementosRadio.length] = con_num_rad;
                                }
                            }
                            
                            radio_valido = 0;
                            
                            // VERIFICA UM POR UM DOS RADIO BUTTONS SE ALGUM DELES ESTÁ MARCADO
                            for (contador_radios = 1; contador_radios <= aElementosRadio.length; contador_radios++)
                            {
                                // SE ALGUM DELES ESTIVER MARCADO, VALIDA O GRUPO DE RADIO BUTTONS
                                numero_radio = aElementosRadio[contador_radios-1];
                                
                                if (formulario.elements[numero_radio].checked)
                                    radio_valido = 1;
                            }
                            
                            // SE O GRUPO DE RADIO BUTTONS NÃO FOR VALIDADO, MARCA O FORMULÁRIO COMO INVÁLIDO E IDENTIFICA 
                            // O CAMPO COMO O RESPONSÁVEL PELA INVALIDAÇÃO
                            if (radio_valido == 0)
                            {
                                valido = 0;
                                numero_elemento_vazio = contador;
                                id_elemento_vazio = formulario.elements[contador].id;
                            }
                            aElementosRadio.length = 0;
                        }
                        break;
                    case "checkbox" : // SE FOR CAMPO CHECKBOX, VERIFICA SE ESTÁ MARCADO
                        if (formulario.elements[contador].checked == false)
                        {
                            valido = 0;
                            numero_elemento_vazio = contador;
                            id_elemento_vazio = formulario.elements[contador].id;
                        }
                        break;
                    case "textarea" : // SE FOR CAMPO TEXTAREA, VERIFICA SE NÃO ESTÁ VAZIO
                        if (formulario.elements[contador].value == "")
                            {
                                valido = 0;
                                numero_elemento_vazio = contador;
                                id_elemento_vazio = formulario.elements[contador].id;
                            }
                        break;
                    case "select-multiple" : // SE FOR CAMPO SELECT MULTIPLE, VERIFICA SE PELO MENOS UMA OPÇÃO ESTÁ MARCADA
                        if (formulario.elements[contador].selectedIndex == -1)
                        {
                            valido = 0;
                            numero_elemento_vazio = contador;
                            id_elemento_vazio = formulario.elements[contador].id;
                        }
                        break;
                    case "select-one" : // SE FOR CAMPO SELECT ONE, VERIFICA SE ALGUMA OPÇÃO FOI SELECIONADA
                        if (formulario.elements[contador].selectedIndex == 0)
                        {
                            valido = 0;
                            numero_elemento_vazio = contador;
                            id_elemento_vazio = formulario.elements[contador].id;
                        }
                        break;
                } //fim switch
            }  //se for requerido
        } //for (contador = 0; contador <= numero_elementos; contador++)
    } //else
    
    // SE O FORMULÁRIO NÃO ESTIVER CORRETAMENTE PREENCHIDO (valido = 0) MOSTRA MENSAGEM PRO USUÁRIO
    // DIZENDO QUAL É O CAMPO QUE NÃO FOI PREENCHIDO E COLOCANDO O FOCO SOBRE O MESMO
    if (valido == 0) 
    {
        alert("ATENÇÃO! O campo " + id_elemento_vazio + " não foi preenchido corretamente");
        formulario.elements[numero_elemento_vazio].focus();
    }
    else
    {
        formulario.submit();
    }
} //function

function MostraCamada(strNomeCamada, strAcao) {
    var objCamada
    objCamada = document.getElementById(strNomeCamada)
    if (strAcao == "mostra")
        {objCamada.style.visibility = "visible";}
    else
        {objCamada.style.visibility = "hidden";};
}

//===================================================================================
// FUNÇÃO PARA FORMATAR O CAMPO ENQUANTO ESTÁ DIGITANDO
// A FUNÇÃO ESTÁ PREPARADA PARA FORMATAR APENAS OS CAMPOS DE:
// "CEP"   com o formato "xxxxx-xxx"
// "DATA"  com o formato "xx/xx/xxxx"
// "HORA"  com o formato "xx:xx"
// "CPF"   com o formato "xxx.xxx.xxx-xx"
// "R$"	   com o formato "###x,xx"
// FUNCTION FormataDado("intposição_campo_atual", "intTamanho_Max_Campo", "intPosicao_Formatacao", "strTipo_Dado", event)
//===================================================================================
function FormataDado(objCampo,tammax,pos,tipo,teclapres){
	var tecla = teclapres.keyCode;
	var campo = objCampo.id;
	vr = objCampo.value;
	vr = vr.replace( "-", "" ); // KeyAscii = 45
	vr = vr.replace( ".", "" ); // KeyAscii = 46
	vr = vr.replace( "/", "" ); // KeyAscii = 47
	vr = vr.replace( ":", "" ); // KeyAscii = 58
	vr = vr.replace( ":", "" ); // KeyAscii = 58
	vr = vr.replace( ",", "" ); // KeyAscii = 44
	tam = vr.length ;
	
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){ tam = tam - 1 ; }
			
	if ( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 )
			{objCampo.value = vr;};
		if ( tam > pos && tam <= tammax ){
			if (tipo == "data") {
				if ( tam == 3){
					objCampo.value = vr.substr( 0, 2 ) + '/' + vr.substr( tam - pos, tam );
				}else{
					if ( tam == 5){
						if (tecla != 8){
							objCampo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, tam - pos ) + '/' + vr.substr( tam - pos, tam );
						}
					}
				}
			}else{ // IF TIPO = "DATA"
				if (tipo == "cpf" ){
					if (tam == 4){
						objCampo.value = vr.substr( 0, 3 ) + '.' + vr.substr( tam - pos, tam );
					}else{
						if ( tam == 7){
							if (tecla != 8){
								objCampo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 6 ) + '.' + vr.substr( tam - pos, tam );
							}
						}else{
							if ( tam == 11){
								if (tecla != 8){
									objCampo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 7, 3 ) + '-' + vr.substr( tam - pos, tam );
								}
							}
						}
					}
				}else{ // TIPO = "CPF"
					if (tipo == "hora") {
						if ( tam == 3){
							objCampo.value = vr.substr( 0, 2 ) + ':' + vr.substr( 2, tam );
						}
					}else{ // TIPO = "HORA"
						if (tipo == "cep") {
							if ( tam == (tammax - pos)+1 ){
								Campo.value = vr.substr( 0, (tammax - pos) ) + '-' + vr.substr( (tammax - pos), tam );
							}
						}else{
							if (tipo == "R$"){
								if ( tam > pos && tam <= tammax){
									objCampo.value = vr.substr( 0, tam - pos ) + ',' + vr.substr( tam - pos, tam );
								}
							}
						}//FIM DO ELSE IF TIPO="CEP"
					}//FIM DO ELSE TIPO="HORA"
				}//FIM DO ELSE TIPO="CPF"
			}//FIM DO IF TIPO="CPF"
		}//FIM DO ELSE TIPO="DATA"
	}//FIM DO IF ( tam > pos && tam <= tammax )
} // FINAL DA FUNÇÃO QUE FORMATA O CAMPO



//===================================================================================
// FUNÇÃO PARA FORMATAR O CAMPO ENQUANTO ESTÁ DIGITANDO
// A FUNÇÃO ESTÁ PREPARADA PARA FORMATAR APENAS OS CAMPOS DE:
// "CEP"   com o formato "xxxxx-xxx"
// "DATA"  com o formato "xx/xx/xxxx"
// "HORA"  com o formato "xx:xx"
// "CPF"   com o formato "xxx.xxx.xxx-xx"
// "R$"	   com o formato "###x,xx"
// FUNCTION FormataDado("intposição_campo_atual", "intTamanho_Max_Campo", "intPosicao_Formatacao", "strTipo_Dado", event)
//===================================================================================
function FormataDado1(objCampo,tammax,pos,tipo,teclapres){
	var tecla = teclapres.keyCode;
	var campo = objCampo.id;
	vr = objCampo.value;
	vr = vr.replace( "-", "" ); // KeyAscii = 45
	vr = vr.replace( ".", "" ); // KeyAscii = 46
	vr = vr.replace( "/", "" ); // KeyAscii = 47
	vr = vr.replace( ":", "" ); // KeyAscii = 58
	vr = vr.replace( ":", "" ); // KeyAscii = 58
	vr = vr.replace( ",", "" ); // KeyAscii = 44
	tam = vr.length ;
	
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){ tam = tam - 1 ; }
			
	if ( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 )
			{objCampo.value = vr;};
		if ( tam > pos && tam <= tammax ){
			if (tipo == "data") {
				if ( tam == 3){
					objCampo.value = vr.substr( 0, 2 ) + '/' + vr.substr( tam - pos, tam );
				}else{
					if ( tam == 5){
						if (tecla != 8){
							objCampo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, tam - pos ) + '/' + vr.substr( tam - pos, tam );
						}
					}
				}
			}else{ // IF TIPO = "DATA"
				if (tipo == "cpf" ){
					if (tam == 4){
						objCampo.value = vr.substr( 0, 3 ) + '.' + vr.substr( tam - pos, tam );
					}else{
						if ( tam == 7){
							if (tecla != 8){
								objCampo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 6 ) + '.' + vr.substr( tam - pos, tam );
							}
						}else{
							if ( tam == 11){
								if (tecla != 8){
									objCampo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 7, 3 ) + '-' + vr.substr( tam - pos, tam );
								}
							}
						}
					}
				}else{ // TIPO = "CPF"
					if (tipo == "hora") {
						if ( tam == 3){
							objCampo.value = vr.substr( 0, 2 ) + 'h' + vr.substr( 2, tam );
						}
					}else{ // TIPO = "HORA"
						if (tipo == "cep") {
							if ( tam == (tammax - pos)+1 ){
								Campo.value = vr.substr( 0, (tammax - pos) ) + '-' + vr.substr( (tammax - pos), tam );
							}
						}else{
							if (tipo == "R$"){
								if ( tam > pos && tam <= tammax){
									objCampo.value = vr.substr( 0, tam - pos ) + ',' + vr.substr( tam - pos, tam );
								}
							}
						}//FIM DO ELSE IF TIPO="CEP"
					}//FIM DO ELSE TIPO="HORA"
				}//FIM DO ELSE TIPO="CPF"
			}//FIM DO IF TIPO="CPF"
		}//FIM DO ELSE TIPO="DATA"
	}//FIM DO IF ( tam > pos && tam <= tammax )
} // FINAL DA FUNÇÃO QUE FORMATA O CAMPO


//PEGA UM CAMPO DATA E INDICA SE A DATA É VÁLIDA OU NÃO E SE FOR DEIXA A DATA NO FORMATO DD/MM/AAAA
function validaCampoData(objData)
{
	if(objData.value != ""){
		var retorno = verificaData(objData.value);
			
		if(retorno == false){
			alert("Data Inválida");
			objData.focus();
		}else{
			var Data = new Date();
			var arrData = objData.value.split('/');
			      
			var dia = arrData[0];
			var mes = arrData[1]-1;
			var ano = arrData[2];
			      
			Data.setFullYear(ano, mes, dia);
			dia = Data.getDate();
			mes = Data.getMonth()+1;
			ano = Data.getFullYear();
			      
			if (mes < 10){mes = "0" + mes;}
			if (dia < 10){dia = "0" + dia;}
			if (ano < 1900){ano = 2000 + ano;}
			      
			objData.value = dia + "/" + mes + "/" + ano;
		}
	}
}

//Verifica se uma data é válida ou não, retornando verdadeiro ou falso para a data passada
function verificaData(Data)
{
	if (Data != "")
	{
		var dma = -1;
		var data = Array(3);
		var ch = Data.charAt(0); 
		for(i=0; i < Data.length && (( ch >= '0' && ch <= '9' ) || ( ch == '/' && i != 0 ) ); ){
			data[++dma] = '';

			if(ch!='/' && i != 0) return false;
			if(i != 0 ) ch = Data.charAt(++i);
			if(ch=='0') ch = Data.charAt(++i);

			while( ch >= '0' && ch <= '9' ){
				data[dma] += ch;
				ch = Data.charAt(++i);
			} 
		}

		if(ch!='') return false;
		if(data[0] == '' || isNaN(data[0]) || parseInt(data[0]) < 1) return false;
		if(data[1] == '' || isNaN(data[1]) || parseInt(data[1]) < 1 || parseInt(data[1]) > 12) return false;
		if(data[2] == '' || isNaN(data[2]) || ((parseInt(data[2]) < 0 || parseInt(data[2]) > 99 ) && (parseInt(data[2]) < 1900 || parseInt(data[2]) > 9999))) return false;
		if(data[2] < 50) data[2] = parseInt(data[2]) + 2000;
		else if(data[2] < 100) data[2] = parseInt(data[2]) + 1900;

		switch(parseInt(data[1])){
			case 2: { if(((parseInt(data[2])%4!=0 || (parseInt(data[2])%100==0 && parseInt(data[2])%400!=0)) && parseInt(data[0]) > 28) || parseInt(data[0]) > 29 ) return false; break; }
			case 4: case 6: case 9: case 11: { if(parseInt(data[0]) > 30) return false; break;}
			default: { if(parseInt(data[0]) > 31) return false;}
		}
		return true; 
	}
}

function testaCEP(objCEP)
{
	if (isNaN(objCEP.value))
	{
		alert("O CEP deve conter apenas números!.");
		objCEP.value = "";
		objCEP.focus();
	}
}
		
// =============================================================
// INICIO 	: FUNCOES ADICIONADAS PELA E-BRAND
// DATA	: 11/10/2006
// ============================================================= 

// inicio : funcao de mascarar conteudo
function format(value,format) {
	value = value.replace(/\D/g,"");
	var result="";
	
	if(format.length < value.length)
		return value;
	
	for(i=0,j=0;(i<format.length)&&(j<value.length);i++) {
		var ch = format.charAt(i) ;
		if(ch == '#') {
			result += value.charAt(j++);
			continue;
		}
		result += ch;
	}
	return result;
} 
// fim : funcao de mascarar conteudo

// inicio : funcao que valida cnpj
function valida_cnpj(cnpj) {

	cnpj = cnpj.replace(".","");
	cnpj = cnpj.replace(".","");
	cnpj = cnpj.replace("/","");
	cnpj = cnpj.replace("-","");
	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;
	}

}
// fim : funcao que valida cnpj

// inicio : funcao que valida cpf
function check_cpf(pcpf){
	
	pcpf = pcpf.replace(".","");
	pcpf = pcpf.replace(".","");
	pcpf = pcpf.replace("-","");
	
	if (pcpf.length != 11)
	{sim=false}
	else {sim=true}
	//verifica se os numeros digitados são iguais
	if (sim)
	{
	i = 1;
	while(pcpf.charAt(i) == pcpf.charAt(i -1) && i < 10)
	{
	i++;
	}
	if(i == 10) sim=false
	else sim=true
	}
	if (sim)
	{
	for (i=0; i<=(pcpf.length-1) && sim; i++)
	{
	val = pcpf.charAt(i)
	
	if((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4")&&(
	val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {sim=false}
	}
	if (sim)
	{
	soma = 0
	for (i=0;i<=8;i++)
	{
	val = eval(pcpf.charAt(i))
	soma = soma + (val*(i+1))
	}
	resto = soma % 11
	if (resto>9) dig = resto -10
	else dig = resto
	if (dig != eval(pcpf.charAt(9))) { sim=false }
	else
	{
	soma = 0
	for (i=0;i<=7;i++)
	{
	val = eval(pcpf.charAt(i+1))
	soma = soma + (val*(i+1))
	}
	soma = soma + (dig * 9)
	resto = soma % 11
	if (resto>9) dig = resto -10
	else dig = resto
	if (dig != eval(pcpf.charAt(10))) { sim = false }
	else sim = true
	}
	}
	}
	if (sim) return true;
	else return false;
}
// fim : funcao que valida cpf

// inicio : funcao que verifica se a data é realmente válida
function checkData(field) 
{
	var checkstr = "0123456789"; 
	var DateField = field; 
	var Datevalue = ""; 
	var DateTemp = ""; 
	var day; 
	var month; 
	var year; 
	var leap = 0; 
	var err = 0; 
	var i; 
	err = 0; 
	DateValue = DateField.value; 

	for (i = 0; i < DateValue.length; i++) 
	{ 
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) 
		{ DateTemp = DateTemp + DateValue.substr(i,1); } 
	} 

	DateValue = DateTemp; 

	if (DateValue.length == 6) 
	{ DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); } 

	if (DateValue.length != 8) 
	{ err = 1; } 

	year = DateValue.substr(4,4); 
	if (year == 0) 
	{ err = 1; } 

	month = DateValue.substr(2,2); 
	if ((month < 1) || (month > 12)) 
	{ err = 1; } 

	day = DateValue.substr(0,2); 
	if (day < 1) 
	{ err = 1; } 

	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) 
	{ leap = 1; } 
	
	if ((month == 2) && (leap == 1) && (day > 29)) 
	{ err = 1; } 
	
	if ((month == 2) && (leap != 1) && (day > 28)) 
	{ err = 1; } 

	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) 
	{ err = 1; } 
	
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) 
	{ err = 1; } 

	if ((day == 0) && (month == 0) && (year == 00)) 
	{ err = 1; } 
	
	//== verificando se foi encontrado algum erro
	if (err == 0) 
	{ return true; } 
	else 
	{ return false;	} 
	
}
// fim : funcao que valida data


// inicio : função para validação de intervalo de Datas
function comparaDatas(dataInicio, dataTermino)
{
	var erro = 0;
	
	//== quebrando as datas para comparar numeros
	vDataInicio = dataInicio.split("/");
	dataIni = new Date(vDataInicio[2], vDataInicio[1], vDataInicio[0]);
	//diaIni = vDataInicio[0]
	//mesIni = vDataInicio[1]
	//anoIni = vDataInicio[2]	
	
	vDataTermino = dataTermino.split("/");
	dataFim = new Date(vDataTermino[2], vDataTermino[1], vDataTermino[0]);
	
	//diaTerm = vDataTermino[0]
	//mesTerm = vDataTermino[1]
	//anoTerm = vDataTermino[2]	
	
	//== verificando se o ano,mes,dia final é menor que o ano,mes,dia inicial
	if (dataIni.getTime() > dataFim.getTime()) {
		return false;	
	} else {
		return true;
	}
	
	/*if (anoTerm >= anoIni) { return true; } 
	else { return false; }
	
	if (erro == 0) {
		if (mesTerm >= mesIni) { return true; } 
		else { return false; }
	}
	
	if (erro == 0) {
		if (diaTerm >= diaIni) { return true; } 
		else { return false; }
	}*/
	
	//if (erro == 0) { return true; }
	//else { return false; }
	
	/*if (anoTerm < anoIni)
	{ return false; }
	else if (mesTerm < mesIni)
	{ return false;	}
	else if (diaTerm < diaIni)
	{ return false; }
	else
	{ return true; }*/

}
// fim : função para validação de intervalo de Datas

// fim : funcao que valida email
function checaEmail(Email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(Email))
	{ return true; }
	else
	{ return false; }		
}
// fim : funcao que valida email

// inicio: funcao desabilita combobox para edição
function preCarregandoCombobox(combo){
	var objCombo = document.getElementById(combo);

	objCombo.disabled = true;
	objCombo.options.length = 0;
	objCombo.options[0] = new Option('Aguarde...', '-1');
}
// fim: funcao desabilita combobox para edição

// inicio: funcao popular combobox
function popularCombobox(combo,obj_xml){
	var objCombo = document.getElementById(combo);

	objCombo.disabled = false;
	objCombo.options.length = 0;
	objCombo.options[0] = new Option('---','');
	
	var root = obj_xml.getElementsByTagName("root").item(0);
	
	for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
	   var node = root.childNodes.item(iNode);
	   for (i = 0; i < node.childNodes.length; i++) {
		  var sibl = node.childNodes.item(i);
		  var len = parseInt(sibl.childNodes.length / 2);
		  var arr = new Array(len);
		  var cnt = 0;
		  for (x = 0; x < sibl.childNodes.length; x++) {
			 var sibl2 = sibl.childNodes.item(x);
			 var sibl3;
			 if (sibl2.childNodes.length > 0) {
				sibl3 = sibl2.childNodes.item(0);
				arr[cnt] = sibl3.data;   
				cnt++;
			 }
		  }
		  if(arr != "")
			  objCombo[objCombo.length] = new Option(arr[1],arr[0],false);
			  
	   }
	}
}
// fim: funcao popular combobox

// ============================================================= 
// FIM : FUNCOES ADICIONADAS PELA E-BRAND
// ============================================================= 