/** Fecha a caixa de consulta **/
function fecharConsulta() {
    layerCon = parent.document.getElementById("spwConsulta");
    if (layerCon == null) {
       doc = document;
       layerCon = doc.getElementById("spwConsulta");
    } else {
       doc = parent.document;
    }
    layerCon.parentNode.removeChild(layerCon)
    objBody = doc.getElementsByTagName("BODY")[0];
    objBody.onmouseup = null
}

/** Cria a caixa de consulta **/
function abrirConsulta(arquivo, largura, altura, obj){

	//verifica se a consulta ja esta aberta
	if(document.getElementById("spwConsulta") != null){
		return;
	}

	//pega dados da pag
	objBody = document.getElementsByTagName("BODY")[0]
	alturaPag = document.body.clientHeight
	larguraPag = document.body.clientWidth
	posScroll = document.body.scrollTop	

	//cria a layer
	laConsulta = document.createElement("DIV")
	laConsulta.id = "spwConsulta"
	laConsulta.style.position = "absolute"
	laConsulta.style.width = largura
	laConsulta.style.height = altura
	laConsulta.style.left = (larguraPag - largura) / 2
	laConsulta.style.top = (alturaPag - altura) / 2 + posScroll
	laConsulta.className = "spwTabelaGrid"
	laConsulta.style.backgroundColor = "#ffffff"
	laConsulta.style.zIndex = 99
    objBody.appendChild(laConsulta)
	
	//cria a tabela superior
	tabelaCons = document.createElement("TABLE")
	tabelaCons.cellPadding = 0
	tabelaCons.cellSpacing = 0
	tabelaCons.className = "spwTituloGrid"
	cabCons = document.createElement("TBODY")
	tabelaCons.appendChild(cabCons)
	
	//cria a linha da tabela
	linhaCons = document.createElement("TR")
	cabCons.appendChild(linhaCons)
	
	//cria a primeira celula
	celula1Cons = document.createElement("TD")
	celula1Cons.width = "100%"
	linhaCons.appendChild(celula1Cons)
	texto1 = document.createTextNode("Consulta")
	celula1Cons.appendChild(texto1)
	objBody.onmousemove = moverLayer
	celula1Cons.onmousedown = iniciaMover
	objBody.onmouseup = terminaMover
	
	//cria a segunda celula
	celula2Cons = document.createElement("TD")
	linhaCons.appendChild(celula2Cons)
	laConsulta.appendChild(tabelaCons)

    botaoFechar = document.createElement("BUTTON");
    botaoFechar.className = "spwBotaoGrid"
    botaoFechar.value="&nbsp;X&nbsp;"
    botaoFechar.onclick = fecharConsulta
	celula2Cons.appendChild(botaoFechar)

	//cria tabela para conter o iframe
	tabelaIframe = document.createElement("TABLE")	
	linhaIframe = document.createElement("TR")
	celulaIframe = document.createElement("TD")
	tabelaIframe.id = "tabelaIframe"

    //Atualiza os parâmetros
    prmIdObjRetorno="idObjRetorno="+obj.id;
    
    grid = getGrid(obj);
    if (grid != null && gridIsMultiselection(grid)) {
        prmMultiSelection="multiselection=true";
    } else {
        prmMultiSelection="multiselection=false";
    }

    if (arquivo.indexOf("?") < 0) {
        arquivo=arquivo+"?";
    } else {
        arquivo=arquivo+"&";
    }
    arquivo=arquivo+prmIdObjRetorno+"&"+prmMultiSelection;
	
	//cria o iframe
	if( navigator.appName == "Netscape" ) {
		iframeConsulta = document.createElement("iframe")
		iframeConsulta.src = arquivo + "?" + altura
		iframeConsulta.width = "100%"
		iframeConsulta.height = "100%"
		iframeConsulta.frameBorder = "0"
		laConsulta.appendChild(iframeConsulta)
	} else {
        htmlIframe = "<iframe id='teste1' frameBorder='0' style='width:100%; height:100%' src='"+arquivo+"'></iframe>"
		document.getElementById("spwConsulta").insertAdjacentHTML( "beforeEnd", htmlIframe );
	}
		
}

/** **/
function setaAlturaLayer(){
	urlPag = new String(document.location.href)
	posInt = urlPag.indexOf("?")
	altura = new Number(urlPag.substr(posInt + 1))
	tableConsulta = document.getElementById("tabelaConsulta")
	layerConsulta = document.getElementById("laConsulta")
	layerConsulta.style.height = (altura - 115) + "px"
	tableConsulta.style.height = (altura - 115 + 1) + "px"
}

var posXinicial;
var posYinicial;
var movendo = false
var posXlayer
var posYlayer

/** seta as variaveis quando clicado no titulo da consulta **/
function iniciaMover(){
	movendo = true
	objBody = document.getElementsByTagName("BODY")[0]
	posXinicial = new Number(event.clientX)
    posYinicial = new Number(event.clientY) + objBody.scrollTop
	layerConsulta = document.getElementById("spwConsulta")
	posXlayer = transNumero(layerConsulta.style.left)
	posYlayer = transNumero(layerConsulta.style.top)
}

/** desabilita a selecao do texto quando esta movendo **/
document.onselectstart = doc_selstart;
function doc_selstart(){
	if(movendo){
	    event.returnValue = false;
	}
}

/** exibe o conteudo da consulta quanto termina de mover **/
function terminaMover(){
	document.getElementById("teste1").style.display = ""
	movendo = false
}

function transNumero(texto){
	texto = new String(texto)
	numero = ""
	for(i = 0; i < texto.length; i++){
		carac = texto.substr(i,1)
		if(!isNaN(carac)){
			numero += carac
		}
	}
	return new Number(numero)
}

