/*
  TItulo: util.js
  DescripciOn: Utilidades genericas.
  Copyright: Copyright (c) 2005
  Empresa: CSD-Systems
  Autor: Jose Manuel Gomez Monton
  Adaptacion: Carmen Aloy Toras
  Adaptacion: Ernesto Calás Blasco
  version 1.0
*/


/**
 * Funcion para precarga de imagenes.
 */
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


/**
 * Funcion para precarga de imagenes.
 */
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}


/**
 * Funcion para precarga de imagenes.
 */
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}


/**
 * Funcion para precarga de imagenes.
 */
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


/**
 * Abre un nueva ventana.
 */
function nuevaVentana(url, w, h, resizable){
  var winl = (screen.width - w) / 2;
  var wint = -25 + (screen.height - h) / 2;

  if (resizable){
    resizable = 'yes';
  }
  else{
    resizable = 'no';
  }

  if (screen.width > 900 || w <= 700){
      propiedades = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=no, menubar=no, resizable=' + resizable + ', toolbar=no, location=no, status=no';
        return window.open(url, '', propiedades);
    }
    else {
        //Estamos en 800x600 --> Maximizamos la ventana y ponemos scrollbars!
      propiedades = ' scrollbars=yes, menubar=no, resizable=yes, toolbar=no, location=no, status=no';
        laventana=window.open(url, '',propiedades);
        laventana.moveTo(0,0);

        if (document.all){
            laventana.resizeTo(screen.availWidth,screen.availHeight);
        }
        else if (document.layers||document.getElementById){
            if (laventana.outerHeight<screen.availHeight||laventana.outerWidth<screen.availWidth){
                laventana.outerHeight = screen.availHeight;
                laventana.outerWidth = screen.availWidth;
            }
        }

        return laventana;
    }
}


/**
 *  Devuelve la fecha con formato dd-aa-yyyy
 */
function fecha(){
  var time=new Date();
  var anyo=time.getMonth() + 1;
  document.write(time.getDate()+"-"+anyo+"-"+time.getFullYear());
}


/**
 * Comprueba si han habido cambios en la pantalla.
 */
function checkCambios(jsAceptar) {
  if (cambios){
    nuevaVentana('/condominios/jsp/confirmacion.jsp?txt=Han habido cambios %BF Desea salir sin guardar ?&jsAceptar=window.opener.' + escape(jsAceptar) + ';window.close();&jsCancelar=cerrar()', 350, 120);
  }
  else{
    eval(jsAceptar);
  }
}


/**
 * Comprueba si han habido cambios en la pantalla para el boton de nuevo y consultar con refresco.
 */
function checkCambiosRefresco(miurl) {
  if (cambios){
    var salir=confirm("Han habido cambios. ¿Desea salir sin guardar?");
    if (salir){
      window.location.href=miurl;
    }
  }else{
    window.location=miurl;
  }
}


function refrescar(miurl){
  window.opener.location.href=miurl;
}
/**
 *  Boton "Salir".
 */
function salir(){
  nuevaVentana('/condominios/jsp/confirmacion.jsp?txt=%BF Realmente desea salir de la aplicaci%F3n ?&jsAceptar=salirAplicacion()&jsCancelar=cerrar()', 325, 120);
}


/**
 *  Sale de la aplicacion cerrando todas las ventanas de la misma
 */
function salirAplicacion(){
  window.opener.close();
  window.close();
}


/**
 * Va la pagina anterior
 */
function atras(history){
  if (history == null || history == '') history = -1;
  checkCambios('history.go(' + history + ')');
}


/**
 *  Cierra la ventana
 */
function cerrar(){
  close();
  return false;
}


/**
 *  Chekea todos los checkbox de un campo.
 */
function checkAll(field) {
  var array = getArray(field);

  for (i = 0; i < array.length; i++) {
    array[i].checked = true ;
  }
}


/**
 *  Des-Chekea todos los checkbox de un campo.
 */
function uncheckAll(field) {
  var array = getArray(field);

  for (i = 0; i < array.length; i++){
    array[i].checked = false ;
  }
}


/**
 *  Si el campo es un array no hace nada, sino, crea un nuevo array con el campo.
 */
