// Variables globales JS
if ( !isset(mensaje_en_pantalla) ) { var   mensaje_en_pantalla = false; }
if ( !isset(message_pos) )         { var   message_pos         = null; }
if (navigator.appName.indexOf('Microsoft') != -1){
    var es_ie  = true;
    var es_ie7 = window.XMLHttpRequest ? true : false;
} else{
	var es_ie = false;
	var es_ie7 = false;
}

var es_safari = navigator.appVersion.indexOf('Safari') != -1 ? true : false;

function getFormValues (id_form)
{
    var form   = document.getElementById (id_form);

    var values = new Array ();

    for (i = 0; i < form.elements.length; i++) {
          values [form.elements [i].id] = form.elements [i].value;
    }

    return values;
}

function insertAfter(newChild, refChild) {
    if (refChild.nextSibling) insertBefore(newChild, refChild.nextSibling);
    else refChild.parentNode.appendChild(newChild);
    return newChild;
}

function insertBefore(newChild, refChild) {
    return refChild.parentNode.insertBefore(newChild, refChild);
}

function isEmpty(aTextField) {
    if ((aTextField.length==0) ||
    (aTextField==null)) {
        return true;
    }
    else { return false; }
}

function isNumerico(strString) {
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return true;

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}


function showElemento(nombre_elemento) {
    var o = new getObj(nombre_elemento);

    exito = false;
    if (o != null && o.style != null) {
        o.style.display = '';
        exito = true;
    }
    return exito;
}

function hideElemento(nombre_elemento) {
    var o = new getObj(nombre_elemento);

    exito = false;
    if (o != null && o.style != null) {
        o.style.display = 'none';
        exito = true;
    }
    return exito;
}

function enterToTab(e, obj) {
  tecla = (document.all) ? e.keyCode :e.which;
  if(tecla != 13) return;
  frm=obj.form;
  for(i=0;i<frm.elements.length;i++) {
    if(frm.elements[i]==obj) { 
        if (i==frm.elements.length-1)  {
            i=-1;
        }
        break; 
    }
  }
  frm.elements[i+1].focus();
  return false; 
}

function showEdicionSpan (id_span, func)
{
    document.getElementById (id_span).onclick = null;
    label           = document.getElementById (id_span).childNodes [0];
    oldlabel        = label;
    valor_anterior  = label.innerHTML;
    label.htmlFor   = null;
    label.innerHTML = '<input type="text" value="'+valor_anterior+'" id="input'+id_span+'"/>'+
    '<input type="button" value=":)" onclick="'+func+'(\''+id_span+'\', document.getElementById (\'input'+id_span+'\').value, oldlabel);" />';
}

/**
* showHideElemento
*
* Descripcion:
*
* Autor: mpacheco
* Fecha: Wed 17 May 2006 02:05:44 PM CDT
*
* @param nombre_elemento $nombre_elemento
* @access public
* @return void
*/
function showHideElemento (nombre_elemento) {
    var o = new getObj(nombre_elemento);

    exito = false;
    if (o != null && o.style != null) {
        if (o.style.display == 'none') {
            return showElemento(nombre_elemento);
        } else {
            return hideElemento(nombre_elemento);
        }
    }
    return exito;
}

// Inicio de función para cambiar colores de filas

// Estas funciones sirven para hacer que las filas de una tabla cambien de color
// segun los eventos qe se activen por medio del mouse.

// filaActual es el objeto tr de la tabla
// tipoFila es 'par' o 'non'

// Es necesario definir seis clases distintas en el css, dos por cada estado.
// renglon-non y renglon-par, que definen el color de las filas por default.
// renglon-non-hover y renglon-par-hover, definen el color de las filas cuando ocurre un mouseover.
// renglon-non-click y renglon-par-click, definen el color de las filas cuando ocurre un onclick.

function cambiaColorFila(filaActual, tipoFila){

    if( (filaActual.clicked==undefined && filaActual.className.indexOf('-click') < 1)
    || filaActual.clicked==false ){
        if(filaActual.className.indexOf('hover')!=-1){
            filaActual.className = 'renglon-'+tipoFila;
        }
        else{
            filaActual.className = 'renglon-'+tipoFila+'-hover';
        }
    }
}

function activaClick(filaActual, tipoFila){
    if(filaActual.clicked==undefined || filaActual.clicked==false) {
        filaActual.clicked           = true;
        filaActual.className         = 'renglon-' + tipoFila + '-click';
    }
    else{
        filaActual.clicked           = false;
        filaActual.className='renglon-'+tipoFila;
    }
}

// Fin de función para cambiar colores de filas

// Inicio de funciones para activar las pestañas cuando se les da click

