
/**
 * Clase que contiene utilidades 
 * varias
 */
function JUtil() {}
JUtil.IE  = 1001;
JUtil.MOZ = 1002;
JUtil.getNav = function() {
    var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1;
    var isMoz = document.implementation && document.implementation.createDocument;
    if ( isIE ) return this.IE;
    if ( isMoz) return this.MOZ;
}

/**
 * Redondea y formatea un número en base
 * a la precisión
 * @param   (double)    value        Número a formatear 
 * @param   (int)       precision    Número de decimales 
 */
Math.roundOFF = function (value, precision) {
    value = "" + value //convert value to string
    precision = parseInt(precision);
    var whole = "" + Math.round(value * Math.pow(10, precision));
    if ( precision == 0) return whole;
    var decPoint = whole.length - precision;

    if(decPoint != 0) {
        result = whole.substring(0, decPoint);
		result += ",";
        result += whole.substring(decPoint, whole.length);
		if (result==",0") result="0,00";
    } else {
        result = "0,"+whole;
    }
    return result;
}


// Funciones de cadena
String.digito            = "0123456789";
String.puntoDecimal      = ".,";
String.caracterMayuscula = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String.caracterMinuscula = "abcdefghijklmnopqrstuvwxyz";
String.caracer           = String.caracterMayuscula + String.caracterMinuscula;
String.alfaNumerico      = String.digito+String.caracterMayuscula+String.caracterMinuscula;
String.signos            = "_-."; 
String.arroba            = "@";
String.cadenaValida      = String.alfaNumerico+String.signos+String.arroba;

/**
 * Valida una cadena
 * @param (String) mascara Secuencia de carácteres de filtro
 * @param (String) cadena  Cadena que se quiere validar
 * @return (bool) true si la cadena es válida, false en caso contrario
 */
String.validarCadena = function (mascara,cadena) {
    if (cadena.length==0) return false;
    for(i=0;i<cadena.length;i++) {
        if (mascara.indexOf(cadena.charAt(i))==-1) return false;
    }
    return true;
}



/**
 * Limpia todos los ceros a la izquierda de una 
 * cadena
 * @return (String) Cadena sin ceros a la izquierda
 */
String.prototype.limpiaCeros = function() {
    temp="";
    numeros=0;
    for(i=0;i<this.length;i++) {
        if ( this.charAt(i)!="0" || numeros>0) {  
           temp+=this.charAt(i);
           numeros++;
        } 
    }
    return temp;
}

String.prototype.mascara = function(mask, align) {
	var i;
	var cadena = "";
    if( align == "right" ) {
       for(i=0;i<mask.length - this.length;i++) {
           cadena += mask.charAt(i);
       }
       cadena+=this;
    }
    return cadena;
}


/**
 * Valida si una cadena tiene un formato correcto de email
 * @param (String)  cadena  Cadena de texto a validar
 * @return (boolean) True si tiene un formato válido , false en caso contrario
 */
String.prototype.esMail = function() {

    if(!String.validarCadena(this,String.arroba)) return false;
	
	parte = this.split("@");
	aaaa=parte[0];
		
	ultimoPunto = parte[1].lastIndexOf(".");	
	if (ultimoPunto==-1) return false;
	
	bbbb=parte[1].slice(0,ultimoPunto);
	
	if (bbbb.length<2)
		{error='bbbb no puede ser menor que 2';return false;}
	
	if (!String.validarCadena(String.alfaNumerico+String.signos,aaaa+bbbb)) return false;
	

	cc=parte[1].slice(ultimoPunto+1);


	if (cc.length<2 || cc.length>4) return false;
	if (!String.validarCadena(String.caracterMayuscula+String.caracterMinuscula,cc)) return false;
	
	return true;
}

/*-----------------------------------------------------------------------------------*/

/**
 * Objeto que controla las pilas globales
 * @return (void)
 */
function JPile() {
    // Propiedades
    this.arrRefObjects = Array();
    this.arrRefDialogs = Array();
    
    // Métodos
    this.addRefObject  = JPileAddRefObject;
    this.getRefObject  = JPileGetRefObject;
    this.addDialog     = JPileAddDialog;
    this.getDialog     = JPileGetDialog;
    this.popDialog     = JPilePopDialog;
}

/**
 * Añade un nuevo dialogo a la pila
 */
function JPileAddDialog(obj) {
    this.arrRefDialogs.push(obj);
}

function JPileGetDialog() {
    if ( this.arrRefDialogs.length == 0 ) return null;
    return this.arrRefDialogs[ this.arrRefDialogs.length -1 ];
}

function JPilePopDialog() {
    this.arrRefDialogs.pop();
}


/**
 * Funcion que controla los objetos asignados
 * a elementos HTML
 * @param  (Object) Objeto que se quiere añadir
 * @return (int) Identificador al objeto añadido
 */
function JPileAddRefObject( obj ) {
    id = this.arrRefObjects.length;
    this.arrRefObjects[id] = obj;
    return id;
}
 
/**
 * Recupera la referencia del objeto
 * @param (int) Identificador asignado del objeto
 * @return (Object) Objeto indicado o undefined si no se encuentra
 */
function JPileGetRefObject(id) {
    if ( this.arrRefObjects[id] ) return this.arrRefObjects[id];
    return undefined;
}

// Instancia del objeto para poder utilizar sus propiedades
jPile = new JPile();

/*-------------------------------------------------------------------------------------------------*/

/** 
 * Objeto para controlar
 * el funcionamiento de un formulario
 */
function JForm( form ) {

    // Propiedades
    this.form      = form;
    this.arrInputs = Array();
    this.arrCalcul = Array();
    this.mensaje   = "";
    this.action    = form.getAttribute("action");
    this.method    = form.getAttribute("method")? form.getAttribute("method") : "POST" ;
    this.target    = form.getAttribute("target")? form.getAttribute("target") : "_self";
    
    // Metodos
    this.addInput       = JFormAddInput;
    this.validar        = JFormValidar;
    this.submit         = JFormSubmit;
    this.ejecutarAccion = JFormEjecutarAccion;
    this.getInput       = JFormGetInput;
    this.captureInputs  = JFormCaptureInputs
    
    // Captura de los inputs
    this.captureInputs();
    
}

/**
 * Captura automática de los inputs del formulario
 * @return (void)
 */
function JFormCaptureInputs() {
    var inp;
    var type;
    var sub;
    var jInp;
    elements = Array();
    for(i=0;i<this.form.elements.length;i++) {
        elements[i] = this.form.elements[i];
    }
    
    
    for(i=0;i<elements.length;i++) {
        inp = elements[i];
        if ( inp.getAttribute("auto")=='1') continue;
        type = inp.type;
        sub  = inp.getAttribute("subType");
        
        if ( sub ) type = sub;

        // Comprobación del tipo
        switch(type) {
            case "text":
                jInp = new JInput(inp,this);
                this.addInput(jInp);
            case "hidden":
            break;
            case "fecha":
                jInp = new JInputFecha(inp,this);
                this.addInput(jInp);
            break;
            case "fecha":
                jInp = new JInputFecha(inp,this);
                this.addInput(jInp);
            break;       
            case "fechahora":
                jInp = new JInputFecha(inp,this,true);
                this.addInput(jInp);
            break;       
                 
            case "imagen":
                jInp = new JInputImage(inp,this);
                this.addInput(jInp);
            break;
            case "link":
                jInp = new JInputLink(inp,this);
                this.addInput(jInp);
            break;
            case "select-one":
                jInp = new JInput(inp,this);
                this.addInput(jInp);
            break;
            case "textarea":
                jInp = new JInput(inp,this);
                this.addInput(jInp);
            break;
            case "checkbox":
            	jInp = new JInputCheckBox(inp,this);
                this.addInput(jInp);
            break;
        }
    }   
}

