// JavaScript Document

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 0.  - Declaracion de variables
// 1.  - objCB() - Funcion declaradora              (PUBLICO)
// 2.  - Declaracion del Objeto Control ComboBox
// 3.  - _inicio_CCB()
// 4.  - _creaBoton_CCB()
// 5.  - _mostrarCaja_CCB()                        (PUBLICO)
// 6.  - _vis_CCB()
// 7.  - _addOpc_CCB()
// 8.  - _delOpc_CCB()
// 9.  - _updOpc_CCB()
// 10. - _creaOPCs_CCB()
// 11. - _escoge_CCB()
// 12. - _cambia_pag_CCB()
// 13. - _clean_timer_CCB()
// 14. - _incPAg_CCB()
// 15. - _decPAg_CCB()
// 16. - _locate_CCB()

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Requerimientos
// - Libreria JS de multiples utilidades (varias.js)
//     <script type="text/javascript" src="/axys_comun.beta/libs/js/varias.js"></script>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 0. Variables
var _aControlBox = new Array();
var dirLibsPHP = (dirLibsPHP)?dirLibsPHP:"./";
var dirLibImages = (dirLibImages)?dirLibImages:"/axys.comun/beta/img/";
var _to1_CCB = null;
var _to2_CCB = null;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 1. Control ComboBox - Crea el objeto CB y su respectivo controlador

 * \param sDest 	- ( STRING ) nombre del Objeto destino, parte de un HTML
 * \param sTabla  - ( STRING ) nombre de la tabla de donde se sacaran los datos apra llenarlo
 * \param sPK     - ( STRING ) nombre del Campo a devolver, normalmente la Primary Key
 * \param sCampos - ( STRING ) lista de campos separadas por coma
 * \param nCamposMostrar - ( INTEGER ) Numero de campos que se mostraran de sCampos
 * \param sSQL 		- ( STRING ) Cadena SQL adicional.
 * \return oLista - ( Objeto ) devuelve un objeto Listado, el cual permite controlar la lista
 * \author EG - (egonpin@gmail.com) - 27/07/2005
 */
