// JavaScript Document

/*
Codigo modificado de :
http://www.webreference.com/programming/javascript/jf/column14/index.html
Autor :Jonathan Fenocchi;
Modificacoes: MAURICIO BARROS  em 02/06/2006
UTILIDADE: Aplicacao da "LOV" de busca em consultas sem abrir popup.
OBS: E executado com em paralelo com outors codigos, principalmente arquivo_consulta.php.
*/

var string_old = '';//contem o valor da ultima string
var last_time = new Date();//contem o tempo do ultimo keyup
var conta_key_press = 0;
var conta_key_press_old = 0;
var id_retorno;//contem o id do campo de retorno para o resultado final da consulta
var file='';//contem o arquivo em que serao executadas as consultas
var file_new = '';
var botao_new = 'vazio';//contem o id atual do botao que chama a lov
var botao_old = 'vazio';//contem o id anterir do botao que cama a lov
var campo_recebe;
var botao_chama_lov;
var nr_colunas;//numero que colunas a serem mostradas
var nr_campo_recebe;
var vet_campo_recebe    = new Array();
var vet_id_campo_recebe = new Array();
var vet_desc_coluna     = new Array();;//contem o camecalho da consulta
var nr_campo_focu;
var vet_condicoes_formulario = '';
var nr_caracteres = ''; //numero minimo de caracteres para consulta
var debug = '';
var sql   = '';
var oci   = '';
var existe_debug = false;
var count_id = '';
var lov_load = false;
var vetRetornoDireto = '';
var autoRetorno    = '';
var id_campo_focu = '';
/*********************************************************************************************************************
inicio_ajax_lov: seta as variveis globais, mostra o div de consultas posicionado com o botao que o chama.
p_file: endereço do arquivo onde serao executadas as buscas.
p_id_retorno: id do campo que receberá o resultado final da caonsulta.
p_desc_coluna: nome de apresentacao da busca. Vai no canto esquerdo do div "ch_campo_dados".
p_id_botao: id do botao que chama a lov.
p_local_div_ch_campo_dados: complemento para a localizacao do div_ch_campo_dados
							util quendo se trabalho om frames
/*********************************************************************************************************************/
var count_id = 0;
//inicio_ajax_lov('lov/arquivo_consulta.php?ind=0','Nome','nome**nr_codigo**armazena_usada_ufg','alterar','frame_main.frame_main.','2','2','3');}
function inicio_ajax_lov(campo_digite,p_file,p_desc_coluna,p_id_campo_recebe,p_id_botao,p_local_campo_recebe,p_nr_colunas,p_nr_campo_focu,p_vet_condicoes_formulario,p_nr_caracteres,p_div_load)
{
	
	vet = p_file.split('=');
	
	count_id = vet[1];
	
 	f_controi_div(count_id,campo_digite);
	
	file       				 = p_file;
	nr_colunas		    	 = p_nr_colunas;
	vet_id_campo_recebe 	 = p_id_campo_recebe.split('**');
	nr_campo_recebe    	 	 = vet_id_campo_recebe.length;
	vet_desc_coluna    	 	 = p_desc_coluna.split('**');
    nr_campo_focu       	 = p_nr_campo_focu;
	vet_condicoes_formulario = p_vet_condicoes_formulario;
	nr_caracteres 			 = p_nr_caracteres;
	lov_load				 = p_div_load;
	
	
	if(p_local_campo_recebe == '')
	{
		 for(i = 0; i < nr_campo_recebe ; i++)
		 {
			if(document.getElementById(vet_id_campo_recebe[i]))
				vet_campo_recebe[i] = document.getElementById(vet_id_campo_recebe[i]);
		 }
		 
		 botao_new     = document.getElementById(p_id_botao);
	}
	else
	{
		 for(i = 0; i < nr_campo_recebe ; i++)
		 {
			if(eval(p_local_campo_recebe+'document.getElementById(\''+vet_id_campo_recebe[i]+'\')'))
				vet_campo_recebe[i] = eval(p_local_campo_recebe+'document.getElementById(\''+vet_id_campo_recebe[i]+'\')');
		 }
		
		 botao_new      = eval(p_local_campo_recebe+'document.getElementById(\''+p_id_botao+'\')');
    }
	
	y = 70;
	
	x = 160;
	document.getElementById('div_principal_lov').style.top = y+'px';
	document.getElementById('div_principal_lov').style.left = x+'px';
	document.getElementById('div_principal_lov').style.visibility = 'visible';
	
	if(document.getElementById('div_table'))
	{	
		document.getElementById('ch_campo_dados').removeChild(document.getElementById('div_table'));
	}
		
	//document.getElementById('ch_campo_dados').innerHTML ='<div style="width:auto; background-color:#CADDE3; vertical-align:middle; height:18px;"  class="titulo_campo"> Digite algo para localizar!</div>';
	document.getElementById('ch_nome_'+count_id).value= '';
	string_old = '';
	botao_old = botao_new;
	
    //lov_load = true;
    document.getElementById('ch_nome_'+count_id).focus();
	//alert(count_id);
	//	setInterval("nm_aquivo",tempo_ms)--chama f_ajaxRead() a cada 0.001 s! 
	setInterval("f_ajaxRead()",1);
}