/**
 * Recupera un imput a partir de su nombre
 * @param   (String)    nombre  Nombre del input
 * @return  (JInput)    Objeto JInput o null si no lo encuentra
 */
function JFormGetInput(nombre) {
    var i;
    for(i=0;i<this.arrInputs.length;i++) {
         if ( this.arrInputs[i].name == nombre ) {
             return this.arrInputs[i];
         }
    }
    return null;
}

/**
 * Hace un submit del formulario con la acción 
 * indicada
 * @param   (String)  accion   Acción a realizar
 * @mensaje (String)  mensaje  (Opcional) Mensaje de confirmación para el usuario
 * @validar (boolean) validar  (Opcional) Indica si se ha de validar el formulario antes de enviarlo
 */
function JFormEjecutarAccion( accion , mensaje, validar) {
    var accionObj;
    if ( mensaje ) { que = confirm(mensaje); if ( !que ) return; }
    accionObj = eval("document."+this.form.name+"."+this.form.name+"accion");
    if ( accionObj ) accionObj.value = this.form.name+accion;
    this.submit(validar);
}
     
/**
 * Añade un nuevo input al formulario
 * @param (JInput)   input   Objeto JInput 
 * @return (boolean) true si se consigue añadir el input , false en caso contrario
 */
function JFormAddInput( input ) {
    if( !input ) return false;
	input.form = this;
    this.arrInputs[ this.arrInputs.length ] = input;
    return true;
}

/**
 * Realiza el submit del formulario
 * @param   (boolean)   validar Indica si se debe validar el formulario antes de enviarlo
 */
function JFormSubmit(validar) {

    if  ( validar && !this.validar() ) {}
    else {

	   /* this.form.action = this.action;
	    this.form.method = this.method;
	    this.form.target = this.target;
	    */
	    this.form.submit();
    }
}

/**
 * Valida si los datos del formulario son correctos,
 * para ello recorre todos sus inputs y los valida 
 * uno por uno
 * @return (boolean) True si el formulario es válido, false en caso contrario
 */
function JFormValidar() {
    var result = true;
    var msg   = "";
    var firstInput = null;
    for(iInp=0;iInp<this.arrInputs.length;iInp++) {
        if ( !this.arrInputs[iInp].validar() ) {
            if ( firstInput == null ) firstInput = this.arrInputs[iInp];
            if ( this.arrInputs[iInp].log ) {
                msg += " - " + this.arrInputs[iInp].log + "\n";
                result = false;
            }
            
        }
    }   
    
    if ( !result ) {
    	alert("Se han encontrado los siguientes problemas\n\n" + msg);
    	firstInput.focus();
    }	
    
    return result;
}


/*---------------------------------------------------------------------------------------------------------*/

/**
 * Objeto para controlar el funcionamiento de un input
 * de tipo texto
 * @param (Object)  input   Objeto input
 * @param (String)  alias   Nombre identificativo del input
 * @param (String)  tipo    Tipo de input [texto,numerico,email]
 * @param (boolean) notNull Indica si puede contener nulos
 */
function JInput( input, form ) {
    
    // Captura de propiedades 
    this.input   = input;
    this.alias   = this.input.getAttribute("alias");
    this.tipo    = this.input.getAttribute("tipo");
    this.notNull = this.input.getAttribute("notNull")!=null? true : false;
    this.mensaje = this.input.getAttribute("mensaje");
    this.log     = "";
    this.form    = form;

    
    // Métodos
    this.validar  = JInputValidar;
    this.focus    = JInputFocus;
    
    // Asignación de eventos y estilos al input
    if ( !this.input.className && !this.input.onchange ) {
        this.input.onchange += JInputModificado;
    }
    
    if ( this.tipo == "numerico" ) {

        if ( this.input.addEventListener ) {
        
           this.input.setAttribute("onkeypress","return JInputNumericValidate(event);");
        } else {
           this.input.onkeypress = JInputNumericValidate; 
        }
        
        this.input.value = this.input.value.replace(/\./gi,",");
    }
}


function JInputFocus() {
	//if ( this.input.type != "textarea" ) 
	this.input.focus();
}

/**
 * Cambia el estilo cuando un input es modificado
 * @return (void)
 */
function JInputModificado() {
    this.className = "inputMod";
}

/**
 * Validación del input
 * @return (boolean) true si es válido, false en caso contrario
 */
function JInputValidar() {

    // Comprueba si acepta nulos
    if ( this.notNull ) {
      if ( this.input.value.length == 0 ) {
          if ( !this.mensaje ) this.log = "El campo " + this.alias + " no puede quedar vacio";
          else this.log = this.mensaje;
          //if ( this.input.type != "textarea") this.input.focus();
          return false;
      }
    }
      
    // Tipo númerico
    if ( this.notNull &&  this.tipo == "numerico" && this.input.value == 0) {
    
        if ( !this.mensaje ) this.log = "El campo " + this.alias + " no puede ser 0";
        else this.log = this.mensaje;
        //this.input.focus();
        return false;
    } 

    // Formateado del valor númerico
    if ( this.tipo == "numerico" ) {
        numcomas = 0;
        for(i=0;i < this.input.value.length;i++) {
            numcomas += (this.input.value.charAt(i) == ",") ? 1 : 0;
        }

        this.input.value = this.input.value.replace(/\./gi,"");
        this.input.value = this.input.value.replace(/,/gi,".");
        this.input.value = this.input.value.limpiaCeros();
        if ( this.input.value.length == 0 ) this.input.value = 0;
        if ( isNaN(this.input.value) ) {
            this.input.value = this.input.value.replace(/\./gi,",");
            if ( this.mensaje ) this.log = this.mensaje;
            else this.log = "El campo " + this.alias + " debe contener valores númericos";
            //this.input.focus();
            return false;
        }
    }

    // Tipo email
    if ( this.tipo == "email"  ) {
        
        if ( this.input.value.length > 0 && !this.input.value.esMail()) {
	        if ( this.mensaje ) this.log = this.mensaje;
	        else this.log = "El campo "+ this.alias +" no contiene un formato correcto válido";
	        //this.input.focus();
	        return false;
        }
    }
   
    return true;  
}

/**
 * Valida la pulsación de una tecla en un
 * imput numérico
 * @param   Event   e   Objeto Evento (solo en Netscape)
 */
function JInputNumericValidate(e) {

    if ( e ) {
        return JInputNumericValidateNS(e);
    } else {
        return JInputNumericValidateIE(event);
    }
}
/**
 * Valida la pulsación de una tecla en un
 * imput numérico
 * @param   Event   e   Objeto Evento (solo en Netscape)
 */