function highlightPestana(elementoActual, claseElemento){
    elementoActual.className = claseElemento;
}

function activatePestana(elementoActual, claseElementoAct, claseElementoInact){
    if(elementoActual.clicked==undefined || elementoActual.clicked==false){
        var elementos = elementoActual.parentNode.getElementsByTagName('LI');
        for(i=0; i<elementos.length; i++){
            elementos[i].clicked = false;
            elementos[i].className = claseElementoAct;
        }
        elementoActual.clicked = true;
        elementoActual.className = claseElementoInact;
    }
}

// Fin de funciones para activar las pestañas cuando se les da click

function showDinero (cantidad)
{
    pd = cantidad < 0 ? ")" : "";
    pi = cantidad < 0 ? "(" : "";

    cantidad = Math.abs (cantidad);

    if (isNaN (cantidad)) {
        cantidad = "-";
    } else {
        cantidad += '';
        x = cantidad.split('.');
        x1 = x[0];
        if (isset (x[1])) {
            if (x[1].length > 1) {
                x2 = "." + x [1].substr (0, 2);
            } else if (x[1].length < 1) {
            } else {
                x2 = "." + x[1] + "0";
            }
        } else {
            x2 = ".00";
        }
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        cantidad = x1 + x2;
    }

    return "$&nbsp;" + cantidad;
}

/**
* Función para abrir popups
*/
function showPopup(url, nombre_popup, parametros){
    if(parametros == undefined){
        if(typeof( window[ 'ancho_popup_default' ] ) == 'undefined'){
            window[ 'ancho_popup_default' ] = 300;
        }
        if(typeof( window[ 'alto_popup_default']) == 'undefined'){
            window[ 'alto_popup_default'] = 200;
        }
        parametros = 'width='+window[ 'ancho_popup_default' ]+',height='+window[ 'alto_popup_default']+',scrollbars=yes';
    }
    if(nombre_popup == undefined){
        nombre_popup = 'popUpSistema';
    }

    var ventana = window.open(url, nombre_popup, parametros);
    if ( isset(ventana) ) {
        ventana.moveTo(0,0);
        ventana.focus();
    } else {
        msgbox("Favor de activar los popups en su navegador para\npoder utilizar el sistema correctamente.");
    }
    return ventana;
}

	//Id del elemento actual e id_forma para hacer focus al elemento siguiente
	function focusNextElement (id_form, id_element)
	{
		if (id_form == false) {
			var form = document.getElementById (id_element).form;
		} else {
			var form = document.getElementById (id_form);
		}
		
		try { 
	    	
	    	for (i = 0; i < form.elements.length; i++) {
	    		  if (typeof (form.elements [i].id) !== "undefined" &&
	 		 	  	  form.elements [i].id 			 == id_element) {
	 		 	  	  i++;
	 		 	  	  while (form.elements [i].type == 'hidden') {
	 		 	  	  	 i++;
	 		 	  	  }
	 		 	  	  form.elements [i].focus ();
	 		 	  	  break;
			      } else {
			      
			      }
		    }
		} catch (e) {
			window.status = 'Focus! :)';
	    }
	}
	
// Fin de función para esconder mensajes del sistema

//Función para darle el tamaño necesario al iframe
function ajustaIframe() {
    if(!(self==parent)) {
        if(typeof( window[ 'incremento_iframe_default' ] ) == 'undefined'){
            window[ 'incremento_iframe_default' ] = 0;
        }

        var bodyHeight = document.body.scrollHeight + window[ 'incremento_iframe_default' ];
        /* bodyID is the ID of the framed page's BODY tag
        pixels prevent an unnecessary scrollbar. */

        var parentIframe = document.defaultView
                ? document.defaultView.frameElement
                : document.parentWindow.frameElement;

        parentIframe.height = bodyHeight;
        /* iframeId is the ID of the inline frame in the parent page. */
    }
}

var s_nombre_forma = null;
var s_nombre_campo = null;
function activateFocus(nombre_forma, nombre_campo, select){
    try {
        if (   nombre_forma != ""
        && nombre_campo != ""
        && nombre_forma != null
        && nombre_campo != null) {

            s_nombre_forma = nombre_forma;
            s_nombre_campo = nombre_campo;
            s_select       = select;
            eval("var forma = document."+nombre_forma+";");

            //     eval("var elemento = document."+nombre_forma+"."+nombre_campo);
            if(forma != undefined){

                if (nombre_campo) {
                    eval("var campo = forma."+nombre_campo+";");
                    if(campo != undefined){
                        if(campo.type != "hidden" && !campo.disabled && campo.focus) {
                            campo.focus();
                            if (select) {
                                campo.select();
                            }
                        } else {
                            nombre_campo = false;
                        }
                    } else {
                        nombre_campo = false;
                    }
                }
            } else {
                //             alert('No se encuentra la forma a darle focus');
            }

        } else if (s_nombre_forma != null && s_nombre_campo != null) {
            // En caso de no recibir parámetros, entonces lo llamamos con lo último llamado
            activateFocus(s_nombre_forma, s_nombre_campo, s_select);
        }
    } catch (e) {
        error = e
    }
}