function inicioLov(p_campo_digite_aqui,p_arquivo_consulta,p_indice,p_titulo,p_localizacao_tela,p_nr_col_retorno,p_id_campo_focu,p_string,p_nr_caracteres,p_auto_consulta,p_nr_colunas_mostrar,p_autoRetorno,p_id_campo_recebe){
	
	file       				 = p_arquivo_consulta;
	nr_colunas		    	 = p_nr_colunas_mostrar;
	vet_desc_coluna    	 	 = p_titulo.split('**');
    id_campo_focu       	 = p_id_campo_focu;
	vet_condicoes_formulario = p_string;
	nr_caracteres 			 = p_nr_caracteres;
	lov_load				 = p_auto_consulta;
	count_id                 = p_indice;
	p_local_campo_recebe     = p_localizacao_tela;
	f_controi_div(count_id,p_campo_digite_aqui);
	
	file += '?ind='+count_id+'&auto_retorno='+p_autoRetorno;
	
	if(p_autoRetorno == 'V'){
			vet_id_campo_recebe 	 = '';
			nr_campo_recebe    	 	 = p_nr_col_retorno;
	}
	else{
			//alert(p_id_campo_recebe)
			vet_id_campo_recebe 	 = p_id_campo_recebe.split('**');
			nr_campo_recebe    	 	 = vet_id_campo_recebe.length;
			
			//alert(nr_campo_recebe);
			if(p_local_campo_recebe == ''){
				 for(i = 0; i < nr_campo_recebe ; i++){
					if(document.getElementById(vet_id_campo_recebe[i]))
						vet_campo_recebe[i] = document.getElementById(vet_id_campo_recebe[i]);
				 }
				 
		
			}
			else{
				 for(i = 0; i < nr_campo_recebe ; i++){
					if(eval(p_local_campo_recebe+'document.getElementById(\''+vet_id_campo_recebe[i]+'\')'))
						vet_campo_recebe[i] = eval(p_local_campo_recebe+'document.getElementById(\''+vet_id_campo_recebe[i]+'\')');
				 }
				
			}
	}
	
	y = 70;
	//y = findPosY_lov('alterar_'+count_id);
	
	if(y > 200)
		y -= 150;
	else
		y = 150;
		
	x = 160;
	document.getElementById('div_principal_lov').style.top = y+'px';
	document.getElementById('div_principal_lov').style.left = x+'px';
	document.getElementById('div_principal_lov').style.visibility = 'visible';
	
	if(document.getElementById('div_table')){	
		document.getElementById('ch_campo_dados').removeChild(document.getElementById('div_table'));
	}
		
	document.getElementById('ch_nome_'+count_id).value= '';
	string_old = '';
	botao_old = botao_new;
	
	document.getElementById('ch_nome_'+count_id).focus();
	
	setInterval("f_ajaxRead()",1);
}


