/** Cria a caixa de consulta **/
function abrirConsulta(obj, url, largura, altura, titulo){
	if(obj == null || obj.tagName != 'IMG' || (obj.tagName == 'IMG' && IMG_isEnabled(obj))){
	    alturaTitulo = 18;
		//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
		var 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.style.width = '100%';
		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.height = alturaTitulo;
		linhaCons.appendChild(celula1Cons);
		texto1 = document.createTextNode(titulo);
		celula1Cons.appendChild(texto1);
		objBody.onmousemove = moverLayer;
		celula1Cons.onmousedown = iniciaMover;
		objBody.onmouseup = terminaMover;
		
		//cria a segunda celula
		celula2Cons = document.createElement("TD");
		linhaCons.appendChild(celula2Cons);
	
		celula2Cons.style.width = '20px';
		laConsulta.appendChild(tabelaCons);
	
	    botaoFechar = document.createElement("BUTTON");
	    botaoFechar.className = "spwBotaoGrid";
	    if (F_isIExplorer()) {
	      botaoFechar.value="&nbsp;X&nbsp;";
	    } else {
	      botaoFechar.appendChild(document.createTextNode('X'));
	      botaoFechar.style.width="100%";
	      botaoFechar.style.height="100%";
	      botaoFechar.type="button";
	    }
	    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&contador=0&gotInputParam=false&contadorMaior=0";
	    } else {
	        prmMultiSelection="multiselection=false";
	    }
	
		url = insertParamUrlAntesConsulta(url,obj.id);
	
	    if (url.indexOf("?") < 0) {
	        url=url+"?";
	    } else {
	        url=url+"&";
	    }
	    url=url+prmIdObjRetorno+"&"+prmMultiSelection+"&height="+(altura-alturaTitulo);
		
		//cria o iframe
		if( navigator.appName == "Netscape" ) {
			iframeConsulta = document.createElement("iframe");
			iframeConsulta.src = url;
			iframeConsulta.width = "100%";
			iframeConsulta.height = altura - alturaTitulo;
			iframeConsulta.frameBorder = "0";
	        iframeConsulta.id = "layerFormConsulta";
			laConsulta.appendChild(iframeConsulta);
		} else {
	        htmlIframe = "<iframe id='layerFormConsulta' frameBorder='0' style='width:100%; height:100%' src='"+url+"'></iframe>";
			document.getElementById("spwConsulta").insertAdjacentHTML("beforeEnd", htmlIframe);
		}
	}		
}

function insertParamUrlAntesConsulta(url,sender){
	return url;
}


/** desabilita a selecao do texto quando esta movendo **/
document.onselectstart = doc_selstart;
function doc_selstart(aEvent) {
    var theEvent = aEvent ? aEvent : window.event;
    if (movendo){
        theEvent.returnValue = false;
    }
}

/** Faz com que o ESC feche a tela **/
document.onkeydown = doc_keydown;
function doc_keydown(aEvent){
    var theEvent = aEvent ? aEvent : window.event;
    if (theEvent.keyCode == 27) {
       fecharConsulta();
    }
}

/** Fecha a caixa de consulta **/
function fecharConsulta() {
	onclosewindow();
    layerCon = parent.document.getElementById("spwConsulta");
    var doc = parent.document;
    if (layerCon == null) {
       layerCon = document.getElementById("spwConsulta");
       doc = document;
    }
    if (layerCon != null) {
      layerCon.parentNode.removeChild(layerCon);
      objBody = doc.getElementsByTagName("BODY")[0];
      objBody.onmouseup = null;
      objBody.onmousemove = null;
    }
}

function converteNumero(texto) {
    texto = new String(texto);
    numero = "";
    for (i = 0; i < texto.length; i++) {
        carac = texto.substr(i,1);
        if(!isNaN(carac) || carac == "." || carac == ","){
            numero += carac;
        }
    }
    return new Number(numero);
}

var posXinicial;
var posYinicial;
var movendo = false;
var posXlayer;
var posYlayer;