function highlightField (field,color,texto_estatus) {
    if(field.select){
        field.select();
    }
    window.status = texto_estatus;
    return true;
}

function hideTableColumn(tableName, colNumber) {
    tableObject = document.getElementById(tableName);
    rows = tableObject.getElementsByTagName('tr');

    for (i = 0; i < rows.length; i++) {
        if (isset(rows[i].cells[colNumber]))  {
            rows[i].cells[colNumber].style.display = "none";
        }
    }
}

function showTableColumn(tableName, colNumber) {
    tableObject = document.getElementById(tableName);
    rows = tableObject.getElementsByTagName('tr');

    for (i = 0; i < rows.length; i++) {
        if (isset(rows[i].cells[colNumber]))  {
            rows[i].cells[colNumber].style.display = "";
        }
    }
}

function showHideTableColumn(tableName, colNumber) {
    tableObject = document.getElementById(tableName);
    rows = tableObject.getElementsByTagName('tr');

    for (i = 0; i < rows.length; i++) {
        if (isset(rows[i].cells[colNumber]))  {
            if (rows[i].cells[colNumber].style.display == "none") {
                rows[i].cells[colNumber].style.display = "";
            } else {
                rows[i].cells[colNumber].style.display = "none";
            }
        }
    }
}

function showHideTableRow (tableName, rowNumber) {
    tableObject = document.getElementById(tableName);
    rows = tableObject.getElementsByTagName('tr');
    if (isset(rows[rowNumber])) {
        rowLength = rows[rowNumber].cells.length;
        for (var i=0; i < rowLength; i++) {
            if (rows[rowNumber].cells[i].style.display == "none") {
                rows[rowNumber].cells[i].style.display = "";
            } else {
                rows[rowNumber].cells[i].style.display = "none";
            }
        }
    }
}

function hideTableRow(tableName, rowNumber, startPos, endPos) {
    tableObject = document.getElementById(tableName);
    startPos = (startPos) ? startPos : 0;
    rows = tableObject.getElementsByTagName('tr');

    if (isset(rows[rowNumber])) {
        rowLength = rows[rowNumber].cells.length;
        endPos = (endPos) ? (endPos + 1) : rowLength;
        for (var i=startPos; i < endPos; i++) {
            rows[rowNumber].cells[i].style.display = "none";
        }
    }
}

function showTableRow(tableName, rowNumber, startPos, endPos) {
    tableObject = document.getElementById(tableName);
    startPos = (startPos) ? startPos : 0;
    rows = tableObject.getElementsByTagName('tr');

    if (isset(rows[rowNumber])) {
        rowLength = rows[rowNumber].cells.length;
        endPos = (endPos) ? (endPos + 1) : rowLength;
        for (var i=startPos; i < endPos; i++) {
            rows[rowNumber].cells[i].style.display = "";
        }
    }
}

function updateAtributoElementosPorTagEnColision(tag_elementos, x1, y1, x2, y2, atributo) {

    for (var i = 0; i < tag_elementos.length; i++) {
        elementos = document.getElementsByTagName(tag_elementos[i]);
        for (var j = 0; j < elementos.length; j++) {
            e = elementos[j];
            p = getAbsolutePos(e);
            p.x2 = p.x + e.offsetWidth;
            p.y2 = p.y + e.offsetHeigth;

            if ( ( (p.x >= x1 && p.x <= x2) || (p.x2 >= x1 && p.x2 <= x2) )
            &&  ( (p.y >= y1 && p.y <= y2) || (p.y2 >= y1 && p.y2 <= y2) ) ) {
                //                window.status = window.status + ".";
                eval("e."+atributo);
            }
        }
    }
}
// Funciones para el manejo de las opciones del men
var nombre = false;
var opcion = false;
function showOpciones(identificador, fuente){
    if (es_ie){
        if(fuente==1) {nombre=true;}
        else{opcion=true;}
        if((nombre && !opcion) || (!nombre && opcion)) {
            var bloque_menu = document.getElementById(identificador);
            bloque_menu.style.display='block';

            p = getAbsolutePos(bloque_menu);
            y_arriba = p.y;
            y_abajo  = p.y+bloque_menu.offsetHeight;
            updateAtributoElementosPorTagEnColision(new Array("applet", "iframe", "select")
            , 0
            , y_arriba
            , 1000
            , y_abajo + 10
            , 'style.visibility = "hidden";');
        }
    }
}
function hideOpciones(identificador, fuente){
    if (es_ie){
        if(fuente==1) {nombre=false;}
        else{opcion=false;}
        if(!opcion) {
            var bloque_menu = document.getElementById(identificador);

            p = getAbsolutePos(bloque_menu);
            y_arriba = p.y;
            y_abajo  = p.y+bloque_menu.offsetHeight;
            updateAtributoElementosPorTagEnColision(new Array("applet", "iframe", "select")
            , 0
            , y_arriba
            , 1000
            , y_abajo + 10
            , 'style.visibility = "visible";');
            bloque_menu.style.display = 'none';
        }
    }
}