/***************************************************************************************************************************
funcao chamada pelo botao localizar. 
executa a busca no tempo do usuario, e nao no tempo de setInterval.(garantia de funcionamento)*/
function f_seta_variaveis_ajax()
{
	f_ajaxRead();
	return false;
}
/***************************************************************************************************************************
f_ajaxRead(): funcao que faz a chamada e execucao da página contida em "file_new".
			   A variavel file_new e o resultado da concatenacao do endereco do arquivo onde serao realizadas
			   as buscas mais os parâmeros de buscae (linha "file+'&nm_consulta='+document.getElementById('ch_nome').value;)".
			   Esses parametros sao na pagina em 'file_new' como variaveis de request ($_REQUEST['nm_consulta']).
			   Realiza a chamada de  processXML(obj) somente quando o xmlObj.readyState == 4-indicando que o status é 'concluido'.
*/
function f_ajaxRead()
{
	if(document.getElementById('ch_nome_'+count_id))
	{
		var string = '';
		
		string = trim(document.getElementById('ch_nome_'+count_id).value);   
		var time = new Date();
		var diff = time.getTime() - last_time.getTime();
	
		//condicoes necessarias para realizar a abertura da pagia file:
		if(lov_load || ((string != string_old && diff >= 500) && (conta_key_press - conta_key_press_old) > 1 )&& string.length >= nr_caracteres)
		{		
				if(lov_load)
					nm_consulta = '';
				else
					nm_consulta = document.getElementById('ch_nome_'+count_id).value;
				
			
				lov_load = false;
				/********************************************************-**************/
				file_new = file+'&nm_consulta='+nm_consulta+'&nr_colunas='+nr_colunas;
				/***********************************************************************/
				if(vet_condicoes_formulario != '')
					file_new +='&vet_form='+vet_condicoes_formulario; 
					
				//alert(file_new);
				string_old = string;
				window.status = 'Pesquisando...';
				conta_key_press_old = conta_key_press;
				
				
				
				 document.getElementById('ch_campo_dados').innerHTML = ' <div id="load" style="height:auto; width:auto"><table aling="center"><tr><td aling="center">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="lov/imagens_lov/loading.gif" align="middle"></td></tr></table></div>  ';
				
				req = null;
				// Procura por um objeto nativo (Mozilla/Safari)
				if (window.XMLHttpRequest) 
				{
					req = new XMLHttpRequest();
					req.onreadystatechange = function()
											{   
												if(req.readyState == 4)
												{	
													processXML(req.responseXML);
												}
											}
					//alert(file_new);
					req.open("GET", file_new, true);
					req.send(null);
					// Procura por uma versão ActiveX (IE)
				}
				else if (window.ActiveXObject) 
					{
						req = new ActiveXObject("Microsoft.XMLHTTP");
						if (req) 
						{
							req.onreadystatechange = function()
													{   
														if(req.readyState == 4)
														{	
															processXML(req.responseXML);
														}
													}
							
							
							req.open("GET", file_new, true);
							req.send();
						}
				} 
				
				
				
		}
	}
}
/**********************************************************************************************************************************
processXML(obj): funcao que traz os dados da consulta:
	*dataArray = obj.getElementsByTagName('mae')[0].childNodes: retorna os nodos que sao filhos da tag XML 'mae' e amazana-os em um vetor dataArray.
	*dataArray[i].tagName: retorna o nome das tags que estao armazenadas em dataArray;
	*dataArray[i].getAttribute('nome'): retorna o conteudo armazenado no atributo "nome".
				  ----na pagina de consulta estao definidas as tags "mae" e filha(i) em que 'i' e um contador.
				  	  Como trata-se de um documento XML as tags podem conter qualquer nome. Por questoes didaticas, coloquei 'vo' , 'mae' e 'filha'
	*insertData: recebe a pagina HTML que será monstrada no DIV "ch_campo_dados".		  
*/
function processXML(obj)
{    
	var dataArray    = obj.getElementsByTagName('main')[0].childNodes;
	var dataArrayLen = dataArray.length;
	
	var insertData   = '<div style="height:200px; overflow:auto; width:auto;" id="div_table_'+count_id+'">';
   
    insertData      += ' <table width="100%" cellspacing="0" id="tb_lov_'+count_id+'" >';
	
	insertData += ' <tr  style="vertical-align:middle;  background-color:#CADDE3; width:auto;">';
	
	var td = '';
	
	for(j=0 ; j < nr_colunas; j++ )
	{
		
		if(vet_desc_coluna[j])
		{
			td += '<td class="subtitulo_lov_ajax">';
			
			td +=  vet_desc_coluna[j];
				
			td += ' <\/td> ';
		}
	}
	
	insertData += td ;
	insertData += '<\/tr>';
	
	for (var i=0; i<dataArrayLen; i++)
	{
		
		if(dataArray[i].tagName)
		{
		
			   
			if(dataArray[i].getAttribute('sql'))
			{
				existe_debug = true;
				
				sql    = dataArray[i].getAttribute("sql");
				
				if(dataArray[i].getAttribute('erro_oci'))
				{
					oci = dataArray[i].getAttribute('erro_oci');
				}
				else
					oci = 'Nada encontrado!';
				
				
				if(file_new.length > 50)
				{
					file_new = file_new.substr(0,50)+'\n'+file_new.substr(50,file_new.length)
				}
				
				f_construir_debug();
				
			}
			else if(dataArray[i].getAttribute('retorno_direto')){
				//alert('1');
				vetRetornoDireto = dataArray[i].getAttribute('retorno_direto');
				
			} //if(dataArray[i].getAttribute('retorno_direto'))
			else{//alert(2);
						if(dataArray[i].getAttribute('valor') == 'vazio')
						{
							insertData = '<div style="vertical-align:middle; height:18px; width: auto; background-color:#CADDE3;" class="titulo_campo">' + 'Nada localizado!<\/div>';
							valida = 0;
						}
						else
						{
							insertData += ' <tr id="tr'+i+'" ';
							insertData += ' onMouseOver="window.document.getElementById(\'tr'+i+'\').style.background=\'#E7F8EC\'"';
							insertData += ' onMouseOut="window.document.getElementById(\'tr'+i+'\').style.background=\'#FFFFFF\';"';
							insertData += ' style="width: auto; cursor:pointer; height:22px; background-color:#FFFFFF; vertical-align:middle;"';
							insertData += ' onClick="f_retorno( ';
							
							var retorno = '';
							
							for(j = 0; j < nr_campo_recebe ; j++)
							{
								if(dataArray[i].getAttribute('retorno_0'))
								{
									
										retorno += '\''+dataArray[i].getAttribute('retorno_'+j)+'\'';
									
									if(j < nr_campo_recebe -1)
									retorno += ',';
								}
							 }//for(j = 0; j < nr_campo_recebe ; j++)
							 
							insertData += retorno+' )"> ';
							
							
							var td      = '';
							for(j=0 ; j < nr_colunas; j++ )
							{
								td += ' <td class="cell_lov_ajax">';
								
								if(dataArray[i].getAttribute('retorno_'+j) == '' || dataArray[i].getAttribute('retorno_'+j) == 'null'||dataArray[i].getAttribute('retorno_'+j) == ' ')
									td += '&nbsp;';
								else
									td += dataArray[i].getAttribute('retorno_'+j);
									
								td += ' <\/td> ';
							}//for(j=0 ; j < nr_colunas; j++ )
							insertData += td;
							insertData +=' <\/tr>';
							valida = 1;
							
							//alert(insertData);
						}//else de if(dataArray[i].getAttribute('valor') == 'vazio')
			}
		}
	}

	insertData += '<\/table>';
	insertData += '<\/div>';
	document.getElementById('ch_campo_dados').innerHTML = insertData;
	
	if(existe_debug)
	document.getElementById('window_id_1_content').innerHTML = debug;
	
	window.status = 'Concluído';
}
/**********************************************************************************************************************************
f_retorno(ch_retorno): funcao que passa o conteudo pesquisado para o campo com id 'ch_retorno' e esconde o div 'div_principal_lov' 
*/


