EXTRAS = {
	addEvent : function(obj, evType, fn, useCapture){
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		} 
		else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} 
		else {
			return false;
		}
	},	
	getElementsByClass : function(className,node) {
		if(!node) node=document;
		var refTags = document.all ? node.all : node.getElementsByTagName("*");
		var retVal = new Array();
		for(var z=0;z<refTags.length;z++) {
			if(refTags[z].className == className) 
			retVal.push(refTags[z]);
		}
		return retVal; 
	}
}

init = function() {
    CrearPestanas();
    enviarDatosCeca();
    AccionesFormularios();
    ActivarToggleCheckField();
    ActivarOcultacionCheckField();
    ActivarOrdenacion();
}

/**
*Detecta el formulario con los datos a enviar al tpv virtual y lo envia directamente,
* realiza el submit del formulario
*/
enviarDatosCeca = function() {
    try {
        var formularioCeca = document.getElementById("formularioCeca");
        if(formularioCeca != null) {
            formularioCeca.submit();
        }
    } catch (exception) {
        return true;
    }
}

/**
*Detectará si en la página existe algún div con id = "/pestana[0-9]+/" y creará
* antes del primero un bloque con id = "enlacesPestanas" que contendrá tantas 
* etiquetas 'a' como el número de bloques 'div' encontrados con dichos id. El 
* contenido de las etiquetas 'a' se corresponderá con el valor del atributo 
* 'title' de los divs encotrados. El enlace presionado tendrá la clase de 
* estilo class = "pestanaActiva".
*/
accionar = function(numero, total, esteNodo) {
    var divPestanas = new Array(total);
    var enlacesAccion = esteNodo.parentNode.getElementsByTagName("A");
    flag = false;
    for(var j = 0; j < total; j++) {
        divPestanas[j] = document.getElementById("pestana" + j);
        if(j == numero) {
            divPestanas[j].style.display = "block";
        } else {
            divPestanas[j].style.display = "none";
        }
    }
    for(var j = 0;j < enlacesAccion.length; j++) {
        enlacesAccion[j].className = "";
    }
    esteNodo.className = "pestanaActiva";
}

CrearPestanas = function() {
    var divContenido = document.getElementById("contenido");
    var divBlocks = divContenido.getElementsByTagName("DIV");
    var numPestanasMax = divBlocks.length;
    var contadorPestanas = 0;
    //obtenemos los divs que deberémos convertir en pestañas
    for(var i = 0; i < numPestanasMax; i++) {
        var divAux = document.getElementById("pestana" + i);
        if(divAux != null) {
            contadorPestanas = contadorPestanas+1;
        }
    }
    if(contadorPestanas > 0) {
        var divEnlacesPestanas = document.createElement("DIV");
        var form = document.createElement("div");
        var principal = document.getElementById("cuadro");//document.getElementsByTagName("FIELDSET");
        if(document.getElementById("pestanasIExp") == null) {
            var pestanas = new Array(contadorPestanas);
            var enlacesPestanas = new Array(contadorPestanas);
            for(var j = 0; j < contadorPestanas; j++) {
                pestanas[j] = document.getElementById("pestana" + j);
                pestanas[j].className = "contenidoPestana";
            }
            //añadimos el div que contendrá los enlaces
            form.appendChild(divEnlacesPestanas);
            divEnlacesPestanas.id = "enlacesPestanas";
            for(var j = 0; j < contadorPestanas; j++) {
                //añadimos la 'capa'
                form.appendChild(pestanas[j]);
                //añadimos el enlace con el código pertinente (o impertinente?):
                if(j > 0) {
                    divEnlacesPestanas.innerHTML += "<a href=\"#pestana0\" onClick=\"accionar("
                        +j+", "+contadorPestanas+", this)\"><span class=\"ladoI\"></span>"
                        +pestanas[j].title+"</a>";
                    pestanas[j].style.display = "none";
                } else {
                    divEnlacesPestanas.innerHTML += "<a href=\"#pestana0\" onClick=\"accionar("
                        +j+", "+contadorPestanas+", this)\" class=\"pestanaActiva"
                        +"\"><span class=\"ladoI\"></span>"+pestanas[j].title
                        +"</a>";
                }
            }
            principal.appendChild(form);
        }
    }
}