function isset( expr ) {
    return  typeof(expr) != 'undefined';
}

/**
* Función para que regrese un objeto independientemente de la versión
* del navegador. Esto si es soportado.  Ejemplo de uso:
* var  objeto = new getObj('id');
*/
function getObj( name, win ) {
    if ( !isset(win) ) {
        win = self;
    }
    this.obj   = null;
    this.style = null;
    if ( win ) {
        if ( win.document.getElementById ) {
            if ( this.obj = win.document.getElementById(name) )
            this.style = this.obj.style;
        } else if ( win.document.all ) {
            if ( this.obj = win.document.all[name] )
            this.style = this.obj.style;
        } else if ( win.document.layers ) {
            if ( this.obj = win.document.layers[name] )
            this.style = this.obj;
        }
    }
    // return this;
}

// Fin de funciones para el manejo de las opciones del men

// Función para el manejo de bloques con pestañas internas
//   Requiere el arreglo bloques que contiene los nombres descriptivos de los
//   bloques que se van a mostrar y ocultar con las pestañas internas
//   Ej. var bloques = new Array('bloqueDatos','bloqueFoto');
function showBloque(bloqueMostrar){
    for (i=0; i<bloques.length; i++){
        bloqueActual = new getObj(bloques[i]);

        if(bloqueActual != null){
            bloqueActual.style.display = 'none';
        }
    }

    var bloqueOculto = new getObj(bloqueMostrar);
    if(bloqueOculto != null){
        bloqueOculto.style.display = 'block';

        objetos_bloque = isset(bloqueOculto.obj.childNodes) ? bloqueOculto.obj.childNodes : bloqueOculto.obj.children;
        if(typeof( window[ 'incremento_iframe_default' ] ) == 'undefined'){
            window[ 'incremento_iframe_default' ] = 0;
        }

        for(var i=0; i<objetos_bloque.length; i++){
            if (objetos_bloque[i].tagName == "IFRAME") {
                try {
                    window.status = "";
                    objetos_bloque[i].height = objetos_bloque[i].contentWindow.document.body.scrollHeight + window[ 'incremento_iframe_default' ];
                    objetos_bloque[i].height = objetos_bloque[i].contentWindow.document.body.scrollHeight + window[ 'incremento_iframe_default' ];
                } catch (e) {
                    window.status = "Cargando; favor de esperar";
                }
            }
        }
        //alert(document.frames.iframeDocumentos.document.body.scrollHeight);
    }
}

function showBloqueConPrefijo(bloqueMostrar, prefijo){
    arreglo_bloques = document.getElementsByTagName ("div");
    bloques = new Array ();
    j = 0;
    for (i = 0; i < arreglo_bloques.length; i++) {
        if (arreglo_bloques [i].id.search(prefijo) == 0) {
            bloques [j++] = arreglo_bloques [i].id;
        }
    }

    for (i=0; i<bloques.length; i++){
        bloqueActual = new getObj(bloques[i]);
        //        var bloqueActual = document.getElementById(bloques[i]);

        if(bloqueActual != null){
            bloqueActual.style.display = 'none';
        }
    }

    var bloqueOculto = new getObj(bloqueMostrar);
    if(bloqueOculto != null){
        bloqueOculto.style.display = 'block';

        objetos_bloque = isset(bloqueOculto.obj.childNodes) ? bloqueOculto.obj.childNodes : bloqueOculto.obj.children;
        if(typeof( window[ 'incremento_iframe_default' ] ) == 'undefined'){
            window[ 'incremento_iframe_default' ] = 0;
        }
        for(var i=0; i<objetos_bloque.length; i++){
            if (objetos_bloque[i].tagName == "IFRAME") {
                try {
                    window.status = "";
                    objetos_bloque[i].height = objetos_bloque[i].contentWindow.document.body.scrollHeight + window[ 'incremento_iframe_default' ];
                    objetos_bloque[i].height = objetos_bloque[i].contentWindow.document.body.scrollHeight + window[ 'incremento_iframe_default' ];
                } catch (e) {
                    window.status = "Cargando; favor de esperar";
                }
            }
        }
    }
}