function f_retorno2(){
	
	exitem_elementos = 'nao';
	
	f_construir_debug();
				
	count  = "0";
	debug_ = '';
	//alert('f_retorno');
	if(vetRetornoDireto != '' && f_retorno.arguments.length > 0){
		//alert('vetRetornoDireto '+vetRetornoDireto);
		
		vetRetornoDireto = vetRetornoDireto.split('**');
		var erro = '';
		
		for( i =0; i < vetRetornoDireto.length; i++){
			
			if(eval(p_local_campo_recebe+'document.getElementById("'+vetRetornoDireto[i]+'")'))
				eval(p_local_campo_recebe+'document.getElementById("'+vetRetornoDireto[i]+'").value="'+f_retorno.arguments[i]+'"');
			else
				erro += vetRetornoDireto[i]+'<br>';
				
		}	
		
		if(erro != ''){
			debug += erro;
			alert(erro);
		}
		
		eval(p_local_campo_recebe+'document.getElementById("'+id_campo_focu+'").focus();');
	}
	else{
			
		 for (var i = 0; i <  f_retorno.arguments.length; i++)
		 {	
			 if(vet_campo_recebe[i])
			 {
				if(f_retorno.arguments[i] == 'null' || f_retorno.arguments[i] == 'undefined')
					vet_campo_recebe[i].value = '';
				else
					vet_campo_recebe[i].value =  f_retorno.arguments[i];
					exitem_elementos = 'sim';
			 }
			 else
			 {
				
				if(vet_campo_recebe[i] == 'undefined')
					debug_ += 'Elemento indefinido!';
				else
					debug_ += 'O elemento "'+vet_campo_recebe[i]+'" não existe!  ';
				 
			  }
		 }
		 
		 if(debug_ != '')
		debug += 'Você passou para a funcao que chama a lov Ids de elementos<br> que não existem: <br>'+debug_;
		else
			debug += 'Nada loacalizado';
		//alert(id_campo_focu);
		if(exitem_elementos && id_campo_focu)	
			eval(p_local_campo_recebe+'document.getElementById("'+id_campo_focu+'").focus();');
		else{																				
			if(exitem_elementos == 'sim')
				vet_campo_recebe[eval(nr_campo_focu -1)].focus()
		}
	
	}
	
	

	
	
	
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += '</table>';
	
	document.getElementById('div_principal_lov').style.visibility = 'hidden';
	document.getElementById('div_principal_lov').removeChild(document.getElementById('menu_'+count_id));
	document.getElementById('div_principal_lov').removeChild(document.getElementById('ch_campo_dados'));

	if(existe_debug)
		document.getElementById('window_id_1_content').innerHTML = debug;
	
	//setar variaveis para proxima consulta.
	f_setar_variaveis();
}