/**
 *Detecta los inputs con id "maestro"+n y "esclavo"+n+m y oculta o muestra todos
 * los "esclavo"+n+m segun el estado de "maestro"+n.
 */
ActivarOcultacionCheckField = function() {
    var j=0;
    var continuarMaestro = true;
    var continuarEsclavo;
    while(continuarMaestro) {
        try {
            var e = document.getElementById("maestro"+j);
            if(e != null) {
                e.onchange = ocultarCheckField;
                e.onfocus = ocultarCheckField;
            } else {
                continuarMaestro = false;
            }
            var i=0;
            continuarEsclavo = true;
            while(continuarEsclavo) {
                try {
                    f = document.getElementById("esclavo"+j+i);
                    if(f != null) {
                        f.onchange = ocultarCheckField;
                        f.onfocus = ocultarCheckField;
                        if(!e.checked) {
                            f.style.display = "none";
                        } else {
                            d.style.display = "block";
                        }
                    } else {
                        continuarEsclavo = false;
                    }
                } catch (exception) {
                    continuarEsclavo = false;
                }
                i++;
            }
        } catch(exception) {
            continuarMaestro = false;
        }
        j++;
    }
}

/**
 *Funcion del disparador para que los esclavos se activen y desactiven al 
 * activar o desactivar el maestro.
 */
ocultarCheckField = function() {
    var j=0;
    var continuarMaestro = true;
    var continuarEsclavo;
    while(continuarMaestro) {
        try {
            var e = document.getElementById("maestro"+j);
            if(e == null) {
                continuarMaestro = false;
            } else {
                var i=0;
                continuarEsclavo = true;
                while(continuarEsclavo) {
                    try {
                        f = document.getElementById("esclavo"+j+i);
                        if(f != null) {
                            if(e.checked == false) {
                                f.style.display = "none";
                                tag = f.tagName;
                                if(tag == "INPUT") {
                                    if(f.type != "checkbox" && 
                                         f.type != "radio") {
                                         f.value == "";
                                    }
                                    if(f.type == "checkbox") {
                                         f.checked = false;
                                    }
                                } else if(tag == "TEXTAREA") {
                                    f.value = "";
                                }
                            } else {
                                f.style.display = "block";
                            }
                        } else {
                            continuarEsclavo = false;
                        }
                    } catch(exception) {
                        continuarEsclavo = false;
                    }
                    i++;
                }
            }
        } catch(exception) {
            continuarMaestro = false;
        }
        j++
    }
}

/**
*Detecta inputs con id "trigger"+n y "slave"+n+m y pone como "disabled" o no
* todos los "slave"+n+m según el estado de "trigger"+n.
*/
ActivarToggleCheckField = function() {
   var j = 0;
   var continuarTrigger = true;
   var continuarSlave;
   while (continuarTrigger) {
        try {
            var e = document.getElementById("trigger"+j);
            var r = document.getElementById("reset");
            if(e!=null) {
                e.onchange = toggleCheckField;
                e.onfocus = toggleCheckField;
                if(r != null) {
                    r.onclick = toggleResetButton;
                }
            } else {
                continuarTrigger = false;
            }
            var i = 0;
            continuarSlave = true;
            while(continuarSlave) {
                try {
                   f = document.getElementById("slave"+j+i);
                   if(f != null) {
                       f.onchange = toggleCheckField;
                       f.onfocus = toggleCheckField;
                       f.disabled = !e.checked;
                       var k = 0;
                       var continuarSub = true;
                       while(continuarSub) {
                            try {
                                s = document.getElementById("subslave"+j+i+k);
                                if(s != null) {
                                    s.disabled = !f.checked;
                                } else {
                                    continuarSub = false;
                                }
                            } catch (exception) {
                                continuarSub = false;
                            }
                            k++;
                       }
                   } else {
                       continuarSlave = false;
                   }
                } catch (exception) {
                    continuarSlave = false;
                }
                i++;
            }
        } catch (exception) {
            continuarTrigger = false;
        }
        j++;
    }
}