/** seta as variaveis quando clicado no titulo da consulta **/
function iniciaMover(aEvent){
    var theEvent = aEvent ? aEvent : window.event;
    movendo = true;
    posXinicial = new Number(theEvent.clientX + document.body.scrollLeft);
    posYinicial = new Number(theEvent.clientY + document.body.scrollTop);
    layerConsulta = document.getElementById("spwConsulta");
    posXlayer = converteNumero(layerConsulta.style.left);
    posYlayer = converteNumero(layerConsulta.style.top);
}

/** exibe o conteudo da consulta quanto termina de mover **/
function terminaMover(){
	document.getElementById("layerFormConsulta").style.display = "";
	movendo = false;
}

/** move a layer **/
function moverLayer(aEvent){
    var theEvent = aEvent ? aEvent : window.event;
    if (movendo == true) {
        document.getElementById("layerFormConsulta").style.display = "none";
        currentX = new Number(theEvent.clientX + document.body.scrollLeft);
        currentY = new Number(theEvent.clientY + document.body.scrollTop);
        layerConsulta = document.getElementById("spwConsulta");
        layerConsulta.style.left = posXlayer + (currentX - posXinicial);
        layerConsulta.style.top = posYlayer + (currentY - posYinicial);
    }
}

//limpa o grid de pesquisa
function limparGrid() {
	tabela = getTBody(document.getElementById("tabelaResultado"));
	if(tabela != null){
		grid = getGrid(tabela);
		nmGrid = getNomeGrid(grid);
		qtFilhos = tabela.childNodes.length;
		for (i = 0; i < qtFilhos; i++) {
			tabela.removeChild( tabela.lastChild );
		}
    	document.getElementById("textQtLinhas"+nmGrid).childNodes[0].nodeValue = "0";
    }
}

//limpa o conteúdo dos filtros de pesquisa
function limparFiltros( theForm ) {
    objForm = document.forms[0];
    var length = objForm.length;
	for (i = 0; i < length; i++) {
    	if (objForm[i].name != "" && objForm[i].type != "button" && objForm[i].type != "submit" && objForm[i].type != "hidden") {
            if (objForm[i].type == "checkbox") {
                objForm[i].checked = false;
            } else {
                objForm[i].value = "";
            }
        }
	}
}

//verifica se existe pelo menos um filtro de pesquisa preenchido
function filtroPesquisaValido( form ) {
    //Comentado a pedido da salt 31003.
    /*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;*/
    return true;
}

function verificaCamposObrigatorios(form){	
	var length = form.length;
	for( i = 0; i < length; i++ ) {				
        if( form[i].type == "text" && form[i].getAttribute('obrigatorio') != null && (form[i].getAttribute('obrigatorio')).toUpperCase() == "TRUE") {
            if(!C_verificaObrigatorio(form[i])) {
                return false;
            }
        }
    }    
    
    return true;
}

function executePesquisaDB( form ) {
    if (filtroPesquisaValido( form )) {
    	if(verificaCamposObrigatorios(form)){
        	IS_restauraEstadoSelecao();
            var formURL = document.getElementById("requesterUrl");
            if(formURL) {
                var valorCampo = formURL.value;
                if(valorCampo) {
                    var index = valorCampo.indexOf('/search/');
                    if(index > 0) {
                        formURL.value = valorCampo.substr(index);
                    }
                }
            }
        	form.submit();
    	}else{
    		document.getElementById('pbProcurar').disabled = false;
    		return false;
    	}
    }
}

function selecionarRegistros() {
	var selecionados = pegaSelecionados( document.forms[0] );
	var objRetorno = parent.document.getElementById(idObjRetorno);
    if(isInputSelect(objRetorno)){
    	if(objRetorno.getAttribute('multiplaSelecao') == 'true'){
    		copiarParaInputSelect(objRetorno,selecionados);
    	} else {
    		copiarParaForm(selecionados);
    	}
    	parent.setOldValueInputSelect(objRetorno.id);
		if(temFilho(objRetorno)){
			parent.habilitaInputsFilhos(objRetorno, parent.document);
		} 
		if(F_isIExplorer() && parent._focusObject && objRetorno.getAttribute("useModulo") != 'true'){
			parent._focusObject.focus();
		}
    }else{
	    grid = getGrid(objRetorno);
	    if (grid != null) {
	        var selecionadosList = IS_getInputParamValue(document,idObjRetorno);
	        if (selecionadosList == null || selecionadosList == "") {
		        if(selecionados.length == 0) {
		        	alert(msgKey("label.js.selecaoVazia",""));
			        return;
		        }else{
		        	copiarParaGrid(grid,objRetorno,selecionados);
		        }
			}
	        copiarParaGridSearchPaginada(grid, objRetorno);
	    } else {
	    	if (selecionados.length == 0) {
		        alert(msgKey("label.js.selecaoVazia",""));
		        return;
			}
	        copiarParaForm(selecionados);
	    }
	}   	
//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();
   	
}