// Fin de función para el manejo de bloques con pestañas internas

//Temporary function
function showFolderEditar (id, params) {
    document.getElementById ("edit_iframe").src = document.getElementById ("edit_iframe").src + params;
    lis = document.getElementById ('fc_'+id).getElementsByTagName ("li");
    lis [2].style.display = "";
    activatePestana(lis [2], "pestana", "pestanaActual");
    showBloqueConPrefijo("content_"+id+"_2", "content_"+id+"_");
    if(typeof( window[ 'incremento_iframe_default' ] ) == 'undefined'){
        window[ 'incremento_iframe_default' ] = 0;
    }
    var bodyHeight = document.getElementById("edit_iframe").scrollHeight + window[ 'incremento_iframe_default' ];
    document.getElementById("edit_iframe").height = bodyHeight;

}


/**
* Sets a Cookie with the given name and value.
*
* name       Name of the cookie
* value      Value of the cookie
* [expires]  Expiration date of the cookie (default: end of current session)
* [path]     Path where the cookie is valid (default: path of calling document)
* [domain]   Domain where the cookie is valid
*              (default: domain of calling document)
* [secure]   Boolean value indicating if the cookie transmission requires a
*              secure transmission
*/
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

/**
* Gets the value of the specified cookie.
*
* name  Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
*   or null if cookie does not exist.
*/
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
* Deletes the specified cookie.
*
* name      name of the cookie
* [path]    path of the cookie (must be same as path used to create cookie)
* [domain]  domain of the cookie (must be same as domain used to create cookie)
*/
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// Muestra los elementos (TODOS) del objeto enviado
var conf = true;

function showVars(o, per_page) {
    if ( !isset(o) ) {
        alert( 'undefined' );
        return ;
    }
    var texto = 'typeof: ' + typeof(o) + ' / nodeType '+ o.nodeType
    +' / tagName: '+ o.tagName +' / type '+ o.type +'\n',
    cnt   = 1;
    if ( isNaN(per_page) || per_page < 1 ) {
        per_page = 25;
    }
    for ( p in o ) {
        //        texto += p +'\n';
        //        texto += p +': '+ typeof(o[p]) +'\n';
        texto += "\n"+ p
        + ( 0 == p.indexOf('selection') || 'unknown' == typeof(o[p])
        ? ' (die if showed)'
        : ': '+ ( 'function' == typeof(o[p]) ? typeof(o[p]) : o[p] ) );
        if ( ++ cnt >= per_page ) {
            cnt   = 0;
            conf  = confirm(texto);
            texto = '';
            if ( !conf ) {
                break;
            }
        }
    }
    if ( conf && texto ) {
        alert(texto);
    }
}

function confirmAccionUrl (msg, url) {
    if (confirm (msg)) {
        gotoURL (url);
    }
}

function getNodeListSelectedValue( node_list, return_array ) {
    var  valor = null;
    if ( !isset(node_list) || !node_list.length ) {
        return  valor;
    }
    if ( return_array ) {
        valor = new Array();
    }
    for ( var  i = 0;  i < node_list.length;  i ++ ) {
        if ( node_list.item(i).checked ) {
            if ( return_array ) {
                //valor[valor.length] = node_list.item(i).value;
                valor[node_list.item(i).value] = node_list.item(i).value;
            } else {
                valor = node_list.item(i).value;
                break;
            }
        }
    }
    return  valor;
}