function objCB()
{
	var sDest          = new String(arguments[0]);
	var sTabla         = new String(arguments[1]?arguments[1]:sDest);
	var sPK            = new String(arguments[2]?arguments[2]:sDest);
	var sCampos			 = new String(arguments[3]?arguments[3]:"");
	var nCamposMostrar = new Number(arguments[4]?arguments[4]:1);
	var sSQL           = new String(arguments[5]?arguments[5]:"");
	var bAutoCarga     = ((arguments[6]!= null)?arguments[6]:true);

	var oCCB = new _oCCB();

  oCCB.tabla     = trim(sTabla);
  oCCB.pk        = trim(sPK);
  oCCB.campos    = trim(sCampos);
  oCCB.numCols   = nCamposMostrar;
  oCCB.SQL       = trim(sSQL);
  oCCB.oriSQL    = trim(sSQL);
  oCCB.autoCarga = bAutoCarga;
  oCCB.id        = "" + trim(sDest);

	oCCB.Inicio();
	if (oCCB.autoCarga == true)
	{
  	oCCB.consulta(true);
	}

	return oCCB;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 2. Objeto Control ComboBox
 * \ingroup fPrivada
 * \author EG - (egonpin@gmail.com) - 27/07/2005
*/
function _oCCB()
{
	// Publico
	this.id 			= new String("");
  	this.value 		= new String("");
 	this.idForm 	= new String("");     // Id que debe tener el input del control para
  											              // cuando esta dentro de un formulario
                                      // si se deja vacio tomara el que genere el objeto
	this.enabled 	= new Boolean(true); // Indica si el control esta Enable o Disable
	this.tamBox    = new Number(5);     // Tamaño de la caja de seleccion solo cantidad de opciones a mostrar
	this.isNull    = false; // Indica si el control permite dato nulo o no;
	this.isNullVis = true; // Booleano que indica si se muestra la opción Nula
	this.valueNull = "";  // Valor que retornara el campo NULL
	this.nombreNull = " --- ";  // Nombre que se mostrara en el campo NULL
	this.opcHeight = new Number(18);    // Tamaño en pixeles de cada opcion del CB
	this.orden     = new String("");    // Cadena de campos separados por coma para que ordene los datos
	this.autoCarga = new Boolean(true); // Indica si al crear el combobox carga los datos automaticamente

	this.visCB   	= new Boolean(true);

	this.creaBoton = _creaBoton_CCB;
	this.addOpc    = _addOpc_CCB;
	this.delOpc    = _delOpc_CCB;
	this.updOpc    = _updOpc_CCB;
	this.locate    = _locate_CCB; //onkeypress
	this.selOpc    = _selOpc_CCB;
	this.onBlur    = _onBlur_CCB;
//	this.onFocus   = _onFocus_CCB;
	this.onChange 	= _onChange_CCB;
	this.vaciar 	= _vaciar_CCB;

	this.funOnChange = new String("");
//	this.eKeyPress = _eKeyPress_CCB;

	// Privado
	this.idDest = new String("");  // ID HTML del DIV/SPAN donde quedará el combo box
	this.oDest 	= null; // antes oCB

	this.idBox 	= new String(""); //   id HTML - Div que contiene la Tabla de Datos del ComboBox
	this.oBox   = null;           //  obj HTML - Div que contiene la Tabla de Datos del ComboBox
	this.aBox   = new Array();    // Array que contiene las opciones del comboBox
	                                 /*
	                                    [0] texto    - (STR) a Mostrar
	                                    [1] valor    - (STR) a devolver
	                                    [2] hint     - (STR) a Mostrar en el HINT
	                                    [3] enable   - (BOOL) Enable o Disable
	                                    [4] selected - (BOOL) Selected o NoSelected
												*/

	this.posActBox = new Number(0);  // controla la posicion o scroll de la Box
	this.visBox    = new Boolean(false);
	this.visUD     = new Boolean(true); // indica si esta visible las flechas UP/DOWN de la caja
	this.visFL     = new Boolean(true); // indica si esta visible las flechas FIRST/LAST de la caja
	this.cantSel   = new Number(0);     // indica la cantidad de registros seleccionados en el CB
	this.primeraSel  = new Number(-1);    // Guarda el indice del array aBox cuando existe un solo registro seleccionado

	this.idBut     = new String("");
	this.cmdBut    = new String("javascript:"); // comando que muestra la box
	this.visBut    = new Boolean(true);
	this.oBut      = null;

	this.idInput     = new String("");
	this.oInput      = null; // Input Contenedor del Valor
	this.oInputMaq   = null; // Input Contenedor del Dato Maquillado

	this.idTDatos    = new String(""); //  id HTML - Tabla que contiene los Datos del ComboBox
	this.oTDatos     = null;           // obj HTML - Tabla que contiene los Datos del ComboBox

	this.autoCarga = new Boolean(true);
	this.Inicio    = _inicio_CCB;
	this.mostrar   = _vis_CCB;
	this.creaOPC   = _creaOPC_CCB;
	this.borraOPCs = _limpia_CCB;       // Borra las opciones de un cb

	// Coneccion a BD
	this.construyeSQL = _construyeSQL_CB;
	this.consulta     = _consulta_CB;

	this.tabla     = new String("");
	this.pk        = new String("");
	this.campos    = new String("");
	this.numCols   = new Number(1);
	this.SQL       = new String("");
	this.orden     = new String("");
	this.TipoOrd   = new String("");

	this.genSQL    = new String("");
	this.SQLmanual = new String("");
	this.sSQL      = new String("");

	this.oriSQL    = new String("");

  // Coneccion con otros Objetos
	this.filtrar   = _fSQL_CB_db;           // Metodo para hacer que el combobox dependa de otro campo
	this.sFiltro   = new String("");       // Condicion de Filtro que debe ejecutar el query sSQL en el WHERE

	this.type      = new String("COMBOBOX");

	this.valAct    = _cambiarVal_CCB;

  // Controla los timer para hacer que el control se oculte automaticamente
	this._to1_CCB     = null;
	this.noAutoOculta = _elimina_timer_CCB;

	this.buscaValor = _buscaValor_CCB;
	this.busca1erValor = _busca1erValor_CCB;

	this.evtOnSel = null;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 3. Funcion Inicio
 * \ingroup fPrivada
 * \param sDest 	- ( STRING ) nombre del Objeto destino, parte de un HTML
 * \author EG - (egonpin@gmail.com) - 27/07/2005
*/
function _inicio_CCB()
{
	var sDest 	= new String(trim(this.id));
	var sForm 	= this.pk;

	var _sHTMLB = null;

	this.idForm   = sForm.trim();
	this.idInput  = sDest.trim();
	this.idDest   = sDest.trim();
	this.idBox    = "icbx_box_" + this.idDest;
	this.idBut    = "icbx_but_" + this.idDest;
	this.idTDatos = "icbx_tdatos_" + this.idDest;

	this.oInput    = oBusca(this.idInput);
	this.oInputMaq = oBusca('maqCB_' + this.idInput); // Prefijo Standard para [forms_fx.php - gen_campo_html()]
	//_sHTML += "<div id=\"" + this.idBox + "\" name=\"" + this.idBox + "\" class='icbxDatos' onmouseover=\"clearTimeout(_to1_CCB)\" onmouseout=\"_clean_timer_CCB('"+ this.idDest +"',false)\"></div>";
	_sHTMLB = "<div id=\"" + this.idBox + "\" name=\"" + this.idBox + "\" class='icbxDatos' tabindex='-1' onScroll='buscaComboBox(\""+ this.id +"\").noAutoOculta();' onBlur='_clean_timer_CCB(\""+ this.id +"\");'></div>";

	this.oDest = oBusca("CB_" + this.idDest );
// 	this.oDest.className = "icbxDatos";
// 	this.oDest.parent.className = "icbxDatos";
	obj_writeHTML(this.oDest, _sHTMLB);

	this.oBox = oBusca(this.idBox);
	this.oBut = oBusca(this.idBut);

	this.creaBoton();
	this.mostrar(this.idBox, false);

	_aControlBox.push(this);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 4. Crea Boton
 * \ingroup fPrivada
 * \param sCad 	- ( STRING ) Cadena HTML para generar el boton
 * \author EG - (egonpin@gmail.com) - 27/07/2005
*/
function _creaBoton_CCB()
{
	var sCad = new String(arguments[0]?arguments[0]:"");

// 	if(sCad == "")
// 	{ sCad = "<img tabindex=\"-1\" src='" + dirLibImages + "bComboBox.gif' border='0'>"; }

// 	sCad = "<a tabindex=\"-1\" href=\"javascript:_mostrarCaja_CCB('" + this.idDest + "');\" class='icbxBoton' >" + sCad + "</a>";
	this.cmdBut = "_mostrarCaja_CCB('" + this.id + "');";
  obj_writeHTML(this.oBut, sCad);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 5. Muestra Caja de un ComboBox
 * \param sCad 	- ( STRING ) Nombre de la caja a Mostrar
 * \param bStd    - ( BOOLEAN ) TRUE lo muestra, FALSE lo oculta
 * \author EG - (egonpin@gmail.com) - 27/07/2005
*/
function _mostrarCaja_CCB()
{
	var sCad = new String(arguments[0]?arguments[0]:"");

  var _oTMP = false;

  _oTMP = _localiza_CB(sCad);

	if(_oTMP.enabled == true)
	{
		if(_oTMP.oBox)
		{
			if( _oTMP.visBox == true )
			{
				_oTMP.mostrar("CAJA",false);
			}
			else
			{
				_oTMP.oInputMaq.focus();
				if (_oTMP.oInputMaq.value.trim() != "")
				{ _oTMP.selOpc(_oTMP.oInputMaq.value); }
				_oTMP.noAutoOculta();
				_oTMP.mostrar("CAJA",true);
			}
		}
	}
	else
	{
		_oTMP.mostrar("CAJA",false);
		_oTMP.visBox = false;
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 6. Visibilidad - Muestra u Oculta una parte o una opcion del control
 * \ingroup fPrivada
 * \param sDes 	- ( STRING ) parte a ocultar si es de tipo String oculta ese objeto
 *                  ( NUMBER ) si es numerica oculta la opcion de la caja
 * \param bStd    - ( BOOLEAN ) TRUE lo muestra, FALSE lo oculta
 * \author EG - (egonpin@gmail.com) - 27/07/2005
*/
function _vis_CCB()
{
 	var sDes = arguments[0];
 	var bStd = arguments[1];
 	var _tmp = null;

 	var tipoDes = new String(typeof(sDes));

 	if( tipoDes.trim() == "string" )
	{
	  switch( sDes.trim() )
	  {
		case "BOTON":
		      if(bStd == true)  {  obj_show(this.oBut); }
		      else  { obj_hide(this.oBut); }
		break;
		case "CAJA":
          this.visBox = bStd;
		      if(bStd == true)  {  obj_show(this.oBox); }
		      else  { obj_hide(this.oBox); }
		break;
		case "INPUT":
		      if(bStd == true)  {  obj_show(this.oInput); }
		      else  { obj_hide(this.oInput); }
		break;
		case "INPUTMAQ":
		      if(bStd == true)  {  obj_show(this.oInputMaq); }
		      else  { obj_hide(this.oInputMaq); }
		break;
		default:
			_tmp = oBusca(sDes);
			if(_tmp)
			{
		      if(bStd == true)  {  obj_show(_tmp); }
		      else  { obj_hide(_tmp); }
			}
		break;
	  }
	}

  if( tipoDes.trim() == "number" )
  {  // ocultamos las opciones de la caja
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 7. Adicionar Opcion a la caja del Control
 * \ingroup fPrivada
 * \param sTxt 	- ( STRING ) Texto a mostrar en el control
 * \param sVal 	- ( STRING ) Texto a devolver en el control, despues de seleccionar
 * \param sHint 	- ( STRING ) Texto a mostrar en la ayuda o Hint
 * \param bEna 	- ( BOOLEAN ) TRUE enable, FALSE disable
 *
 * \return Retorna la posicion que se le asigno + 1 o (-1) si fallo la adicion
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _addOpc_CCB()
{
  var sTxt 	= new String(arguments[0]?arguments[0]:"");
  var sVal 	= new String(arguments[1]?arguments[1]:"");
  var sHint = new String(arguments[2]?arguments[2]:"");
  var bEna 	= new Boolean(arguments[3]);
  var bSel 	= new Boolean(arguments[4]?arguments[4]:false);

  var _return = this.aBox.push( new Array(sTxt,sVal,sHint,bEna,bSel) );
//  this.creaOPC();
  return _return;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 8. Borrar Opcion a la caja del Control
 * \ingroup fPrivada
 * \param nPos 	- ( NUMBER ) Posicion de la opcion
 *
 * \return Retorna TRUE si se elimino con exito o FALSE si fallo la eliminacion
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _delOpc_CCB()
{
  var nPos 	= arguments[0]?new Number(arguments[0]): -1;

  var _resp = null;

  if(nPos == -1)  { _resp = false; }
  else
  { this.aBox.splice(nPos,1,"");
   _resp = true;
  }

	this.creaOPC();
  return _resp;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 9. Actualiza Opcion a la caja del Control
 * \ingroup fPrivada
 * \param nPos 	- ( NUMBER ) Posicion de la opcion
 * \param sTxt 	- ( STRING ) Texto a mostrar en el control
 * \param sVal 	- ( STRING ) Texto a devolver en el control, despues de seleccionar
 * \param sHint 	- ( STRING ) Texto a mostrar en la ayuda o Hint
 * \param bEna 	- ( BOOLEAN ) TRUE enable, FALSE disable
 *
 * \return Retorna la posicion que se le asigno o (-1) si fallo la actualizacion
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _updOpc_CCB()
{
  var nPos 	= arguments[0]?new Number(arguments[0]): -1;
  var sTxt 	= new String(arguments[0]?arguments[0]:"");
  var sVal 	= new String(arguments[1]?arguments[1]:"");
  var sHint = new String(arguments[2]?arguments[2]:"");
  var bEna 	= new Boolean(arguments[3]);
  var bSel 	= new Boolean(arguments[4]?arguments[4]:false);

  this.aBox.splice( nPos, 1, new Array(sTxt,sVal,sHint,bEna,bSel) );
	this.creaOPC();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 10. Genera las opciones de la caja
 * \ingroup fPrivada
 *
 * \return Retorna TRUE si se creo con exito
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _creaOPC_CCB()
{
	var _html = "<table id=\"" + this.idTDatos + "\" name=\"" + this.idTDatos + "\" class='icbxDatos' tabindex='-1'>";
	//if (this.isNull == true)
	//   _html += "<tr><td colspan='2' class='icbxDato' id='icbxDato_"+n+"' name='icbxDato_"+n+"' onmouseover=\"cambiaClass(this,'icbxDato','icbxDatoOver')\" onmouseout=\"cambiaClass(this,'icbxDato','icbxDato')\" onclick=\" _escoge_CCB('"+ this.idDest + "','" + this.aBox[n][1] +"','" + this.aBox[n][0] +"') \" >" + this.aBox[n][0] + "</td></tr>";

	for(var _n=0; _n<this.aBox.length; _n++)
	{
//Servidor	   _html += "<tr><td colspan='2' class='icbxDato' style='height:"+this.opcHeight+"px;' id='icbxDato_"+_n+"' name='icbxDato_"+_n+"' onmouseover=\"cambiaClass(this,'icbxDato','icbxDatoOver')\" onmouseout=\"cambiaClass(this,'icbxDato','icbxDato')\" onclick=\"_escoge_CCB('" + this.id + "','" + this.aBox[_n][1] + "','" + this.aBox[_n][0] + "'," + _n + "); \" tabindex='-1'>" + this.aBox[_n][0] + "</td></tr>";
	   _html += "<tr><td class='icbxDato' style='height:"+this.opcHeight+"px;' id='icbxDato_"+_n+"' name='icbxDato_"+_n+"' onmouseover=\"cambiaClass(this,'icbxDato','icbxDatoOver')\" onmouseout=\"cambiaClass(this,'icbxDato','icbxDato')\" onclick=\"_escoge_CCB('" + this.id + "','" + this.aBox[_n][1] + "','" + this.aBox[_n][0] + "'," + _n + "); \" tabindex='-1'>" + this.aBox[_n][0] + "</td></tr>";
	}
	_html += "</table>";
	obj_writeHTML(this.oBox, _html);

	this.oTDatos = oBusca(this.idTDatos);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 11. Oculta y devuelve el valor
 * \ingroup fPrivada
 * \param idDest (STRING)
 * \param sValor (STRING)
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _escoge_CCB()
{
	var id          = arguments[0];
	var sValor      = arguments[1];
	var sOpcion     = arguments[2];
	var sIndiceoBox = arguments[3];
	var n = 0;
	var _oTMP = null;

 	for(n=0; n<_aControlBox.length; n++)
	{
	   if(_aControlBox[n].id == id)
	   {
       _oTMP = _aControlBox[n];
       n = _aControlBox.length;
     }
	}
	_oTMP.primeraSel      = sIndiceoBox;
	_oTMP.cantSel         = 1;
	_oTMP.value           = sValor;
	_oTMP.mostrar("CAJA",false);
	_oTMP.oInput.value    = sValor;
	_oTMP.oInputMaq.value = sOpcion;
	_oTMP.oInputMaq.focus();
	_onSelectCB(_oTMP, sIndiceoBox, 'mouse');

	_oTMP.onChange();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 12. cambia de pagina
 * \ingroup fPrivada
 * \param idDest (STRING)
 * \param sValor (STRING) - Acepta SUBE o BAJA
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _cambia_pag_CCB()
{
	var idDest = arguments[0];
	var sValor = arguments[1];
	var n = 0;
	var _oTMP = null;

 	for(n=0; n<_aControlBox.length; n++)
	{
	   if(_aControlBox[n].idDest == idDest)
	    {  _oTMP = _aControlBox[n]; }
	}

	if(sValor == "U")  _oTMP.posActBox--;
	if(sValor == "D")  _oTMP.posActBox++;
	if(sValor == "F")  _oTMP.posActBox=0;
	if(sValor == "L")  _oTMP.posActBox=_oTMP.aBox.length-_oTMP.tamBox;

	_oTMP.creaOPC();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 13. Crea el timer del evento onBlur, para ocultar el Box
 * \ingroup fPrivada
 * \param idDest (STRING)
 * \param bValor (BOOLEAN)
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _clean_timer_CCB()
{
	var idDest = arguments[0];
	var bValor = arguments[1];
	var _obj = _localiza_CB(idDest);

	// update by xButil 8/2/2007 2:50:39 AM
	if( typeof(_obj.aBox[_obj.primeraSel]) == "object" && (_obj != null))
	{
	   if((_obj.oInputMaq.value == "") && (_obj.isNull == true) )
	   {
	   	_obj.oInputMaq.value = "";
	   	_obj.oInput.value    = "";
		}
	   else
	   {
   	_obj.oInputMaq.value = _obj.aBox[_obj.primeraSel][0];
   	_obj.oInput.value    = _obj.aBox[_obj.primeraSel][1];
   }
   }
  _onSelectCB(_obj, _obj.primeraSel, 'teclado');

 	_obj._to1_CCB = setTimeout("_localiza_CB('"+idDest+"').mostrar('CAJA',false)", 500); //2000
 	//buscaComboBox('$v_nom_campo_id').mostrar('CAJA',false);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 13. Elimina el timer del evento
 * \ingroup fPrivada
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _elimina_timer_CCB()
{
  clearTimeout(this._to1_CCB)
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 14. Incrementa Pagina
 * \ingroup fPrivada
 * \param idDest (STRING)
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _incPAG_CCB()
{
	var idDest = arguments[0];
	clearInterval(_to2_CCB);
	_to2_CCB=setInterval("_cambia_pag_CCB('" + idDest + "','U')",40);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 15. Decrementa Pagina
 * \ingroup fPrivada
 * \param idDest (STRING)
 *
 * \author EG - (egonpin@gmail.com) - 28/07/2005
*/
function _decPAG_CCB()
{
	var idDest = arguments[0];
	clearInterval(_to2_CCB);
	_to2_CCB=setInterval("_cambia_pag_CCB('" + idDest + "','D')",40);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 16. Localiza un elemento
 * \ingroup fPrivada
 *
 * \author xButil - (xbutil@gmail.com) - 2006-05-31 11:15:18 a.m.
*/
function _locate_CCB()
{
	var e     = arguments[0];
	var _cant = arguments[1]?arguments[1]:0;

	var valor    = new String("");
	var encontro = false;

	// 13 = Enter
	// 38 = Flecha Arriba
	// 40 = Flecha Abajo
	//  9 = TAB

	if  (_onKeyPress(e) == 38 && this.cantSel == 1)
	{
		if (this.primeraSel > 0)
      	this.primeraSel--;
		this.oInputMaq.value = this.aBox[this.primeraSel][0];
		this.oInput.value    = this.aBox[this.primeraSel][1];
    	encontro = true;
		this.mostrar("CAJA",true);
    // this.oBox.scrollTop = this.primeraSel*this.opcHeight; // 18px Height TD de cada Dato del CB
	}
	if  (_onKeyPress(e) == 40 && this.cantSel == 1)
	{
		if (this.primeraSel < this.aBox.length-1)
	      this.primeraSel++;
		this.oInputMaq.value = this.aBox[this.primeraSel][0];
		this.oInput.value    = this.aBox[this.primeraSel][1];
    	encontro = true;
		this.mostrar("CAJA",true);
      //this.oBox.scrollTop = this.primeraSel*this.opcHeight; // 18px Height TD de cada Dato del CB
	}
	else if  (_onKeyPress(e) == 40 && this.cantSel == 0) // this.cantSel == 0
	{
		this.primeraSel = 0; // Selecciona el primer registro de aBox
		this.cantSel  = 1; // Marca la Bandera de cantSel como 1 registro
    	encontro = true;
		this.oInputMaq.value = this.aBox[this.primeraSel][0];
		this.oInput.value    = this.aBox[this.primeraSel][1];
		this.mostrar("CAJA",true);
	}
	else if  (_onKeyPress(e) == 40 && this.cantSel > 1) // this.cantSel == 0
	{
		//this.primeraSel = 0; // Selecciona el primer registro de aBox
		this.cantSel = 1; // Marca la Bandera de cantSel como 1 registro
    	encontro = true;
		this.oInputMaq.value = this.aBox[this.primeraSel][0];
		this.oInput.value    = this.aBox[this.primeraSel][1];
		this.mostrar("CAJA",true);
	}
	if ((_onKeyPress(e) == 13 || _onKeyPress(e) == 9) && this.cantSel == 1)
	{
		this.oInputMaq.value = this.aBox[this.primeraSel][0];
		this.oInput.value    = this.aBox[this.primeraSel][1];
		this.mostrar("CAJA",false);
    //encontro = true;
    _onSelectCB(this, this.primeraSel, 'teclado');
	}
	else
	{
		this.oInput.value = "";
		valor = this.oInputMaq.value;

		for(var i=0; i<this.aBox.length; i++)
		{
			if (valor.trim().length > 0 && this.aBox[i][0].substr(0, valor.length).toUpperCase() == valor.toUpperCase())
			{
				encontro = true;
				if (this.aBox[i][0].toUpperCase() == valor.toUpperCase())
				{
					this.oInput.value = this.aBox[i][1];
        		}
				i = this.aBox.length;
				//break;
			}
		}
		if (encontro == false)
		{
			this.oInputMaq.value = this.oInputMaq.value.substr(0,this.oInputMaq.value.length-1);
			this.cantSel = 0;
			// 16-05-07 la sig linea la agregue para que el valide una palabra buena despues de escribirle un caracter invalido
			if(_cant == 0) this.locate(e, 1); // Se llama a si misma
		}
 }
	if (encontro == true)
	{
		this.selOpc(valor);
		this.mostrar("CAJA",true);
		//if (this.primeraSel*this.opcHeight > this.opcHeight*8)
    	this.oBox.scrollTop = this.primeraSel*this.opcHeight; // 18px Height TD de cada Dato del CB
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 17. Marca un elemento para ser selecionado de acuerdo al texto
 * \ingroup fPrivada
 * \param e (evento)
 *
 * \author xButil - (xbutil@gmail.com) - 2006-05-31 11:15:18 a.m.
*/
function _selOpc_CCB()
{
	var _txt = new String(arguments[0]);
	var _cantSel = 0;
	var _sel = -1;
	var i = 0;

	// soAux = this.oTDatos;

	for (i=0; i < this.oTDatos.rows.length; i++)
   {
		if (_txt.trim().length > 0 && this.oTDatos.rows[i].cells[0].innerHTML.substr(0, _txt.length).toUpperCase() == _txt.toUpperCase())
		{
         this.oTDatos.rows[i].cells[0].className = 'icbxDatoOver';
         this.aBox[i][4] = true;
			_cantSel++;
			if (_sel == -1)
				_sel = i;
    	}
		else
		{
         this.oTDatos.rows[i].cells[0].className = 'icbxDato';
    	}
	}

	this.primeraSel = _sel;
	this.cantSel = _cantSel;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 18. Verifica que ocurre cuando se abandona el objeto CB que se encuentra invisible y contiene el dato real
 * \ingroup fPrivada
 *
 * \author xButil - (xbutil@gmail.com) - 2006-05-31 11:15:18 a.m.
*/
function _onBlur_CCB()
{
  var _found = false;

  if(this.aBox.length == 0)
  {
    this.consulta();
  }

	if (this.oInput.value.trim() == "")
	{
   	this.oInput.value    = "";
   	this.oInputMaq.value = "";
	}
	else
	{
    for(var n=0; n<this.aBox.length; n++)
    {
      if(this.aBox[n][1] == this.oInput.value)
      {
        this.oInputMaq.value = "" + this.aBox[n][0];
        _found = true;
        n = this.aBox.length;
      }
    }
    if(!_found)
    {
     	this.oInput.value    = "";
     	this.oInputMaq.value = "";
    }
  }

}

////////////////////////////////////////////////////////////////////////////////
/** 19. - Genera la cadena SQL
 * \param _bConsulta - (BOOLEAN) Si es verdadero genera SQL con LIMITE y ORDEN
 * \param _scampos - [STRING] Contiene la cadena de campos a traer - Opcional
 * \author EG - (egonpin@gmail.com) - 15/05/2007
 */
function _construyeSQL_CB()
{
	var _bConsulta	 = arguments[0];
	var _scampos    = arguments[1]?arguments[1]:"";

	var _cadSQL = "";
	var _orden = null;
	var _where = null;

	// construyendo el SELECT

// EG 10/10/2006
// cuando tengo un filtro me borra los campos por eso lo agregue
  if(this.campos.trim() == "") this.campos = _scampos;
  if(this.campos.trim() == "") this.campos = "*";

//
	if (trim(this.SQLmanual).length > 0)
	{
		this.sSQL = trim(this.SQLmanual);
	}
	else
	{
		if(_bConsulta == true)
		{
			if(trim(this.pk) != "")
			{
				this.sSQL = "SELECT " + this.campos.trim() + "," + this.pk.trim() + " FROM " + this.tabla.trim() ;
			}
			else
				this.sSQL = "SELECT " + this.campos.trim() + " FROM " + this.tabla.trim();
		}
		else
		{
			this.sSQL = "SELECT * FROM " + this.tabla.trim();
		}
  }

	//construye ORDER BY
	if (this.orden == "")
		_orden = "";
	else
		_orden = " ORDER BY " + this.orden + " " + this.TipoOrd;

	//BEGIN - construyendo el WHERE
	_where = trim(this.SQL);

	if (_where.trim()!="")
	{
		if (((this.sSQL.indexOf("WHERE"))<0))
			_where = " WHERE " + _where;
  }
	//END construyendo el WHERE

	if(_bConsulta == true)
	{
		_cadSQL = this.sSQL + " "+ _where + " "+ _orden;
	}
	else
	{
		_cadSQL = this.sSQL + " "+ _where;
	}

	this.genSQL = trim(_cadSQL);

	return _cadSQL;
}

////////////////////////////////////////////////////////////////////////////////
/** 20. - Busca un Control ComboBox
 * \param _sID - (STRING) Nombre del Control a Buscar
 * \author EG - (egonpin@gmail.com) - 15/05/2007
 */
function _localiza_CB()
{
	var _sID = arguments[0];
	var _objx = null;
	var x=0;

 	for(x=0; x<_aControlBox.length; x++)
	{
		if(trim(_aControlBox[x].id) == trim(_sID) )
		{
			_objx = _aControlBox[x];
      	x     = _aControlBox.length;
		}
	}
	return _objx;
}

function buscaComboBox()
{
  var _sID = arguments[0];
  return _localiza_CB(_sID);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 21. - Consulta de SQL (Privada)
 *
 * \ingroup fPrivada
 * \param Inicial
 * \sa _ret_consulta_CB
 * \author EG - (egonpin@gmail.com) - 15/05/2007
 */
function _consulta_CB()
{
  var _Inicial = arguments[0]?arguments[0]:false;
  var parametros = new Array();
  var _select = null;
  var sidname = sid.split('=');

// EG - 01-03-2007 => agregada la siguiente linea para asegurar que filtre
 if( trim(this.sFiltro) != "") this.filtrar();
// 01-03-2007

	if(trim(this.tabla) != "")
	{
	_select = this.construyeSQL(true);
	this.sSQL = _select;
//	parametros.push(_select, this.idDest, "", _Inicial);

  parametros = { "sidname":sidname[1], "funcion":"Consulta", "sql":_select, "id":this.idDest, "ruta": "", "inicial": _Inicial };

	if(this.enabled)
		{
//			jsrsExecute(dirLibsPHP+"listar_db.php?"+sid, _ret_consulta_CB, "Consulta", parametros, false);
			jsrsE = new Ajax.Request(dirLibsPHP+"listar_db.php",
			{
				method: 'post',
				encoding: axHTMLCharSet,
				onSuccess: _ret_consulta_CB,
				parameters: parametros
			}
			);
		}
	}

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 22. - Retorno del SR de Consulta (Privada)
 * \ingroup fPrivada
 * \param _str - (STRING)
 *
 * \sa _consulta_CB
 * \author EG - (egonpin@gmail.com) - 15/05/2007
 */
function _ret_consulta_CB()
{
	var transport = arguments[0];
// alert(transport.status + " - " + transport.statusText + " - " + transport.readyState +  "\n\n" + transport.getAllHeaders() + "\n\n" + transport.getAllResponseHeaders() );
//alert(transport.responseText);
	xo = transport.responseXML;

	var _str     = arguments[0];
	var _error 	 = " ";
	var _cols 	 = "0";
	var _filas 	 = "0";
	var _id 		 = "";
	var _obj 		 = null;
	var _campos  = "";
	var _inicial = false;
	var _data    = null;
	var _result  = null;
	var _columnas = null;

	if(xo.getElementsByTagName('error')[0].childNodes.length !=0)
	{
		var _error = _extractXML(xo.getElementsByTagName('error')[0].childNodes[0]);
	}
	else { var _error = ""; }

	if(xo.getElementsByTagName('ncolumnas')[0].childNodes.length !=0)
	{
		var _columnas = _extractXML(xo.getElementsByTagName('ncolumnas')[0].childNodes[0]);
	}
	else { var _columnas = "0"; }
	if(xo.getElementsByTagName('ncols')[0].childNodes.length !=0)
	{
		var _cols = _extractXML(xo.getElementsByTagName('ncols')[0].childNodes[0]);
	}
	else { var _cols = "0"; }
	if(xo.getElementsByTagName('id')[0].childNodes.length !=0)
	{
		var _id = _extractXML(xo.getElementsByTagName('id')[0].childNodes[0]);
	}
	else { var _id = ""; }
	if(xo.getElementsByTagName('nfilas')[0].childNodes.length !=0)
	{
		var _nFilas = _extractXML(xo.getElementsByTagName('nfilas')[0].childNodes[0]);
	}
	else { var _nFilas = "0"; }
	if(xo.getElementsByTagName('inicial')[0].childNodes.length !=0)
	{
		var _inicial = _extractXML(xo.getElementsByTagName('inicial')[0].childNodes[0]);
	}
	else { var _inicial = ""; }
	if(xo.getElementsByTagName('reg').length !=0)
	{
		var _result = xo.getElementsByTagName('reg');
	}
	else { var _result = ""; }
/*
alert(
		"error: " + _error +
		"\ncols: " + _columnas +
		"\ncols: " + _cols +
		"\nid: " + _id +
		"\nfilas: " + _nFilas +
		"\ninicial: " + _inicial +
		"\n_result: " + _result
);
*/
	Anuncio("Generando");
	_obj = _localiza_CB(_id);
	if(_obj == null)
	{
    msg_error("Error en el Formulario objeto ComboBox");
  }
  else
  {
    	_data = new Array();
//    	if(_result != "") _data = StringtoArray(_result,separador_reg);
		// recorriendo registros
//alert("tam result "+   _result.length);
/*
		for(var n=0; n<_result.length; n++ )
		{
			_data[n] = _result[n].getElementsByTagName('col').length==0?"":_result[n].getElementsByTagName('col');
			// recorriendo columnas
			var tcol = new Array();
			for(var m=0; m<_data[n].length; m++)
			{
				tcol[m] = _extractXML(_data[n][m].childNodes[0]);
			}
			_data[n] = tcol;
		}
*/

    	if(_obj.camposMostrar != 0)
    	{ _columnas = _obj.camposMostrar; }
    	else
    	{ _columnas = _campos.length; }
//    	for(var n=0; n<_data.length; n++)
//    	{ _data[n] = StringtoArray(_data[n],separador_col); }

    	if(_error != "")
      {
        Anuncio("");
        msg_error(_error);
      }
    	else
      {
			if(_result.length > 0) _obj.aBox = new Array();

          if((_obj.isNull == true) && (_obj.isNullVis == true))
          {
             _obj.addOpc(_obj.nombreNull,_obj.valueNull,"Valor Nulo",true);
			 }

			for(var n=0; n<_result.length; n++ )
			{
				_data[n] = _result[n].getElementsByTagName('col').length==0?"":_result[n].getElementsByTagName('col');
				// recorriendo columnas
				var tcol = new Array();
				for(var m=0; m<_data[n].length; m++)
	        	{
					tcol[m] = _extractXML(_data[n][m].childNodes[0]);
				}
				_data[n] = tcol;
             _obj.addOpc(_data[n][0],_data[n][_cols-1],_data[n][1],true);
          }
			_obj.creaOPC();
      }
  }

 if(_inicial == true)
 {
  _obj.onBlur();
 }

 Anuncio("");
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 23. - Filtra la lista por otro cObjeto HTML (Privado)
 * \param _avisar [ BOOLEAN ] True muestra un aviso de que falta un parametro por defecto es True
 * \sa
 * \author EG - (egonpin@gmail.com) - 15/05/2007
 */
function _fSQL_CB_db()
{
	// fSQL( "(,id_via,=,formatNumero);(AND,id_via,>=,);(,id_via,id_via,)" );
  var _avisar = arguments[0]?arguments[0]:true;

	var cTxt = this.sFiltro;
	var aTxt = StringtoArray(cTxt, ';');
	var aArr = new Array(aTxt.length);
	var tam = new Number(0);
	var operadores = new Array();
	var conectores = new Array();
	var cad = null;
	var aT = null;
	var conector = "";
	var objeto = "";
	var oT = false;
	var oT2 = false;
	var operador = "";
	var _oT2VAL = null;
	var n = 0;
	var m = 0;

	for(n=0; n<aTxt.length; n++)
	{
		tam = aTxt[n].length;
		if((aTxt[n].substr(0,1) == '(') && (aTxt[n].substr(tam-1,1) == ')') )
			aTxt[n] = aTxt[n].substr(1,tam-2);
		aArr[n] = StringtoArray(aTxt[n], ',');
	}

	// contar los argumentos, cada argumento sera un array de 4
	/*
	conector booleanos - sale de un array
	id del campo
	operandos booleanos - sale de un array - si no esta en la lista busquelo como id de campo
	funcion JS para maquillar el valor antes de enviarlo
	*/

	conectores[0] = "OR";
	conectores[1] = "AND";

	operadores[0] = ">";
	operadores[1] = "<";
	operadores[2] = ">=";
	operadores[3] = "=";
	operadores[4] = "<=";
	operadores[5] = "LIKE";
	operadores[6] = "IN";

	//  verificando que todos los parametros sean array de tamano 4
	for(n=0; n<aArr.length; n++)
	{
		if((typeof(aArr[n]) != "object") || (aArr[n].length != 4))
		{
			if( trim(cTxt) != "" )
			{
				msg_error("CBJS\nTodos los parametros deben ser ARRAY de tamano 4");
			}
			return(false);
		}
	}

	cad = "";
	for(n=0; n<aArr.length; n++)
	{
		aT = aArr[n];
		conector = "";
		objeto = "";
		oT = false;
		oT2 = false;
		operador = "";
		for(m=0; m<conectores.length; m++) { if(conectores[m] == aT[0]) {conector = conectores[m];} }
		// se puede implementar para que verifique si es una variable de JS
		oT = oBusca(aT[1]);
		if(!oT)
		{
			valor = "";
// 			msg_error("CBJS \n No se encontro el campo " + aT[1]);
// 			return(false);
		}
		else
		{
			valor = oT.value;
		}
		for(m=0; m<operadores.length; m++) { if(operadores[m] == aT[2]) {operador = operadores[m];} }
		if(n == 0) {conector = "";} else {conector = " " + conector;}
		// no se encontro el operador puede ser un Between

		if(operador == "")
		{
			oT2 = oBusca(aT[2]);

			if(oT2)
			{
				_oT2VAL = eval( "" + aT[3] + "(" + oT2.value + ")" );
				operador = " BETWEEN '" + valor + "' AND '" + _oT2VAL + "'";
				cad += conector + " " + aT[1] + operador;
			}
			else
			{ return(false); }
		}
		else
		{
			if(operador == "IN")
			{
				_oT2VAL = eval( "" + aT[3] + "(" + valor + ")" );
				cad += conector + " " + aT[1] + " " + operador + " " + "("+ _oT2VAL + ")";
			}
			else
			{
				if (oT.value != "")
				{
						_oT2VAL = eval( "" + aT[3] + "(" + valor + ")" );
						cad += conector + " " + aT[1] + " " + operador + " " + "'"+ _oT2VAL + "'";
	         }
				else
				{
						cad += conector + " " + aT[1] + " " + operador + " " + "' 0 '";
						if(_avisar) msg_error("CBJS\n El campo Requerido esta Vacio");
				}
			}
		}
	}
	if(this.SQL.trim() == "")
		this.SQL = cad;
	else
	{
		if(this.oriSQL != "")
			this.SQL = this.oriSQL + " AND " + cad;
		else
			this.SQL = cad;
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 24. - Cambia el valor de un Control (Privado)
 * \param _valor ( STRING )
 * \sa
 * \author EG - (egonpin@gmail.com) - 15/05/2007
 */
function _cambiarVal_CCB()
{
 var _valor = trim(arguments[0]);

	this.consulta(false);
	this.value = _valor;
	this.oInput.value    = _valor;
	this.oInputMaq.value = _valor;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 25. - Elimina todas las opciones del ComboBox (Privado)
 *
 * \sa
 * \author EG - (egonpin@gmail.com) - 22/05/2007
 */
function _limpia_CCB()
{
 this.aBox = new Array();
 this.creaOPC();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 26. - Busca un valor en el combobox y refresca el Maquillado
 *
 * \sa
 * \author EG - (egonpin@gmail.com) - 13/07/2007
 */
function _buscaValor_CCB()
{
 var _valor = trim(arguments[0]);

 //valida si es booleano y ajusta su valor entre 1 o 0 si es el caso
 //ajuste F0 19/05/2009 10:14 am
 switch(_valor){
	case "f":
	case "false":
	case "falso":
		_valor = 0;
	break;
	case "v":
	case "t":
	case "true":
	case "verdadero":
		_valor = 1;
	break;
 }

 var n = 0;
 for(n=0; n<this.aBox.length; n++)
 {
   if(this.aBox[n][1] == _valor)
   {
		this.oInputMaq.value = this.aBox[n][0];
		this.value = _valor;
	  	this.oInput.value = this.aBox[n][1];
   }
 }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 27. - Funcion que se lanza al seleccionar una opcion del ComboBox
 *
 * \sa
 * \author EG - (egonpin@gmail.com) - 30/09/2008
**/
function _onChange_CCB()
{
	if(trim(this.funOnChange) != "")
	{
		if( typeof(eval(this.funOnChange)) == "function" )
		{
     		var _tmpR = trim(this.funOnChange) + "('" + this.id + "')";
			eval(_tmpR);
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 28. - Funcion que se lanza para Limpiar el valor del ComboBox
 *
 * \sa
 * \author EG - 09/12/2008
**/
function _vaciar_CCB()
{
	Anuncio("Limpiando...");
//alert(this.oInput + "\n" + this.id);
  	this.oInput.value    = "";
  	this.oInputMaq.value = "";
 	this.value = "";
	this.onBlur();
	Anuncio("");
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 29. - Busca 1er valor en el combobox y refresca el Maquillado
 *
 * \sa
 * \author EG - 12/12/2008
 */
function _busca1erValor_CCB()
{
	this.value = this.aBox[0][1];
  	this.oInput.value = this.aBox[0][1];
	this.oInputMaq.value = this.aBox[0][0];
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  version 0.1
//  27-Julio-2005 - Inicio
//  28-Julio-2005 - Finalizada 1 Etapa, faltan pruebas
//  version 0.25
//  29-Mayo-2006
//  08-Mayo-2007 - Adicion a AXYS