//Copia os registros para um inputSelect..
function copiarParaInputSelect(objRetorno,selecionados){
	var parentDoc = parent.document;
	var contador = getContadorValue(document,'');
	var inputs = objRetorno.getElementsByTagName('INPUT');
	parent.limparInputSelect(objRetorno.id);
	if(contador == 0){
		habilitaInputSelect(objRetorno, parent.document);
	} else if(contador == 1){
		habilitaInputSelect(objRetorno, parent.document);
		if(selecionados.length > 0){
			copiarParaCampos(selecionados);
		}else{
			var registro = IS_inputParamToArray(document, objRetorno.id)[0];
			registro = registro.substring(registro.indexOf('^')+1);
			var linha = document.getElementById( "linha_0");
	        var nodosRef = pegaReferencias( linha );        
	        for( j = 0; j < nodosRef.length; j++ ) {
				var propriedadeValor = "";
				
				if(registro.indexOf('^') != -1) {
					propriedadeValor = registro.substring(0,registro.indexOf('^'));
				} else {
					propriedadeValor = registro.substring(0,registro.indexOf('$'));;
				}
				
				var valor = propriedadeValor.substring(propriedadeValor.indexOf('=')+1);
				      		
		       	var pageReference = getAttribute(nodosRef[j], 'pageReference');
		        copiaValorColunaParaForm(getAttribute(nodosRef[j], 'reference'), valor, pageReference);
		        				
				if(registro.indexOf('^') != -1) {
					registro = registro.substring(registro.indexOf('^')+1);
				} else {
					registro = null;
				}
			}
		}		
	} else{
		var c = -1;
		for(var i = inputs.length -1; i >= 0; i--){
			if(inputs[i].type!='hidden'){
				parent.disable(inputs[i]);
				if(inputs[i].offsetHeight != 0 && c == -1){
					c = i;
				}
			}
		}
		inputs[c].value=contador+' Registros selecionados';
		
	}
	
	var divsExistentes = objRetorno.getElementsByTagName('DIV');
	for(var k = 0; k < divsExistentes.length; k++){
		if(divsExistentes[k].getAttribute('multSelecao') == 'true'){
			divsExistentes[k].parentNode.removeChild(divsExistentes[k]);
			k--;
		}
	}
	
	var inputParamArray = IS_inputParamToArray(document, objRetorno.id);
	for(var i = 0; i < inputParamArray.length; i++) {
		var divMetadado = inputParamArray[i];
		var div = createDivFromMetadata(parentDoc,divMetadado);
		objRetorno.appendChild(div);
	}
	
	var parentContador = parentDoc.getElementById('contador'+objRetorno.id);
	parentContador.value = document.getElementById('contador').value;
	var parentInputParam = parentDoc.getElementById(objRetorno.id+'SelectedEntitiesList');
	parentInputParam.value = document.getElementById(objRetorno.id+'SelectedEntitiesList').value;
	var parentContadorMaior = parentDoc.getElementById('contadorMaior'+objRetorno.id);
	parentContadorMaior.value = document.getElementById('contadorMaior').value;
		
}

function createDivFromMetadata(doc,metadata){
	var divId = metadata.substring(0,metadata.indexOf('^'));
	var novoDiv = doc.createElement("DIV");
	novoDiv.id = divId;
	novoDiv.style.display = 'none';
	novoDiv.setAttribute('multSelecao','true');
	
	var resto = metadata.substring(metadata.indexOf('^') + 1);
	while(resto != null && resto != ''){
		var indexChapeu = resto.indexOf('^');
		var input = '';
		if(indexChapeu != -1) {
			input = resto.substring(0,indexChapeu);
			resto = resto.substring(resto.indexOf('^')+1);
		} else {
			input = resto.substring(0,resto.indexOf('$'));
			resto = null;
		}
		var name = input.substring(0,input.indexOf('='));
		var value = input.substring(input.indexOf('=')+1);
		
		var novoInput = criaElemento(doc,'INPUT','HIDDEN',name,name,unescape(value),name);	
		novoDiv.appendChild(novoInput);	
		
	}
	return novoDiv;
}