function getArray(field) {
  if (field.length != null) {
    return field;
  }
  else {
    var array = new Array(1);
    array[0] = field;
    return array;
  }
}


/**
 *  Valida el campo de hora que se le pasa.
 */
function validaHora(campoHora) {
  var arr_time = campoHora.value.split(':');

  if (!isInteger(arr_time[0]) || arr_time[0] > 23 || !isInteger(arr_time[1]) || arr_time[1] > 59){
    campoHora.focus();
    alert('Formato de hora inválido (HH:MM)');
    return false;
  }

  if (arr_time[0].length < 2){
    campoHora.value = '0' + arr_time[0] + ':' + arr_time[1];
    arr_time = campoHora.value.split(':');
  }

  if (arr_time[1].length < 2){
    campoHora.value = arr_time[0] + ':0' + arr_time[1];
  }

  return true;
}


/**
 * Copia una columna de una tabla.
 */
function copyRow(tabla, row, id, hmValores) {
  var cells = row.cells;
  var fila = tabla.insertRow(-1);
  if (id == null) id = "new" + new Date().getTime();
  if (hmValores == null) hmValores = "valor";
  fila.id = id;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];
    var col = fila.insertCell(i);
    col.width = cell.width;
    col.align = cell.align;
    col.vAlign = cell.vAlign;
    col.className = cell.className;
    col.colSpan = cell.colSpan;
    var html = cell.innerHTML;
    html = html.replace(new RegExp(hmValores + "\\(" + row.id, "g"), hmValores + '(' + id);
    col.innerHTML = html;
  }

  limpiaRow(id);

  return id;
}
/**
 * Copia una columna de una tabla.
 */
function copyRow2(tabla, row, id, hmValores) {
  var cells = row.cells;
  var fila = tabla.insertRow(-1);
        if (id == null) id = "new" + new Date().getTime();
        if (hmValores == null) hmValores = "valor";
  fila.id = id;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];
    var col = fila.insertCell(i);
    col.width = cell.width;
    col.align = cell.align;
    col.vAlign = cell.vAlign;
    col.className = cell.className;
    col.colSpan = cell.colSpan;
    var html = cell.innerHTML;
    html = html.replace(new RegExp(hmValores + "\\(" + row.id, "g"), hmValores + '(' + id);
    col.innerHTML = html;
  }


  limpiaRow2(id);
  return id;
}

/**
 * Copia una columna de una tabla.
 */
function copyRowPub(tabla, row, id, hmValores) {

  var cells = row.cells;
  var fila = tabla.insertRow(-1);
        if (id == null) id = "new" + new Date().getTime();
        if (hmValores == null) hmValores = "valor";
  fila.id = id;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];
    var col = fila.insertCell(i);
    col.width = cell.width;
    col.align = cell.align;
    col.vAlign = cell.vAlign;
    col.className = cell.className;
    col.colSpan = cell.colSpan;
    var html = cell.innerHTML;
    html = html.replace(new RegExp(hmValores + "\\(" + row.id, "g"), hmValores + '(' + id);
    col.innerHTML = html;
  }

  limpiaRowPub(id);

  return id;
}
/**
 * Limpia los valores de una columna copiada.
 */
function limpiaRowPub(id){
  var maxim=0;
  var uno=1;
  for (i = 0; i < document.forms[0].elements.length; i++) {
    var campo = document.forms[0].elements[i];
          if ((campo.name.indexOf('$orden_firma') != -1 ) && campo.value!="" && isNumber(campo.value)){
                  if (campo.value>=maxim){
                          maxim=campo.value;
      }
    }
  }
  maxim=parseInt(maxim)+parseInt(uno);

  var row = document.getElementById(id);

  var cells = row.cells;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];

    for (j=0; j < cell.childNodes.length; j++){
      var child = cell.childNodes[j];

      if (child.type == "text"){

        if (child.name.indexOf('$orden_firma')!= -1){
                 child.value = maxim;
        }else{
                 child.value = "";
              }
      }
      if (child.type == "select-one") child.selectedIndex = 0;
    }
  }
}

/**
 * Copia una columna de una tabla.
 */