// Obtiene la posición absoluta dentro de la pantalla
// del elemento pasado como parámetro
function getAbsolutePos( el, win ) {
    var SL = 0, ST = 0;
    //	var is_div = /^div$/i.test(el.tagName);
    var is_div = ( 'DIV' == el.tagName );
    if (is_div && el.scrollLeft)
    SL = el.scrollLeft;
    if (is_div && el.scrollTop)
    ST = el.scrollTop;
    var r = { x: el.offsetLeft - SL,  y: el.offsetTop - ST,
    h: el.offsetHeight,     w: el.offsetWidth };
    if (el.offsetParent) {
        var tmp = this.getAbsolutePos(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y;
    }
    return r;
}


function getArrayIndex( array, valor ) {
    if ( !array.length ) {
        return  false;
    }
    for ( var  i = 0;  i < array.length;  i ++ ) {
        if ( array[i] == valor ) {
            return  ++ i;
        }
    }
    return  0;
}

function setNodeListSelectedValue( node_list, value ) {
    var  valores = null;
    if ( !isset(node_list) || !node_list.length ) {
        return  false;
    }
    if ( 'object' != typeof(value) ) {
        valores = new Array(value);
    } else {
        valores = value;
    }
    for ( var  n = 0, i = 0;  i < node_list.length;  i ++ ) {
        if ( getArrayIndex(valores, node_list.item(i).value) ) {
            node_list.item(i).checked = true;
            n ++;
        }
    }
    return  n;
}


function manageTeclado( e ) {
    if ( !e ) {
        e = window.event;
    }

    // Información del evento
    var  tecla  = ( e.keyCode   ? e.keyCode   : e.which ),
    objeto = ( e.target    ? e.target    : e.srcElement ),
    modifs = ( e.modifiers ? e.modifiers
    : ( e.shiftKey ? 4 : 0 ) | ( e.ctrlKey ? 2 : 0 ) | ( e.altKey ? 1 : 0 ) );
    // Safari bug
    if ( objeto && 3 == objeto.nodeType ) {
        objeto = objeto.parentNode;
    }

    if ( 27 == tecla ) {
        if ( mensaje_en_pantalla && isset(escondeMensaje) ) {
            escondeMensaje('mensaje');
        }
    }

    // En casoque exista la función catchTeclado en la página
    // quiere decir que se está solicitando un tratamiento especial (con dicha función)
    // a alguna tecla.
    if ( window.catchTeclado ) {
        catchTeclado(tecla, objeto, modifs);
    }
}

// Handler OnKeyDown
var   old_onkeydown_handler = false;
function __catch_onkeydown_event( e ) {
    manageTeclado(e);
    if ( old_onkeydown_handler ) {
        old_onkeydown_handler(e);
    }
}
if ( !document.onkeydown || document.onkeydown.toString() != __catch_onkeydown_event.toString() ) {
    old_onkeydown_handler = document.onkeydown;
    document.onkeydown    = __catch_onkeydown_event;
}

var  debug_updateFormOnWindowBlur = false;
function updateFormOnWindowBlur( frmObj, win ) {

    if ( !isset(win) ) {
        win = self;
    }
    if ( !win || !win.document ) {
        return  false;
    }

    if ( 'string' == typeof(frmObj) ) {
        if ( win.document.forms && isset(win.document.forms[frmObj]) ) {
            frmObj = win.document.forms[frmObj];
        } else {
            frmObj = null;
        }
    }

    var  ufowb_old_onblur_func = win.onblur;
    win.onblur                 = function( e ) {
        if ( !e )  e = win.event;
        var  htmlObj = e.target;

        if ( frmObj && frmObj.submit ) {
            if ( ( frmObj.data_changed || !isset(frmObj.data_changed) && win.data_changed )
            && '[object HTMLDocument]' == htmlObj.toString() ) {

                if ( debug_updateFormOnWindowBlur )
                top.status = '- Actualización automática efectuada';
                frmObj.submit();

            } else if ( debug_updateFormOnWindowBlur ) {
                top.status = '- No se actualizó porque no han cambiado los datos';
            }
        } else {
            alert('No existe el objeto indicado o el método ::submit()');
            if ( debug_updateFormOnWindowBlur )
            top.status = '* ERROR: No se encontró el objeto FORM a actualizar';
        }

        if ( ufowb_old_onblur_func ) {
            if ( debug_updateFormOnWindowBlur )
            top.status += ' / se invoca manejador anterior';
            ufowb_old_onblur_func(e);
        }
    }
    return  true;
}

/**
* gotoURL
*
* Descripcion: gotoURL de javascript ;)
*
* Autor: mpacheco
* Fecha: Tue 23 May 2006 10:37:06 AM CDT
*
* @param url $url
* @param timeout $timeout
* @access public
* @return void
*/
function gotoURL (url, timeout)
{
    if (!isset (timeout)) {
        timeout = 0;
    }
    setTimeout ("location.href='" + url + "'", timeout);
}

function addParametroURL(parametro, url) {
    var separador = url.indexOf('?') > 0
    ? '&'
    : '?';

    url = url+separador+parametro;
    return url;
}

/**
Pendiente; no funciona todavía
function removeParametroURL(parametro, url) {
var r = new RegExp("/([?;&])("+parametro+"=.*?)([&$])/");
url.replace(r, '$1$3');
return url;
}
*/

/**
* Funcion para eliminar de un Hash o arreglo un valor
* @param array El arreglo
* @param mixed Valor o índice
* @param bool true para buscar ambos
* @param bool true para hash arrays
* @return array Arreglo con el elemento eliminado
*/
function unset(array, valueToUnset, valueOrIndex, isHash){
    var output=new Array(0);
    for(var i in array){
        if(!valueOrIndex){//search value
            if(array[i]==valueToUnset){continue};
            if(!isHash){
                output[++output.length-1]=array[i];
            }
            else{
                output[i]=array[i];
            }
        }
        else{//search index (or key)
            if(i==valueToUnset){continue};
            if(!isHash){
                output[++output.length-1]=array[i];
            }
            else{
                output[i]=array[i];
            }
        }
    }
    return output
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    //		num = Math.round(num);
    if(isNaN(num)) {
        num = "0";
    }
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10) {
        cents = "0" + cents;
    }
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
        num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
    }

    return (((sign)?'':'-') + num + '.' + cents);

    //return (((sign)?'':'-') + '$' + num);
}