function getSelectedDivs(doc,objId){
	var divs = IS_getDivTemp(doc,objId).getElementsByTagName('DIV');
	var divArray = new Array();
	for(var j = 0; j < divs.length; j++){
		if(divs[j].getAttribute('multSelecao') == 'true'){
			divArray[divArray.length] = divs[j];
		}
	}
	return divArray;
}

function cloneDiv(doc, div){
	var novoDiv = doc.createElement("DIV");
	novoDiv.id = div.id;
	cloneInputsHidden(doc,div,novoDiv);
	novoDiv.style.display = 'none';
	novoDiv.setAttribute('multSelecao','true');
	return novoDiv;
}

function cloneInputsHidden(doc, divFonte, divAlvo){
	for(var i = 0; i < divFonte.childNodes.length; i++){
		if(divFonte.childNodes[i].nodeName == 'INPUT'){	
			var input = divFonte.childNodes[i];
			var novoInput = criaElemento(doc,'INPUT','HIDDEN',input.name,input.id,input.value,input.getAttribute('property'));	
			novoInput.setAttribute('remover',input.getAttribute('remover'));
			divAlvo.appendChild(novoInput);
		}
	}
}

//Copia uma linha do form de consulta para o form que o chamou
function copiarParaCampos(selecionados) {
    for( i = 0; i < selecionados.length; i++ ) {
        linhaSel = document.getElementById( "linha_" + selecionados[ i ] );
        nodosRef = pegaReferencias( linhaSel );        
        for( j = 0; j < nodosRef.length; j++ ) {      		
       	    var valorRetorno = SR_getValorCelulaSearch(nodosRef[j]);
       	    var pageReference = getAttribute(nodosRef[j], 'pageReference');
            copiaValorColunaParaCampos(getAttribute(nodosRef[j], 'reference'), valorRetorno, pageReference);
        }
    }
}

//copia o valor de uma coluna da tela de consulta para um campo do form que o chamou
function copiaValorColunaParaCampos(coluna, valor, pageReference) {
    var idDoElemento;
    if(pageReference == null || pageReference == "false"){
	    idDoElemento = parent.nomeCampoEquivalenteInputSelect(idObjRetorno, coluna);
	} else {
		idDoElemento = coluna;
	}
    if ((idDoElemento != null) && (idDoElemento != "")) {
      obj = parent.document.getElementById(idDoElemento);
      if(obj != null){
	      obj.value = valor;
	  }
    }
}


//Copia uma linha do form de consulta para o form que o chamou
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++ ) {      		
       	    var valorRetorno = SR_getValorCelulaSearch(nodosRef[j]);
       	    var pageReference = getAttribute(nodosRef[j], 'pageReference');
            copiaValorColunaParaForm(getAttribute(nodosRef[j], 'reference'), valorRetorno, pageReference);
        }
    }
}

//copia o valor de uma coluna da tela de consulta para um campo do form que o chamou
function copiaValorColunaParaForm(coluna, valor, pageReference) {
	var idDoElemento;
	var bindings = parent.document.getElementById(idObjRetorno).getAttribute('bindings');
	if(bindings == null || bindings == ''){
	    idDoElemento = parent.nomeCampoEquivalenteForm(idObjRetorno, coluna);
	} else {
		if(pageReference == null || pageReference == "false"){
			return;
		}		
		idDoElemento = coluna;
	}
    if ((idDoElemento != null) && (idDoElemento != "")) {      
      obj = F_getElementByNameOrId(parent.document, idDoElemento);
      if(obj != null){
	      obj.value = unescape(valor);	      
	  }
    }
}


//Método pode ser "sobrescrito" para modificar os nomes das colunas correspondentes
function nomeCampoEquivalenteForm(sender, coluna) {
	return coluna;
}