function copyRowPubIni(tabla, row, id, hmValores) {

  var cells = row.cells;
  var fila = tabla.insertRow(-1);
        if (id == null) id = "new" + new Date().getTime();
        if (hmValores == null) hmValores = "valor";
  fila.id = id;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];
    var col = fila.insertCell(i);
    col.width = cell.width;
    col.align = cell.align;
    col.vAlign = cell.vAlign;
    col.className = cell.className;
    col.colSpan = cell.colSpan;
    var html = cell.innerHTML;
    html = html.replace(new RegExp(hmValores + "\\(" + row.id, "g"), hmValores + '(' + id);
    col.innerHTML = html;
  }

  limpiaRowPubIni(id);

  return id;
}
/**
 * Limpia los valores de una columna copiada.
 */
function limpiaRowPubIni(id){
  var row = document.getElementById(id);

  var cells = row.cells;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];

    for (j=0; j < cell.childNodes.length; j++){
      var child = cell.childNodes[j];

      if (child.type == "text"){
        child.value="";
      }
      if (child.type == "select-one") child.selectedIndex = 0;
    }
  }
}


/**
 * Limpia los valores de una columna copiada.
 */
function limpiaRow(id){

  var row = document.getElementById(id);

  var cells = row.cells;

  for (i = 0; i < cells.length; i++){
    var cell = cells[i];

    for (j=0; j < cell.childNodes.length; j++){
      var child = cell.childNodes[j];
      if (child.type == "text") child.value = "";
      if (child.type == "select-one") child.selectedIndex = 0;
      if(child.type == "textarea") child.value="";

    }
  }
}


/**
 * Limpia los valores de una columna copiada.
 */
function limpiaRow2(id){

  var row = document.getElementById(id);
  if (row!=null){
    var celdas0 = row.cells[1].childNodes;


    var celdas1 = celdas0[0].childNodes;

    if (celdas1.length >0){
      var celdas2 = celdas1[0].childNodes;

      if (celdas2.length>0){
        var celdas = celdas2[0].childNodes;

        for (k=0; k < celdas2.length; k++){

          var celdas = celdas2[k].childNodes;
          for (i = 0; i < celdas.length; i++){
             var celda = celdas[i];

             for (j=0; j < celda.childNodes.length; j++){
               var child = celda.childNodes[j];
               if (child.type == "text") child.value = "";
               if (child.type == "select-one") child.selectedIndex = 0;
            }
          }
        }
      }
    }
  }
}


/**
 * Establece los valores de un campo LOV.
 */

function setValorLOV(id, valor, ded_ensayos, ded_proyectos){

  opener.document.lovCampoId.value = id;
  opener.document.lovCampoTxt.value = valor;
  cerrar();
}

/**
 * Limpia los campos de un formulario.
 */
function limpiaForm(form){

  if (form!=null){
    for (i = 0; i < form.elements.length; i++) {
      var campo = form.elements[i];
      if (campo.type == "text") campo.value = "";
      if (campo.type == "hidden" && campo.name!="op" && campo.name!="history") campo.value = "";
      if (campo.type == "select-one") campo.selectedIndex = 0;
      if (campo.type == "radio") {
        if (campo.value == "") campo.checked=true;
      }
    }
  }
  else {
    for (i = 0; i < document.forms[0].elements.length; i++) {
      var campo = document.forms[0].elements[i];
      if (campo.type == "text") campo.value = "";
      if (campo.type == "hidden" && campo.name!="op" && campo.name!="history") campo.value = "";
      if (campo.type == "select-one") campo.selectedIndex = 0;
      if (campo.type == "radio") {
        if (campo.value == "") campo.checked=true;
      }
    }
  }
}


/**
 * Busca un elemento en una lista, si esta devuelve su posicion, sino devuelve -1
 */
function buscarItem(lista, valor){
  var ind, pos;
  for(ind=0; ind<lista.length; ind++){
    if (lista[ind] == valor)
      break;
  }
  pos = (ind < lista.length)? ind : -1;
  return (pos);
}

/**
 * Busca el numero de repeticiones de un elemento en una lista
 */
function buscarRepeticionesItem(lista, valor){
  var ind;
  var veces=0;
  for(ind=0; ind<lista.length; ind++){
    if (lista[ind] == valor)
      veces=veces+1;
  }
  return (veces);
}