function JInputNumericValidateIE(event) {
    src    = event.srcElement;
    key    = event.keyCode;
    
    keyNom = String.fromCharCode(key);

    validos = "0123456789.,";
    if ( key == 46 ) {
       event.keyCode = 44;
    }
    
    if ( validos.search(keyNom)==-1 ) {
        msg = src.getAttribute("msgNum");
        
        if ( !msg ) alert("Este campo solo admite valores númericos");
        else alert(msg);
        event.keyCode = null;
        return;
    }
    return;
}

/**
 * Valida la pulsación de una tecla en un
 * imput numérico
 * @param   Event   e   Objeto Evento (solo en Netscape)
 */
function JInputNumericValidateNS(event) {
    src = event.target;
    key = event.charCode? event.charCode : event.keyCode;
    if ( key == 0 ||
         key == 9 ||
         key == 8 ||
         key == 37 ||
         key == 39 ||                  
         key == 46 ||                  
         key == 116
    ) {
            return true;
    }
    keyNom = String.fromCharCode(key);

    validos = "0123456789.,";
    if ( key == 46 ) {
        src.value += ",";
        return false;
    }
    
    if ( validos.search(keyNom)==-1 ) {
        msg = src.getAttribute("msgNum");
        if ( !msg ) alert("Este campo solo admite valores númericos");
        else alert(msg);
        return false;
    }
    return true;
}


/*--------------------------------------------------------------------------------------------------*/

/**
 * Objeto para controlar un Input de tipo
 * Select
 * @param (Object)  select  Objeto HTML select
 */
function JSelect(select) {
    // Propiedades
    this.select = select;
    this.textoInicial = this.select.getAttribute("textoIni");
    this.valorInicial = this.select.getAttribute("valorIni");
    
    // Métodos
    this.addValue    = JSelectAddValue;
    this.ini         = JSelectIni;
    this.setValue    = JSelectSetValue;
    this.addOpcion   = JSelectAddOpcion;
}    

/**
 * Añade una nueva opción al select
 * @param (String)  codigo    Código de la opcion
 * @param (String)  valor     Texto de la opción
 * @param (boolean) selected  Indica si esta opción estará seleccionada
 */
function JSelectAddValue(codigo,texto,selected) {
    selected = (selected) ? true : false;
    anadir(this.select, codigo, valor, selected);
}
    
/**
 * Inicializa los valores del select
 */
function JSelectIni() {
    this.select.length = 0;
    this.addValue(this.valorInicial,this.textoInicial,true);
}

/**
 * Selecciona un valor del select
 * @param (String)  codigo  Código de la opción 
 */
function JSelectSetValue(codigo) {
	for(i=0;i<(this.select.length);i++) {
        if (this.select.options[i].value==codigo)
                this.select.options[i].selected=true;
    }
}  

/**
 * Añade una nueva opción al select
 * @param   (String)    codigo      Código de la opción
 * @param   (String)    texto       Texto de la opción
 * @param   (boolean)   selected    Indica si esta seleccionada
 */
function addOpcion(codigo,texto,selected) {
    this.select.length++;
    this.select.options[this.select.length-1].text=texto;
    this.select.options[this.select.length-1].value=codigo;
    this.select.options[this.select.length-1].selected=selected;	
}

/*---------------------------------------------------------------------------------------------------------------------------*/


/**
 * Objeto que controla la selección de una fecha
 * @param (HTMLElement)     input   Elemento HTML que recogerá el valor
 */
function JDialogFecha(jInput) {
    // Propiedades
    this.ruta = "http://www.racodelpla.com/acceso_admin/funciones/calendar.php";    
    this.jInput = jInput;
    this.width  = 210;
    this.height = 200;
    this.value  = "";
    this.div    = null;
    
    // Métodos
    this.convFecha   = JDialogFechaConvFecha;   
    this.Show        = JDialogFechaShow;
    this.returnValue = JDialogFechaReturnValue;
    this.cerrar      = JDialogFechaClose;
}    
    
/**
 * Establece la fecha en el input
 * @return (void)
 */
function JDialogFechaConvFecha(fecha) {
    tokens = fecha.split("-");
    if ( tokens.length != 3 ) return "";
    
    dia = parseInt(tokens[0],10);
    mes = parseInt(tokens[1],10);
    ano = parseInt(tokens[2],10);
    
    return ano+"-"+mes+"-"+dia;
}

/**
 * Muestra un popup con la fecha
 * @return (String) Fecha seleccionada
 */
function JDialogFechaShow(e) {
    dialog = new JDialog(this.ruta,this,"Seleccionar Fecha");
    dialog.show();
}

function JDialogFechaReturnValue(value) {
    
    this.jInput.setValue(this.convFecha(value));
} 


function JDialogFechaClose(e) {
    
    if ( e ) {
        obj = e.target;
    }  else {
        obj = event.srcElement;
    }
    
    
    
    jDialog = obj.getAttribute("jDialog");

    jDialog.div.style.display = "none";
    jDialog.div = null;
    
} 

/*--------------------------------------------------------------------------------------------------------------------*/
/**
 * Objeto que controla la creación, subida y edicion de una imagen
 * @param (Object)  input   Objeto HTML de tipo input=text
 */
function JInputImage( input ) {
    // Propiedades
    this.input   = input;
    this.rutaImg = this.input.getAttribute("rutaImg");
    this.tabla   = this.input.getAttribute("tabla");
    this.campo   = this.input.getAttribute("campo");
    this.notNull = this.input.getAttribute("notNull")? true : false;
    this.mensaje = this.input.getAttribute("mensaje")? this.input.getAttribute("mensaje") : "";
    this.alias   = this.input.getAttribute("alias")?   this.input.getAttribute("alias") : "";
    
    
    // privado
    this.img     = null;
    
    
    // Métodos
    this.validar  = JInputImageValidar;
    this.getImage = JInputImageGetImage;
    this.setValue = JInputImageSetValue;
    this.getValue = JInputImageGetValue;
    this.crearGUI = JInputImageCreateGUI;
    
    this.crearGUI();
}    
    
/**
 * Crea la interfaz de la imagen
 * @return (void) 
 */
function JInputImageCreateGUI() {
    // Td 
    td = this.input.parentNode;
    
    // Creación del icono de búsqueda
    img = document.createElement("img");
    img.src = "http://www.racodelpla.com/graficos/ico_buscar.gif";
    img.setAttribute("JInputImage",jPile.addRefObject(this));
    img.style.cursor = "pointer";
    img.title = "Buscar imagen";
    img.onclick = JInputImageGetImage;
    
    td.appendChild(img);
    
    // Creación de un espacio
    nbsp = document.createTextNode(" ");
    td.appendChild(nbsp);
    
    // Creación de la imagens
    this.img = document.createElement("img");
    this.img.border = 0;
    this.img.align  = "absmiddle";
    this.img.width  = 50;
    this.img.height = 50;
    if ( this.input.value.length > 0 ) this.img.src = this.rutaImg + this.input.value;
    else this.img.src = this.rutaImg + "img_nodisponible.gif";
    td.appendChild(this.img);
    
}


/**
 * Valida el campo imagen
 * @return (boolean) True si es válido, false en caso contrario
 */
