//------------------------------------------------------------------------------
// abysal.js para  MS Internet Explorer - Netscape
// Fecha creacion: 04-02-2002
// 31/04/2004: Excluir abysal_debug si aby_sistema no es 'webdtp'
// 03/05/2004: las var aby_modif, control_close se declaran independ. aby_conf
// 09/06/2004: Compatibilizar las funciones ayudadir y DoNewWindow para j2ee
// 17/08/2004: Parametrizar Comprobar_close_x
// 18/08/2004: Introducir opcion de debug
// 30/08/2004: Introducir variable aby_control_desarrollo_url
// 20/11/2004: DoTpCall/DoTPCallSec actualizacion para una compatibilidad con J2EE
// 02/03/2005: Si esta cargando y pulsas <a href> no se lanza el onload y el
//             DoInit no se ejecuta.Ahora no hace falta ejecutar el DoInit en el
//             onload.No pasa nada si se ejecuta DoInit en el onload del body.
// 04/03/2005: La funcion DoInit solo se ejecuta 1 vez, en la carga del abysal.js.
//             Con el parametro 'forzarDoInit' de la función DoInit puesto a True,
//             se fuerza la ejecución del DoInit. Esto es util para poder
//             cambiar parametros del aby_conf.js despues de su carga (por ejemplo:
//             la variable aby_control_x)
// 10/05/2005: Agregamos SubmitVar() en funcion DoXsl
// 11/05/2005: Agregamos parametro aby_command en funcion DoNewWindow().
// 31/05/2005: Actualizamos DeleteSubmitVar y SubmitVar.
// 02/06/2005: Quitamos la instruccion document.body.style.cursor='wait' porque
//             con ella el explorer pide recursos antes de pedir el programa.
// 26/10/2005: Quitamos variable global cansubmit que da problemas con Firefox.
// 27/10/2005: Para Firefox no podemos llamar la linea que incluye el aby_conf.js
// 17/01/2006: En DeleteSubmitVar borramos el <input> con removeNode en vez de
//             removeChild ya que en idoneo fallaba esta instruccion.
// 19/05/2006: Desactivateclasmolestas: se aniade funcionalidad para anular las
//             combinaciones de teclas ctrl + ...
// 25/05/2006: PseudoDate: si PesudoDate = yes la validacion de fechas admite
//             que el mes y el dia tengan valor 0.
//             Validamos limites de anios con  LimYearUp y LimYearDown.
// 16/01/2007: Funcion DoValidateObject. Esta funcion permite utilizar las rutinas
//             de validacion del abysal.js sobre un objeto concreto,
//             independientemente de la validacion automatica propia del DoCall,
//             DoTpCall, etc.
// 24/01/2007: SubmitVar(): Se envian todos los campos de la lista suministrada,
//             aunque esten vacios. Se soluciona el problema de los campos
//             vacios en lista repetitivas
//             DeleteSubmitVar(): Se eliminan todos los campos input, aunque esten vacios.
//             Antes del cambio en SubmitVar() no existian campos input vacios, ahora si.
// 30/01/2007: browser_check(): Se incluye el miembro 'ie7' y se cambia 'ie' y 'bw'
// 01/03/2007: DoNewWindow. Se agrega el parametro 'metodo_open'
// 25/05/2007: Se implementan las siguientes funciones:
//               DoCallJ2EE(), DoCallSecJ2EE(), DoTpcallJ2EE(), DoTpcallSecJ2EE(), DoNewWindowJ2EE()
//               y DoNewWindowJ2EE()
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Inicializacion variables generales por aplicacion.
// DESCRIPCION: Debe existir por proyecto un fichero llamado aby_conf.js
//              que inicialice esas variables.
//------------------------------------------------------------------------------
// Variable que indica si el sistema donde ejecutamos es: webdtp | j2ee
var aby_sistema = "webdtp";

// Variable que define el separador de decimales en campos numericos
var aby_sepdec = ",";

// Variable que define el separador de miles en campos numericos
var aby_sepmil = ".";

// Variable que define si el proyecto esta en desarrollo o no.
// Si esta en desarrollo el protocolo es http y se activa abysal_debug
var aby_control_desarrollo = false;

// URL de la maquina de pruebas. Funciona si la var aby_control_desarrollo=true
// Ejemplo de formato: 'http://aries.sdsoftware:8000'
// Si no se rellena se ejecuta en la misma maquina y ruta
var aby_control_desarrollo_url = "";

// Variable que define si vamos a utilizar rutinas de control de teclas pulsadas
var aby_control_teclas = false;

// Variable que define si vamos a controlar cuando se cierra explorador con x
var aby_control_x = false;

// En esta variable indicamos el URL de la llamada que hacemos al servidor
// cuando controlamos que el explorador se cierra con x
// Ejemplo de formato: 'Sirene?accion=cerrar'
var aby_control_x_url = '';

// Variable que define si se controla con mensaje de adventencia la salida de
// pantalla con campos modificados
var aby_control_modificado = false;

// Con esta variable activamos o desactivamos el debug de javascript
var aby_control_debug = false;

// Para sistema = j2ee

// Variable que define el proyecto para la llamada
var aby_contexto = "";

// Variable que define el nombre del servlet que trata la transaccion
var aby_servlet = "";

// Variable que define el nombre de la variable en la que el servidor espera
// recibir el nombre del jsp
var aby_nombre_variable_jsp = "";

//Testea si la llamda al programa viene cn extension y en caso afirmativo, la elimina
var aby_testea_extension_programa = true;

//document.write( "<script src='aby_conf.js'></script>" );  jmf lo mueve abajo

var readyACK = false;
var formulario = null;
var host = null;
var port = null;

// Variable global para comprobar si en una pantalla de modificacion
// de datos algun campo ha sido modificado.
var abysal_modificado = "N";

// Para cuando cierren el explorador con la 'x' controlar la salida.
// Si se cierra salta el evento onunload. Si ControlClose es 'N' cerramos sesion.
var ControlClose = 'N';

// Creamos el objeto necesario para la opcion de ventana de debug
var ABYDebug = new Object();
var DoInitHecho = false;

// Variable de uso interno para forzar una llamada j2ee dentro de un sistema webdtp.
// Se utiliza en las llamadas DoTpcallJ2EE, DoTpcallSecJ2EE, DoCallJ2EE y DoCallSecJ2EE.
var aby_fuerza_j2ee = false;

//------------------------------------------------------------------------------
//  FUNCION:       browser_check
//  DESCRIPCION:   Funcion que devuelve un objeto con miembros cuyos valores
//                 informan de agente, version y DOM.
//  RETORNO:       Objeto que ha de crearse: var bc = new browser_check;
//------------------------------------------------------------------------------

function browser_check()
{
//  Indica la version del explorador.(ej.:5.5).
    this.ver    = navigator.appVersion;
//  Indica el navegador(agente).Devuelve nombre del navegador.(ej.:Netscape).
    this.agent  = navigator.userAgent;
//  Indica el modelo del DOM.(ej.:dom1)
    this.dom    = document.getElementById?1:0;
//  Indica si es version 5 de Internet Explorer de Microsoft.(valor logico).
    this.ie5    = ( this.ver.indexOf("MSIE 5") > -1 && this.dom )?1:0;
//  Indica si es version 6 de Internet Explorer de Microsoft.(valor logico).
    this.ie6    = ( this.ver.indexOf("MSIE 6") > -1 && this.dom )?1:0;
//  Indica si es version 7 de Internet Explorer de Microsoft.(valor logico).
    this.ie7    = ( this.ver.indexOf("MSIE 7") > -1 && this.dom )?1:0;
//  Indica si es version 4 de Internet Explorer de Microsoft.(valor logico).
    this.ie4    = ( document.all && !this.dom )?1:0;
//  Indica si es Internet Explorer de Microsoft.(valor logico).
    this.ie     = this.ie4 || this.ie5 || this.ie6 || this.ie7;
//  Indica si es Internet Explorer de Microsoft compatible Macintosh.(valor logico).
    this.mac    = this.agent.indexOf("Mac")>-1;
//  Indica si es version del Opera 5.(valor logico).
    this.opera5 = this.agent.indexOf("Opera 5")>-1;
//  Indica si es version 6 de Netscape.(valor logico).
    this.ns6    = ( this.dom && parseInt( this.ver ) >= 5 ) ?1:0;
//  Indica si es version 4 de Netscape.(valor logico).
    this.ns4    = ( document.layers && !this.dom )?1:0;
//  Indica si es browser compatible con nuestro codigo.(valor logico).
    this.bw     = (this.ie7 || this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5 || this.dom);
    return this;
}

//------------------------------------------------------------------------------
//  FUNCION:       BrowserCheck
//  DESCRIPCION:   Nueva funcion BrowserCheck().Mas completa.
//  RETORNO:       Objeto que ha de crearse: var bc = new BrowserCheck;
//------------------------------------------------------------------------------