//--Funciones para la ayuda--

function activarAyuda() {

 var test;
 test = document.getElementById("ayuda").value

        if (test=="off"){
        document.getElementById("divAyuda").style.visibility = "visible";
        document.getElementById("ayuda").value="on";
        }
        if (test=="on"){
        document.getElementById("divAyuda").style.visibility = "hidden";
        document.getElementById("ayuda").value="off";
        }
 }

function alertaAyuda(valor) {

  var help = document.getElementById("ayuda").value;
  if (help=="on") {

    //botones comunes
     if (valor == "verCasas"){
            document.getElementById("textoAyuda").value="Muestra las casas pertenecientes al condominio.";
     }
     if (valor == "verDocumentos"){
            document.getElementById("textoAyuda").value="Muestra los documentos relacionados con el condominio.";
     }
     if (valor == "botonNuevo"){
            document.getElementById("textoAyuda").value="Añade una nueva linea de formulario para insertar la información deseada.";
     }
     if (valor == "botonGuardar"){
            document.getElementById("textoAyuda").value="Guarda/actualiza los cambios en la base de datos.";
     }
     if (valor == "campoBusqueda"){
            document.getElementById("textoAyuda").value="Campo para especificar el filtro de busqueda ";
     }
     if (valor == "botonBusqueda"){
            document.getElementById("textoAyuda").value="Ejecuta la busqueda en función de los filtros especificados.";
     }
     if (valor == "botonBorrar"){
            document.getElementById("textoAyuda").value="Elimina la fila asociada a dicho boton. Para borrar definitivamente hay que darle a guardar.";
     }

     if (valor == "ordenar"){
              document.getElementById("textoAyuda").value="Ordena la información basandose en el campo pulsado";
     }

     //areasCentros.jsp
     if (valor == "areaCentroCodigoArea") {
       document.getElementById("textoAyuda").value="Código asociado al área";
     }
     if (valor == "areaCentroTextoArea") {
       document.getElementById("textoAyuda").value="Descripción del área";
     }

     //areasCentrosServicios.jsp

     if (valor == "areaCentroServiciosDesplegable") {
       document.getElementById("textoAyuda").value="Seleccione un área centro para realizar el filtrado por medio del desplegable";
     }
     if (valor == "areaCentroServiciosCodigo") {
       document.getElementById("textoAyuda").value="Código asociado al servicio";
     }
      if (valor == "areaCentroServiciosDescripcion") {
       document.getElementById("textoAyuda").value="Descripción del servicio";
     }
      if (valor == "areaCentroServiciosArea") {
       document.getElementById("textoAyuda").value="Área que sera asignada al servicio a traves del desplegable";
     }
      if (valor == "areaCentroServiciosBorrar") {
       document.getElementById("textoAyuda").value="Borra el servicio asociado";
     }

     //areasTematicas.jsp

      if (valor == "areaTematicaCodigo") {
       document.getElementById("textoAyuda").value="Código del área tematica";
     }
      if (valor == "areaTematicaDescripcion") {
       document.getElementById("textoAyuda").value="Descripción del área tematica";
     }

     //categoriasProfesionales.jsp
      if (valor == "categoriasProfesionalesCodigo") {
       document.getElementById("textoAyuda").value="Código asociado a la categoria profesional";
     }
      if (valor == "categoriasProfesionalesDescripcion") {
       document.getElementById("textoAyuda").value="Descripción de la categoria profesional";
     }

     //codigoUnesco.jsp
     if (valor == "codigoUnescoDescripcion"){
            document.getElementById("textoAyuda").value="Descripcion asociada al codigo Unesco";
     }

     //departamentosSalud
      if (valor == "departamentosSaludCodigo"){
            document.getElementById("textoAyuda").value="Código asociado al departamento";
     }
      if (valor == "departamentosSaludDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del departamento";
     }

     //entidadesFinanciadoras
     if (valor == "entidadesFinanciadorasTipoEntidad"){
            document.getElementById("textoAyuda").value="Seleccione mediante el desplegable el tipo de entidad";
     }
     if (valor == "entidadesFinanciadorasDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de entidad";
     }
     if (valor == "entidadesFinanciadorasCodigo"){
            document.getElementById("textoAyuda").value="Código de la entidad financiadora";
     }
     if (valor == "entidadesFinanciadorasDesplegable"){
            document.getElementById("textoAyuda").value="Seleccione el tipo de entidad para realizar el filtrado";
     }

     //idiomas
      if (valor == "idiomasDescripcion"){
            document.getElementById("textoAyuda").value="Nombre del Idioma asociado al código";
     }
     if (valor == "idiomasCodigo"){
            document.getElementById("textoAyuda").value="Código del idioma especificado";
     }

     //pais
     if (valor == "paisCodigo"){
            document.getElementById("textoAyuda").value="Código del pais especificado";
     }
      if (valor == "paisDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del país especificado";
     }

     //provincia
      if (valor == "provinciaCodigo"){
            document.getElementById("textoAyuda").value="Código de la provincia especificada";
     }
      if (valor == "provinciaDescripcion"){
            document.getElementById("textoAyuda").value="Descripción de la provincia especificado";
     }

     //regimenesJuridicos
     if (valor == "regimenesJuridicosCodigo"){
            document.getElementById("textoAyuda").value="Código del régimen jurídico especificado";
     }
     if (valor == "regimenesJuridicosDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del régimen jurídico especificado";
     }

     //situacionAdministrativa
     if (valor == "situacionAdministrativaCodigo"){
            document.getElementById("textoAyuda").value="Código de la situación administrativa especificada";
     }
     if (valor == "situacionAdministrativaDescripcion"){
            document.getElementById("textoAyuda").value="Descripción de la situación administrativa especificada";
     }

     //tipoActividad
      if (valor == "tipoActividadCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de actividad especificada";
     }
      if (valor == "tipoActividadDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de actividad especificada";
     }

     //tipoCentro
      if (valor == "tipoCentroCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de centro especificado";
     }
      if (valor == "tipoCentroDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de centro especificado";
     }

     //tipoEnsayosClinicos
      if (valor == "tipoEnsayosClinicosCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de ensayo clínico especificado";
     }
      if (valor == "tipoEnsayosClinicosDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de ensayo clínico especificado";
     }

     //tipoEntidades
     if (valor == "tipoEntidadesCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de entidad especificada";
     }
     if (valor == "tipoEntidadesDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de entidad especificada";
     }

     //tipoEstudios
     if (valor == "tipoEstudiosCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de estudios especificados";
     }
      if (valor == "tipoEstudiosDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de estudios especificados";
     }

     //tipoEventos
     if (valor == "tipoEventosCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de evento especificado";
     }
     if (valor == "tipoEventosDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de evento especificado";
     }

     //tipoFinanciacion
     if (valor == "tipoFinanciacionCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de financiacion especificado";
     }
     if (valor == "tipoFinanciacionDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de financiacion especificado";
     }

     //tipoParticipacionesCongreso
     if (valor == "tipoParticipacionesCongresoCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de Participacion en congreso especificada";
     }
     if (valor == "tipoParticipacionesCongresoDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de Participacion en congreso especificada";
     }

     //tipoRelaciones
     if (valor == "tipoRelacionesCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de relación especificada";
     }
     if (valor == "tipoRelacionesDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de relación especificada";
     }

     //tipoRevistas
     if (valor == "tipoRevistasCodigo"){
            document.getElementById("textoAyuda").value="Código del tipo de revista especificada";
     }
     if (valor == "tipoRevistasDescripcion"){
            document.getElementById("textoAyuda").value="Descripción del tipo de revista especificada";
     }

     //titulaciones
     if (valor == "titulacionesCodigo"){
            document.getElementById("textoAyuda").value="Código de la titulación especificada";
     }
     if (valor == "titulacionesDescripcion"){
            document.getElementById("textoAyuda").value="Descripción de la titulación especificada";
     }

     //revistas
     if (valor == "revistasCodigo"){
            document.getElementById("textoAyuda").value="Código de la revista especificada";
     }
     if (valor == "revistasNombre"){
            document.getElementById("textoAyuda").value="Nombre de la revista especificada";
     }
     if (valor == "revistasTipo"){
            document.getElementById("textoAyuda").value="Tipo de revista especificada";
     }
  }
}