function JInputImageValidar() {
    if ( this.notNull ) {
        if ( !this.mensaje ) alert("El campo ["+this.alias+"] no puede quedar vac&#237;o");
        else alert(this.mensaje);
        this.input.focus();
        return false;
    }
    return true;
}

/** 
 * Crea un dialogo para extraer la imagen
 */
function JInputImageGetImage(e) {
   
   src   = e? e.target : event.srcElement;    
   idObj = src.getAttribute("JInputImage");
   obj   = jPile.getRefObject(idObj);
     
   
   imgDialog = new JDialogImagen(obj.tabla,obj.campo,obj);
   imgDialog.Show();  
   
}

/**
 * Establece la imagen 
 */
function JInputImageSetValue(value) {
    this.input.value = value;
    this.img.src = this.rutaImg + this.input.value;
}
 

/**
 * Establece la imagen 
 */
function JInputImageGetValue() {
    return ( this.input.value );
    
}

/*--------------------------------------------------------------------------------------------------------------------*/

/**
 * Objeto que encapsula la búsqueda de una imagen
 */
function JDialogImagen(tabla,campo,current) {
    
   // Propiedades 
   this.tabla   = (tabla) ? tabla : "";
   this.campo   = (campo) ? campo : "";  
   this.current = current ? current : "";
   this.width   = 800;
   this.height  = 500;

   // Métodos
   this.Show     = JDialogImagenShow;
   this.UpLoad   = JDialogImagenUpLoad;
   this.returnValue = JDialogImagenReturnValue;
}

function JDialogImagenReturnValue( value ) {
    this.current.setValue(value);
}
  
/** 
 * Muestra un Dialog para seleccionar la imagen
 * @return (string) Imagen seleccionada ,  cadena vacía si no hubo selección
 */
function JDialogImagenShow() {

   url = "http://www.racodelpla.com/acceso_admin/funciones/mrk_imagenes.php?tabla="+this.tabla+"&campo="+this.campo+"&current="+this.current.getValue();
   
   temp = new JDialog(url,this);  
   temp.width = this.width;
   temp.height = this.height;
   temp.show();
   
}
   
function JDialogImagenUpLoad() {
   var imagen = window.showModalDialog( "http://www.racodelpla.com/acceso_admin/funciones/subir.php?tabla="+this.tabla+"&campo="+this.campo,  "" , "dialogHeight:180px; dialogWidth:500px center:yes; edge:raised; scroll:no; status:no;");
   if ( imagen ) {
       this.TextBox.value = imagen;
       this.Imagen.src = this.rutaImg+imagen;
   }
   return imagen;
}


/*--------------------------------------------------------------------------------------------------------------------*/
/**
 * Objeto que crea un marco para
 * cargar URL's de modo ventana
 * @param   (string)    url     Url que se desea cargar
 */
function JDialog(url,obj,title) {
    // Propiedades
    this.url         = url;
    this.width       = 220;
    this.height      = 200;
    this.heightTitle = 21;
    this.title       = title? title : "Dialog";
    this.dialog      = obj;
    
    // Private
    this.div = null;
    this.dragMode = false;
    this.dragX    = 0 ;
    this.dragY    = 0 ;
    
    // Metodos
    this.show           = JDialogShow;
    this.close          = JDialogClose;
    this.setReturnValue = JDialogSetReturnValue;
    
    jPile.addDialog(this);
    
}
function JDialogSetReturnValue(value) {

    document.body.removeChild(jPile.getDialog().div);
    jPile.popDialog();
    this.dialog.returnValue(value);
    
}



function JDialogCaptureMove(e) {
    src = e? e.target : event.srcElement;
    oId = src.getAttribute("JDialog");
    obj = jPile.getRefObject(oId);
    if ( obj.dragMode ) {
        if ( e && !e.x ) {
        
            obj.div.style.left = e.pageX - obj.dragX;
            obj.div.style.top  = e.pageY - obj.dragY;
        } else {
            obj.div.style.left = event.x - obj.dragX;
            obj.div.style.top  = event.y - obj.dragY;
        }
    }   
    return;
}

function JDialogCaptureDown(e) {
    src = e? e.target : event.srcElement;
    src.style.cursor = "pointer";
    oId = src.getAttribute("JDialog");
    obj = jPile.getRefObject(oId);
    obj.dragMode = true;

    if ( e  && !e.x) {
        
        obj.dragX = e.layerX;
        obj.dragY = e.layerY;
    } else {      
        obj.dragX    = event.offsetX;
        obj.dragY    = event.offsetY;
    }
    
    return;
}

function JDialogCaptureUp(e) {
    src = e? e.target : event.srcElement;
    src.style.cursor = "auto";
    oId = src.getAttribute("JDialog");
    obj = jPile.getRefObject(oId);
    obj.dragMode = false;
    
    return;
}

function JDialogMouseOut(e) {
    src = e? e.target : event.srcElement;
    oId = src.getAttribute("JDialog");
      
    obj = jPile.getRefObject(oId);
    if ( !obj ) return;
    obj.dragMode = false; 
}

function JDialogShow(e) {
    oId = jPile.addRefObject(this);

    posX = (window.screen.width  - this.width)  / 2;
    posY = 30
    if ( e ) {
        posX = e.layerX;
        posY = e.layerY;
    } else {

    }
    
    this.div = document.createElement("div");       
    this.div.style.left     = posX;
    this.div.style.top      = posY;
    this.div.style.position = "absolute";
    this.div.className      = "windowDiv";
    
    this.div.setAttribute("JDialog",oId);
    
    this.div.innerHTML = "<table class='windowTbl' border='0' id='tblDialog' cellpadding='0' cellspacing='0'></table>";
    this.div.onmouseout  = JDialogMouseOut;
    
    document.body.appendChild(this.div);
    
    tbl = document.getElementById("tblDialog");
    tbl.style.width = this.width;
    tbl.cellspacing = 0;
    tbl.cellpadding = 0;
    
    tr  = tbl.insertRow(0);
   
    td  = tr.insertCell(0);
    td.className = "windowTitle";
    td.innerHTML = this.title;
    td.setAttribute("JDialog",oId);
    td.id = "Title";
    td.width     = "100%";
    td.height    = this.heightTitle;
    td.onmousedown   = JDialogCaptureDown;
    td.onmousemove = JDialogCaptureMove;
    td.onmouseup   = JDialogCaptureUp;
    
    
    // Imagen de cierre del popup
    td               = tr.insertCell(1);
    td.width = "10px";
   
    
    td.setAttribute("JDialog",oId);
    td.className     = "windowTitle";
    img              = document.createElement("img");
    img.src          = "http://www.racodelpla.com/graficos/ico_win_cerrar.gif";
    img.style.cursor = "pointer";
    img.title        = "Cerrar";
    img.onclick      = JDialogClose;
    img.setAttribute("JDialog",oId);
    td.appendChild(img);
    
    
    // Creación del frame
    tr = tbl.insertRow(1);
    td = tr.insertCell(0);
    td.setAttribute("colspan","2");
    td.setAttribute("width","100%");
    td.setAttribute("valign","top");
    
    ifrm              = document.createElement("iframe");
    ifrm.frameBorder  = 0;
    ifrm.setAttribute("marginHeight","0");
    ifrm.setAttribute("marginWidth","0");
    ifrm.setAttribute("topMargin","0");
    ifrm.setAttribute("leftMargin","0");        
    ifrm.width        = "220";
    ifrm.height       = this.height - this.heightTitle;
    ifrm.src          = this.url;
    ifrm.scrolling    = "no";
    td.appendChild(ifrm);
    
   
}