function f_retorno(){
	
	
	
	exitem_elementos = 'nao';
	
	f_construir_debug();
				
	count  = "0";
	debug_ = '';
	//alert(1)
	if(vetRetornoDireto != '' && f_retorno.arguments.length > 0){
		//alert('3');
		vetRetornoDireto = vetRetornoDireto.split('**');
		var erro = '';
		
		for( i =0; i < vetRetornoDireto.length; i++){
			//alert('manda');
			if(vetRetornoDireto[i] != 'nr_rows_consulta'){
				if(eval(p_local_campo_recebe+'document.getElementById("'+vetRetornoDireto[i]+'")'))
					eval(p_local_campo_recebe+'document.getElementById("'+vetRetornoDireto[i]+'").value = "'+f_retorno.arguments[i]+'"');
				else
					erro += vetRetornoDireto[i]+'<br>';
			}
				
		}	
		
		if(erro != ''){
			debug += erro;
			alert(erro);
		}
		
		eval(p_local_campo_recebe+'document.getElementById("'+id_campo_focu+'").focus();');
	}
	else{
		
		 for (var i = 0; i <  f_retorno.arguments.length; i++)
		 {
			 
			 if(vet_campo_recebe[i])
			 {
				if(f_retorno.arguments[i] == 'null' || f_retorno.arguments[i] == 'undefined')
					vet_campo_recebe[i].value = '';
				else
					vet_campo_recebe[i].value =  f_retorno.arguments[i];
					exitem_elementos = 'sim';
			 }
			 else
			 {
				
				if(vet_campo_recebe[i] == 'undefined')
					debug_ += 'Elemento indefinido!';
				else
					debug_ += 'O elemento "'+vet_campo_recebe[i]+'" não existe!<br>';
				 
			  }
		 }
		 
		 if(debug_ != '')
		debug += 'Você passou para a funcao que chama a lov Ids de elementos<br> que não existem: <br>'+debug_;
		else
			debug += 'Nada loacalizado';
	}
	
	/*
	if(exitem_elementos == 'sim')
		vet_campo_recebe[eval(nr_campo_focu -1)].focus()*/
	
	
	
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += '</table>';
	
	document.getElementById('div_principal_lov').style.visibility = 'hidden';
	document.getElementById('div_principal_lov').removeChild(document.getElementById('menu_'+count_id));
	document.getElementById('div_principal_lov').removeChild(document.getElementById('ch_campo_dados'));

	if(existe_debug)
		document.getElementById('window_id_1_content').innerHTML = debug;
	
	//setar variaveis para proxima consulta.
	f_setar_variaveis();
}