/*
  Funcion para el cambio de idioma
*/
function cambioIdioma(idioma){
  var direccion=location.href;
  var primeridioma=direccion.indexOf("idioma");
  primeridioma=primeridioma+7 //indice de donde pone castellano o inglés
  if (primeridioma==6)//-1+7=6
  {//No se ha puesto ningun idioma
    if(direccion.indexOf("?")==-1)
    {//No hay ningun interrogante
       window.location=location.href+"?idioma="+idioma;
    }else
    {//Ya hay algun parametro
       window.location=location.href+"&idioma="+idioma;
    }
  }else
  {//Cambiamos donde pone el idioma
   //Si el idioma estuviera delante de otro parametro no funcionaria
   //En principio simpre está lo ultimo
     direccion=direccion.substr(0,primeridioma)
     window.location=direccion+idioma;
  }
}

/*
  Funcion que hace un submit del formaulario colocando el idioma
*/
function submitpagina(idioma){
  document.forms[0].st_idioma.value=idioma;
  document.forms[0].submit();
}
/*
   Funcion para quitar espacios de un valor
*/
function Trim(TRIM_VALUE){
  if(TRIM_VALUE.length < 1){
    return "";
  }
  TRIM_VALUE = RTrim(TRIM_VALUE);
  TRIM_VALUE = LTrim(TRIM_VALUE);
  if(TRIM_VALUE==""){
    return "";
  }
  else{
    return TRIM_VALUE;
  }
} //End Function