/**************** mpacheco Resize Columns *********************************/
function cambiarCursor (ev) {
    if (es_ie) {
        var el = event.srcElement;
    } else {
        var el = ev.target;
    }

    var pNode = document.body;

    var oCurrentNode = el;

    var iLeft=0;

    while((oCurrentNode)&&(oCurrentNode!=pNode)){
        iLeft+=oCurrentNode.offsetLeft;
        oCurrentNode=oCurrentNode.offsetParent;
    }

    iLeft+=document.body.offsetLeft;

    //              window.alert ((parseInt (new Array (iLeft, iTop)) -ev.layerX));
    //                window.alert (el.offsetWidth+":"+iLeft+":"+el.offsetLeft+":"+ev.layerX+":"+ev.clientX);

    //                window.alert ((el.offsetWidth + iLeft) - ev.clientX);
    if(el.tagName=="TD"){
        if (es_ie) {
            pos = el.offsetWidth + iLeft - event.screenX;
        } else {
            pos = el.offsetWidth + iLeft - ev.clientX;
        }
        if(pos < 10){
            el.style.cursor = "e-resize";
        } else {
            el.style.cursor = "default";
        }
    }
}

function empezarResize (ev) {
    if (es_ie) {
        var el = event.srcElement;
    } else {
        var el = ev.target;
    }

    var pNode        = document.body;
    var oCurrentNode = el;

    var iLeft=0;

    while((oCurrentNode)&&(oCurrentNode!=pNode)){
        iLeft+=oCurrentNode.offsetLeft;
        oCurrentNode=oCurrentNode.offsetParent;
    }

    iLeft+=document.body.offsetLeft;

    if(el.tagName=="TD" && el.style.cursor!="default"){
        var lw = el.offsetLeft;

        document.documentElement.onmousemove = function (e) {
            if (es_ie) {
                el.width = event.screenX - iLeft;
                event.srcElement.style.cursor = "e-resize";
            } else {
                e.target.style.cursor = "e-resize";
                el.width = e.clientX - iLeft;
            }
        }

        document.documentElement.onmouseup = function(e) {
            if (es_ie) {
                event.srcElement.style.cursor = "default";
            } else {
                e.target.style.cursor = "default";
            }
            document.documentElement.onmouseup = "";
            document.documentElement.onmousemove = "";
        }
    }
}

function resizeColumn (table_id, no_row, no_column) {
    document.getElementById (table_id).rows [no_row].cells [no_column].onmousemove = cambiarCursor;
    document.getElementById (table_id).rows [no_row].cells [no_column].onmousedown = empezarResize;
}

/**********************************************************************
JS - PARA DEPURACIÓN... (no debe estar en la versión final)
**********************************************************************/

function toggle_debug( srcObj ) {
    var  parentObj = srcObj ? srcObj.parentNode : null,
    arr_child = new Array(),
    divObj    = null,
    n         = 0;

    if ( !srcObj || !parentObj || 'LEGEND' != srcObj.tagName || 'FIELDSET' != parentObj.tagName ) {
        alert( !srcObj ? srcObj : srcObj.tagName +'/'+ srcObj.type +' -> '
        + ( !parentObj ? parentObj : parentObj.tagName +'/'+ parentObj.type ) );
        return  FALSE;
    }

    arr_child = parentObj.childNodes;
    for ( n = 0;  n < arr_child.length;  n ++ ) {
        if ( 'msg' == arr_child[n].className ) {
            divObj = arr_child[n];
            break;
        }
    }
    if ( !divObj ) {
        return  false;
    }

    //divObj.style.cursor  = 'default';
    divObj.style.display = ( divObj.style.display == 'none' ? '' : 'none' );
    return  true;
}


/**
* Función que espera a que XAJAX termine la ejecución de su proceso
* para correr el código pasado como parámetro.
* ATENCIÓN: Hace uso del estilo del cursor (document.body.style.cursor) para funcionar
* Automáticamente detecta comilla / comillas dobles en el contenido del código para
* evitar errores
*/
function xajaxEsperarYCorrer(codigo_correr) {
    if (document.body.style.cursor == 'wait') {
	comilla_comillas = codigo_correr.indexOf("'") > 0 ? '"' : "'";
        setTimeout("xajaxEsperarYCorrer("+comilla_comillas+codigo_correr+comilla_comillas+")", 100);
    } else {
        eval(codigo_correr);
    }
}