/**
*Función del disparador para que los slave se activen y desactiven al activar o
* desactivar el trigger.
*/
toggleCheckField = function() {
   var j = 0;
   var continuarTrigger = true;
   var continuarSlave;
   while (continuarTrigger) { 
        try {
            var e = document.getElementById("trigger"+j);
                if(e==null) {
                   continuarTrigger = false;
                } else {
                    var i = 0;
                    continuarSlave = true;
                    while(continuarSlave) {
                        try {
                           f = document.getElementById("slave"+j+i);
                           if(f != null) {
                               if(e.checked == false) {
                                  tag = f.tagName;
                                  if(tag == "INPUT") {
                                      if(f.type != "checkbox" && 
                                         f.type != "radio") {
                                          f.value == "";
                                      }
                                      if(f.type == "checkbox") {
                                          f.checked = false;
                                      }
                                  } else if(tag == "TEXTAREA") {
                                        f.value == "";
                                  }
                               }
                               f.disabled = !e.checked;
                               var k=0;
                               continuarSub = true;
                               while(continuarSub) {
                                   try {
                                       s = document.getElementById("subslave"+j+i+k);
                                       if(s != null) {
                                           if(f.checked == false) {
                                               tag = s.tagName;
                                               if(tag == "INPUT") {
                                                   if(s.type != "radio" && 
                                                    s.type != "checkbox") {
                                                       s.value == "";
                                                   }
                                                   if(s.type == "checkbox") {
                                                       s.checked = false;
                                                   }
                                               } else if(tag == "TEXTAREA") {
                                                   s.value == "";
                                               }
                                           }
                                           s.disabled = !f.checked;
                                       } else {
                                           continuarSub = false;
                                       }
                                   } catch(exception) {
                                       continuarSub = false;
                                   }
                                   k++;
                               }
                           } else {
                               continuarSlave = false;
                           }
                        } catch (exception) {
                            continuarSlave = false;
                        }
                        i++;
                    }
                }
        } catch (exception) {
            continuarTrigger = false;
        }
        j++;
    }
}

/**
*Función para que cuando se presióne un reset se desactiven todos los slaves
* que existen
*/
toggleResetButton = function () {
    var i = 0;
    var j = 0;
    var continuarTrigger = true;
    var continuarSlave = true;
    var t = document.getElementById("trigger0");
    while(continuarTrigger) {
        t = document.getElementById("trigger"+j);
        if(t != null) {
            i=0;
            continuarSlave = true;
            while(continuarSlave) {
                try {
                   f = document.getElementById("slave"+j+i);
                   if(f != null) {
                       f.disabled = true;
                   } else {
                       continuarSlave = false;
                   }
                } catch (exception) {
                    continuarSlave = false;
                }
                i++;
            }
        } else {
            continuarTrigger = false;
        }
        j++;
    }
}