//copia uma linha do form de consulta para o grid
function copiarParaGrid(grid, objRetorno, selecionados) {
    var nmGrid = getNomeGrid(grid);
    var nuLinhaNova = new Number( parent.document.getElementById("textQtLinhas"+nmGrid).childNodes[0].nodeValue );
    for( i = 0; i < selecionados.length; i++ ) {
       var linhaSel = document.getElementById( "linha_" + selecionados[ i ] );
       var nodosRef = pegaReferencias( linhaSel );        
       var linha = parent.criarLinha(objRetorno, i == selecionados.length-1, false );         
       var actionChanged = false;
       for( j = 0; j < nodosRef.length; j++ ) {      		
       	    var valorRetorno = SR_getValorCelulaSearch(nodosRef[j]);
       	    var pageReference = getAttribute(nodosRef[j], 'pageReference');
       	    var obj = copiaValorColunaParaGrid(grid, nuLinhaNova, references[j], valorRetorno, pageReference);
            if(obj != null && !(actionChanged)){
	       	    parent.changeActionGridInsert(grid,nuLinhaNova);
	       	    actionChanged = true;
       	    }            
        }
        linha.style.display = '';
        nuLinhaNova++;
    }
}

function copiarParaGridSearchPaginada(grid, objRetorno) {
    var nmGrid = getNomeGrid(grid);
    var nuLinhaNova = new Number( parent.document.getElementById("textQtLinhas"+nmGrid).childNodes[0].nodeValue );
    var inputParamArray = IS_inputParamToArray(document, objRetorno.id);
    for( var i = 0; i < inputParamArray.length; i++) {
	   var registroSelecionado = inputParamArray[i];
       var valoresSelecionados = getValoresSelecionados(registroSelecionado);
       var linha = parent.criarLinha(objRetorno, i == inputParamArray.length-1 ,false);         
       var actionChanged = false;
       for( j = 0; j < valoresSelecionados.length; j++ ) {      		
       	    var valor = valoresSelecionados[j];
       	    var pageReference = pageReferences[j];
       	    var obj = copiaValorColunaParaGrid(grid, nuLinhaNova, references[j], valor, pageReference);
       	    if(obj != null && !(actionChanged)){
	       	    parent.changeActionGridInsert(grid,nuLinhaNova);
	       	    actionChanged = true;
       	    }
       	}
       	linha.style.display = '';
        nuLinhaNova++;
    }    
}

//copia o valor de uma coluna da tela de consulta para uma coluna da grid
function copiaValorColunaParaGrid(grid, nuLinhaNova, coluna, valor, pageReference) {
	var inputId;
	if(pageReference == null || pageReference == "false"){
		inputId = parent.nomeCampoEquivalenteGrid(idObjRetorno, coluna);
	} else {
		inputId = coluna;
	}
    if( inputId != null) {
        var idDoElemento = getColumnId(grid, inputId, nuLinhaNova);
       var obj = parent.document.getElementById( idDoElemento ); 
        if(obj != null){
            obj.value = unescape(valor);
        	return obj;
        }
    }
    return null;
}

function getValoresSelecionados(registro){
	var valores = new Array();
	var resto = registro.substring(registro.indexOf('^') + 1);
	while(resto != null && resto != ''){
		var indexChapeu = resto.indexOf('^');
		var input = '';
		if(indexChapeu != -1) {
			input = resto.substring(0,indexChapeu);
			resto = resto.substring(resto.indexOf('^')+1);
		} else {
			input = resto.substring(0,resto.indexOf('$'));
			resto = null;
		}
		valores[valores.length] = input.substring(input.indexOf('=')+1);
	}
	return valores;
	
}

//Método pode ser "sobrescrito" para modificar os nomes das colunas correspondentes
function nomeCampoEquivalenteGrid(sender, coluna) {
	return coluna;
}

//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((!isTextNode(linha.childNodes[j])) && (getAttribute(linha.childNodes[j], 'property') != 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, multSelecao ) {
    if (form.rowSelect != null) {
        var max = form.rowSelect.length;
        if (max!=null) {
            for( var i = 0; i < max; i++) {
               if(form.rowSelect[i].checked != marcado){	
               		form.rowSelect[i].checked = marcado;
               		if(multSelecao){
               			onClickMultiplaSelecao(form.rowSelect[i]);
               		}
               }               
            }
        } else {
             if(form.rowSelect.checked != marcado){
             	form.rowSelect.checked = marcado;
		        if(multSelecao){
		           	onClickMultiplaSelecao(form.rowSelect);
		        }
             } 
        }
    }
}