function JDialogClose(e) {
    src = e? e.target : event.srcElement;
    obj = jPile.getRefObject(src.getAttribute("JDialog"));
    obj.setReturnValue("");
}

/*--------------------------------------------------------------------------------------------------------------------*/

/**
 * Objeto que controla la selección de un valor existente en 
 * otra tabla
 * @param (Object)  input   Objeto HTML de tipo input=text
 */
function JInputLink( input,form) {
    // Propiedades
    this.input   = input;
    this.tabla   = this.input.getAttribute("tabla");
    
    this.notNull = this.input.getAttribute("notNull") ? true : false;
    this.mensaje = this.input.getAttribute("mensaje") ? this.input.getAttribute("mensaje") : "";
    this.alias   = this.input.getAttribute("alias")   ? this.input.getAttribute("alias") : "";
    this.form    = form;    
    this.inputLbl= null;
    
    // Métodos
    this.validar  = JInputLinkValidar;
    this.setValue = JInputLinkSetValue;
    this.getValue = JInputLinkGetValue;
    this.crearGUI = JInputLinkCreateGUI;
    this.setID    = JInputLinkSetID;
    this.show     = JInputLinkShow;
    this.getID    = JInputLinkGetID;
    this.getXML   = JInputLinkGetXML;
    this.setXML   = JInputLinkSetXML;
    // Eventos
    this.input.onblur   = JInputLinkGetID;
    this.input.onchange = JInputLinkGetID;
    
  
    this.crearGUI();
}    
    
/**
 *
 */
function JInputLinkShow(e) {
    src   = e? e.target : event.srcElement;    
    idObj = src.getAttribute("JInputLink");
    obj   = jPile.getRefObject(idObj);

    temp = new JDialogLink(obj.tabla,obj);
    temp.Show();
}

function JInputLinkGetID(e) {
    src   = e? e.target : event.srcElement;    
    idObj = src.getAttribute("JInputLink");
    obj   = jPile.getRefObject(idObj);
    obj.setID();    
}

function JInputLinkSetID() {
    if ( this.input.value.length == 0 ) {
        this.inputLbl.value = "";
        return;
    }
    

    if ( JUtil.getNav() == JUtil.IE ) {
        jXml = new JXML("http://www.racodelpla.com/acceso_admin/funciones/recIdXML.php?tabla=" + this.tabla + "&valor="+this.input.value);    
        docRoot = jXml.load();
        this.setXML(docRoot);
    }
    
    if ( JUtil.getNav() == JUtil.MOZ) {
        jXml = new JXML("http://www.racodelpla.com/acceso_admin/funciones/recIdXML.php?tabla=" + this.tabla + "&valor="+this.input.value);    
        jXml.setOwner(this);
        jXml.load();
    }
}

function JInputLinkGetXML(xmlNode) {
    this.setXML(xmlNode);
}

function JInputLinkSetXML(docRoot) {
    if ( docRoot ) {
        if ( docRoot.getAttribute("type")=="ok") {
            this.inputLbl.value = docRoot.getAttribute("id");
            this.input.value    = docRoot.getAttribute("value");
        } else {
            alert(docRoot.getAttribute("mensaje"));
            this.input.value    = "";
        }
    }
}

/**
 * Crea la interfaz de la imagen
 * @return (void) 
 */
function JInputLinkCreateGUI() {
    // Td 
    td = this.input.parentNode;
    this.input.setAttribute("JInputLink",jPile.addRefObject(this));
    
    
    // Creación del icono de búsqueda
    img = document.createElement("img");
    img.src = "http://www.racodelpla.com/graficos/ico_buscar.gif";
    img.setAttribute("JInputLink",jPile.addRefObject(this));
    img.style.cursor = "pointer";
    img.title = "Buscar " + this.alias;
    img.onclick = JInputLinkShow;
    
    td.appendChild(img);
    
    // Creación de un espacio
    nbsp = document.createTextNode(" ");
    td.appendChild(nbsp);
    
    // Creación de la imagenes
    this.inputLbl  = document.createElement("input");
    this.inputLbl.setAttribute("readonly","readonly");
    this.inputLbl.type = "text";
    this.inputLbl.className = "inputLink";
    this.inputLbl.tabIndex  = -1;
    td.appendChild(this.inputLbl);
    
}




/**
 * Valida el campo imagen
 * @return (boolean) True si es válido, false en caso contrario
 */
function JInputLinkValidar() {
    if ( this.notNull ) {
        if ( !this.mensaje ) alert("El campo ["+this.alias+"] no puede quedar vac&#237;o");
        else alert(this.mensaje);
        this.input.focus();
        return false;
    }
    return true;
}



/**
 * Establece el valor 
 */
function JInputLinkSetValue(value) {
    this.input.value = value;
    this.setID();  
}
 

/**
 * Establece la imagen 
 */
function JInputLinkGetValue() {
    return ( this.input.value );
}
/*--------------------------------------------------------------------------------------------------------------------*/

/**
 * Objeto que encapsula la búsqueda de una imagen
 */
function JDialogLink(tabla,current) {
    
   // Propiedades 
   this.tabla   = (tabla) ? tabla : "";
   this.current = current ? current : "";
   this.width   = 800;
   this.height  = 500;

   // Métodos
   this.Show     = JDialogLinkShow;
   this.UpLoad   = JDialogLinkUpLoad;
   this.returnValue = JDialogLinkReturnValue;
}

function JDialogLinkReturnValue( value ) {
    this.current.setValue(value);
}
  
/** 
 * Muestra un Dialog para seleccionar la imagen
 * @return (string) Imagen seleccionada ,  cadena vacía si no hubo selección
 */
function JDialogLinkShow() {

   url = "http://www.racodelpla.com/acceso_admin/mnt_"+this.tabla+".php?modo=listado";
   
   temp = new JDialog(url,this);  
   temp.width = this.width;
   temp.height = this.height;
   temp.show();
  
}
   
function JDialogLinkUpLoad() {
   var imagen = window.showModalDialog( "http://www.racodelpla.com/acceso_admin/funciones/subir.php?tabla="+this.tabla+"&campo="+this.campo,  "" , "dialogHeight:180px; dialogWidth:500px center:yes; edge:raised; scroll:no; status:no;");
   if ( imagen ) {
       this.TextBox.value = imagen;
       this.Imagen.src = this.rutaImg+imagen;
   }
   return imagen;
}


/*--------------------------------------------------------------------------------------------------------------------*/

/**
 * Objeto para procesar xml's 
 */
function JXML(url) {
    this.url   = url;
    
    // Metodos
    this.load            = JXMLLoad;
    this.createXmlObject = JXMLCreateXmlObject
    this.setOwner        = JXMLSetOwner;
    this.setURL          = JXMLSetURL;
    
    // Inicialización
    this.xml             = this.createXmlObject();
       
}

function JXMLSetURL(url) {
    this.url = url;
}

function JXMLSetOwner(object ) {
    this.owner = object;
}

/**
 * Carga el xml en forma asincrona 
 */