/** move a layer **/
function moverLayer(){
	if(movendo == true){
		document.getElementById("teste1").style.display = "none"
		currentX = new Number(event.clientX + document.body.scrollLeft)
		currentY = new Number(event.clientY + document.body.scrollTop)
		layerConsulta.style.left = posXlayer + (currentX - posXinicial)
		layerConsulta.style.top = posYlayer + (currentY - posYinicial)
	}
}

//limpa o grid de pesquisa
function limparGrid() {
	tabela = document.getElementById( "tabelaResultado" ).childNodes(0);
	qtFilhos = tabela.childNodes.length;
	for(i = 0; i < qtFilhos; i++) {
		tabela.removeChild( tabela.lastChild );
	}
    document.getElementById("qtLinhas").childNodes(0).nodeValue = "0";
}

//limpa o conteúdo dos filtros de pesquisa
function limparFiltros( theForm ) {
    for( i = 0; i < theForm.length; i++ ) {
        if( theForm[i].type == "text" || theForm[i].type == "select" ) {
            theForm[i].value = "";        
        }
    }
}

//verifica se existe pelo menos um filtro de pesquisa preenchido
function filtroPesquisaValido( form ) {
    ok = false;
    for( i = 0; i < form.length; i++ ) {
        if( form[i].type == "text" || form[i].type == "select" ) {
            if( form[i].value != "" ) {
                ok = true;
            }
        }
    }
    if( !ok ) { 
        alert("É necessário informar algum filtro para a pesquisa.");
    }
    return ok;
}

function executePesquisaDB( form ) {
    if (filtroPesquisaValido( form )) {
        form.submit();
    }
}

function selecionarRegistros() {
    selecionados = pegaSelecionados( document.forms[0] );
    objRetorno = parent.document.getElementById(idObjRetorno);
    grid = getGrid(objRetorno);
    if (grid != null) {
        copiarParaGrid(grid, objRetorno, selecionados);
    } else {
        copiarParaForm(selecionados);
    }
    if (selecionados.length == 0) {
        alert("Você deve marcar algum registro para fazer a seleção.")
    } else {
        //Funciona como um evento para que possa ser "sobrescrito" na página
	//Deve viar antes de fechar a consulta senão o script não funciona, pois 
	//o iFrame é destruído antes de chegar a executar a função
        parent.depoisSelecionarRegistros(idObjRetorno);
	//Fecha a tela de consulta
        fecharConsulta();
    }
}

function copiarParaForm(selecionados) {
    for( i = 0; i < selecionados.length; i++ ) {
        linhaSel = document.getElementById( "linha_" + selecionados[ i ] );
        nodosRef = pegaReferencias( linhaSel );        
        for( j = 0; j < nodosRef.length; j++ ) {      		
            obj = parent.document.getElementById( nodosRef[j].reference );                        
            if( nodosRef[ j ].beanValue == -1 ) {
            	obj.value = nodosRef[j].childNodes(0).nodeValue;
            } else {
            	obj.value = nodosRef[j].beanValue;             	
            }
        }
    }
}

//copia uma linha do form de consulta para o grid
function copiarParaGrid(grid, objRetorno, selecionados) {

    nmGrid = getNomeGrid(grid);
    nuLinhaNova = new Number( parent.document.getElementById("textQtLinhas"+nmGrid).childNodes(0).nodeValue );
    for( i = 0; i < selecionados.length; i++ ) {
        linhaSel = document.getElementById( "linha_" + selecionados[ i ] );
        nodosRef = pegaReferencias( linhaSel );        
        parent.criarLinha(objRetorno, i == selecionados.length-1 );         
       for( j = 0; j < nodosRef.length; j++ ) {      		
            idDoElemento = getColumnId(grid, nodosRef[ j ].reference, nuLinhaNova);
            obj = parent.document.getElementById( idDoElemento );                        
            if( nodosRef[ j ].beanValue == -1 ) {
            	obj.value = nodosRef[ j ].childNodes(0).nodeValue;
            } else {
            	obj.value = nodosRef[ j ].beanValue;             	
            }
            parent.changeAction(obj,'I');
        }
        nuLinhaNova++;
    }
}

//referencias das colunas para os campos no grid
function pegaReferencias( linha ) {
    referencias = new Array();
    count = 0;
    for( j = 0; j < linha.childNodes.length; j++ ) {
        if( linha.childNodes( j ).reference != null ) {
            referencias[count] = linha.childNodes( j );
            count++;
        }
    }
    return referencias;
}

//retorna os itens selecionados do grid de pesquisa
function pegaSelecionados( form ) {
    checados = new Array();
    if (form.rowSelect != null) {
        max = form.rowSelect.length;
        cont = 0;
        if (max!=null) {
            for( i = 0; i < max; i++) {
                if (form.rowSelect[i].checked == true) {
                    checados[cont] = form.rowSelect[i].value;
                    cont++;
                }
            }
        } else {
            if (form.rowSelect.checked == true) {
                  checados[0] = form.rowSelect.value;
            }
        }
    }
    return checados;
}

function mudarSelecaoTodos( form, marcado ) {
    if (form.rowSelect != null) {
        max = form.rowSelect.length;
        if (max!=null) {
            for( iCk12329384 = 0; iCk12329384 < max; iCk12329384++) {
               form.rowSelect[iCk12329384].checked = marcado;
            }
        } else {
             form.rowSelect.checked = marcado;
        }
    }
}

/** Chamado qdo for selecionado um registro de uma searchGrid **/
function depoisSelecionarRegistros(sender) {
}