function BrowserCheck()
{

  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isNS    = false;  // Netscape
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ( ( i = ua.indexOf( s ) ) >= 0 )
  {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ( ( i = ua.indexOf( s ) ) >= 0 )
  {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Tratar a los navegadores "Gecko" como NS 6.1.
  s = "Gecko";
  if ( ( i = ua.indexOf( s ) ) >= 0 )
  {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browsercheck = new browser_check();
var browser = new BrowserCheck();

if ( browser.isIE )
   document.write( "<script src='aby_conf.js'></script>" );

if ( browsercheck.ie )
   document.onreadystatechange = DoInit;


//------------------------------------------------------------------------------
//  FUNCION:       DoInit
//  DESCRIPCION:   Se llama desde el evento onload de los BODY de los XSL.
//                 Se hace un parser del validate y convierte su contenido
//                 en atributos para poder acceder a ellos.
//------------------------------------------------------------------------------

function DoInit( forzarDoInit )
{
  if ( browsercheck.ie )
  {
    if ( !document.forms[0] )
      return;
    if ( document.forms[0].readyState != 'complete' )
      return;
  }

  if ( forzarDoInit != true && DoInitHecho == true )
    return;
  else
    DoInitHecho = true;
    
// El formulario que vamos a manejar es el primero que exista en el documento.
  formulario = document.forms[0];

// Inicia el debug de javascript.
//  if (aby_control_debug)
//    ABYDebug.Iniciar()

// Para controlar en el proyecto si pulsan a cerrar ventana con 'x'.
  if ( aby_control_x )
    window.onunload = Comprobar_close_x;

// Para controlar en el proyecto la desactivacion de teclas.
  if ( aby_control_teclas )
  {
    document.onkeydown = desactivateclasmolestas;
    document.onkeypress = desactivateclasmolestas;
    if ( ( browsercheck.ns4 ) || ( browsercheck.ns6 ) )
    {
      document.captureEvents( Event.KEYDOWN );
      document.captureEvents( Event.KEYPRESS );
    }
  }

  var key  = "";
  readyACK = false;
  window.offscreenBuffering = true;

  if ( aby_sistema == 'webdtp' )
    if ( formulario.abysal_command && formulario.abysal_command.value == 'abysal_webdtp_ack' )
      SendACK();

//  var nobj = formulario.elements;
//  Se hacen 2 pasadas, una para textarea y otra para input.
  for ( n = 0; n < 2; n++ )
  {
    var arraytags = new Array( "input", "textarea" );
    var nobj = document.getElementsByTagName( arraytags[n] );
    var num  = nobj.length;
    for( t = 0; t < num; t++ )
    {
      switch( nobj[t].type )
      {
      case 'text':
      case 'textarea':
      case 'password':
        if ( nobj[t].getAttribute( "validate" ) )
        {
          if ( document.all )
            nobj[t].attachEvent( "onblur", DoFormatCtrl );
          else
            nobj[t]. addEventListener( "blur", DoFormatCtrl, true );

          key = getKey( nobj[t], "FieldFormat" );
          if ( key != null )
            nobj[t].setAttribute( "FieldFormat", key );

          key = getKey( nobj[t], "Mask" );
          if ( key != null )
            nobj[t].setAttribute( "Mask", key );

          key = getKey( nobj[t], "PseudoDate" );
          if ( key != null )
            nobj[t].setAttribute( "PseudoDate", key );
          else
            nobj[t].setAttribute( "PseudoDate", 'no' );

          key = getKey( nobj[t], "Upper" );
          if ( key != null )
            nobj[t].setAttribute( "Upper", key );

          key = getKey( nobj[t], "Lower" );
          if ( key != null )
            nobj[t].setAttribute( "Lower", key );

          key = getKey( nobj[t], "Length" );
          if ( key != null )
            nobj[t].setAttribute( "Length", key );

          key = getKey( nobj[t], "Separator" );
          if ( key != null )
            nobj[t].setAttribute( "Separator", key );

          key = getKey( nobj[t], "Whole" );
          if ( key != null )
            nobj[t].setAttribute( "Whole", key );

          key = getKey( nobj[t], "Decimals" );
          if ( key != null )
            nobj[t].setAttribute( "Decimals", key );

          key = getKey( nobj[t], "Sign" );
          if ( key != null )
            nobj[t].setAttribute( "Sign", key );

          key = getKey( nobj[t], "Limdown" );
          if ( key != null )
            nobj[t].setAttribute( "Limdown", key );

          key = getKey( nobj[t], "Limup" );
          if ( key != null )
            nobj[t].setAttribute( "Limup", key );

          key = getKey( nobj[t], "LimYearDown" );
          if ( key != null )
            nobj[t].setAttribute( "LimYearDown", key );

          key = getKey( nobj[t], "LimYearUp" );
          if ( key != null )
            nobj[t].setAttribute( "LimYearUp" , key );

          key = getKey( nobj[t], "Obligatory" );
          if ( key != null )
            nobj[t].setAttribute( "Obligatory", key );
          else
            nobj[t].setAttribute( "Obligatory", 'no' );
          key = getKey( nobj[t], "Zero" );
          if ( key != null )
            nobj[t].setAttribute( "Zero", key);

          if ( nobj[t].getAttribute( "FieldFormat" ) == "Date" )
          {
            key = getKey( nobj[t], "InputDateFormat" );
            if ( key != null )
            {
              nobj[t].setAttribute( "InputDateFormat", key );
            }
            if ( nobj[t].getAttribute("OutputDateFormat") && nobj[t].getAttribute("InputDateFormat") )
            {
              nobj[t].value = ChangeDateFormat( nobj[t].value, nobj[t].getAttribute("InputDateFormat"), nobj[t].getAttribute("OutputDateFormat") );
              switch (nobj[t].getAttribute("OutputDateFormat"))
              {
              case '1':
                nobj[t].setAttribute( "Mask", "ddmmyyyy" );
                break;
              case '2':
                nobj[t].setAttribute( "Mask", "mmddyyyy" );
                break;
              case '3':
                nobj[t].setAttribute( "Mask", "yyyymmdd" );
                break;
              }
            }
          }
        }
        break;
      default:
        break;
      }
    }
  }
  readyACK = true;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// --------------------------------------------------------------------------
// FUNCION:     Inicializa_modificar()
// DESCRIPCION: Asigna a todos los campos input, textarea y select el evento
//              onpropertychange.Cuando cambia algun atributo de cualquiera
//              de esos objetos de la pagina se dispara la funcion
//              Cambia_modificado().
// ARGUMENTOS:  continente: objeto tabla que contiene los objetos input,
//              select o textarea que pueden ser modificados.
// --------------------------------------------------------------------------

function Inicializa_modificar( continente )
{
  if ( !( aby_control_modificado ) )
  {
    alert('Para utilizar esta funcion debe estar activada la variable aby_control_modificado del proyecto');
    return;
  }
  nobjinput = document.getElementById(continente).getElementsByTagName('input');
  numinput = nobjinput.length;
  nobjselect = document.getElementById(continente).getElementsByTagName('select');
  numselect = nobjselect.length;
  nobjtextarea = document.getElementById(continente).getElementsByTagName('textarea');
  numtextarea = nobjtextarea.length;

  for ( i = 0; i < numinput; i++ )
    if ( document.all )
      nobjinput[i].attachEvent( "onpropertychange", Cambia_modificado );
    else
      nobjinput[i].addEventListener( "onpropertychange", Cambia_modificado, true );

  for ( i = 0; i < numselect; i++ )
    if ( document.all )
      nobjselect[i].attachEvent( "onpropertychange", Cambia_modificado );
    else
      nobjselect[i].addEventListener( "onpropertychange", Cambia_modificado, true );

  for ( i = 0; i < numtextarea; i++ )
    if ( document.all )
      nobjtextarea[i].attachEvent( "onpropertychange",Cambia_modificado );
    else
      nobjtextarea[i].addEventListener( "onpropertychange", Cambia_modificado, true );
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// --------------------------------------------------------------------------
// FUNCION:     Cambia_modificado()
// DESCRIPCION: Existe una variable global: 'abysal_modificado'.
//              Su valor por defecto es 'N'. Esta funcion cambia el valor
//              de esa variable global a 'S'.De esta forma al submitir
//              el formulario (utilizando el abysal.js) si la variable
//              es 'S' pedira confirmacion para submitir esa pantalla.
// --------------------------------------------------------------------------

function Cambia_modificado()
{
//  alert(event.propertyName+' --- '+event.srcElement.id+' --- '+event.srcElement.tagName);
  if ( ( event.propertyName == 'value' ) || ( event.propertyName == 'checked' ) )
    abysal_modificado = 'S';
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoTpcall
//  DESCRIPCION:   Valida y hace DoSubmit con abysal_command=tpcall (sin sesion)
//  ARGUMENTOS:    programa: Programa al que se quiere llamar.
//                 lista: array con variables y sus valores para enviar.
//                 ventana: target del form.
//                 validar: flag de validacion para campos del formulario.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//------------------------------------------------------------------------------

function DoTpcall( programa, lista, ventana, validar, host, port )
{
  if ( readyACK == false ) return; // Si no ha enviado ACK no submite

  if ( aby_control_modificado )
    if ( abysal_modificado == 'S' )
      if ( !( window.confirm('Se han realizado cambios en la pantalla.Si pulsa aceptar los perdera') ) )
        return;

  if ( validar == true )
  {
    if ( DoValidate() != 0 )
    {
      if ( aby_control_modificado )
        abysal_modificado = 'S';
      return;
    }
  }

  if ( aby_sistema == 'webdtp' && aby_control_desarrollo )
  {
    if ( formulario.abysal_debug )
      formulario.abysal_debug.value = '3';
    else
      if ( lista != null )
      {
        lista[lista.length] = 'abysal_debug';
        lista[lista.length] = '3';
      }
      else
        lista = new Array('abysal_debug', '3');
  }

  if (aby_sistema == 'webdtp')
  {
    if ( formulario.abysal_command )
      formulario.abysal_command.value = "tpcall";
    else
      if ( lista != null )
      {
        lista[lista.length] = 'abysal_command';
        lista[lista.length] = 'tpcall';
      }
      else
        lista = new Array( 'abysal_command', 'tpcall' );
  }

  if ( aby_sistema == 'j2ee' || aby_fuerza_j2ee )
  {
    if ( aby_testea_extension_programa )
    {
      var prog = programa.substr( 0, ( programa.lastIndexOf('.') ) );
      if (prog == '')
        prog = programa;
      programa = prog;
    }

    //Borrado previo -si la hubiera- de la variable aby_nombre_variable_jsp
    if ( document.getElementById( aby_nombre_variable_jsp ) != null )
    {
      var myform = document.getElementsByTagName("form").item(0);
      var y = document.getElementById( aby_nombre_variable_jsp );
      myform.removeChild( y );
    }

    if ( lista != null )
    {
      lista[lista.length] = aby_nombre_variable_jsp;
      lista[lista.length] = programa;
    }
    else
      lista = new Array( aby_nombre_variable_jsp, programa );
  }

  if ( lista != null )
    SubmitVar( lista );

  DoSubmit( programa, ventana, host, port, false );

}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoTpcallJ2EE
//  DESCRIPCION:   Ejecución de programas Java en una aplicación webDTP.
//  ARGUMENTOS:    Los mismos que en DoTpcall()
//------------------------------------------------------------------------------

function DoTpcallJ2EE( programa, lista, ventana, validar, host, port )
{
   if ( lista != null )
   {
      lista[lista.length] = 'abysal_j2ee';
      lista[lista.length] = programa;
   }
   else
      lista = new Array( 'abysal_j2ee', programa );

   aby_fuerza_j2ee = true;
   DoTpcall( programa, lista, ventana, validar, host, port );
   aby_fuerza_j2ee = false;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoTpcallSec (DoTpcall seguro)
//  DESCRIPCION:   Igual que DoTpcall pero con protocolo seguro.
//  ARGUMENTOS:    programa: Programa al que se quiere llamar.
//                 lista: array con variables y sus valores para enviar.
//                 ventana: target del form.
//                 validar: flag de validacion para campos del formulario.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//------------------------------------------------------------------------------

function DoTpcallSec( programa, lista, ventana, validar, host, port )
{
  if ( readyACK == false ) return; // Si no ha enviado ACK no submite

  if ( aby_control_modificado )
    if ( abysal_modificado == 'S' )
      if ( !( window.confirm('Se han realizado cambios en la pantalla.Si pulsa aceptar los perdera') ) )
        return;

  if ( validar == true )
  {
    if ( DoValidate() != 0 )
    {
      if ( aby_control_modificado )
        abysal_modificado = 'S';
      return;
    }
  }

  if ( ( aby_sistema == 'webdtp' ) && ( aby_control_desarrollo ) )
  {
    if ( formulario.abysal_debug )
      formulario.abysal_debug.value = '3';
    else
      if ( lista != null )
      {
        lista[lista.length] = 'abysal_debug';
        lista[lista.length] = '3';
      }
      else
        lista = new Array('abysal_debug','3');
  }

  if ( aby_sistema == 'webdtp' )
  {
    if ( formulario.abysal_command )
      formulario.abysal_command.value = "tpcall";
    else
      if ( lista != null )
      {
        lista[lista.length] = 'abysal_command';
        lista[lista.length] = 'tpcall';
      }
      else
        lista = new Array( 'abysal_command', 'tpcall' );
  }

  if ( aby_sistema == 'j2ee' || aby_fuerza_j2ee )
  {
    if ( aby_testea_extension_programa )
    {
      var prog = programa.substr( 0, ( programa.lastIndexOf('.') ) );
      if (prog == '')
         prog = programa;
      programa = prog;
    }

    //Borrado previo -si la hubiera- de la variable aby_nombre_variable_jsp
    if ( document.getElementById( aby_nombre_variable_jsp ) != null)
    {
      var myform = document.getElementsByTagName("form").item(0);
      var y = document.getElementById( aby_nombre_variable_jsp );
      myform.removeChild( y );
    }

    if ( lista != null )
    {
      lista[lista.length] = aby_nombre_variable_jsp;
      lista[lista.length] = programa;
    }
    else
      lista = new Array( aby_nombre_variable_jsp,programa );
  }
  if ( lista != null )
    SubmitVar(lista);
  DoSubmit( programa, ventana, host, port, true );
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoTpcallSecJ2EE
//  DESCRIPCION:   Ejecución de programas Java en una aplicación webDTP.
//  ARGUMENTOS:    Los mismos que en DoTpcallSec()
//------------------------------------------------------------------------------

function DoTpcallSecJ2EE( programa, lista, ventana, validar, host, port )
{
   if ( lista != null )
   {
      lista[lista.length] = 'abysal_j2ee';
      lista[lista.length] =  programa;
   }
   else
      lista = new Array( 'abysal_j2ee', programa );

   aby_fuerza_j2ee = true;
   DoTpcallSec( programa, lista, ventana, validar, host, port );
   aby_fuerza_j2ee = false;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoCall
//  DESCRIPCION:   Valida y hace DoSubmit con abysal_command=conv (conversacional)
//  ARGUMENTOS:    programa: Programa al que se quiere llamar.
//                 lista: array con variables y sus valores para enviar.
//                 ventana: target del form.
//                 validar: flag de validacion para campos del formulario.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//------------------------------------------------------------------------------

function DoCall( programa, lista, ventana, validar, host, port )
{
  if ( readyACK == false ) return; // Si no ha enviado ACK no submite

  if ( aby_control_modificado )
    if ( abysal_modificado == 'S' )
      if ( !( window.confirm('Se han realizado cambios en la pantalla.Si pulsa aceptar los perdera') ) )
        return;

  if ( validar == true )
  {
    if ( DoValidate() != 0 )
    {
      if ( aby_control_modificado )
        abysal_modificado = 'S';
      return;
    }
  }

  if ( aby_sistema == 'webdtp' && aby_control_desarrollo )
  {
    if ( formulario.abysal_debug )
      formulario.abysal_debug.value = '3';
    else
      if ( lista != null )
      {
        lista[lista.length] = 'abysal_debug';
        lista[lista.length] = '3';
      }
      else
        lista = new Array('abysal_debug', '3');
  }

  if ( aby_sistema == 'webdtp' )
  {
    if ( formulario.abysal_command ) {
       if ( formulario.abysal_command.value != "end" )
         formulario.abysal_command.value = "conv";
    }
    else
      if ( lista != null )
      {
          lista[lista.length] = 'abysal_command';
          lista[lista.length] = 'conv';
      }
      else
          lista = new Array( 'abysal_command', 'conv' );
  }

  if ( aby_sistema == 'j2ee' || aby_fuerza_j2ee )
  {
    if ( aby_testea_extension_programa )
    {
      var prog = programa.substr( 0,( programa.lastIndexOf('.') ) );
      if (prog == '')
        prog = programa;
      programa = prog;
    }

    //Borrado previo -si la hubiera- de la variable aby_nombre_variable_jsp
    if ( document.getElementById( aby_nombre_variable_jsp ) != null)
    {
      var myform = document.getElementsByTagName("form").item(0);
      var y = document.getElementById( aby_nombre_variable_jsp );
      myform.removeChild( y );
    }

    if ( lista != null )
    {
      lista[lista.length] = aby_nombre_variable_jsp;
      lista[lista.length] = programa;
    }
    else
      lista = new Array( aby_nombre_variable_jsp,programa );
  }

  if ( lista != null )
    SubmitVar( lista );
  DoSubmit( programa, ventana, host, port, false );
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoCallJ2EE
//  DESCRIPCION:   Ejecución de programas Java en una aplicación webDTP.
//  ARGUMENTOS:    Los mismos que en DoCall()
//------------------------------------------------------------------------------

function DoCallJ2EE( programa, lista, ventana, validar, host, port )
{
   if ( lista != null )
   {
      lista[lista.length] = 'abysal_j2ee';
      lista[lista.length] = programa;
   }
   else
      lista = new Array( 'abysal_j2ee', programa );

   aby_fuerza_j2ee = true;
   DoCall( programa, lista, ventana, validar, host, port );
   aby_fuerza_j2ee = false;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DoCallSec (DoCall seguro).
//  DESCRIPCION:   Igual que el DoCall pero con protocolo seguro.
//  ARGUMENTOS:    programa: Programa al que se quiere llamar.
//                 lista: array con variables y sus valores para enviar.
//                 ventana: target del form.
//                 validar: flag de validacion para campos del formulario.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//------------------------------------------------------------------------------

function DoCallSec( programa, lista, ventana, validar, host, port)
{
  if ( readyACK == false) return; // Si no ha enviado ACK no submite

  if ( aby_control_modificado )
    if ( abysal_modificado == 'S' )
      if ( !( window.confirm('Se han realizado cambios en la pantalla.Si pulsa aceptar los perdera') ) )
        return;

  if ( validar == true )
  {
    if ( DoValidate() != 0 )
    {
      if ( aby_control_modificado )
        abysal_modificado = 'S';
      return;
    }
  }

  if ( aby_sistema == 'webdtp' && aby_control_desarrollo )
  {
    if ( formulario.abysal_debug )
      formulario.abysal_debug.value = '3';
    else
      if ( lista != null )
      {
        lista[lista.length] = 'abysal_debug';
        lista[lista.length] = '3';
      }
      else
        lista = new Array('abysal_debug','3');
  }

  if ( aby_sistema == 'webdtp' )
  {
    if ( formulario.abysal_command ) {
       if ( formulario.abysal_command.value != "end" )
         formulario.abysal_command.value = "conv";
    }
    else
      if ( lista != null )
      {
          lista[lista.length] = 'abysal_command';
          lista[lista.length] = 'conv';
      }
      else
          lista = new Array( 'abysal_command', 'conv' );
  }

  if ( aby_sistema == 'j2ee' || aby_fuerza_j2ee )
  {
    if ( aby_testea_extension_programa )
    {
      var prog = programa.substr( 0, ( programa.lastIndexOf('.') ) );
      if (prog == '')
        prog = programa;
      programa = prog;
    }

    //Borrado previo -si la hubiera- de la variable aby_nombre_variable_jsp
    if ( document.getElementById( aby_nombre_variable_jsp ) != null )
    {
      var myform = document.getElementsByTagName("form").item(0);
      var y = document.getElementById( aby_nombre_variable_jsp );
      myform.removeChild( y );
    }

    if ( lista != null )
    {
      lista[lista.length] = aby_nombre_variable_jsp;
      lista[lista.length] = programa;
    }
    else
      lista = new Array( aby_nombre_variable_jsp,programa );
  }
  if ( lista != null )
    SubmitVar( lista );
  DoSubmit( programa, ventana, host, port, true );
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoCallSecJ2EE
//  DESCRIPCION:   Ejecución de programas Java en una aplicación webDTP.
//  ARGUMENTOS:    Los mismos que en DoCallSec()
//------------------------------------------------------------------------------

function DoCallSecJ2EE( programa, lista, ventana, validar, host, port )
{
   if ( lista != null )
   {
      lista[lista.length] = 'abysal_j2ee';
      lista[lista.length] = programa;
   }
   else
      lista = new Array( 'abysal_j2ee', programa );

   aby_fuerza_j2ee = true;
   DoCallSec( programa, lista, ventana, validar, host, port );
   aby_fuerza_j2ee = false;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoXsl
//  DESCRIPCION:   Llama (hace POST) a la transaccion abyshtml con
//                 abysal_command=tpcall (sin sesion)
//  ARGUMENTOS:    Nombre de pantalla a sacar
//------------------------------------------------------------------------------

function DoXsl( pantalla, ventana, host, port )
{
  if ( readyACK == false ) return; // Si no ha enviado ACK no submite

  if ( aby_sistema == 'webdtp' )
  {
    var lista = new Array();
    if ( formulario.abysal_command )
      formulario.abysal_command.value = "tpcall";
    else
    {
      lista[lista.length] = 'abysal_command';
      lista[lista.length] = 'tpcall';
    }
    if ( formulario.abysal_xsl )
      formulario.abysal_xsl.value = pantalla;
    else
    {
      lista[lista.length] = 'abysal_xsl';
      lista[lista.length] = pantalla;
    }
    if ( lista != null )
      SubmitVar( lista );
    if ( document.location.protocol == 'http:' )
      DoSubmit( 'abyshtml.wdtp', ventana, host, port, false );
    else
      DoSubmit( 'abyshtml.wdtp', ventana, host, port, true );
  }
  else
  {
    alert( 'Opcion unicamente implementada para aby_sistema = webdtp' );
    return;
  }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DoEnd
//  DESCRIPCION:   Cierra la sesion actual.Si viene argumento va a esa pagina,
//                 sino va al inicio de la aplicacion definido en el entorno.
//                 El argumento no es un programa aunque se rellene abysal_program
//                 con el,debe ser un recurso del sistema(xml,html...).
//                 El inicio de la aplicacion si que puede ser un programa.
//  ARGUMENTOS:    Debe ser pagina, no prg y debe estar en directorio del proyecto.
//------------------------------------------------------------------------------

function DoEnd( donde )
{
  if ( readyACK == false ) return; // Si no ha enviado ACK no submite
//    if (donde)
//        formulario.abysal_program.value=donde;
//    else
//        formulario.abysal_program.value = '';

//    if ( window.confirm("Desea desconectar la sesion actual?") )
//    {
//        var d = new Date();
//        formulario.action="/abysal_xml"+d.getTime();

  if ( aby_sistema == 'webdtp' )
  {
    var lista = new Array();
    var i =0;
    if ( formulario.abysal_command )
      formulario.abysal_command.value = "end";
    else
    {
      lista[i++] = 'abysal_command';
      lista[i++] = 'end';
    }

    if ( donde )
    {
      if ( aby_fuerza_j2ee ) {
        lista[i++] = aby_nombre_variable_jsp;
        lista[i++] = donde;
        lista[i++] = 'abysal_j2ee';
        lista[i++] = donde;
      }
      else {
        lista[i++] = 'abysal_program';
        lista[i++] = donde;
      }
    }

    if (lista.length != 0)
      SubmitVar(lista);

    if ( aby_fuerza_j2ee )
      var cad1 = "/" + aby_contexto + "/" + aby_servlet;
    else
      var cad1 = "DoEnd.wdtp";

    formulario.action=cad1;
    formulario.target = '_top';
    formulario.submit();
  }
  else
  {
    alert('Opcion unicamente implementada para aby_sistema = webdtp');
    return;
  }
//    }
}

//------------------------------------------------------------------------------
//  FUNCION:       DoEndJ2EE
//  DESCRIPCION:   Fin de la sesión J2EE y webDTP.
//  ARGUMENTOS:    programa: JSP de cierre de sesión.
//------------------------------------------------------------------------------

function DoEndJ2EE( programa )
{
   aby_fuerza_j2ee = true;
   DoEnd( programa );
   aby_fuerza_j2ee = false;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DoSubmit
//  DESCRIPCION:   Submite el formulario con protocolo http.
//  ARGUMENTOS:    programa: Programa al que se quiere llamar.
//                 ventana: target.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//                 sec: true:trama https, false: trama http.
//------------------------------------------------------------------------------

function DoSubmit( programa, ventana, host, port, sec )
{
  if ( readyACK == false ) return;

//  En proyectos en desarrollo siempre se va por http
//  no https para ver las tramas.
  if ( aby_control_desarrollo )
    sec = false;

//  Pregunta si formulario.action esta a blancos para evitar que
//  hagan otra transaccion hasta  que la actual haya terminado.
//  Formulario.action tendra valor cuando la pagina se haya cargado.
  if ( formulario.action=='' )
  {
    alert("El formulario ya ha sido enviado!");
    return;
  }
//  document.body.style.cursor='wait';
  window.status = "Enviando transaccion...";

  if ( aby_sistema == 'webdtp' && !aby_fuerza_j2ee )
  {
    var cad1 = document.location.pathname;
    cad1 = cad1.substr( 0, ( cad1.lastIndexOf('/') + 1 ) );
    if ( cad1.substr(0,1) != '/' )
      cad1 = '/' + cad1;
    cad1 = cad1 + programa;
  }
  else
  {
    var cad1 = "/" + aby_contexto + "/" + aby_servlet;
  }
//  Da valor por defecto a host y a port.
  if ( host == null )
    host = document.location.host;
  if ( port == null )
  {
    if ( sec )
      formulario.action="https://" + host + cad1;
    else
      formulario.action="http://" + host + cad1;
  }
  else
  {
    if ( host.search(":") != -1 )
      for ( i = 0; i < host.length; i++ )
        if ( host.charAt(i) == ":" )
        {
          host = host.substr( 0, i );
          break;
        }
    if ( sec )
      formulario.action = "https://" + host + ":" + port + cad1;	
    else
      formulario.action = "http://" + host + ":" + port + cad1;	
  }

  if ( aby_control_desarrollo )
    if ( aby_control_desarrollo_url != "" )
      formulario.action = aby_control_desarrollo_url + cad1;

  if ( aby_control_x )
    ControlClose = 'S';

  if ( ventana )
    formulario.target = ventana;
  else
    formulario.target = '';


//      ABYDebug.Output(formulario.outerHTML,'blue')


//  Submite el formulario.
  formulario.submit();
  window.status = "Esperando respuesta...";

//  Si la ventana destino es la misma evita submitir hasta que esta se carge.
//  Si la ventana destino es otra no es necesario esperar.
  if ( ( ventana==null ) || ( ventana=='_top' ) )
  {
    if ( formulario.action )
      formulario.action=''; // Evita submitir otra vez
  }
  else
  {
//    document.body.style.cursor='auto';
    window.status='Done';
  }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DoNewWindow()
//  DESCRIPCION:   Hace un window.open y presenta el resultado de la llamada
//                 a un programa via tpcall.
//  ARGUMENTOS:    programa: programa que queremos ejecutar
//                 lista: array con variables y sus valores para enviar.
//                 validar: valida la pantalla actual antes de abrir la otra.
//                 proyecto: si cambia de entorno ej: .../abydoc/
//                 caract: cadena con los parametros para las caracteristicas
//                         de la nueva ventana.
//                 sec: se hace http o https dependiendo de sec false o true.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//------------------------------------------------------------------------------

function DoNewWindow(programa,lista,validar,proyecto,caract,sec,host,port,aby_command,metodo_abrir )
{
// if (aby_sistema == 'webdtp')
// {

  if ( readyACK == false ) return;
  if (validar == true)
  {
    if (DoValidate() != 0)
      return;
  }

//  En proyectos en desarrollo siempre se va por http no https para ver tramas.

  if (aby_control_desarrollo)
    sec = false;

  var cadenafinal = '';


  if (aby_sistema == 'webdtp' && !aby_fuerza_j2ee)
  {
    if (proyecto)
      cad1 = proyecto;
    else
    {
      var cad1 = document.location.pathname;
      cad1 = cad1.substr(0,(cad1.lastIndexOf('/') + 1));
      if (cad1.substr(0,1) != '/')
       cad1 = '/' + cad1;
    }
    cad1 = cad1 + programa;
  }

  if (aby_sistema == 'j2ee' || aby_fuerza_j2ee)
  {
    if (proyecto)
      cad1 = proyecto;
    else
      var cad1 = "/" + aby_contexto + "/" + aby_servlet;
  }


//  Da valor por defecto a host y a port.
  if (host == null)
    host = document.location.host;
  if (port == null)
  {
    if (sec)
      cadenafinal="https://" + host + cad1;
    else
      cadenafinal="http://" + host + cad1;
  }
  else
  {
    if (host.search(":") != -1)
      for (i = 0; i < host.length; i++)
        if ( host.charAt(i) == ":")
        {
          host = host.substr(0,i);
          break;
        }
    if (sec)
      cadenafinal="https://" + host + ":" + port + cad1;	
    else
      cadenafinal="http://" + host + ":" + port + cad1;	
  }

  if (aby_sistema == 'webdtp')
  {
    if ( aby_command != null )
       cadenafinal += '?abysal_command=' + aby_command;
    else
       cadenafinal += '?abysal_command=tpcall';

    if ( aby_control_desarrollo )
      cadenafinal += '&abysal_debug=1';
  }
  if (aby_sistema == 'j2ee')
  {
    cadenafinal += '?';
  }

  // JOP. 2007-05-29.
  // Probar caso aby_sistema=j2ee con lista de parámetros.
  // La URL puede quedar: http://host:puerto/contexto/servlet?&param=valor ...
  //    -------------------------------------------------->  ?&
  // Y además, ¿donde se pone el nombre del jsp?, ¿viene en la lista de parámetros?
  if (lista)
    for (var i=0; i < lista.length; i++)
    {
      if (i % 2 == 0)
        cadenafinal += '&' + lista[i] + '=';
      else
        if (!(lista[i] == ''))
          cadenafinal += lista[i];
    }

  var win = null;
  if ( metodo_abrir )
    win = window.open(cadenafinal,metodo_abrir,caract);
  else
    win = window.open(cadenafinal,'Nueva',caract);
  win.focus();
// }
// else
// {
//   alert('Opcion unicamente implementada para aby_sistema = webdtp');
//   return;
// }
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoNewSession()
//  DESCRIPCION:   Hace un window.open y presenta el resultado de la llamada
//                 a un programa abriendo una nueva sesión en webDTP
//  ARGUMENTOS:    programa: programa que queremos ejecutar
//                 lista: array con variables y sus valores para enviar.
//                 validar: valida la pantalla actual antes de abrir la otra.
//                 proyecto: si cambia de aplicacion ej: .../abydoc/
//                 caract: cadena con los parametros para las caracteristicas
//                         de la nueva ventana.
//                 sec: se hace http o https dependiendo de sec false o true.
//                 host: entorno.
//                 port: puerto.Por defecto 80.
//------------------------------------------------------------------------------

function DoNewSession(programa,lista,validar,proyecto,caract,sec,host,port,aby_command)
{
var usuario;
// if (aby_sistema == 'webdtp')
// {

  if ( readyACK == false ) return;
  if (validar == true)
  {
    if (DoValidate() != 0)
      return;
  }

//  En proyectos en desarrollo siempre se va por http no https para ver tramas.

  if (aby_control_desarrollo)
    sec = false;

  var cadenafinal = '';


  if (aby_sistema == 'webdtp' && !aby_fuerza_j2ee)
  {
    if (proyecto)
      cad1 = proyecto;
    else
    {
      var abyses = GetCookie('abyses');
      if ( abyses == null )
      {
         alert('No se pueden abrir mas sesiones desde esta página: Se ha cerrado la sesión desde el navegador donde se realizó la conexión a la aplicación.');
         return;
      }
      var sigses = GetNextChar(abyses);
      usuario = abyses.substr(2,abyses.length);
      
      var cad1 = document.location.pathname;
      var indice = cad1.indexOf('/abyses');
      if ( indice >= 0 ) {
        usuario = cad1.substr( indice + 10, cad1.length );
        var slash = usuario.indexOf('/');
        usuario = usuario.substr(0, slash+1);
        cad1 = cad1.substr(0,(indice + 1));
      }
      else
        cad1 = cad1.substr(0,(cad1.lastIndexOf('/') + 1));
      if (cad1.substr(0,1) != '/')
        cad1 = '/' + cad1;
    }

    cad1 = cad1 + 'abyses' + sigses + "/" + usuario + "/" + programa;
  }

  if (aby_sistema == 'j2ee' || aby_fuerza_j2ee)
  {
    if (proyecto)
      cad1 = proyecto;
    else {
      var abyses = GetCookie('abyses');
      var sigses = GetNextChar(abyses);
      var cad1 = '/' + aby_contexto + '/' + 'abyses' + sigses + '/' +  abyses.substr(2,abyses.length) + "/" + aby_servlet;
    }
  }


//  Da valor por defecto a host y a port.
  if (host == null)
    host = document.location.host;
  if (port == null)
  {
    if (sec)
      cadenafinal="https://" + host + cad1;
    else
      cadenafinal="http://" + host + cad1;
  }
  else
  {
    if (host.search(":") != -1)
      for (i = 0; i < host.length; i++)
        if ( host.charAt(i) == ":")
        {
          host = host.substr(0,i);
          break;
        }
    if (sec)
      cadenafinal="https://" + host + ":" + port + cad1;	
    else
      cadenafinal="http://" + host + ":" + port + cad1;	
  }

  if (aby_sistema == 'webdtp')
  {
    if ( aby_command != null )
       cadenafinal += '?abysal_command=' + aby_command;
    else
       cadenafinal += '?abysal_command=newses';

    if ( aby_control_desarrollo )
      cadenafinal += '&abysal_debug=1';
  }
  if (aby_sistema == 'j2ee')
  {
    cadenafinal += '?';
  }

  // JOP. 2007-05-29.
  // Probar caso aby_sistema=j2ee con lista de parámetros.
  // La URL puede quedar: http://host:puerto/contexto/servlet?&param=valor ...
  //    -------------------------------------------------->  ?&
  // Y además, ¿donde se pone el nombre del jsp?, ¿viene en la lista de parámetros?
  if (lista)
    for (var i=0; i < lista.length; i++)
    {
      if (i % 2 == 0)
        cadenafinal += '&' + lista[i] + '=';
      else
        if (!(lista[i] == ''))
          cadenafinal += lista[i];
    }

  var win = null;
  win = window.open(cadenafinal, '_blank', caract);
  win.focus();
// }
// else
// {
//   alert('Opcion unicamente implementada para aby_sistema = webdtp');
//   return;
// }
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoNewWindowJ2EE
//  DESCRIPCION:   Hace un window.open y presenta el resultado de la llamada
//                 a un programa Java, en una aplicación webDTP.
//  ARGUMENTOS:    Los mismos que en DoNewWindow()
//------------------------------------------------------------------------------

function DoNewWindowJ2EE(programa,lista,validar,proyecto,caract,sec,host,port,aby_command,metodo_abrir )
{
   if ( lista != null )
   {
      lista[lista.length] = 'abysal_j2ee';
      lista[lista.length] = programa;
   }
   else
      lista = new Array( 'abysal_j2ee', programa );

   aby_fuerza_j2ee = true;
   DoNewWindow(programa,lista,validar,proyecto,caract,sec,host,port,aby_command,metodo_abrir );
   aby_fuerza_j2ee = false;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DoFormatCtrl()
//  DESCRIPCION:   Valida este objeto y si no hay errores le aplica formato de salida
//  ARGUMENTOS:    elemento: objeto.
//------------------------------------------------------------------------------

function DoFormatCtrl(elemen)
{
  var wSep = "";
  if (document.all)
    var elemento = elemen.srcElement;
  else
    var elemento = elemen.target;

  ret = DoValidateCtrl(elemento);
  if (ret != 0)
    return;

// Cuando aplicamos la mascara automaticamente a los campos estos puede
// que disparen el evento onpropertychange y el sistema crea que esa pantalla
// ha sido modificada.
// Las comprobaciones que se hacen de la variable abysal_modificado sirven
// para evitar esto, dejando el valor que tenian al entrar si este era 'N'.

  if (elemento.getAttribute("FieldFormat") == "Alpha")
  {
    if (aby_control_modificado)
      if (abysal_modificado == 'N')
        var cambia_abysal_modificado = 'S';
    if (elemento.getAttribute("Upper") && elemento.getAttribute("Upper")=="yes")
      elemento.value=elemento.value.toUpperCase();
    if (elemento.getAttribute("Lower") && elemento.getAttribute("Lower")=="yes")
      elemento.value=elemento.value.toLowerCase();
    if (aby_control_modificado)
      if (cambia_abysal_modificado == 'S')
        abysal_modificado = 'N';
  }	

  if (elemento.getAttribute("FieldFormat") == "Numeric")
  {
    if (aby_control_modificado)
      if (abysal_modificado == 'N')
        var cambia_abysal_modificado = 'S';
    if (elemento.getAttribute("Separator") && elemento.getAttribute("Separator") == "yes")
      elemento.value = ViewThousandSep(elemento);
    if (elemento.getAttribute("Decimals"))
      elemento.value = ViewDecimal(elemento);
    elemento.value = ViewSign(elemento);
    if (aby_control_modificado)
      if (cambia_abysal_modificado == 'S')
        abysal_modificado = 'N';
  }

  if (elemento.getAttribute("FieldFormat") == "Date")
  {
    if (aby_control_modificado)
      if (abysal_modificado == 'N')
        var cambia_abysal_modificado = 'S';
    elemento.value = DateFormat(day,month,year,elemento.getAttribute("Mask"),elemento.getAttribute("Separator"));
    if (aby_control_modificado)
      if (cambia_abysal_modificado == 'S')
        abysal_modificado = 'N';
  }

  if (elemento.getAttribute("FieldFormat") == "Time")
  {
    if (aby_control_modificado)
      if (abysal_modificado == 'N')
        var cambia_abysal_modificado = 'S';
    elemento.value = TimeFormat(hh,mm,ss,elemento.getAttribute("Mask"),elemento.getAttribute("Separator"));
    if (aby_control_modificado)
      if (cambia_abysal_modificado == 'S')
        abysal_modificado = 'N';
  }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DoValidate()
//  DESCRIPCION:   Valida todos los campos en pantalla.
//                 Si da error se situa sobre el campo y muestra el error.
//  RETORNO:       0: campo correcto.
//                 n: numero del error.
//------------------------------------------------------------------------------

function DoValidate()
{
  for ( n = 0; n < 2; n++ )
  {
    var arraytags = new Array("input","textarea");
    var nobj = document.getElementsByTagName(arraytags[n]);
    var num  = nobj.length;

    for(t = 0; t < num; t++)
    {
      switch(nobj[t].type)
      {
      case 'text':
      case 'textarea':
      case 'password':
        if ( nobj[t].getAttribute("validate") )
        {
          ret = DoValidateCtrl( nobj[t] );
          if ( (ret != 0) && (ret != 9) )
            return ( MensajesError( nobj[t], ret ) )
        }
        break;
      default:
        break;
      }
    }
  }
  return 0;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       DoValidateObject()
//  DESCRIPCION:   Valida el objeto de pantalla pasado como parametro
//                 Este objeto lo valida en base al su atributo "validate".
//                 Si da error se situa sobre el campo y muestra el error.
//  ARGUMENTOS:    El objeto que queremos validar.
//  RETORNO:       0: campo correcto.
//                 n: numero del error.
//------------------------------------------------------------------------------

function DoValidateObject( obj )
{
  switch( obj.type )
  {
  case 'text':
  case 'textarea':
  case 'password':
    if ( obj.getAttribute("validate") )
    {
      ret = DoValidateCtrl( obj );
      if ( ( ret != 0 ) && ( ret != 9 ) )
        return ( MensajesError( obj, ret ) )
    }
    break;
  default:
    break;
  }
  return 0;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:      MensajesError()
//  DESCRIPCION:  Esta funcion contiene los textos de error correspondientes al
//                valor pasado como parametro. Se muestra el error en pantalla
//                y se situa el foco en el obj pasado como parametro.
//  ARGUMENTOS:   obj: objeto donde situaremos el foco.
//                valor: codigo de error que vamos a mostrar.
//  RETORNO:      El codigo de error recibido o -1 si no conocemos ese codigo
//                de error.
//------------------------------------------------------------------------------

function MensajesError( obj, valor )
{
  switch ( valor )
  {
  case 1:
    alert('Campo obligatorio');
    obj.select();
    return 1;
  case 2:
    alert('Campo alfanumerico no admite mas de ' + obj.getAttribute("Length") +
          ' caracteres');
    obj.select();
    return 2;
  case 3:
    alert('FieldFormat de tipo desconocido:' + obj.getAttribute("FieldFormat") +
          '\nFieldFormat debe ser Alpha | Numeric | Date | Time | Email.');
    obj.select();
    return 3;
  case 4:
    alert('La fecha introducida debe cumplir el siguiente formato:\n' +
    obj.getAttribute("Mask"));
    obj.select();
    return 4;
  case 5:
  case 6:
  case 7:
  case 8:
    alert('La fecha introducida es invalida');
    obj.select();
    return 5;
  case 10:
    alert('Mask no especificado');
    obj.select();
    return 10;
  case 11:
    alert('Campo numerico no admite valor con decimales');
    obj.select();
    return 11;
  case 12:
    alert('Campo numerico no admite valores negativos');
    obj.select();
    return 12;
  case 13:
    alert('Caracter no valido en campo numerico');
    obj.select();
    return 13;
  case 14:
    alert('Valor de campo numerico incorrecto');
    obj.select();
    return 14;
  case 15:
    alert('Campo numerico no admite mas de ' + obj.getAttribute("Decimals") +
          ' digitos decimales');
    obj.select();
    return 15;
  case 16:
  case 17:
  case 18:
  case 19:
    alert('La hora introducida debe cumplir el siguiente formato:\n' +
    obj.getAttribute("Mask"));
    obj.select();
    return 16;
  case 20:
    alert('Campo numerico no admite mas de ' + obj.getAttribute("Whole") +
          ' digitos en parte entera');
    obj.select();
    return 20;
  case 21:
    alert('Mascara invalida:' + obj.getAttribute("Mask"));
    obj.select();
    return 20;
  case 22:
    alert('Valor de campo Email incorrecto.Revise @ y .');
    obj.select();
    return 22;
  case 23:
    alert('Valor de campo Email incorrecto.Nombre usuario incorrecto.');
    obj.select();
    return 23;
  case 24:
    alert('Valor de campo Email incorrecto.IP destino invalido.');
    obj.select();
    return 24;
  case 25:
    alert('Valor de campo Email incorrecto.Dominio invalido.');
    obj.select();
    return 25;
  case 26:
    alert('Valor de campo Email incorrecto.Direccion 3 letras si es com o 2 letras si es pais.');
    obj.select();
    return 26;
  case 27:
    alert('Valor de campo Email incorrecto.Direccion erronea.');
    obj.select();
    return 27;
  case 28:
    alert('Este campo numerico no admite que el contenido sea 0');
    obj.select();
    return 28;
  case 29:
    alert('Valor del campo debe ser mayor del limite inferior permitido '
         + obj.getAttribute("Limdown"));
    obj.select();
    return 29;
  case 30:
    alert('Valor del campo debe ser inferior al limite superior permitido '
         + obj.getAttribute("Limup"));
    obj.select();
    return 30;
  case 31:
    alert('Valor del anio debe ser mayor del limite inferior permitido '
         + obj.getAttribute("LimYearDown"));
    obj.select();
    return 31;
  case 32:
    alert('Valor del anio debe ser inferior al limite superior permitido '
         + obj.getAttribute("LimYearUp"));
    obj.select();
    return 32;
  default:
    alert('Error sin definir');
    obj.select();
    return -1;
  }
}

//------------------------------------------------------------------------------
//  FUNCION:       DoValidateCtrl()
//  DESCRIPCION:   Valida elemento pasado como parametro.
//  ARGUMENTOS:    elemento : objeto.
//  RETORNO:       0: el dato contiene datos validos y correctos.
//                 1: campo obligatorio.
//                 3: FieldFormat es desconocido.
//                 9: No es error.Campo vacio pero no obligatorio,no validamos.
//                 10: El campo no tiene definida Mask y es necesario.
//------------------------------------------------------------------------------

function DoValidateCtrl(elemento)
{
    var wSep   = "";
    var matchArray;

    if (readyACK == true && ( elemento.getAttribute("Obligatory") == 'yes' )
        && isBlankOrNull(elemento))             		
    {
        return 1;
    }

//  Si no es obligatorio pero es nulo o blanco se retorna 0.
//  No hace falta seguir validando entrada.
    if(isBlankOrNull(elemento))
    {
        return 9;
    }

    if (elemento.getAttribute("FieldFormat"))
        switch (elemento.getAttribute("FieldFormat"))	
        {
        case 'Alpha':
            merror = checka(elemento);
            if ( merror != 0 )
            {
                return merror;
            }
            break;
        case 'Numeric':
            merror = checkn(elemento);
            if ( merror != 0 )
            {
                return merror;
            }
            break;
        case 'Date':
            if ( elemento.getAttribute("Mask") )
            {
                merror = checkd(elemento);
                if ( merror != 0 )
                    return merror;
            }
            else
                return 10;
            break;
        case 'Time':
            if ( elemento.getAttribute("Mask") )
            {
                merror = checkt(elemento);
                if ( merror != 0 )
                    return merror;
            }
            else
                return 10;
            break;
        case 'Email':
            merror = checke(elemento);
            if ( merror != 0 )
            {
                return merror;
            }
            break;
        default:								
            return 3;
            break;
        }

    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       checka
//  DESCRIPCION:   Valida el campo alfanumerico.
//  ARGUMENTOS:    elemento: objeto a validar.
//  RETORNO:       0: numero correcto de caracteres introducidos.
//                 2: Se han introducido mas caracteres de los permitidos.
//------------------------------------------------------------------------------

function checka(elemento)
{
    if ( (elemento.getAttribute("Length"))
        && (elemento.value.length > elemento.getAttribute("Length")) )
        return 2;
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       checkd
//  DESCRIPCION:   Valida el campo con respecto al elemento Mask.
//  ARGUMENTOS:    elemento: objeto a validar.
//  RETORNO:       0: el valor introducido en campo fecha es correcto.
//                 4: Campo introducido no cumple mascara.Formato invalido.
//                 5: Mes debe estar entre 1 y 12.
//                 6: Dia debe estar entre 1 y 31.
//                 7: Este mes no tiene 31 dias.
//                 8: Febrero de ese anio no tiene esos dias.
//                 21: Mascara invalida.
//------------------------------------------------------------------------------

function checkd(elemento)
{
    var valor;
    var juliano = false;
    sep_defecto = /:|\/|-|\.|,|_| /g;
    switch (elemento.getAttribute("Mask"))
    {
    case 'ddmmyy':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,4);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day = valor.substr(0,2);
        month = valor.substr(2,2);
        year = valor.substr(4,2);
        break;
    case 'ddyymm':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9][0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (elemento.value.length == 7)
                    elemento.value = elemento.value.substr(0,6) + "0" + elemento.value.substr(6,1);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day=valor.substr(0,2);
        year=valor.substr(2,2);
        month=valor.substr(4,2);
        break;
    case 'mmddyy':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,4);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        month=valor.substr(0,2);
        day=valor.substr(2,2);
        year=valor.substr(4,2);
        break;
    case 'mmyydd':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9][0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (elemento.value.length == 7)
                    elemento.value = elemento.value.substr(0,6) + "0" + elemento.value.substr(6,1);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        month=valor.substr(0,2);
        year=valor.substr(2,2);
        day=valor.substr(4,2);
        break;
    case 'yymmdd':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9][0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if ( elemento.value.length == 7)
                    if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                        elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,4);
                    else
                        elemento.value = elemento.value.substr(0,5) + "0" + elemento.value.substr(5,2);
                else
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,2)
                                     + '0' + elemento.value.substr(5,1);

            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        year=valor.substr(0,2);
        month=valor.substr(2,2);
        day=valor.substr(4,2);
        break;
    case 'yyddmm':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9][0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if ( elemento.value.length == 7)
                    if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                        elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,4);
                    else
                        elemento.value = elemento.value.substr(0,5) + "0" + elemento.value.substr(5,2);
                else
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,2)
                                     + '0' + elemento.value.substr(5,1);

            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        year=valor.substr(0,2);
        day=valor.substr(2,2);
        month=valor.substr(4,2);
        break;
    case 'ddmmyyyy':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9][0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9][0-9][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,6);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day=valor.substr(0,2);
        month=valor.substr(2,2);
        year=valor.substr(4,4);
        break;
    case 'ddyyyymm':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9][0-9][0-9][0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (elemento.value.length == 9)
                    elemento.value = elemento.value.substr(0,8) + "0" + elemento.value.substr(8,1);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day=valor.substr(0,2);
        year=valor.substr(2,4);
        month=valor.substr(6,2);
        break;
    case 'mmddyyyy':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9][0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9][0-9][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,6);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        month=valor.substr(0,2);
        day=valor.substr(2,2);
        year=valor.substr(4,4);
        break;
    case 'mmyyyydd':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9][0-9][0-9][0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (elemento.value.length == 9)
                    elemento.value = elemento.value.substr(0,8) + "0" + elemento.value.substr(8,1);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        month=valor.substr(0,2);
        year=valor.substr(2,4);
        day=valor.substr(6,2);
        break;
    case 'yyyymmdd':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9][0-9][0-9][0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (elemento.value.length == 8)
                    elemento.value = elemento.value.substr(0,5) + "0" + elemento.value.substr(5,2)
                                     + '0' + elemento.value.substr(7,1);
                if (elemento.value.length == 9)
                    if (isNaN(elemento.value.substr(7,1)) || elemento.value.substr(7,1)==' ')
                        elemento.value = elemento.value.substr(0,8) + "0" + elemento.value.substr(8,1);
                    else
                        elemento.value = elemento.value.substr(0,5) + "0" + elemento.value.substr(5,4);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        year=valor.substr(0,4);
        month=valor.substr(4,2);
        day=valor.substr(6,2);
        break;
    case 'yyyyddmm':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9][0-9][0-9][0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (elemento.value.length == 8)
                    elemento.value = elemento.value.substr(0,5) + "0" + elemento.value.substr(5,2)
                                     + '0' + elemento.value.substr(7,1);
                if (elemento.value.length == 9)
                    if (isNaN(elemento.value.substr(7,1)) || elemento.value.substr(7,1)==' ')
                        elemento.value = elemento.value.substr(0,8) + "0" + elemento.value.substr(8,1);
                    else
                        elemento.value = elemento.value.substr(0,5) + "0" + elemento.value.substr(5,4);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        year=valor.substr(0,4);
        day=valor.substr(4,2);
        month=valor.substr(6,2);
        break;
    case 'dddyy':
        // Compruebo el formato de entrada
        var juliano = true;
        var mascara_1 = "^[0-9][0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9]?[0-9][-/:.,_ ][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (elemento.value.length == 4)
                    elemento.value = "00" + elemento.value;
                else
                    elemento.value = "0" + elemento.value;
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day=valor.substr(0,3);
        month=0;
        year=valor.substr(3,2);
        break;
    case 'dddyyyy':
        // Compruebo el formato de entrada
        var juliano = true;
        var mascara_1 = "^[0-9][0-9][0-9][-/:.,_ ]?[0-9][0-9][0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9]?[0-9][-/:.,_ ][0-9][0-9][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (elemento.value.length == 6)
                    elemento.value = "00" + elemento.value;
                else
                    elemento.value = "0" + elemento.value;
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day=valor.substr(0,3);
        month=0;
        year=valor.substr(3,4);
        break;
    case 'mmyyyy':
        // Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9][0-9][0-9][0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 4;
            }
	    else
            {
                if (elemento.value.length == 6)
                    elemento.value = "0" + elemento.value;
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        day=1;
        month=valor.substr(0,2);
        year=valor.substr(2,4);
        break;
    default :
        return 21;
        break;
    }
    if (!(juliano))
    {

      if ( elemento.getAttribute("PseudoDate") && ( elemento.getAttribute("PseudoDate") == 'yes' ) )
      {
        if (month < 0 || month > 12)
            return 5;
        if (day < 0 || day > 31)
            return 6;
      }
      else
      {
        if (month < 1 || month > 12)
            return 5;
        if (day < 1 || day > 31)
            return 6;
      }

      if ( elemento.getAttribute("LimYearDown") && ( elemento.getAttribute("LimYearDown") > year  ) )
         return 31;

      if ( elemento.getAttribute("LimYearUp") && ( elemento.getAttribute("LimYearUp") < year  ) )
         return 32;


      if ((month==4 || month==6 || month==9 || month==11) && day==31)
          return 7;
      if (month == 2)
      {
          var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
          if (day > 29 || (day == 29 && !isleap))
              return 8;
      }
    }
    else
    {
        if (day < 1 || day > 366)
            return 6;
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day == 366 && !isleap)
            return 8;
    }
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       checkt
//  DESCRIPCION:   Valida el campo hora con respecto al elemento Mask.
//  ARGUMENTOS:    elemento: objeto a validar.
//  RETORNO:       0: el valor introducido en campo hora es correcto.
//                 16: Campo introducido no cumple mascara.Formato invalido.
//                 17: Hora debe estar entre 0 y 23.
//                 18: Minuto debe estar entre 0 y 59.
//                 19: Segundo debe estar entre 0 y 59.
//                 21: Mascara invalida.
//------------------------------------------------------------------------------

function checkt(elemento)
{
    var valor;
    sep_defecto = /:|\/|-|\.|,|_| /g;

    switch (elemento.getAttribute("Mask"))
    {
    case 'hhmmss':
//      Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9]?[0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 16;
            }
	    else
            {
                if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                    elemento.value = "0" + elemento.value;
                if (isNaN(elemento.value.substr(4,1)) || elemento.value.substr(4,1)==' ')
                    elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,4);
                if (elemento.value.length == 7)
                    elemento.value = elemento.value.substr(0,6) + "0" + elemento.value.substr(6,1);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        hh = valor.substr(0,2);
        mm = valor.substr(2,2);
        ss = valor.substr(4,2);
        break;
    case 'hhmm':
//      Compruebo el formato de entrada
        var mascara_1 = "^[0-9][0-9][-/:.,_ ]?[0-9][0-9]$";
        matchArray = elemento.value.match(mascara_1);
        if (matchArray == null)
        {
            mascara_2 = "^[0-9]?[0-9][-/:.,_ ][0-9]?[0-9]$";
            matchArray2 = elemento.value.match(mascara_2);
            if (matchArray2 == null)
            {
                return 16;
            }
	    else
            {
                if (elemento.value.length == 3)
                    elemento.value = '0' + elemento.value.substr(0,2) + '0' + elemento.value.substr(2,1);
                else
                    if (isNaN(elemento.value.substr(1,1)) || elemento.value.substr(1,1)==' ')
                        elemento.value = "0" + elemento.value;
                    else
                        elemento.value = elemento.value.substr(0,3) + "0" + elemento.value.substr(3,1);
            }
        }
        // Quito los caracteres separadores si los hay.
        valor = elemento.value;
        valor = valor.replace(sep_defecto,'');
        hh = valor.substr(0,2);
        mm = valor.substr(2,2);
        ss = '00';
        break;
    default:
        return 21;
        break;
    }

    if (hh < 0 || hh > 23)
        return 17;
    if (mm < 0 || mm > 59)
        return 18;
    if (ss < 0 || ss > 59)
        return 19;
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       checkn
//  DESCRIPCION:   Valida campo numerico.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       0: el valor introducido en campo numerico es correcto.
//                 11: se ha introducido el separador decimal y campo no admite
//                     decimales.
//                 12: campo no admite negativos y se ha introducido caracter -.
//                 13: se ha introducido algun caracter no valido en campo numerico.
//                 14: Campo introducido no cumple mascara.Formato invalido.
//                 15: ValidateDecimal().Se han introducido mas decimales
//                     de los permitidos.
//                 20: ValidateWhole().Se han introducido mas digitos enteros
//                     de los permitidos.
//                 29: No cumple limite inferior
//                 30: No cumple limite superior
//------------------------------------------------------------------------------

function checkn(elemento)
{
//  Error si introducen algun caracter que no sea - + . , digito.
    if (!isFieldNumeric(elemento))
        return 13;
//  Error si no permite decimales e introducen el separador decimal.
    if (!(elemento.getAttribute("Decimals")) || elemento.getAttribute("Decimals") == 0)
        if (elemento.value.search(aby_sepdec) != -1)
            return 11;
//  Error si no permite negativos e introduce el signo '-'.
    if (!(elemento.getAttribute("Sign")) || elemento.getAttribute("Sign") == "no")
        if (elemento.value.search("-") != -1)
            return 12;
//  Error si permite decimales e introducen mas de los permitidos.
    if (elemento.getAttribute("Decimals"))
    {
        ret = ValidateDecimal(elemento);
        if (ret != 0)
            return ret;
    }
//  Error no permite valor 0
    if (elemento.getAttribute("Zero") == "no")
    {
        ret = ValidateZero(elemento);
        if (ret != 0)
            return ret;
    }
//  Compruebo el formato de entrada
    var mascara_1 = "^[+-]?[0-9]{1,3}([.]?[0-9]{3})*([,][0-9]+)?$";
    matchArray = elemento.value.match(mascara_1);
    if (matchArray == null)
    {
        var mascara_2 = "^[+-]?[,][0-9]+$";
        matchArray = elemento.value.match(mascara_2);
        if (matchArray == null)
        {
            return 14;
        }
    }
//  Error si introducen mas digitos en la parte entera de los permitidos.
    ret = ValidateWhole(elemento);
    if (ret != 0)
        return ret;
// Comprobamos limite inferior y superior
    if (elemento.getAttribute("Limdown"))
      if (parseFloat(elemento.value) <  elemento.getAttribute('Limdown'))
        return 29;
    if (elemento.getAttribute("Limup"))
      if (parseFloat(elemento.value) >  elemento.getAttribute('Limup'))
        return 30;
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       checke
//  DESCRIPCION:   Valida campo email.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       0: el valor introducido en campo numerico es correcto.
//                 22: campo email incorrecto.Revisa @ y ..
//                 23: nombre ususario no es valido.
//                 24: IP de destino invalido.
//                 25: Dominio no valido.
//                 26: Direccion 3 letras si es .com o 2 si es algun pais.
//                 27: Direccion erronea.
//------------------------------------------------------------------------------


function checke (elemento) {
    /* Verificar si el email tiene el formato user@dominio. */
    var emailPat=/^(.+)@(.+)$/ ;

    /* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" ;

    /* Verifica los caracteres que son validos en una direccion de email */
    var validChars="\[^\\s" + specialChars + "\]" ;
    var quotedUser="(\"[^\"]*\")" ;

    /* Verifica si la direccion de email esta representada con una direccion IP Valida */
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;


    /* Verificar caracteres invalidos */
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

    /*domain, as opposed to ipDomainPat, shown above. */
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray=elemento.value.match(emailPat);
    if (matchArray==null)
    {
//        alert("Email address seems incorrect (check @ and .'s)");
        return 22;
    }
    var user=matchArray[1];
    var domain=matchArray[2];

    // Si el user "user" es valido
    if (user.match(userPat)==null)
    {
//        alert("El nombre de usuario no es valido.");
        return 23;
    }

    /* Si la direccion IP es valida */
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null)
    {
        for (var i=1;i<=4;i++)
        {
            if (IPArray[i]>255)
            {
//                alert("IP de destino invalida");
                return 24;
            }
        }
        return 0;
    }

    var domainArray=domain.match(domainPat);
    if (domainArray==null)
    {
//        alert("El dominio parece no ser valido.");
        return 25;
    }

    var atomPat=new RegExp(atom,"g");
    var domArr=domain.match(atomPat);
    var len=domArr.length;
    if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
    {
//        alert("La dicreccion debe tener 3 letras si es ."com" o 2 si en de algun pais.");
        return 25;
    }

    if (len<2)
    {
//        var errStr="La direccion es erronea";
//        alert(errStr);
        return 27;
    }

    // La direccion de email ingresada es Valida
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DateFormat()
//  DESCRIPCION:   Devuelve la fecha formateada.
//  ARGUMENTOS:    day:dia;month:mes;year:anio;
//                 wType: formato en el que quieres que te devuelva la fecha
//                 wSep:  separador con el que se devolvera la fecha
//  RETORNO:       Fecha formateada.
//------------------------------------------------------------------------------

function DateFormat(day,month,year,wType,wSep)
{
    var year4 = year;
    var year2 = year;
    if (year4.length == 4)
        year2 = year4.substr(2,2);
    switch(wType)
    {
    case "ddmmyy":
        return day + wSep + month + wSep + year2;
        break;
    case "ddyymm":
        return day + wSep + year2 + wSep + month;
        break;
    case "mmddyy":
        return month + wSep + day + wSep + year2;
        break;
    case "mmyydd":
        return month + wSep + year2 + wSep + day;
        break;
    case "yymmdd":
        return  year2 + wSep + month + wSep + day;
        break;
    case "yyddmm":
        return year2 + wSep + day + wSep + month;
        break;
    case "ddmmyyyy":
        return day + wSep + month + wSep + year4;
        break;
    case "ddyyyymm":
        return day + wSep + year4 + wSep + month;
        break;
    case "mmddyyyy":
        return month + wSep + day + wSep + year4;
        break;
    case "mmyyyydd":
        return month + wSep + year4 + wSep + day;
        break;
    case "yyyyddmm":
        return year4 + wSep + day + wSep + month;
        break;
    case "yyyymmdd":
        return  year4 + wSep + month + wSep + day;
        break;
    case "dddyy":
        return day + wSep + year2;
        break;
    case "dddyyyy":
        return day + wSep + year4;
        break;
    case 'mmyyyy':
        return month + wSep + year4;
        break;
    default:
        return day + "/" + month + "/" + year;
        break;
    }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//------------------------------------------------------------------------------
//  FUNCION:       ChangeDateFormat()
//  DESCRIPCION:   Muestra la fecha en el campo como se especifique en parametro
//                 salida.Se ejecuta al cargar el campo, en el DoInit.
//                 El atributo Mask debe coincidir con el formato de salida para
//                 que no haya errores en la validacion.
//  ARGUMENTOS:    valfec: valor de la fecha.
//                 entrada:1 (ddmmyyyy), 2 (mmddyyyy) y 3 (yyyymmdd).
//                 salida:1 (ddmmyyyy), 2 (mmddyyyy) y 3 (yyyymmdd).
//  RETORNO:       Fecha formateada o error.
//------------------------------------------------------------------------------

function ChangeDateFormat(valfec,entrada,salida)
{
  if (!(valfec))
    return '';

  var resultado = 'Error fecha';
  var conSeparador = 'S';

  if ( valfec.length == 8 )
    conSeparador = 'N';
  else if ( valfec.length == 10 )
    conSeparador = 'S';
  else
    return resultado;

  switch(entrada)
  {
  case "1":
    switch(salida)
    {
    case "1":
      resultado = valfec;
      break;
    case "2":
      if ( conSeparador == 'S' )
      {
        resultado = valfec.substr(3,2);
        resultado += valfec.substr(2,1);
        resultado += valfec.substr(0,2);
        resultado += valfec.substr(5,1);
        resultado += valfec.substr(6,4);
      }
      else
      {
        resultado = valfec.substr(2,2);
        resultado += valfec.substr(0,2);
        resultado += valfec.substr(4,4);
      }
      break;
    case "3":
      if ( conSeparador == 'S' )
      {
        resultado = valfec.substr(6,4);
        resultado += valfec.substr(5,1);
        resultado += valfec.substr(3,2);
        resultado += valfec.substr(2,1);
        resultado += valfec.substr(0,2);
      }
      else
      {
        resultado = valfec.substr(4,4);
        resultado += valfec.substr(2,2);
        resultado += valfec.substr(0,2);
      }
      break;
    }

    break;
  case "2":
    switch(salida)
    {
    case "1":
      if ( conSeparador == 'S' )
      {
        resultado = valfec.substr(3,2);
        resultado += valfec.substr(2,1);
        resultado += valfec.substr(0,2);
        resultado += valfec.substr(5,1);
        resultado += valfec.substr(6,4);
      }
      else
      {
        resultado = valfec.substr(2,2);
        resultado += valfec.substr(0,2);
        resultado += valfec.substr(4,4);
      }
      break;
    case "2":
      resultado = valfec;
      break;
    case "3":
      if ( conSeparador == 'S' )
      {
        resultado = valfec.substr(6,4);
        resultado += valfec.substr(5,1);
        resultado += valfec.substr(0,2);
        resultado += valfec.substr(2,1);
        resultado += valfec.substr(3,2);
      }
      else
      {
        resultado = valfec.substr(4,4);
        resultado += valfec.substr(0,4);
      }
      break;
    }

    break;
  case "3":
    switch(salida)
    {
    case "1":
      if ( conSeparador == 'S' )
      {
        resultado = valfec.substr(8,2);
        resultado += valfec.substr(7,1);
        resultado += valfec.substr(5,2);
        resultado += valfec.substr(4,1);
        resultado += valfec.substr(0,4);
      }
      else
      {
        resultado = valfec.substr(6,2);
        resultado += valfec.substr(4,2);
        resultado += valfec.substr(0,4);
      }
      break;
    case "2":
      if ( conSeparador == 'S' )
      {
        resultado = valfec.substr(5,2);
        resultado += valfec.substr(7,1);
        resultado += valfec.substr(8,2);
        resultado += valfec.substr(4,1);
        resultado += valfec.substr(0,4);
      }
      else
      {
        resultado = valfec.substr(4,4);
        resultado += valfec.substr(0,4);
      }
      break;
    case "3":
      resultado = valfec;
      break;
    }
    break;
  }
  return resultado;
}

/*
function ChangeDateFormat(valfec,entrada,salida)
{
  if (!(valfec))
    return '';
  var resultado = 'Error fecha';
  switch(entrada)
  {
  case "1":
    switch(salida)
    {
    case "1":
      resultado = valfec;
      break;
    case "2":
      resultado = valfec.substr(3,2);
      resultado += valfec.substr(2,1);
      resultado += valfec.substr(0,2);
      resultado += valfec.substr(5,1);
      resultado += valfec.substr(6,4);
      break;
    case "3":
      resultado = valfec.substr(6,4);
      resultado += valfec.substr(5,1);
      resultado += valfec.substr(3,2);
      resultado += valfec.substr(2,1);
      resultado += valfec.substr(0,2);
      break;
    }

    break;
  case "2":
    break;
  case "3":
    switch(salida)
    {
    case "1":
      resultado = valfec.substr(8,2);
      resultado += valfec.substr(7,1);
      resultado += valfec.substr(5,2);
      resultado += valfec.substr(4,1);
      resultado += valfec.substr(0,4);
      break;
    case "2":
      resultado = valfec.substr(5,2);
      resultado += valfec.substr(7,1);
      resultado += valfec.substr(8,2);
      resultado += valfec.substr(4,1);
      resultado += valfec.substr(0,4);
      break;
    case "3":
      resultado = valfec;
      break;
    }
    break;
  }
  return resultado;
}
*/
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       TimeFormat
//  DESCRIPCION:   Devuelve la hora formateada.
//  ARGUMENTOS:    hh,mm,dd : hora, minutos y segundos.
//                 wType: formato en el que quieres que te devuelva la hora.
//                 wSep:  separador con el que se devolvera la hora.
//  RETORNO:       Hora formateada.
//------------------------------------------------------------------------------

function TimeFormat(hh,mm,ss,wType,wSep)
{
    switch(wType)
    {
    case "hhmmss":
        return hh + wSep + mm + wSep + ss;
        break;
    case "hhmm":
        return hh + wSep + mm;
        break;
    default:
        return hh + ":" + mm + ":" + ss;
        break;
    }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       SendACK
//  DESCRIPCION:   En el SEND del programa que presenta el xsl existe parametro
//                 &aw_wait_ack.
//                 Si su valor es 0 abysal_command es enviado sin peticion de ack.
//                 En este caso el servidor devuelve el control al prg despues del
//                 send y no sabe si se ha presentado la pantalla correctamente, solo
//                 sabe si el SEND lo ha hecho bien.
//                 Si su valor es 1 abysal_command es enviado con ack.El DoInit del
//                 abysal.js detecta el ack y pide la imagen ack2.jpg mediante esta
//                 funcion.Al detectar esta peticion el servidor devuelve el control
//                 al programa indicando si el SEND se ha hecho bien y si se ha
//                 presentado la pantalla correctamente.
//------------------------------------------------------------------------------

function SendACK()
{
//    document.forms[0].ack.src="ack2.jpg";
    document.getElementById('ack').src = "ack2.jpg";
    return;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       getKey
//  DESCRIPCION:   Develve el contenido del campo del validate key.
//  ARGUMENTOS:    obj:El objeto al que pertenece la key.
//                 key:Campo del que se quiere obtener el contenido (ej.:Mask...)
//------------------------------------------------------------------------------

function getKey( obj, key )
{
//  obj.indexof devuelve la posicion de inicio de la cadena pasada como argumento en el objeto
    var indice_llave_inicio = obj.getAttribute("validate").indexOf( key + "=" );
    if ( indice_llave_inicio != -1 )
    {
        indice_llave_inicio += key.length + 1;
        var indice_llave_fin = obj.getAttribute("validate").indexOf( "~", indice_llave_inicio );
        if ( indice_llave_fin == -1 )
            indice_llave_fin = obj.getAttribute("validate").length;
        return obj.getAttribute("validate").substring(indice_llave_inicio, indice_llave_fin);
    }
    else
        return null;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ViewThousandsep
//  DESCRIPCION:   Pone el separador de miles.
//  ARGUMENTOS:    elemento : objeto.
//------------------------------------------------------------------------------

function ViewThousandSep(elemento)
{
    var dec = "";
    var tam = 0;
    var j = 0;
    if (aby_sepmil == ".")
        var masc = /\./g;
    if (aby_sepmil == ",")
        var masc = /,/g;
    elemento.value = elemento.value.replace(masc,'');
    for (i = 0; i < elemento.value.length; i++){
        if ( elemento.value.charAt(i) == "+" || elemento.value.charAt(i) == "-")
            j = 1;
        if ( elemento.value.charAt(i) == "," ) {
            dec = elemento.value.substr(i+1 , elemento.value.length - i - 1)
            break;
        }
        tam++;
    }
    tam--;
    var aux = "";
    var z = -1;
    if ( tam > 2 ){
        for ( i = tam ; i > j-1; i--){
            z++;
            if ( z > 2){
                aux = "." + aux;
                z = 0;
            }
            aux = elemento.value.substr(i , 1) + aux;
        }
        if (j == 1)
            aux = elemento.value.charAt(0) + aux;
        if (dec != "" )
            aux = aux + "," + dec;
        return aux;
    }
    return elemento.value;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ValidateDecimal
//  DESCRIPCION:   Valida si el numero de decimales introducidos es correcto.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       0: el numero de decimales es igual o menor al permitido.
//                 15: se han introducido mas decimales de los permitidos.
//------------------------------------------------------------------------------

function ValidateDecimal(elemento)
{
    var dec="";
    var tam = 0;
    for ( i=0; i < elemento.value.length; i++){
        if ( elemento.value.charAt(i) == "," ) {
            dec=elemento.value.substr(i+1,elemento.value.length-i-1);
            break;
        }
    }
    tam = dec.length;
    if ( tam > elemento.getAttribute("Decimals") )
        return 15;
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ValidateZero
//  DESCRIPCION:   Valida si el valor del campo es cero.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       0: el valor del campo es distinto de cero.
//                 28: el valor del campo es cero.
//------------------------------------------------------------------------------

function ValidateZero(elemento)
{
    var j = 0;
    sep_defecto = /:|\/|-|\.|,|_| /g;
    valor = elemento.value;
    valor = valor.replace(sep_defecto,'');
//    if ( parseInt(valor) == 0 )
//        return 28;
    for (j=0; j < valor.length; j++)
        if ( valor.substr(j,1) != "0" )
            return 0;
    return 28;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ValidateWhole
//  DESCRIPCION:   Valida si el numero de digitos introducidos como parte entera
//                 es correcto.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       0: el numero de digitos enteros es igual o menor al permitido.
//                 20: se han introducido mas digitos enteros de los permitidos.
//------------------------------------------------------------------------------

function ValidateWhole(elemento)
{
    sep = /\+|-|\.|/g;
    var valor = elemento.value;
    valor = valor.replace(sep,'');
    var ent="";
    var dec="";
    for (i = 0; i < valor.length; i++){
        if ( valor.charAt(i) == "," ) {
            ent = valor.substr(0,i);
            dec = valor.substr(i+1,valor.length - i - 1);
            break;
        }
    }
    if ( dec == "" )
        ent = valor;
    var tam = ent.length;
    if ( tam > elemento.getAttribute("Whole") )
        return 20;
    return 0;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ViewDecimal
//  DESCRIPCION:   Aniade 0 a la derecha si el numero de decimales es menor que
//                 el permitido.
//  ARGUMENTOS:    elemento: objeto.
//------------------------------------------------------------------------------

function ViewDecimal(elemento)
{
    if (elemento.getAttribute("Decimals") != 0){
        if (elemento.value.search(aby_sepdec) != -1)
        {
            var dec="";
            var ent="";
            var tam = 0;
            for ( i=0; i < elemento.value.length; i++){
                if ( elemento.value.charAt(i) == "," ) {
                    ent = elemento.value.substr(0,i);
                    dec=elemento.value.substr(i+1,elemento.value.length-i-1);
                    break;
                }
            }
            if ((ent == "+") || (ent == "-"))
                ent = ent + "0";
            if (ent == "")
                ent = "0";
            tam = dec.length;
            if ( tam < elemento.getAttribute("Decimals") )
                for (i=tam ; i < elemento.getAttribute("Decimals") ; i++)
                    dec = dec + "0";
            return  ent + "," + dec;
        }
        else
        {
            elemento.value = elemento.value + ",";
            for ( i = 0 ; i < elemento.getAttribute("Decimals"); i++ )
                elemento.value = elemento.value + "0";
            return elemento.value;
        }
    }
    else
        return elemento.value;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ViewSign
//  DESCRIPCION:   Oculta el signo si este es +, si es - no lo oculta.
//  ARGUMENTOS:    elemento : objeto.
//------------------------------------------------------------------------------

function ViewSign(elemento)
{
    if (elemento.value.charAt(0) == "+")
        elemento.value = elemento.value.substr(1,elemento.value.length);
    return elemento.value;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       isBlankOrNull
//  DESCRIPCION:   Funcion que comprueba si el campo esta relleno a blancos o
//                 es nulo.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       true: campo relleno blancos o es nulo.
//                 false: Resto de los casos.
//------------------------------------------------------------------------------

function isBlankOrNull(elemento)
{
    var regexp = new RegExp("[\\S]",["g"]);
    var matchArray = elemento.value.match(regexp);
    if (matchArray == null)
        return true;
    return false;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       isFieldNumeric
//  DESCRIPCION:   Indica si el caracter estar permitido en un campo numerico.
//  ARGUMENTOS:    elemento: objeto.
//  RETORNO:       false: Alguno de los caracteres no esta permitido.
//                 true: Todos los caracteres son admitidos en campo numerico.
//------------------------------------------------------------------------------

function isFieldNumeric(elemento)
{
    for (i = 0 ; i < elemento.value.length ; i++ )
        if ( isNaN(elemento.value.charAt(i)) && elemento.value.charAt(i) != ","
        && elemento.value.charAt(i) != "." && elemento.value.charAt(i) != "-"
        && elemento.value.charAt(i) != "+")
            return false;
    return true;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:      setStyle(), getStyle(),getRef()
//  DESCRIPCION:   Funciones que configuran (setStyle) o devuelven (getStyle)
//                 atributos del style en netscape e Internet Explorer.
//  ARGUMENTOS:    obj      = object reference or element id.
//                 style    = the style to be changed.
//                 value    = the value assigned to the style.
//------------------------------------------------------------------------------

function setStyle(obj, style, value){
    getRef(obj).style[style]= value;
}
//function getStyle(obj, style){
//    return getRef(obj).style[style];
//}

function getStyle(x,styleProp)
{
  if (document.defaultView)
    var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
  else if (x.currentStyle)
    var y = eval('x.currentStyle.' + styleProp);
  return y;
}


function getRef(obj){
    return (typeof obj == "string") ?
    document.getElementById(obj) : obj;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       multitrim
//  DESCRIPCION:   Funcion que quita espacios en blanco de una cadena.
//  ARGUMENTOS:    cad: Cadena a la que hacer el trim
//                 tipotrim: Tipo de TRIM ( "L" para LTrim(), "R" para RTrim()
//                           o "T" para Trim() )
//------------------------------------------------------------------------------

function multitrim(cad,tipotrim) {
    var trimvalue = "";
    cadlen = cad.length;
    if (cadlen < 1)
        return trimvalue;
    if (tipotrim == "L" || tipotrim== "T")
    {
        i = 0;
        pos = -1;
        while (i < cadlen)
        {
            if (cad.charCodeAt(i) != 32 && !isNaN(cad.charCodeAt(i)))
            {
                pos = i;
                break;
            }
            i++;
        }
    }
    if (tipotrim == "R" || tipotrim== "T")
    {
        var lastpos = -1;
        i = cadlen;
        while (i >= 0) {
            if (cad.charCodeAt(i) != 32 && !isNaN(cad.charCodeAt(i)))
            {
                lastpos = i;
                break;
            }
            i--;
        }
    }

    if (tipotrim == "L")
        trimvalue = cad.substring(pos,cadlen-1);

    if (tipotrim == "R")
        trimvalue = cad.substring(0,lastpos+1);

    if (tipotrim == "T")
        trimvalue = cad.substring(pos,lastpos + 1);

    return trimvalue;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       putFocus()
//  DESCRIPCION:   Funcion que posiciona el cursor en un objeto
//                 determinado de la pagina.A esta funcion hay que llamarla
//                 desde el onload del body.
//  ARGUMENTOS:    elementName: literal del atributo id del objeto.
//                 seleccionado: valor logico que indica si selecciona el campo
//                 que recibe el foco o no.
//------------------------------------------------------------------------------

function putFocus(elementName,seleccionado) {
    if (document.getElementById(elementName) != null)
    {
        document.getElementById(elementName).focus();
        if (seleccionado)
          document.getElementById(elementName).select();
    }


}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       SubmitVar()
//  DESCRIPCION:   Funcion incluye objetos input type=hidden en el forms[0].
//  ARGUMENTOS:    Esta funcion recoge argumentos por pares.El primero es el
//                 nombre del campo que quieres submitir y el segundo es el
//                 valor con el que quieres que submita ese campo.
//                 ej.:SubmitVar("nom1","valor1","nom2","valor2"...);
//------------------------------------------------------------------------------

function SubmitVar(lista) {
    var myform = document.getElementsByTagName("form").item(0);
    var myinput;
    for (var i=0; i < lista.length; i++)
    {
        if (i % 2 == 0)
        {
            myinput = document.createElement("input");
            myinput.setAttribute("type","hidden");
            myinput.setAttribute('id',lista[i]);
            myinput.setAttribute('name',lista[i]);
            myinput.setAttribute('SubmitVar','S');
        }
	else
        {
     // JOP (24/01/2007)
     // No descomentar esta comprobación.
     // Soluciona el problema de los elementos vacios
     // en lista repetitivas.
	  //if (!(lista[i] == ''))
          {
            myinput.setAttribute('value',lista[i]);
            myform.appendChild(myinput);
          }
        }
    }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       DeleteSubmitVar()
//  DESCRIPCION:   Funcion elimina objetos input type=hidden del forms[0] cuyo
//                 atributo lista sea igual a yes.
//  ARGUMENTOS:    Se llama a la funcion con todos los nombres de los objetos
//                 input a eliminar separados por comas.
//                 ej.:DeleteSubmitVar("nom1","nom2",...);
//------------------------------------------------------------------------------

function DeleteSubmitVar(lista) {
  var myform = document.getElementsByTagName("form").item(0);
  var y;
  for (var i=0; i < lista.length; i++)
  {
    if (i % 2 == 0)
    {
      // JOP (24/01/2007)
      // No descomentar esta comprobación.
      // Deben borrase todos, incluso aquellos con contenido vacio.
      // Antes no podia haber variables vacias, pero ahora si. Ver SubmitVar().
      //if (!(lista[i+1] == ''))
      {
        var objmyform = document.getElementsByName(lista[i]);
        var j = 0;
        while ( j < objmyform.length )
        {
          if ( objmyform[j].getAttribute('SubmitVar') && objmyform[j].getAttribute('SubmitVar') == 'S' )
          {
            y = objmyform[j];
//            myform.removeChild(y);
            y.removeNode();
          }
          else
            j++;
        }
      }
    }
  }
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       ayudadir()
//  DESCRIPCION:   Funcion que llama a las pantallas de ayuda
//  ARGUMENTOS:    Esta funcion recoge doc como argumento(numero de ayuda)
//                 ej.:ayudadir(187);
//------------------------------------------------------------------------------

function ayudadir(doc)
{
    var lista = new Array('iddoc',doc);
    var caracteristicas = 'resizable=yes,scroll=yes,status=no,menubar=no,toolbar=no,height=500,width=585';
    DoNewWindow('p_doc00.wdtp',lista,false,'/abydoc/',caracteristicas,true);
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


function GetNextChar(letra)
{
  var myString = new String(letra);
  var dValor = myString.charCodeAt(0) + 1;
  var ret = String.fromCharCode(dValor) + letra.substr(1,1);
  return ret;
}

//------------------------------------------------------------------------------
//  FUNCION:       GetCookie()
//  DESCRIPCION:   Recupera el valor de la cookie con el nombre especificado.
//  ARGUMENTOS:
//------------------------------------------------------------------------------

function GetCookie(sName)
{
    var aCookie = document.cookie.split("; ");
    for (var i=0; i < aCookie.length; i++)
    {
    // a name/value pair (a crumb) is separated by an equal sign
        //alert('Cookie: ' + aCookie[i]);
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0]) {
            return (aCrumb[1]);
        }
    }
    return null;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       SetCookie()
//  DESCRIPCION:   Crea una cookie con el nombre y valor especificados.
//  ARGUMENTOS:
//------------------------------------------------------------------------------


function SetCookie(sName, sValue)
{
  date = new Date();
  document.cookie = sName + "=" + escape(sValue) + "; expires = Sun, 24 02 2019 23:59:59 GMT"
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       desactivateclasmolestas()
//  DESCRIPCION:   Rutina de captura del evento de teclado
//  ARGUMENTOS:    Debe existir input type=hidden que definan las teclas a anular
//                 en el xsl. En el IE el id=teclas_anuladas_IE y en el
//                 NS el id=teclas_anuladas_NS.
//                 22-05-2006: se aniade funcionalidad para anular las teclas
//                 precedidas de ctrl. Para ello se debe crear un input type=hidden
//                 con id=teclas_ctrl_anuladas_IE. Si en el value de ese input
//                 pones por ejemplo 85, se elimina la tecla ctrl + U, no la tecla
//                 U.
//------------------------------------------------------------------------------

function desactivateclasmolestas(e) {
// Teclas habitualmente destinadas a ser desactivadas por molestas
//   8 : tecla de borrado (backspace) sobre todo en IE
// 114 : Tecla F3  (buscar)
// 116 : Tecla F5  (actualizar)
// 122 : Tecla F11 (Cambio de visualizacion del browser)
// NOTA : Esta funcion permite desactivar cualquier tecla MENOS la 112 (F1 ayuda)

    if (browsercheck.ie)
    {
//Circunstancia especial - aclaracion : Al usar esta misma funcion para dos eventos diferentes (KeyDown y
//KeyPress), tenemos un problema. Los keycode de LA MISMA TECLA dependiendo del evento en que entren, tienen
//distinto valor, es decir, el hecho de pulsar la tecla 'R' no genera el mismo KeyCode en el OnKeyDown que en el
//OnKeyPress (por motivos demasiado largos de explicar), por lo que si se quiere usar la misma funcion para los
//dos eventos, hay que dividir el funcionamiento segun el tipo de evento que este actuando


//        if (document.getElementById('teclas_ctrl_anuladas_IE') != null) {
//
//           var strDisabledCtrlKeys = document.getElementById('teclas_ctrl_anuladas_IE').value;
//           var aDisabledCtrlKeys = strDisabledCtrlKeys.split(',');
//
////           var etype = event.type;
////           etype = etype.toUpperCase();
//
////           if (etype == 'KEYDOWN') {
//               var loop=0;
//               for ( loop = aDisabledCtrlKeys.length-1; loop >=0; loop--) {
//                   if ( (event.keyCode == aDisabledCtrlKeys[loop]) && (event.ctrlLeft) ) {
//                       event.keyCode = 0;
//                       event.cancelBubble = true;
//                       event.returnValue = false;
//                   }
//               }
////           }
//        }



        if (document.getElementById('teclas_anuladas_IE') != null) {
           var strDisabledKeys = document.getElementById('teclas_anuladas_IE').value;
           var aDisabledKeys = strDisabledKeys.split(',');
//           alert('entra' + event.keyCode);

           var etype = event.type;
           etype = etype.toUpperCase();

           if (etype == 'KEYDOWN') {
               var loop=0;
               for ( loop = aDisabledKeys.length-1; loop >=0; loop--) {
                   if (event.keyCode == aDisabledKeys[loop]) {
                       if (event.keyCode == 8) {
                           //Caso especial : Tecla de borrado (<--) : Si el elemento activo es un elemento editable,
                           //si tiene sentido el habilitar esta tecla, sino, no, porque si el elemento activo no es
                           //editable, produce un 'back'
                           if (document.activeElement.isContentEditable == false) {
                               event.keyCode = 0;
                               event.cancelBubble = true;
                               event.returnValue = false;
                           }
                       }
                       else
                       {
                           event.keyCode = 0;
                           event.cancelBubble = true;
                           event.returnValue = false;
                       };
                   };
               };
           };
        };
    };
    if (browsercheck.ns4 == true || browsercheck.ns6 == true)
    {
        if (document.getElementById('teclas_anuladas_NS') != null) {
            var strDisabledKeys = document.getElementById('teclas_anuladas_NS').value;
            var aDisabledKeys = strDisabledKeys.split(',');
            var loop=0;
            for ( loop = aDisabledKeys.length-1; loop >=0; loop--) {
                if (e.keyCode == aDisabledKeys[loop]) {
                    e.cancelBubble = true;
                    e.returnValue = false;
                    return false;
                };
            };
        };
    }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       getProtocol()
//  DESCRIPCION:   Devuelve en MAYUSCULAS el protocolo en el que se esta visualizando
//                 la pagina donde se ejecute esta funcion.
//  RETORNO:       FILE si estamos viendo pagina de forma local
//                 HTTP si estamos viendo pagina a traves de web
//                 HTTPS si estamos viendo pagina a traves de servidor seguro
//------------------------------------------------------------------------------

function getProtocol() {
    var cprot = window.location.protocol;
    cprot = cprot.toUpperCase();
    cprot = cprot.substr(0,cprot.length-1);
    return cprot
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       cookie_check()
//  DESCRIPCION:   Funcion que comprueba si el navegador admite cookies
//  RETORNO:       true: admite cookies
//                 false: no admite cookies
//------------------------------------------------------------------------------

function cookie_check()
{
    document.cookie = "test=ok";
    if (document.cookie.indexOf("test=ok")!=-1)
        return true;
    else
        return false;
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


// --------------------------------------------------------------------------
// FUNCION:    CambiaFormatoFecha(tdnombre)
// DESCRIPCION:Funcion que trata los campos que contienen fechas para
//             cambiarlas de formato dependiendo del atributo OutputDateFormat
//             que contenga el objeto.
//             Debido a que los campos afectados suelen ser listados y las
//             fechas suelen ir precedidas de blanco se contempla en el
//             algoritmo que pueda o no ir un blanco delante.
// ARGUMENTOS: tdnombre: id de todos los campos cuyo contenido es tipo fecha
//             y que queremos cambiar de formato.
// --------------------------------------------------------------------------

function CambiaFormatoFecha(tdnombre){
  var objfechas = document.getElementsByName(tdnombre);
  var numobjfechas = objfechas.length;
  for (i=0; i < numobjfechas; i++)
    if (objfechas[i].childNodes.length > 0 )
    {
      //if (objfechas[i].childNodes.item(0).nodeValue.substr(0,1) == ' ')
      var blanco160 = objfechas[i].childNodes.item(0).nodeValue.substr(0,1);
      if ( blanco160.charCodeAt(0) == 160 )
      {
        var auxfecha = ChangeDateFormat(objfechas[i].childNodes.item(0).nodeValue.substr(1,10),objfechas[i].getAttribute('InputDateFormat'),objfechas[i].getAttribute('OutputDateFormat'));
        //objfechas[i].childNodes.item(0).nodeValue = ' ' +  auxfecha;
        objfechas[i].childNodes.item(0).nodeValue = blanco160 + auxfecha;
      }
      else
        objfechas[i].childNodes.item(0).nodeValue = ChangeDateFormat(objfechas[i].childNodes.item(0).nodeValue, objfechas[i].getAttribute('InputDateFormat'),objfechas[i].getAttribute('OutputDateFormat'));
    }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//------------------------------------------------------------------------------
//  FUNCION:       Comprobar_close_x
//  DESCRIPCION:   Al evento de la ventana onunload se le ha asociado esta
//                 funcion. Si la variable ControlClose esta a 'N' se asume
//                 que el usuario esta cerrando incontroladamente el navegador,
//                 por ejemplo dando al boton 'x'.
//                 El objetivo de esta funcion es hacer una llamada al servidor
//                 para informarle del evento y que cierre sesion o haga lo que
//                 considere oportuno.
// -----------------------------------------------------------------------------
//                 errorsm: esta a 'S' cuando ha ocurrido un error irrecuperable
//                 en una ventana ShowModalDialog. "error irrecuperable" es que
//                 el servidor ya ha desconectado sesion. El usuario si da a la
//                 'x' en la showmodaldialog que presenta el error se cierra
//                 tanto esa ventana como la ventana padre.
//------------------------------------------------------------------------------

function Comprobar_close_x()
{
  if (ControlClose == 'N')
  {
    if (!(document.getElementById('errorsm')) )
    {
      var d = new Date();
      var nombre;
      if (browser.isIE)
        //jmf no funciona en Firefox
        nombre = d.getVarDate() + d.getMilliseconds();
      if (!browser.isIE)
        nombre = d.getYear() + (d.getMonth() + 1) + d.getDate() + d.getMilliseconds();

      var corx = 1;
      var cory = 1;
      var ancho = 1;
      var alto = 1;
      var url = aby_control_x_url;
      var features = "directories=yes,status=yes,toolbar=yes,menubar=yes,location=yes,scrollbar=yes,resizable=yes,top=" + cory +",left=" + corx + ",width=" + ancho + ",height=" + alto;
      var ventana = window.open(url, nombre, features);
      ventana.moveTo(-2000,-2000)
      ventana.close();
    }
    else
    {
      if ( document.getElementById('errorsm').value == 'S' )
      {
        ControlClose = 'S';
        var ventanacerrar = dialogArguments;
        ventanacerrar.close();
      }
    }
  }
}


//------------------------------------------------------------------------------
//  FUNCION:       ABYDebug
//  DESCRIPCION:   Funciones para debug de javascript. La idea es escribir los
//                 mensajes que queramos en una ventana de debug paralela a la
//                 de la aplicacion.
//                 Donde queramos que salga una linea de display, en el codigo
//                 javascript escribimos: ABYDebug.Output("mensaje","color").
//                 Entonces cuando se ejecute esa linea se abrira una ventana
//                 nueva donde se escribira el mensaje en el color indicado.
//                 Si la ventana de debug ya esta abierta no se abrira otra,
//                 escribira en la misma.
//                 Es necesario poner la variable aby_control_debug
//                 del aby_conf.js a true.
//                 ABYDebug.Iniciar: sirve para abrir la ventana debug.
//                 ABYDebug.Output:  sirve para escribir lineas de debug. Si
//                                   no hay ventana abierta abre una nueva.
//  ARGUMENTOS:    mensaje: cadena de texto con el mensaje que queremos
//                          visualizar.
//                 color:   color (red, blue, green ...) en el que saldra ese
//                          mensaje.
//------------------------------------------------------------------------------

ABYDebug.Iniciar = function ()
{
   if (! Debug)
   {
      return;
   }
   else
   {
      if ( !this.DebugWindow || this.DebugWindow.closed )
      {
         this.DebugWindow = window.open( 'abydebug.html', 'ABYeditorDebug', 'menubar=no,scrollbars=no,resizable=yes,location=no,toolbar=no,width=600,height=500', true ) ;
      }
   }
}

ABYDebug.Output = function( message, color )
{
  if (aby_control_debug)
  {
       alert(aby_control_debug);
    if ( !this.DebugWindow || this.DebugWindow.closed )
    {
       this.DebugWindow = window.open( 'abydebug.html', 'ABYeditorDebug', 'menubar=no,scrollbars=no,resizable=yes,location=no,toolbar=no,width=600,height=500', true ) ;
//       Pause(200);
    }
    if (Debug)
    {
      if ( message != null && isNaN( message ) )
      {
        message = message.replace(/</g, "&lt;") ;
      }
      if ( this.DebugWindow.Output)
      {
        this.DebugWindow.Output( message, color ) ;
      }
    }
  }
}
/*
* This function will not return until (at least)
* the specified number of milliseconds have passed.
* It uses a modal dialog.
*/
/*
function Pause(numberMillis) {

        var dialogScript =
           'window.setTimeout(' +
           ' function () { window.close(); }, ' + numberMillis + ');';
        var result =
// For IE5.
         window.showModalDialog(
           'javascript:document.writeln(' +
            '"<script>' + dialogScript + '<' + '/script>")');

// For NN6, but it requires a trusted script.
//         openDialog(
//           'javascript:document.writeln(' +
//            '"<script>' + dialogScript + '<' + '/script>"',
//           'pauseDialog', 'modal=1,width=10,height=10');

}
*/