/**********************************************************************************************/
/*AccionesFormularios: inicializacion del evento en los inputs para pedir confirmación de que se*/
/*                   desea eliminar un item de información. También detectará las etiquetas   */
/*                   'a' cuyo contenido concuerde con la cadena 'Eliminar' y pedirá
/*                   confirmación antes de realizar la acción. También 
/**********************************************************************************************/
var msgConfirmacion = '';
var element;
var inputTags;
var aConfirmTags;
var aHrefs;
AccionesFormularios = function() {
    inputTags = document.getElementsByTagName("INPUT");
    aConfirmTags = document.getElementsByTagName("A");
    var contador = 0;
    var bloqueIzq = document.getElementById("contenido");
    if(inputTags != null) {
        this.confirmar = function() {
            if(!confirm(msgConfirmacion)) {
                for(var i=0; i < inputTags.length; i++){
                    if(inputTags[i].value.match(/Eliminar/g) && inputTags[i].type == "submit") {
                        inputTags[i].type= 'reset';
                    }
                }
            } else {
                for(var i=0; i < inputTags.length; i++){
                    if(inputTags[i].value.match(/Eliminar/g) && (inputTags[i].type == "submit" || inputTags[i].type == "reset")) {
                        inputTags[i].type = 'submit';
                    }
                }
            }
        }
        for(var i = 0; i < inputTags.length; i++) {
            if(inputTags[i].value.match(/Eliminar/g) && inputTags[i].type == "submit") {
                msgConfirmacion = '¿Seguro que desea eliminar el/los elemento(s) seleccionado(s)?';
                EXTRAS.addEvent(inputTags[i],'click',this.confirmar,true);
            }
        }
    }
    contador = 0;
    for(var j = 0; j < aConfirmTags.length; j++) {
        if(aConfirmTags[j].innerHTML.match(/Eliminar/g) || (aConfirmTags[j].href.match(/Eliminar/g) && !aConfirmTags[j].href.match(/#/g))) {
            msgConfirmacion = '¿Seguro que desea eliminar el/los elemento(s) seleccionado(s)?';
            var hrefActual = aConfirmTags[j].href;
            aConfirmTags[j].href = null;
            aConfirmTags[j].href = "javascript:confirmarEnlace('"+hrefActual+"');"
        }
    }
}

confirmarEnlace = function(newLocation) {
    if(confirm(msgConfirmacion)) {
        window.location.href = newLocation;
    }
}

/******************************************************************************
 *Ordenador de tablas. Toma una tabla construida con solo una fila dentro de 
 * <thead> y crea para cada columna un enlace en la misma que permite ordenar el
 * resto de filas dentro de <tbody>.
/*****************************************************************************/
var estadoOrdenacion = "descendente";
var columnaOrdenacion = -1;
var thNodes = null;
var tbodyNode = null;

ActivarOrdenacion = function() {
    var tablaNode = document.getElementsByTagName('TABLE');
    for(var t =0; t < tablaNode.length; t++) {
        if(tablaNode[t].className != 'noOrdenar') {
            var theadNodes = tablaNode[t].getElementsByTagName('THEAD');
            for(var j = 0; j < theadNodes.length; j++) {
                if(theadNodes[j].parentNode == tablaNode[t]) {
                    thNodes = theadNodes[j].getElementsByTagName('TH');
                    for(var i = 0; i < thNodes.length; i++) {
                            thNodes[i].innerHTML="<a href=\"#\" title=\"Pulse aqu&iacute; para ordenar por esta columna\" onClick=\"javascript: "+
                                    "ordenaTabla("+i+",this);\">"+thNodes[i].innerHTML+"</a>";
                    }
                }
            }
        }
    }
}

 /**
 * Funcion que ordena una tabla según el número de la cabecera que se le pase
 **/
ordenaTabla = function(nNode, Node) {
    var tableNode = Node.parentNode;//TH
    tableNode = tableNode.parentNode;//TR
    tableNode = tableNode.parentNode;//THEAD
    tableNode = tableNode.parentNode;//TABLE
    var aTbodyNode = tableNode.getElementsByTagName('TBODY');
    tbodyNode = aTbodyNode[0];
    if(tbodyNode != null) {
        var trNodes = tbodyNode.getElementsByTagName('TR');
        var len = trNodes.length;
        var contadorNodes = 0;
        for(var j = 0; j < len ; j++) {
            if(trNodes[j].parentNode == tbodyNode) {
                contadorNodes++;
            }
        }
        var trNodesSaved = new Array();
        for(var j = 0; j < contadorNodes; j++) {
            if(trNodes[0].parentNode == tbodyNode) {
                trNodesSaved[j] = tbodyNode.removeChild(trNodes[0]);
            }
        }
        /** Algoritmo de ordenación....
        * tomamos la primera posicion, calculamos el elemento menor del array y lo
        * intercambiamos por el que está en la primera posición. Después continuamos
        * por la siguiente posición.
        */
        var tdNodes = null;
        var actualText = "";
        var partialText = "";
        var actualNode = null;
        var aux = null;
        var indiceMenor = 0;
        for(var i = 0; i < trNodesSaved.length; i++) {
            tdNodes =  trNodesSaved[i].getElementsByTagName("TD");
            actualNode = trNodesSaved[i];//el TR padre...
            actualText = getTdText(tdNodes[nNode]);//texto del nodo que minimizamos
            for(var j = i; j < trNodesSaved.length; j++) {
                aux = trNodesSaved[j].getElementsByTagName("TD");
                partialText = getTdText(aux[nNode]);
                if(estadoOrdenacion == "descendente" || nNode != columnaOrdenacion){
                    if(partialText < actualText) {
                        indiceMenor = j;
                        actualText = partialText;
                    }
                } else {
                    if(partialText > actualText) {
                        indiceMenor = j;
                        actualText = partialText;
                    }
                }
            }
            if(indiceMenor > i) {
                aux = trNodesSaved[indiceMenor];
                trNodesSaved[indiceMenor] = trNodesSaved[i];
                trNodesSaved[i] = aux;
            }
            indiceMenor = i;
        }
        for(var j = 0; j < trNodesSaved.length; j++) {
            tbodyNode.appendChild(trNodesSaved[j]);
        }
        if(estadoOrdenacion == "descendente") {
            estadoOrdenacion = "ascendente";
        } else {
            estadoOrdenacion = "descendente";
        }
        if(columnaOrdenacion == -1) {
            columnaOrdenacion = nNode;
        }
        thNodes = Node.parentNode.parentNode.getElementsByTagName("TH");
        for(var i = 0; i < thNodes.length; i++) {
            aNodes = thNodes[i].childNodes[0];
            if(i == nNode) {
                if(columnaOrdenacion == nNode) {
                    thNodes[nNode].innerHTML = "<a href=\"#\" title=\"Pulse aqu&iacute; para ordenar por esta columna\" onClick=\"javascript: "+
                        "ordenaTabla("+nNode+",this);\" class=\""+
                        estadoOrdenacion+"\">"+aNodes.innerHTML+"</a>";
                } else {
                    columnaOrdenacion = -1;
                    thNodes[nNode].innerHTML = "<a href=\"#\" title=\"Pulse aqu&iacute; para ordenar por esta columna\" onClick=\"javascript: "+
                        "ordenaTabla("+nNode+",this);\" class=\"ascendente\">"+
                        aNodes.innerHTML+"</a>";
                }
            } else {
                thNodes[i].innerHTML="<a href=\"#\" title=\"Pulse aqu&iacute; para ordenar por esta columna\" onClick=\"javascript: "+
                                "ordenaTabla("+i+",this);\">"+aNodes.innerHTML+"</a>";
            }
        }
        columnaOrdenacion = nNode;
    }
}

/**
 * Obtiene el texto dentro de cualquier td aunque esté contenido en una etiqueta
 * LABEL.
 */
getTdText = function(Node) {
    var contenidoNode = Node.getElementsByTagName("LABEL");
    var devolver;
    if(contenidoNode.length > 0) {
        devolver = contenidoNode[0].innerHTML.toLowerCase().replace(/ /g, "").replace(/\n/g,"").replace(/€/g,"");
    } else {
        devolver = Node.innerHTML.toLowerCase().replace(/ /g, "").replace(/\n/g,"").replace(/€/g,"");
    }
    if(isNaN(devolver)) {
        var elemFecha = devolver.split("/");
        if(elemFecha.length == 3) {
            var fecha  = new Date(elemFecha[2],elemFecha[1],elemFecha[0]);
            return fecha.getTime();
        } else {    
            return devolver;
        }
    } else {
        return parseInt(devolver);
    }
}

/**
 *Muestra u oculta las filas de una tabla en funcion de los valores buscados.
 *arrayIdFiltro array con los id de los input que contienen los valores que queremos buscar.
 *arrayTd array con el numero de la columna de la tabla en la que buscar el valor de arrayIdFiltro.
 */
filtrar = function(arrayIdFiltro, arrayTd) {
    if(arrayIdFiltro != null && arrayIdFiltro.length > 0 && arrayTd != null && arrayTd.length > 0 && arrayIdFiltro.length == arrayTd.length) {
        var valoresBuscar = new Array(arrayIdFiltro.length);
        for(var i=0; i<arrayIdFiltro.length; i++) {
            valoresBuscar[i] = document.getElementById(arrayIdFiltro[i]).value;
        }
        var body = document.getElementById('tablaFiltrar');
        var tr = body.getElementsByTagName('TR');
        for(var i=0; i<tr.length; i++) {
            var td = tr[i].getElementsByTagName('TD');
            var valoresTd = new Array(arrayTd.length);
            var ver = true;
            for(var j=0; j<valoresTd.length; j++) {
                valoresTd[j] = td[arrayTd[j]].innerHTML.replace(/<(.|\n)+?>\n*/gi,"").replace(/\n/g,"").replace(/^[ \t]+|[ \t]+$/g,"");
                if(valoresTd[j] != valoresBuscar[j] && valoresBuscar[j] != "") {
                    ver = false;
                }
            }
            if(ver) {
                tr[i].style.display = "table-row";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

var marcar = true;
marcarDesmarcarCheck = function(ele) {
    var padre = ele.parentNode;
    var inp = padre.getElementsByTagName("INPUT");
    if(inp != null) {
        for(var i=0; i<inp.length; i++) {
            if(inp[i].type == "checkbox") {
                inp[i].checked = marcar;
            }
        }
        marcar = !marcar;
    }
}

/**
*FUNCIONES JAVASCRIPT PARA VALIDAR FECHAS EN FORMATO dd/mm/aaaa
*/
esdigito = function(schr) {
    var scod = schr.charCodeAt(0);
    return ((scod > 47) && (scod < 58));
}

valsep = function(otxt) {
    var bok = false;
    bok = (bok || ((otxt.value.charAt(2) == "/") && (otxt.value.charAt(5) == "/")));
    return bok;
}

valsephora = function(otxt) {
    var bok = false;
    bok = (bok || (otxt.value.charAt(2) == ":"));
    return bok;
}

finmes = function(otxt) {
    var nmes = parseInt(otxt.value.substr(3, 2), 10);
    var nres = 0;
    switch (nmes){
        case 1: nres = 31; break;
        case 2: nres = 29; break;
        case 3: nres = 31; break;
        case 4: nres = 30; break;
        case 5: nres = 31; break;
        case 6: nres = 30; break;
        case 7: nres = 31; break;
        case 8: nres = 31; break;
        case 9: nres = 30; break;
        case 10: nres = 31; break;
        case 11: nres = 30; break;
        case 12: nres = 31; break;
    }
    return nres;
}

valdia = function(otxt){
    var bok = false;
    var ndia = parseInt(otxt.value.substr(0, 2), 10);
    bok = (bok || ((ndia >= 1) && (ndia <= finmes(otxt))));
    return bok;
}

valmes = function(otxt){
    var bok = false;
    var nmes = parseInt(otxt.value.substr(3, 2), 10);
    bok = (bok || ((nmes >= 1) && (nmes <= 12)));
    return bok;
}

valano = function(otxt){
    var bok = true;
    var nano = otxt.value.substr(6,4);
    bok = (bok && (nano.length == 4));
    if (bok){
        for (var i = 0; i < nano.length; i++){
            bok = (bok && esdigito(nano.charAt(i)));
        }
    }
    return bok;
}

valhora = function(otxt){
    var bok = false;
    var nhor;
    if(otxt.value.length <= 5) {
        nhor = parseInt(otxt.value.substr(0,2),10);
    } else {
        nhor = parseInt(otxt.value.substr(11,2),10);
    }
    bok = (bok || ((nhor >= 0) && (nhor <= 23)));
    return bok;
}

valminuto = function(otxt) {
    var bok = false;
    var nmin;
    if(otxt.value.length <= 5) {
        nmin = parseInt(otxt.value.substr(3),10);
    } else {
        nmin = parseInt(otxt.value.substr(14),10);
    }
    bok = (bok || ((nmin >= 0) && (nmin <= 59)));
    return bok;
}

valHora = function(otxt){
    var bok = true;
    if(otxt.value != ""){
        bok = (bok && (valhora(otxt)));
        bok = (bok && (valminuto(otxt)));
        bok = (bok && (valsephora(otxt)));
        if(!bok) {
            alert("Formato de hora inválido.\nFormato correcto (hh:mm)");
            otxt.value = "";
            otxt.focus();
        }
    }
}

valfecha = function(otxt){
    var bok = true;
    if (otxt.value != ""){
        bok = (bok && (valano(otxt)));
        bok = (bok && (valmes(otxt)));
        bok = (bok && (valdia(otxt)));
        bok = (bok && (valsep(otxt)));
        if (!bok){
            alert("Formato de fecha inválido.\nFormato correcto (dd/mm/aaaa)");
            otxt.value = "";
            otxt.focus();
        }
    }
}

valFechaHora = function(otxt){
    var bok = true;
    if(otxt.value != ""){
        bok = (bok && (valano(otxt)));
        bok = (bok && (valmes(otxt)));
        bok = (bok && (valdia(otxt)));
        bok = (bok && (valsep(otxt)));
        bok = (bok && (valhora(otxt)));
        bok = (bok && (valminuto(otxt)));
        if (!bok){
            alert("Formato de fecha inválido.\nFormato correcto (dd/mm/aaaa hh:mm)");
            otxt.value = "";
            otxt.focus();
        }
    }
}

fechaMayorIgual = function(fec0, fec1) {
    var bRes = false;
    var sDia0 = fec0.substr(0, 2);
    var sMes0 = fec0.substr(3, 2);
    var sAno0 = fec0.substr(6, 4);
    var sDia1 = fec1.substr(0, 2);
    var sMes1 = fec1.substr(3, 2);
    var sAno1 = fec1.substr(6, 4);
    if (sAno0 > sAno1) {
        bRes = true;
    } else {
        if (sAno0 == sAno1) {
            if (sMes0 > sMes1) {
                bRes = true;
            } else {
                if (sMes0 == sMes1) {
                    if (sDia0 >= sDia1) {
                        bRes = true;
                    }
                }
            }
        }
    }
    return bRes;
}

fechaMenorIgual = function(fec0, fec1) {
    var bRes = false;
    var sDia0 = fec0.substr(0, 2);
    var sMes0 = fec0.substr(3, 2);
    var sAno0 = fec0.substr(6, 4);
    var sDia1 = fec1.substr(0, 2);
    var sMes1 = fec1.substr(3, 2);
    var sAno1 = fec1.substr(6, 4);
    if (sAno0 < sAno1) {
        bRes = true;
    } else {
        if (sAno0 == sAno1) {
            if (sMes0 < sMes1) {
                bRes = true;
            } else {
                if (sMes0 == sMes1) {
                    if (sDia0 <= sDia1) {
                        bRes = true;
                    }
                }
            }
        }
    }
    return bRes;
}
/**
*FIN FUNCIONES JAVASCRIPT PARA VALIDAR FECHAS EN FORMATO dd/mm/aaaa
*/

/**
*FUNCIONES JAVASCRIPT PARA NOTIFICACIONES (envio de correos)
*/

// document.getElementById abreviado 
$= function(x) { return document.getElementById(x); }

mostrarDestinatarios = function () {
    if($('opciones').style.display == "block") {
        $('opciones').style.display = "none";
    } else {
        $('opciones').style.display = "block";
    }
}

buscarenSelect=function() {
    formu=$('formulario');
    caracteres=$('buscarusuarios').length;
    if(caracteres != 0) {
        for (x=0; x<formu['usuarios'].options.length; x++){
            cadena=formu['usuarios'].options[x].text;
            if(cadena.search($('buscarusuarios').value) >= 0) {
                formu['usuarios'].selectedIndex=x;
                break;
            }
        }
    }
}

seleccionarOpcion = function () {
    txt="";
    if($('opcionElegidaDiv').value != "") {
	txt = $('opcionElegidaDiv').value;
    }
    var selObj = $('usuarios');
    var count = 0;
    for (var i=0; i<selObj.options.length; i++) {
        if (selObj.options[i].selected) {
            cadenaelegida = selObj.options[i].value;
            if(txt.length > 0) {
                txt = txt +" ; "+cadenaelegida;
            } else {
                txt = cadenaelegida;
            }
            direcciones = $('opcionElegidaDiv').value;
            if(cadenaelegida != "" && !(direcciones.search(cadenaelegida) >= 0)) {
                $('opcionElegidaDiv').value = txt;
            }
        }
    }
}

cerrarLibreta = function (opt) {
    txt = "";
    if(opt == "A") {
        if($('destinatarios').value != "") {
            $('destinatarios').value = $('destinatarios').value + " ; " + $('opcionElegidaDiv').value;
        } else {
            $('destinatarios').value = $('destinatarios').value + $('opcionElegidaDiv').value;
        }
    }
    $('opciones').style.display = "none";
}

nuevoArchivo = function(numero) {
    var label = $('cabinet');
    //obtenemos el input con el archivo
    var anterior = $('archivo'+(numero-1));
    anterior.style.display = "none";
    var ele = document.createElement("a");
    ele.setAttribute("id", "eliminar"+(numero-1));
    ele.setAttribute("href", "#");
    ele.setAttribute("title", "Eliminar fichero");
    ele.setAttribute("class", "eliminarDocAdjunto");
    ele.setAttribute("className", "eliminarDocAdjunto");
    ele.innerHTML = "[Eliminar]";
    ele.onclick = function() { eliminarArchivo(this) };
    $('archivos').appendChild(ele);
    //insertarmos el nombre del archivo
    ele = document.createElement("span");
    ele.setAttribute("class", "spanArchivo");
    ele.setAttribute("className", "spanArchivo");
    ele.setAttribute("id", "spanArchivo"+(numero-1));
    ele.innerHTML = anterior.value.substr(anterior.value.lastIndexOf("\\")+1);
    $('archivos').appendChild(ele);
    //insertamos el input con el archivo
    anterior.removeAttribute("onchange");
    anterior.onchange = function() {};
    $('archivos').appendChild(anterior);
    ele = document.createElement('br');
    ele.setAttribute("id", "br"+(numero-1));
    $('archivos').appendChild(ele);
    //creamos el nuevo input
    ele = document.createElement("input");
    ele.setAttribute("type", "file");
    ele.setAttribute("id", "archivo"+numero);
    ele.setAttribute("name", "archivo"+numero);
    ele.setAttribute("class", "file");
    ele.setAttribute("className", "file");
    ele.setAttribute("title", "Adjuntar nuevo fichero")
    ele.onchange = function() {nuevoArchivo((numero+1))};
    label.appendChild(ele);
    SI.Files.stylizeById('archivo'+numero);
}

eliminarArchivo = function(ele) {
    var n = ele.id.match(/[0-9]+/i);
    var span = $('spanArchivo'+n);
    var a = $('eliminar'+n);
    var inp = $('archivo'+n);
    var br = $('br'+n);
    $('archivos').removeChild(span);
    $('archivos').removeChild(a);
    $('archivos').removeChild(inp);
    $('archivos').removeChild(br);
    var hijos = $('archivos').childNodes;
    if(hijos != null) {
        for(var j=0; j<hijos.length; j++) {
            if(hijos.item(j).id != undefined) {
                var num = hijos.item(j).id.match(/[0-9]+/i);
                if(num != null) {
                    if(parseInt(num) > parseInt(n)) {
                        if(hijos.item(j).tagName == "INPUT") {
                            hijos.item(j).name = hijos.item(j).name.match(/[a-z]+/i)+(parseInt(num)-1);
                        } else if(hijos.item(j).tagName == "A") {
                            hijos.item(j).onclick = function() { eliminarArchivo(this); };
                        }
                        hijos.item(j).id = hijos.item(j).id.match(/[a-z]+/i)+(parseInt(num)-1);
                    }
                }
            }
        }
    }
    var input = $('cabinet').getElementsByTagName("INPUT");
    var nume = input[0].id.match(/[0-9]+/i);
    input[0].id = "archivo"+(parseInt(nume)-1);
    input[0].name = "archivo"+(parseInt(nume)-1);
    input[0].onchange = function() { nuevoArchivo(parseInt(nume)); };
}
/**
*FIN FUNCIONES JAVASCRIPT PARA NOTIFICACIONES (envio de correos)
*/

EXTRAS.addEvent(window, 'load', init, false);