/*
   Funcion para quitar espacios de un valor por la derecha
*/
function RTrim(VALUE){
  var w_space = String.fromCharCode(32);
  var v_length = VALUE.length;
  var strTemp = "";
  if(v_length < 0){
    return"";
  }
  var iTemp = v_length -1;

  while(iTemp > -1){
    if(VALUE.charAt(iTemp) == w_space){
    }
    else{
      strTemp = VALUE.substring(0,iTemp +1);
      break;
    }
    iTemp = iTemp-1;
  } //End While
  return strTemp;
} //End Function

/*
   Funcion para quitar espacios de un valor por la derecha
*/
function LTrim(VALUE){
  var w_space = String.fromCharCode(32);
  if(v_length < 1){
    return"";
  }
  var v_length = VALUE.length;
  var strTemp = "";

  var iTemp = 0;

  while(iTemp < v_length){
    if(VALUE.charAt(iTemp) == w_space){
    }
    else{
      strTemp = VALUE.substring(iTemp,v_length);
      break;
    }
    iTemp = iTemp + 1;
  } //End While
  return strTemp;
} //End Function


/*
   Funcion para comprobar si valor es numérico
*/
function IsNumeric(valor)
{
  var log=valor.length; var sw="S";
  for (x=0; x<log; x++)
  {
    v1=valor.substr(x,1);
    v2 = parseInt(v1);
    //Compruebo si es un valor numérico
    if (isNaN(v2)) {
      sw= "N";
    }
  }
  if (sw=="S") {
    return true;
  }
  else {
    return false;
  }
}

//variables para formateaFecha y formateaHora
var primerslap=false;
var segundoslap=false;

/*
   Funcion para validar el formatio de fecha
   Ejemplo llamada a función:
   <input type="text" name="f_hasta" id="campo_fecha2" size="12" maxlength="12" onKeyUp = "this.value=formateafecha(this.value);" class="input">
*/
function formateafecha(fecha)
{
  var longi = fecha.length;
  var dia;
  var mes;
  var ano;

  if ((longi>=2) && (primerslap==false)) {
    dia=fecha.substr(0,2);
    if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) { fecha=fecha.substr(0,2)+"/"+fecha.substr(3,7); primerslap=true; }
    else { fecha=""; primerslap=false;}
  }
  else
  {
    dia=fecha.substr(0,1);
    if (IsNumeric(dia)==false)
    {
      fecha="";
    }
    if ((longi<=2) && (primerslap=true)) {
      fecha=fecha.substr(0,1); primerslap=false;
    }
  }
  if ((longi>=5) && (segundoslap==false))
  {
    mes=fecha.substr(3,2);
    if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) { fecha=fecha.substr(0,5)+"/"+fecha.substr(6,4); segundoslap=true; }
    else { fecha=fecha.substr(0,3);; segundoslap=false;}
  }
  else { if ((longi<=5) && (segundoslap=true)) { fecha=fecha.substr(0,4); segundoslap=false; } }
  if (longi>=7)
  {
    ano=fecha.substr(6,4);
    if (IsNumeric(ano)==false) { fecha=fecha.substr(0,6); }
    else { if (longi==10){ if ((ano==0) || (ano<1900) || (ano>2100)) { fecha=fecha.substr(0,6); } } }
  }

  if (longi>=10)
  {
    fecha=fecha.substr(0,10);
    dia=fecha.substr(0,2);
    mes=fecha.substr(3,2);
    ano=fecha.substr(6,4);
    // Año no viciesto y es febrero y el dia es mayor a 28
    if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { fecha=fecha.substr(0,2)+"/"; }
  }
  return (fecha);
}