function JXMLLoad() {
    CurrentXML = this;
    this.xml.load(this.url);
    
    return;
}

function JXMLCreateXmlObject() {
   
    // Caso netscape
    if (document.implementation && document.implementation.createDocument) {
        //Document.prototype.owner = "ADF";
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.onload = JXMLOnLoad;
		return xmlDoc;
	} else {
    	xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    	xmlDoc.async = true;
    	xmlDoc.onreadystatechange = JXMLOnReadyStateChange;
        return xmlDoc;
	}
}

function JXMLOnReadyStateChange() {

    if ( xmlDoc.readyState == 4 ) {
		CurrentXML.owner.getXML(xmlDoc.documentElement);
	}
}

function JXMLOnLoad() {
    CurrentXML.owner.getXML(this.documentElement);
}
/*--------------------------------------------------------------------------------------------------------------------*/
/**
 * Objeto fecha
 */
function JInputFecha( input, form, hora  ) {

    // Propiedades
    this.input   = input;
    this.alias   = this.input.getAttribute("alias");
    this.notNull = this.input.getAttribute("notNull");
    this.mensaje = this.input.getAttribute("mensaje");
    this.dia     = null;
    this.mes     = null;
    this.ano     = null;
    this.hor     = null;
    this.min     = null;
    this.inpDia  = null;
    this.inpMes  = null;
    this.inpAno  = null;
    this.inpHor  = null;
    this.inpMin  = null;
    this.form    = form;
    this.log     = "";
    this.hora    = hora? true : false;

    // Metodos
    this.validar      = JInputFechaValidar;
    this.crearGUI     = JInputFechaCrearGui;
    this.getFecha     = JInputFechaGetFecha;
    this.setValue     = JInputFechaSetValue;
    this.validarFecha = JInputFechaValidarFecha;
    this.limpiaCeros  = JInputFechaLimpiaCeros;
    this.focus        = JInputFechaFocus;
    
    // Creación de la interfaz grafica
    this.crearGUI();
    
    // Asignación de la fecha 
    this.setValue(this.input.value);
    
    
}


function JInputFechaFocus() {
	//this.dia.focus();
}

/**
 * Establece una fecha en formato MySQL 
 */
function JInputFechaSetValue(value) {

    // Extracción de la fecha 
    diaValue = "";
    mesValue = "";
    anoValue = "";
    arrVal = value.split("-");
    if ( arrVal.length == 3 ) {
        diaValue = arrVal[2];
        mesValue = arrVal[1];
        anoValue = arrVal[0];
    }
    
    this.dia.value = diaValue;
    this.mes.value = mesValue;
    this.ano.value = anoValue;
    this.input.value = value;
} 

/**
 * Muestra un selector de fechas
 */
function JInputFechaGetFecha(e) {
     
    if ( !e ) {
        obj = event.srcElement;
    } else {
        obj = e.target;  
    }   
         
    OID = obj.getAttribute("OID");
    jInput = jPile.getRefObject(OID);
    
    inp = new JDialogFecha(jInput);
    inp.Show(e);
}

/**
 * Crea los inputs necesarios para introducir una fecha
 * @return (void);
 */
function JInputFechaCrearGui() {

    //
    // Creación de los inputs
    //

    // Dia 
    this.dia = document.createElement("input");
    this.dia.type      = "text";
    this.dia.setAttribute("alias",this.name+" dia " );
    this.dia.setAttribute("tipo","numerico" );
    this.dia.setAttribute("notNull",true );
    this.dia.name      = this.input.name+"_dia";
    this.dia.size      = 2;
    this.dia.maxLength = 2;
    this.dia.style.width = "24px";
    this.dia.setAttribute("auto",1);
    
    this.inpDia = new JInput(this.dia);
    
    // Mes
    this.mes = document.createElement("input");
    this.mes.type      = "text";
    this.mes.name      = this.input.name+"_mes";
    this.mes.setAttribute("alias",this.name+" mes " );
    this.mes.setAttribute("tipo","numerico" );
    this.mes.setAttribute("notNull",true );
    this.mes.setAttribute("auto",1);
    this.mes.style.width = "24px";
    
    this.mes.size      = 2;
    this.mes.maxLength = 2;
    this.inpMes = new JInput(this.mes);
    
        
    // Año
    this.ano = document.createElement("input");
    this.ano.type      = "text";
    this.ano.name      = this.input.name+"_ano";
    this.ano.setAttribute("alias",this.name+" a&#241;o " );
    this.ano.size      = 4;
    this.ano.maxLength = 4;
    this.ano.style.width = "38px";
    this.ano.setAttribute("tipo","numerico" );
    this.ano.setAttribute("notNull",true );
    this.ano.setAttribute("auto",1);
    this.inpAno = new JInput(this.ano);
    
    
    
    
    // Imagen para el calendar
    img = document.createElement("img");
    img.src       = "http://www.racodelpla.com/graficos/ico_calendar.gif";
    img.className = "imgLink";
    img.border    = 0;
    img.align     = "absmiddle";
    img.title     = "Obtener fecha";
    img.onclick   = JInputFechaGetFecha;
    img.setAttribute("Oid",jPile.addRefObject(this));
    
    if ( this.hora ) {
	    
	    // Hora 
	    this.hor = document.createElement("input");
	    this.hor.type      = "text";
	    this.hor.name      = this.input.name+"_hor";
	    this.hor.setAttribute("alias",this.name+" hora " );
	    this.hor.size      = 2;
	    this.hor.maxLength = 2;
	    this.hor.style.width = "24px";
	    this.hor.setAttribute("tipo","numerico" );
	    this.hor.setAttribute("notNull",true );
	    this.hor.setAttribute("auto",1);
	    this.inpHor = new JInput(this.hor);    
	    
	    // Minutos
	    this.min = document.createElement("input");
	    this.min.type      = "text";
	    this.min.name      = this.input.name+"_min";
	    this.min.setAttribute("alias",this.name+" minutos " );
	    this.min.size      = 2;
	    this.min.maxLength = 2;
	    this.min.style.width = "24px";
	    this.min.setAttribute("tipo","numerico" );
	    this.min.setAttribute("notNull",true );
	    this.min.setAttribute("auto",1);
	    this.inpMin = new JInput(this.min);      
	    
    }
    
    
    
    // Span para contener a los elementos
    tbl = document.createElement("table");
    tr = tbl.insertRow(0);
    
    td  = tr.insertCell(tr.cells.length);
    td.appendChild(this.dia); 
    
    
    td  = tr.insertCell(tr.cells.length);
    td.appendChild(this.mes); 
    td  = tr.insertCell(tr.cells.length);
    td.appendChild(this.ano); 
    
   	
    
    td  = tr.insertCell(tr.cells.length);
    td.appendChild(img); 

	if ( this.hora ) {
   	
	   	td  = tr.insertCell(tr.cells.length);
    	td.innerHTML = "&nbsp;&nbsp;";
   	
		td  = tr.insertCell(tr.cells.length);
    	td.appendChild(this.hor); 

		
		td  = tr.insertCell(tr.cells.length);
		td.width = 2;
    	td.innerHTML = ":";
		
	
    	
    	td  = tr.insertCell(tr.cells.length);
    	td.appendChild(this.min); 
	}
    
    
    // Incorporación de los inputs
    this.input.style.display = "none";
    this.input.setAttribute("auto",1);
    obj = this.input.parentNode;
    //obj.innerHTML = "";
    obj.appendChild(tbl);
    //obj.appendChild(this.input);
    
}