function getIndexRow(objTR){
	var idObjTr = objTR.getAttribute('id');
	var table = objTR.parentNode;
	while(table.nodeName != 'TABLE'){
		table = table.parentNode;
	}
	var filhos = table.childNodes;
	for(var i = 0; i < filhos.length; i++){
		filho = filhos[i];
		if(filho.getAttribute('id') == idObjTr){
			return i;
		}
	}
	return null;
}

function mudarSelecaoRegistroAtual(objTR) {
    if (objTR != null) {
		var objRadio = objTR.getElementsByTagName('INPUT')[0];
       	objRadio.checked = true;
       	var grid = getGrid(objTR);
       	grid.setAttribute('selected', objTR.getAttribute('id'));
    }
}

function alterneSelecaoRegistroAtual(objTD, doc, isInputSelect) {
    if (objTD != null) {
    	var objTR = objTD.parentNode;
		var objCheck = objTR.getElementsByTagName('INPUT')[0];
       	objCheck.checked = !objCheck.checked;
       	if(isInputSelect){
       		onClickMultiplaSelecao(objCheck);
       	}
    }
}

function alterneSelecaoRegistroAtualDoubleClick(objTD, doc) {
    if (objTD != null) {
    	var objTR = objTD.parentNode;
		var objCheck = objTR.getElementsByTagName('INPUT')[0];
		//objCheck.checked = true;
       	onClickMultiplaSelecao(objCheck);       	
    }
}

function selecionarRegistroAtual(objTR) {
	mudarSelecaoRegistroAtual(objTR);
	selecionarRegistros();
}

/** Chamado qdo for selecionado um registro de uma searchGrid **/
function depoisSelecionarRegistros(sender) {
}

// SR_ para funções relacionadas a search
function SR_getSearchInputs(vassoura){
	var objTable = vassoura;
	while(objTable.nodeName != "TABLE"){
		objTable = objTable.parentNode;
	}
	return objTable.getElementsByTagName("INPUT");
}

function SR_antesLimparCampos(vassoura){
	return true;
}

function SR_depoisLimparCampos(vassoura){
}

function SR_getBotaoProcurar(searchId){
	return document.getElementById(searchId);
}

function SR_getBotaoLimpar(searchId){
	return document.getElementById(searchId + '_limpar');
}

function SR_habilitaBotaoLimpar(searchId, habilitado){
	IMG_enable(SR_getBotaoLimpar(searchId), habilitado);
}

function SR_habilitaBotaoProcurar(searchId, habilitado){
	IMG_enable(SR_getBotaoProcurar(searchId), habilitado);
}

function SR_habilitaBotoes(searchId, habilitado){
	SR_habilitaBotaoLimpar(searchId, habilitado);
	SR_habilitaBotaoProcurar(searchId, habilitado);
}

function limpaCampos(obj){
	if(IMG_isEnabled(obj)){
		if(SR_antesLimparCampos(obj)){
			var arrayInput = SR_getSearchInputs(obj);
			for(i = 0; i < arrayInput.length; i++){
				arrayInput[i].value = "";
			}
			SR_depoisLimparCampos(obj);
		}
	}
}

/** Método para ser sobrescrito para tratar o evento de fechamento da janela de consulta **/
function onclosewindow(){
}

function SR_limparConsulta(){
	limparGrid();
	limparFiltros(document.forms[0]);
    FF_desabilitaBotoes(document.forms[0]); 
   
    var btProcurar = document.getElementById('pbProcurar');
    var btLimpar = document.getElementById('pbLimpar');
    var btFechar = document.getElementById('pbFechar');
    
    btProcurar.disabled = false;
    if(btProcurar.getAttribute('oldClassName') != null){
		btProcurar.className = btProcurar.getAttribute('oldClassName');
	}
	
	btLimpar.disabled = false;
    if(btLimpar.getAttribute('oldClassName') != null){
		btLimpar.className = btLimpar.getAttribute('oldClassName');
	} 
	
	btFechar.disabled = false;
    if(btFechar.getAttribute('oldClassName') != null){
		btFechar.className = btFechar.getAttribute('oldClassName');
	}  
}