/**
* Funciones para agregar funcionalidad al onload de una página
* En el onload se debería ejecutar executeOnloadStack()
*/

// Variable de arreglo para código a ejecutar
var onload_stack = new Array();

/**
* Función que ejecuta directamente todo el código contenido en cada
* elemento del arreglo onload_stack
*/
function executeOnloadStack() {
    for (var i = 0; i< onload_stack.length; i++) {
        eval(onload_stack[i]);
    }
}

/**
* Función que agrega código al arreglo global onload_stack
*/
function pushCodeOnloadStack(code) {
    onload_stack.push(code);
}

/**
* FIN de funciones para agregar funcionalidad al onload de la página
*/

/*** Utilidades para comillas ***/
	function addslashes (str) {
		str=str.replace(/\'/g,'\\\'');
		str=str.replace(/\"/g,'\\"');
		str=str.replace(/\\/g,'\\\\');
		str=str.replace(/\0/g,'\\0');
		return str;
	}
	
	function stripslashes (str) {
		str=str.replace(/\\'/g,'\'');
		str=str.replace(/\\"/g,'"');
		str=str.replace(/\\\\/g,'\\');
		str=str.replace(/\\0/g,'\0');
		return str;
	}
	
	
	//Funciones para formato de dinero
	//------------ BoB Rulz! (Banco del Bajio Style)
		function FormatAmount(amount)
		{
			amount = WithOutFormatAmount(amount);
			Num = amount;
			dec = Num.indexOf(".");
			end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ".00");
			Num = "" + parseInt(Num);
			var temp1 = "";
			var temp2 = "";
			if (checkNum(Num) == 0)
			{
				return '';
			}
			else
			{
				if (end.length == 2) end += "0";
				if (end.length == 1) end += "00";
				if (end == "") end += ".00";
				var count = 0;
				for (var k = Num.length-1; k >= 0; k--)
				{
					var oneChar = Num.charAt(k);
					if (count == 3)
					{
						temp1 += ",";
						temp1 += oneChar;
						count = 1;
						continue;
					}
					else
					{
						temp1 += oneChar;
						count ++;
					}
				}
				for (var k = temp1.length-1; k >= 0; k--)
				{
					var oneChar = temp1.charAt(k);
					temp2 += oneChar;
				}
				return  temp2 + end;
			}
		}
		
		function WithOutFormatAmount(amount)
		{
			out = ",";
			add = "";
			temp = "" + amount;
			while (temp.indexOf(out)>-1)
			{
				pos= temp.indexOf(out);
				temp = "" + (temp.substring(0, pos) + add +
				temp.substring((pos + out.length), temp.length));
			}
			return temp;
		}
		
		function checkNum(data)
		{
			var valid = "0123456789.";
			var ok = 1; var checktemp;
			for (var i=0; i<data.length; i++)
			{
				checktemp = "" + data.substring(i, i+1);
				if (valid.indexOf(checktemp) == "-1")
				return 0;
			}
			return 1;
		}
			
		//Tomado desde: http://www.anieto2k.com/2006/10/16/gestion-de-eventos-en-javascript/
		//Ejemplo de uso: listen ('click', 'enlace', 'send');
		function listen(event, elem, func) {
    		elem = document.getElementById (elem);
    		if (elem.addEventListener)  // W3C DOM
        		elem.addEventListener(event,func,false);
    		else if (elem.attachEvent) { // IE DOM
         		var r = elem.attachEvent("on"+event, func);
				return r;
    		}
    		else throw 'No es posible añadir evento';
		}
		
 function getFormatoDinero(num , precision)
{

	if(typeof(precision) == "undefined"){
		precision = 2;
	}	

     num = num.toString().replace(/\$|\,/g,'');
     var partes = num.split('.');
     if(isNaN(num))
      num = "0";
    var sign = (num == (num = Math.abs(num)));

    num = partes[0];

    if (typeof(partes[1]) != "undefined"){
      mantisa = "." + partes[1] ;
    } else {
       mantisa = "";
    }

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
       num = num.substring(0,num.length-(4*i+3))+','+
                   num.substring(num.length-(4*i+3));

  return ( num + mantisa.substr(0,precision + 1) ); 
  }
  
  function getNumeroSinFormato(num)
  {
      num = num.toString().replace(/\$|\,/g,'');
      num = parseFloat(num);
      return num;
  }
  
		