/**
 * Valida los datos introducidos
 * @return (boolean) true si es válido, false en caso contrario
 */
function JInputFechaValidar() {

	dia = this.inpDia;
	mes = this.inpMes;
	ano = this.inpAno;
	hor = this.inpHor;
	min = this.inpMin;

    if ( this.notNull ) {
        if ( dia.input.value==0 || mes.input.value==0 || ano.input.value == 0 ) {
            dia.input.value = "";
            mes.input.value = "";
            ano.input.value = "";
            if ( this.mensaje ) this.log = this.mensaje;
            else this.log = "El campo [" + this.alias + "] no puede quedar vac&#237;o";
            return false;
        }
        
        if ( this.hora ) {
           if ( this.hor.value.length == 0 || this.min.value.length == 0 ) {
               if ( this.mensaje ) this.log = this.mensaje;
               else this.log = "El campo [" + this.alias + "] no puede quedar vac&#237;o";
               return false;
           }
        }
    }

    // Comprobación de la fecha
    if ( this.dia.value.length > 0 || this.mes.value.length > 0 || this.ano.value.length > 0)  {
        if ( !this.validarFecha( this.dia.value , this.mes.value , this.ano.value )) {
            if ( this.mensaje ) this.log = this.mensaje;
            else this.log = "El campo [" + this.alias + "] no contiene una fecha v&#225;lida";
            this.dia.focus();
            return false;
        }
    }
    
    if ( this.hora ) {
    	if ( this.hor.value < 0 || this.hor.value > 23 ) {
    		if ( this.mensaje ) this.log = this.mensaje;
            else this.log = "El campo [" + this.alias + "] no contiene una hora v&#225;lida";
            return false;
    	}
    	
    	if ( this.min.value < 0 || this.min.value > 59 ) {
    		if ( this.mensaje ) this.log = this.mensaje;
            else this.log = "El campo [" + this.alias + "] no contiene una hora v&#225;lida";
            return false;
    	}
    }
    
    
    this.input.value = this.ano.value+"-"+this.mes.value.mascara("00","right")+"-"+this.dia.value.mascara("00","right");
    if ( this.hora ) {
        this.input.value += " " + this.hor.value.mascara("00","right") + ":"+ this.min.value.mascara("00","right");
    }
    return true;
}

/**
 * Valida una fecha 
 * @param   (String)   dia     Dia de la fecha
 * @param   (String)   mes     Mes de la fecha
 * @param   (String)   ano     Año de la fecha
 */
function JInputFechaValidarFecha(dia,mes,ano) {

    if ( dia.length == 0 ) return false;
    if ( mes.length == 0 ) return false;
    if ( ano.length == 0 ) return false;
    
	dia=parseInt(dia.limpiaCeros());
	mes=parseInt(mes.limpiaCeros());
	ano=parseInt(ano.limpiaCeros());
	
    fecha = new Date();
	 
	if (mes<1 || mes>12) return false;

	meses = new Array(13)
	meses[1] = 31;
	if ( ( (ano%4)==0 && (ano%100)!=0  ) || (ano%400)==0 ) meses[2]=29;
	else meses[2]=28;
	meses[3] = 31;
	meses[4] = 30;
	meses[5] = 31;
	meses[6] = 30;
	meses[7] = 31;
	meses[8] = 31;
	meses[9] = 30;
	meses[10] = 31;
	meses[11] = 30;
	meses[12] = 31;

	if (dia<1 || dia>meses[mes]) return false;	
		
	return true;
}

/** 
 * Elimina los ceros antes de cualquier número
 * @param   (String)    cadena  Cadena a limpioar
 */
function JInputFechaLimpiaCeros( cadena ) {
    temp="";
    numeros=0;
    for(i=0;i<cadena.length;i++) {
        if ( cadena.charAt(i)!="0" || numeros>0) {  
           temp+=cadena.charAt(i);
           numeros++;
        } 
    }
    return temp;
}

/*--------------------------------------------------------------------------------------------------------------------*/
/**
 * Objeto que controla un listado
 * @param (String) id Identificador de la tabla del listado
 */
function JListado(id) {

    // Propiedades
    this.list = document.getElementById(id);
    this.id   = id;
    this.form = null;
    

    
    //this.urlDatos = this.list.getAttribute("urlDatos");
    if ( !this.list ) {
        alert("No se encuentra el Id del Listado ["+id+"]");        
    }

    this.arrRows    = Array();
    this.arrColumns = Array();
    this.urlDatos = this.list.getAttribute("urlDatos");
    
    // Métodos
    this.capture       = JListadoCapture;
    this.getColumn     = JListadoGetColumn;
    this.capturarFilas = JListadoCapturarFilas;
    this.crearFilas    = JListadoClearFilas;
    this.getXML        = JListadoGetXML;
    this.selectRow     = JListadoSelectRow;
    this.executeAction = JListadoExecuteAction;
    this.selectAll     = JListadoSelectAll;

    // Captura de los inputs
    this.capture();
    
    if ( this.urlDatos ) {
        this.capturarFilas();
    }
} 

function JListadoSelectAll(value, columnName) {
	var i;
	for(i=0;i<this.arrColumns.length;i++) {
		if ( this.arrColumns[i].nombre == columnName) {
		    this.arrColumns[i].selectAll(value);
		}
	}
}

function JListadoExecuteAction(accion,msg,validar) {
	if (msg &&  !confirm(msg)) return;
	// Crear el input 
	inp = document.createElement("input");
	inp.type  = "hidden";
	inp.name  = "accion";
	inp.value = accion;
	

	this.form.submit();
}

function JListadoCapturarFilas() {
    xml = new JXML();
    xml.setURL(this.urlDatos);
	xml.setOwner(this);
	xml.load();
}

function JListadoSelectRow(valor) {
    alert(valor);
}

function JListadoGetXML(rootElement) {
	nodeList = rootElement.getElementsByTagName("fila");
	var i;

	
	for(i=0;i<nodeList.length;i++) {
	    node = nodeList[i];
		
		tr = this.list.insertRow(this.arrRows.length+1);
				
		var j;
		for(j=0;j<this.arrColumns.length;j++) {
			col = this.arrColumns[j];
			
			
			td = col.crearCelda(node.getAttribute(col.id));
		    tr.appendChild(td);
		}
	}
	
	
}

function JListadoClearFilas(fila) {

}


/**
 * Devuelve la columna a partir de su índice
 * @param (int) index Íncide de la columna
 */
function JListadoGetColumn(index) {
    if ( index > this.arrColumns.length ) return null;
    return this.arrColumns[index];     
}


/**
 * Captura automática de las filas y celdas
 * @return (void) 
 */