function SR_getValorCelulaSearch(celula){
	var valorRetorno = "";
   	var isHidden = getAttribute(celula, 'hidden');
   	if(isHidden != null && isHidden == "true") {
    	valorRetorno = getAttribute(celula, 'beanValue');
   	} else {
       	if(celula.childNodes[0]){
	  	    valorRetorno = celula.childNodes[0].nodeValue;
	   	}
   	}
   	return valorRetorno;
}

var reqMarcarTodosAjax;
var selecionarItens;
function SR_selecionaTodosAjax(selecionar){
	
	FF_desabilitaBotoes(document.forms[0]);
	selecionarItens = selecionar;
	var url = getSelecionarTodosServletUrl();
	
	if (window.XMLHttpRequest) {
		reqMarcarTodosAjax = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		reqMarcarTodosAjax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	reqMarcarTodosAjax.open("GET", url, true);
	reqMarcarTodosAjax.onreadystatechange = SR_selecionaTodosAjaxResponse;
	reqMarcarTodosAjax.send(null);
}


function SR_selecionaTodosAjaxResponse(){
	if (reqMarcarTodosAjax.readyState == 4) {
		if (reqMarcarTodosAjax.status == 200) {
		    if( !exceptionTagPresent(reqMarcarTodosAjax) ) { 
		      	var entidades = reqMarcarTodosAjax.responseXML.getElementsByTagName('isr')[0].childNodes[0]; 
				if(entidades && entidades.childNodes.length != 0){	
					var	idObjRetorno = document.getElementById('idObjRetorno').value;
					var registrosSelecionados = IS_getInputParamValue(document,idObjRetorno);
					var entidadesChildNodesLength = entidades.childNodes.length;
					var parentDocument = parent.document;
					var ehInputSelect = isInputSelect(parentDocument.getElementById(idObjRetorno));
					var adicionarNoInputParam = [];
					for(var i = 0; i < entidadesChildNodesLength; i++){
						var registro = entidades.childNodes[i];
						var chave = "";
						var atributos = "";
						var registroChildNodesLength = registro.childNodes.length;
						for(var j = 0; j < registroChildNodesLength; j++) {
							var atributo = registro.childNodes[j];
							var nome = atributo.getAttribute('n');
							if(ehInputSelect){
								var property = document.getElementById('multSelecaoProperty').value;
								var indice = getContadorMaiorValue(document,'');
								nome = property+'['+indice+'].'+nome;
							}
							var valor = atributo.getAttribute('v');
							var pk = atributo.getAttribute('pk');
							if(pk != null && pk == 'true'){
								chave += valor + ";";
							}
							atributos += "^" + nome + "=" + valor;
						}
						var divId = IS_createMultSelecaoDivId(idObjRetorno,chave);
						if(selecionarItens){
							if(registrosSelecionados == null || registrosSelecionados.indexOf(divId) == -1) {
								adicionarNoInputParam.push('DivID='+divId+atributos+"$");
								incrementaContadorSelecionados(document,'');
							}
						} else {
							if(registrosSelecionados != null && registrosSelecionados.indexOf(divId) != -1) {
								var posicao = registrosSelecionados.indexOf("DivID="+divId+'^');
								if(posicao > -1){
									var subV = registrosSelecionados.substring(posicao,registrosSelecionados.length);
									var resto = subV.substring(subV.indexOf('$')+1,subV.length);
									registrosSelecionados = registrosSelecionados.substring(0,posicao) + resto;	
								}								
								decrementaContadorSelecionados(document,'');
							}
						}
					}
					if(selecionarItens){
						addToInputParam(document,idObjRetorno,adicionarNoInputParam.join(""));
					} else {
						var inputParam = document.getElementById(idObjRetorno+'SelectedEntitiesList');
						inputParam.value = registrosSelecionados;
					}
					mudarSelecaoTodos(document.forms[0], selecionarItens, false);
					FF_habilitaBotoes(document.forms[0]);
				}
			}
		}
	}
}