/**********************************************************************************************************************************
 f_marca_passo(): pega o tempo atual do keyup do usuario e itera conta_key_press.
 esses parametros sao nesessarios para validar se a consulta vai ou nao acontecer em f_ajaxRead();
*/
function f_marca_passo()
{
	
	last_time = new Date();
	conta_key_press += 1;
}

/*********************************************************************************************************************/
/*findPosX e findPosY retornam a posicao x e a posicao y de um objeto!
OBS: IE retorna lavores diferentes em relacao ao Moz. Por isso, deve-se procurar por um fator de correcao!
*/
/*
function findPosX_lov(objnome)
{
   var curleft = 0;
 	//obj = document.getElementById(objnome);
   obj	 = botao_new;
   
   if(obj.offsetParent)
   { 
		while(obj.offsetParent)
		{ 
			curleft += obj.offsetLeft;
		    obj = obj.offsetParent;
		 }
   }
   return curleft;
}
*/
function findPosY_lov(objnome)
{
   var curtop = 0;

   obj = eval(p_local_campo_recebe+'document.getElementById("'+objnome+'")');
  
   if (obj.offsetParent)
    { 
		while(obj.offsetParent) 
		{ 
			curtop += obj.offsetTop;
			obj = obj.offsetParent; 
		}
	}
	
   return curtop;
 
}

function trim(string)
{
	//caso tenha espaços no fim
	while(string.charAt(string.length - 1) == ' ')
	{
		string = string.substring(0, string.length - 1);
	}
	//caso tenha espaços no início
	while(string.charAt(0) == ' ')
	{
		string = string.substring(1, string.length);
	}
	
	return string;
}

function f_setar_variaveis(){
	string_old = '';
	conta_key_press_old = 0;
	lov_load  = false;
	vetRetornoDireto = '';
}

function f_construir_debug()
{
	
	debug  = '<table width="100%" class="dialog_content" cellspacing="1px" cellpadding="1px" >';
	debug += 	'<tr>';
	debug += 		'<td   bgcolor="#CCCCCC" class="cell_debug" style="vertical-align:top; font-size:13px; color:#000000;" align="center">';
	debug += 			'URL';
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>';
	debug += 		'<td  style="vertical-align:top; color:#000000;" bgcolor="#FFFFFF" class="cell_debug">';
	debug += 			file_new;
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>';
	debug += 		'<td  bgcolor="#CCCCCC" class="cell_debug" style="vertical-align:top; font-size:13px; color:#000000;" align="center">';
	debug += 			'SQL';
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>';
	debug += 		'<td  style="vertical-align:top; color:#000000;" bgcolor="#FFFFFF" class="cell_debug">';
	debug += 			sql;
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>';
	debug += 		'<td   bgcolor="#CCCCCC" class="cell_debug" style="vertical-align:top; font-size:13px; color:#000000;" align="center">';
	debug += 			'OCI ERROR';
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>';
	debug += 		'<td  style="vertical-align:top; color:#000000;" bgcolor="#FFFFFF" class="cell_debug">';
	debug += 			oci;
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>';
	debug += 		'<td   bgcolor="#CCCCCC" class="cell_debug" style="vertical-align:top; font-size:13px; color:#000000;" align="center">';
	debug += 			'Retorno';
	debug += 		'</td>';
	debug += 	'</tr>';
	debug += 	'<tr>'; 
	debug += 		'<td  style="vertical-align:top;" bgcolor="#FFFFFF" class="cell_debug">';
	
}


/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 * Script featured on Dynamic Drive (http://www.dynamicdrive.com) 12.08.2005
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************/

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};
/*********************************************************************************************************************/