function JListadoCapture() {
    if ( !this.list ) return;
    
    this.form = document.forms["frm"+this.id];
    if ( !this.form ) return;
    
    rows = this.list.rows;

    // Captura de las Columnas
    var iCell;
    var i;
    var iCol = 0;
    for(i=0;i<rows.length;i++) {
        type = rows[i].getAttribute("tipo");
        if ( type == "rowHd" ) {
            cells = rows[i].cells;
            for(iCell=0;iCell<cells.length;iCell++) {
                this.arrColumns[iCol] = new JListadoColumna(this,cells[iCell]);
                iCol++;
            }
        }
    }

    


    // Captura de las filas 
    
    var iRow = 0;
    for(i=0;i<rows.length;i++) {
        type = rows[i].getAttribute("tipo");
        if ( type == "rowDat" ) {
            this.arrRows[iRow] = new JListadoFila(this,rows[i]);
            iRow++;
            
        }
    }
 

     

}
/*-------------------------------------------------------------------------------------------------*/

/**
 * Objeto que controla una columna del listado
 * @param (JListado)   list Listado que contiene las columnas
 * @param (HTMLObject) td Td que contiene la columna
 */
function JListadoColumna(list,td) {
    // Propiedades
    this.td       = td;
    this.list     = list;
    this.type     = "";
    this.nombre   = "";
    this.arrCells = Array();
    this.accion   = this.td.getAttribute("accion");
 
        // Propiedades únicas de tipo Marcador
        this.check = null;
    
    // Métodos
    this.capture = JListadoColumnaCapture;
    this.addCell = JListadoColumnaAddCell;
    this.crearCelda = JListadoColumnaCrearCelda;
    this.selectAll  = JListadoColumnaSelectAll;
    this.capture();
    
    // Eventos
    this.checkEvent = JListadoColumnaCheckEvent;
}

function JListadoColumnaSelectAll(value) {
	var i;
	for(i=0;i<this.arrCells.length;i++) {
		td = this.arrCells[i];
		td.check(value);
	}
}	

/**
 * Crea una celda con el valor pasado
 * @param (String) valor
 */
function JListadoColumnaCrearCelda(valor) {

    switch(this.type) {
		case "texto":
			td = document.createElement("td");
			td.innerHTML = valor;
			return td;
		break;
		case "numero":
			td = document.createElement("td");
			td.innerHTML = valor;
			return td;
		break;
		case "marca":
			td = document.createElement("td");
			td.innerHTML = "<input type='checkbox'>";
			return td;
		break;
	}
	td = document.createElement("td");
	td.innerHTML = valor;
	return td;
}

/**
 * Evento que salta cuando se hace check en el input
 * de una columna marcador
 */ 
function JListadoColumnaCheckEvent() {
    var i;
    for(i=0;i<this.arrCells.length;i++) {
        this.arrCells[i].check(this.check.checked);
    }
}

function JListadoColumnaAddCell(celda) {
    this.arrCells[ this.arrCells.length ] = celda;
}

/**
 * Captura las propiedades de la columna
 * @return (void)
 */
function JListadoColumnaCapture() {
    this.type   = this.td.getAttribute("tipo");
    this.nombre = this.td.getAttribute("name");
    this.id     = this.td.getAttribute("id");
    this.indice = this.td.getAttribute("indice");

}




function JListadoColumnaCheck(e) {

    src = e? e.target : event.srcElement;
    oID = src.getAttribute("oID");
    if ( oID >= 0 ) {
        object = jPile.getRefObject(oID);
        object.checkEvent();        
    }
}

/**
 * Objeto que controla una fila del listado
 * @param (HTMLObject) Tr     Tr de la fila del listado
 * @param (JListado)   list   Referencia al objeto JList que lo contiene
 */
function JListadoFila(list,tr) {
    // Propiedades
    this.tr        = tr;
    this.listado   = list;
    this.position  = 0;
    this.arrCells  = Array(); 
    this.className = "";
    this.classOver = "rowOver";

    // Métodos 
    this.capture   = JListadoFilaCapture;
    this.capture();
}

/**
 * 
 */
function JListadoFilaCapture() {
    // Captura de propiedades de la fila
    type = this.tr.getAttribute("tipo");
    this.className = this.tr.getAttribute("className");
    this.position  = this.tr.getAttribute("pos");
    cells = this.tr.cells;
    var i;
    var iCell;
    for(i=0;i<cells.length;i++) {
        col = this.listado.getColumn(i);
        
        this.arrCells[iCell] = new JListadoCelda(this,cells[i],col);
        col.addCell(this.arrCells[iCell]);
    }
}


/*--------------------------------------------------------------------------------------------------*/

/** 
 * Objeto que representa una celda del listado
 * @param (HTMLObject)      td   Objeto td que contiene la celda 
 * @param (JListadoFila)    fila Objeto JListadoFila que la contiene
 * @param (JListadoColumna) col Objeto columna que la contiene
 */
function JListadoCelda(fila,td,col) {
    
    // Propiedades
    this.td    = td;
    this.fila  = fila;
    this.col   = col;
    this.valor = this.td.getAttribute("valor");
    
        // Propiedades especiales de tipo marcador
        this.inputCheck = null;
    
    
    // Metodos
    this.capture   = JListadoCeldaCapture;
    
        // Métodos especiales para el tipo marcador
        this.check = JListadoCeldaCheck;
    
    this.capture();
}

/**
 * Evento que captura la acción sobre una celda
 * @return (void)
 */ 
function JListadoCeldaCapture() {
    
    // Captura de propiedades
    this.td.setAttribute("oID",jPile.addRefObject(this));      

    switch(this.col.type) {
        case "Marcador":
             check = this.td.getElementsByTagName("input");
             this.inputCheck = check.length == 1 ? check[0] : null;
             
        break;
    }
    
    // Establecimiento de la accion
    if ( this.col.accion ) {
        this.td.innerHTML = "<a href='javascript:jList"+this.col.list.id+"."+this.col.accion+"(\""+this.valor+"\")'>"+this.valor+"</a>";
    }
    
    // Comprobacion si la celda es indice
    if ( this.col.indice ) {
    	inp = document.createElement("input");
    	inp.name  = this.col.nombre+"["+this.fila.position+"]";
    	inp.value = this.valor;
    	inp.type  = "hidden";
    	this.fila.listado.form.appendChild(inp);
    	
    }
	
}

/**
 * Establece como chequeado el input
 * de checkbox
 * @param (boolean) valor True para marcar, False para desmarcar
 */
function JListadoCeldaCheck(valor) {
    if ( this.inputCheck ) {
        this.inputCheck.checked = valor? true : false;
    }
}


/**
 * Objeto input de tipo checkbox
 */
function JInputCheckBox( input, form ) {
    
    // Captura de propiedades 
    this.input   = input;
    this.alias   = this.input.getAttribute("alias");
    this.notNull = this.input.getAttribute("notNull")!=null? true : false;
    this.mensaje = this.input.getAttribute("mensaje");
    this.log     = "";
    this.form    = form;

    
    // Métodos
    this.validar  = JInputCheckBoxValidar;
    this.focus    = JInputCheckBoxFocus;
}


function JInputCheckBoxValidar() {
	
	if ( this.notNull ) {
	    if ( !this.input.checked ) { 
	       if ( this.mensaje ) {
	           this.log = this.mensaje;
	           return false;
	       } else {
	           this.log = "Debe seleccionar el campo ["+this.alias+"]";
	           return false;
	       }
	    }
	}

    return true;
}

function JInputCheckBoxFocus() {

}