/*
   Funcion para validar formato de hora
*/
function formateahora(hora)
{
  var longi = hora.length;
  var hh;
  var mm;

  if ((longi>=2) && (primerslap==false)) {
    hh=hora.substr(0,2);
    if ((IsNumeric(hh)==true) && (hh<=23)) { hora=hora.substr(0,2)+":"+hora.substr(3,4); primerslap=true; }
    else { hora=""; primerslap=false;}
  }
  else {
    hh=hora.substr(0,1);
    if (IsNumeric(hh)==false) {hora="";}
    if ((longi<=2) && (primerslap=true)) {hora=hora.substr(0,1); primerslap=false; }
  }
  if ((longi>=5) && (segundoslap==false)) {
    mm=hora.substr(3,2);
    if ((IsNumeric(mm)==true) &&(mm<=59)) { hora=hora.substr(0,5); segundoslap=true; }
    else { hora=hora.substr(0,3);; segundoslap=false;}
  }
  else {
    if ((longi<=5) && (segundoslap=true)) { hora=hora.substr(0,4); segundoslap=false; }
  }
  return (hora);
}


/*
   Funcion para validar formato numérico decimal
   var entero  --> numero de dígitos permitidos para la parte entera
                   (si se pasa -1 no valida el número de dígitos enteros)
   var decimal --> numero de dígitos permitidos para la parte decimal
                   (si se pasa -1 no valida el número de decimales)
   ejemplo de llamada: onkeyup="cambios=true;this.value=validarFormatoNumerico(this.value, 4, -1);"
*/
function validarFormatoNumerico(numero, entero, decimal)
{
  var longi = numero.length;
  var x;
  var pos = -1;//posición de la coma si existe
  var encontrado = false;

  //se busca la posición de la coma
  for (x=0; x<longi; x++)
  {
    v1 = numero.substr(x,1);
    //alert(v1);
    if (v1 == '.'){
      pos = x;
      encontrado = true;
      //alert('. en la posicion '+pos);
    }
  }
  //----- SI EXISTE COMA
  if (encontrado == true){
    //se valida la parte entera
    var parteEntera = numero.substr(0,pos);
    if ((IsNumeric(parteEntera)==false)){
      alert ("Se debe poner valor numérico")
      numero = "";
    }
    else{
      if (parteEntera.length > entero  && entero!=-1){
        alert("No pueden haber más de "+entero+" dígitos enteros");
        numero = "";
      }
    }
    //se valida la parte decimal
    var parteDecimal = numero.substr(pos+1, longi);
    if ((IsNumeric(parteDecimal)==false)){
      alert ("Se debe poner valor numérico")
      numero = "";
    }
    else {
      if (parteDecimal.length > decimal  && decimal!=-1) {
        alert("No pueden haber más de "+decimal+" dígitos decimales");
        numero = "";
      }
    }
    //si en el número solo se pone una '.'
    if (longi == 1) {
      alert ("Se debe poner valor numérico '.'")
      numero = "";
    }
  }
  //----- NO EXISTE COMA
  else{
    if ((IsNumeric(numero))==true){
      if (longi > entero  && entero!=-1){
        alert("No pueden haber más de "+entero+" dígitos enteros");
        numero = "";
      }
    }
    else {
      alert ("Se debe poner valor numérico")
      numero = "";
    }
  }

  return numero;
}

