// Variables globales

// Javascript para vista mensual.
var mouseX=0, mouseY=0;
var MOUSE_DIST_X = 15;
var MOUSE_DIST_Y = 25;
var MSIE = false;
var GECKO = false;
var popupActivo = null;
var popupVisible = false;
var anchoCapa = 386;
var altoCapa = 150;


/** Añade el evento onfocus a los inputs de tipo texto **/
function focusInputs(){	
    var campo, campos =  new Array();
    var i;
    
    var	aInputs = document.getElementsByTagName("input");    
    var aTextareas = document.getElementsByTagName("textarea");
    var aSelects = document.getElementsByTagName("select");
    
    for( i=0; i<aInputs.length; i++ ){
        if( aInputs[i].type == "text" ){
            campos.push( aInputs[i] );
        }
    }       
    for( i=0; i<aTextareas.length; i++ ){
        campos.push( aTextareas[i] );
    }
    for( i=0; i<aSelects.length; i++ ){
        campos.push( aSelects[i] );
    }
                    
	// Recorremos los input quedándonos solo con los de tipo texto
	for ( i=0; i<campos.length; i++ ){
        campo = campos[i];
        campo.onfocus = function(){				
            enfocar(this);
        }
        campo.onblur = function(){
            desenfocar(this);
        }
	}
}

/* 
Función que se ejecutará al cargar la página.
*/
function init (){
    focusInputs();
    loadExternalUrl();
    initPopup();    
}

if( navigator.userAgent.indexOf('MSIE')!=-1 ){
   ie = true;
   ns = false;
   MSIE = true;
   window.attachEvent('onload', init );
}       
if( navigator.userAgent.indexOf('Gecko')!=-1 ){		
   ie = false;
   ns = true;
   GECKO = true;
   window.addEventListener( 'load', init, false );
}

function enfocar(campo){
	if ( campo.className.indexOf("Enfocado") == -1 ){
		campo.className += "Enfocado";	
	}    
}

function desenfocar( campo ){	
	if ( campo.className.indexOf("Enfocado") != -1){
		campo.className = campo.className.replace( "Enfocado", "" );
	}		
}

/***************************************************************************************/

function swapImgRestore()
{
	var i,x,a=document.sr;
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function preloadImages()
{
	var d=document;
	if(d.images)
	{
		if(!d.p) d.p=new Array();
		var i,j=d.p.length,a=preloadImages.arguments;
		for(i=0; i<a.length; i++)
		    if (a[i].indexOf("#")!=0)
			{
				d.p[j]=new Image;
				d.p[j++].src=a[i];
			}
	}
}

function findObj(n, d)
{
	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=findObj(n,d.layers[i].document);
	if(!x && document.getElementById) x=document.getElementById(n);
	return x;
}

function swapImage()
{
	var i,j=0,x,a=swapImage.arguments;
	document.sr=new Array;
	for(i=0;i<(a.length-2);i+=3)
		if ((x=findObj(a[i]))!=null)
		{
			document.sr[j++]=x;
			if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
		}
}

function initPopup(){                            
		
    // Capturamos los eventos del ratón
    if( MSIE ){
        document.onmousemove = mouseMove;
    }else if( GECKO ){    		
        document.onmousemove = mouseMove;
        document.captureEvents(Event.MOUSEMOVE);
    }                                
}                        

function getOffsetLeft (el) {
    var ol = el.offsetLeft;
    while ((el = el.offsetParent) != null){
        ol += el.offsetLeft;
    }
    return ol;
}

function getOffsetTop (el) {
    var ot = el.offsetTop;
    while((el = el.offsetParent) != null){
        ot += el.offsetTop;
    }
    return ot;
}      

function getOrigenX(){
    if( GECKO ){                
        return window.pageXOffset;                    
    } else if( MSIE ){
        return document.documentElement.scrollLeft;
    }
}
function getOrigenY(){                
    if( GECKO ){
        return window.pageYOffset;
    } else if( MSIE ){                    
        return document.documentElement.scrollTop;
    }
}            

// Funciones para posicionar el layer.
function mouseMove (e) {                                            	
    if( popupVisible ){
        if( GECKO ){
            mouseX= parseInt(e.pageX,10);
            mouseY= parseInt(e.pageY,10);                                        
        } else if( MSIE ){
            mouseX= event.clientX + getOrigenX();
            mouseY= event.clientY + getOrigenY();
        }
                    
        if( GECKO ){
            anchoDoc = window.innerWidth;
            altoDoc = window.innerHeight;
        } else if( MSIE ){
            anchoDoc = document.documentElement.clientWidth;
            altoDoc = document.documentElement.clientHeight;
        }
        anchoDoc += getOrigenX();
        altoDoc += getOrigenY();
    
        var obj = document.getElementById(popupActivo);                    
    
        // Obtenemos el rectángulo del area cliente (el area visible).
        clientLeft = getOrigenX();
        clientTop = getOrigenY();
        clientRight = anchoDoc - 20;    // Asumimos 20 pixels de ancho de las barras de scroll.
        clientBottom = altoDoc - 20;                                                                                        
                
        // Posicionamos la capa inicialmente alejada del ratón.
        capaX = mouseX + MOUSE_DIST_X;
        capaY = mouseY + MOUSE_DIST_Y;
                                
        if( capaX+anchoCapa > clientRight ){
             capaX = clientRight - anchoCapa;
        }
        if( capaY+altoCapa > clientBottom ){
            capaY = clientBottom - altoCapa;
        }
        if( capaY < clientTop ){
            capaY = clientTop;
        }                  
        if( capaX < clientLeft ){
            capaX = clientLeft;
        }                        
        
        // Si al final el puntero del ratón nos queda dentro de la capa, la movemos para no interferir en el rollover.
        if( mouseX > capaX && mouseX < capaX+anchoCapa && mouseY > capaY && mouseY < capaY+altoCapa ){
            espacio=new Array();
            espacio[0] = clientBottom - mouseY; // abajo
            espacio[1] = mouseY - clientTop;    // arriba
            espacio[2] = mouseX - clientLeft;   //izq
            espacio[3] = clientRight - mouseX;  //der
            
            max = pos = 0;                                
            for( i=0; i<4; i++ ){                      
                if( espacio[i] > max ){
                    max = espacio[i];
                    pos = i;
                }
            }
            switch( pos ){
                case 0:capaY = mouseY + MOUSE_DIST_Y; break;
                case 1:capaY = mouseY - altoCapa - MOUSE_DIST_Y*2; break;
                case 2:capaX = mouseX - anchoCapa - MOUSE_DIST_X*2; break;
                case 3:capaX = mouseX + MOUSE_DIST_X; break;
            }
        }                
        obj.style.left = capaX + "px";
        obj.style.top = capaY + "px";
        obj.style.display = "block";
    }
}                            

function mostrarPopup(id){
    //popupActivo = "popupEvento_"+id;
    popupActivo = id;
    var obj = document.getElementById(popupActivo);                                
    popupVisible = true; 
}

function ocultarPopup(){                
    popupVisible = false;
    var obj = document.getElementById(popupActivo);
    if( obj ){
        obj.style.display = "none";
        obj.style.left="0px";
        obj.style.top="0px";
    }
}
            
// Abir una ventana popup (no resizable)
function abrirPopup( url ,f_amp, f_alt, nom_finestra, scroll ){
	ancho=screen.width;				//ample pantalla
	alto=screen.height;				//alt pantalla
	v_top=(alto-f_alt)/2;	
	v_left=(ancho-f_amp)/2;
	if (typeof(v_fin)!="undefined"){
		v_fin.close();
	}
	v_fin=window.open(url,nom_finestra,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars="+(scroll?'yes':'no')+",resizable=no,width="+f_amp+",height="+f_alt+",top="+v_top+",left="+v_left);

}

/* Modificar los enlaces externos (aquellos con el atributo rel="external") para que se abran
 en ventana nueva. */
function loadExternalUrl(){
	if( !document.getElementsByTagName ){
        return;
    }
	var links=document.getElementsByTagName( 'a' );
	for( var i=0; i<links.length; i++ ){
		if( links[i].rel=="external" ){
			links[i].target="_blank";
		}
	}
}

/**
 * Cambia la clase de un elemento a "desplegado".
 */
function desplegar( id ){
    var bloque = document.getElementById(id);    
    bloque.className = "desplegado";
}            
/**
 * Cambia la clase de un elemento a "plegado".
 */
function plegar( id ){
    var bloque = document.getElementById(id);    
    bloque.className = "plegado";
}

/**
 * Función para actualizar los el texto de carácteres restentes de un textarea.
 */
function carsRestantes( textarea, id, maximo ){
    var nodo = document.getElementById( id );
    maximo = maximo || 5000;    
    if( textarea.value.length >= maximo ){
        textarea.value = textarea.value.substr( 0, maximo );
    }
    nodo.firstChild.nodeValue = maximo - textarea.value.length;
}

/** Muestra/Oculta Bloques **/
function ocultar(oAnchor){

	/* Obtenemos el identificador del nodo a ocultar */
	var keyWord = oAnchor.id.substring(oAnchor.id.indexOf("_")+1);

	/* Cambiamos la visibilidad del nodo */
	bloque = document.getElementById('extendido_'+keyWord);

	/* Nodo de cabecera de seccion */
	nCabecera = document.getElementById("cabecera_"+keyWord);

	/* Caja contenedora de cabecera */
	nCajaCabecera = document.getElementById("cabeceraBloque_"+keyWord);

	if(bloque.className == ''){
		bloque.className = "oculto";
		nCabecera.className = "plegado";
		nCajaCabecera.className += " plegado";
	}else{
		bloque.className = '';
		nCabecera.className = "desplegado";
		nCajaCabecera.className = "cabeceraBloque";
	}
}	

/**
 * Extensión del objeto Date para comparar dos fechas.
 */
Date.prototype.compareTo=function (objFecha){
    if ( this.getTime() == objFecha.getTime() ){
        return 0;
    }else if (this.getTime() > objFecha.getTime() ){
        return 1;
    }else{
        return -1;
    }
}
 
/**
 * Función para marcar el valor de un select.
 */           
function marcarSelect( sel, value ){
    for( var i=0; i<sel.options.length; i++ ){
        if( sel.options[i].value == value ){
            sel.selectedIndex = i;
        }
    }
}

/*
 * Función para actualizar dos grupos de campos de fecha (inicial y final).
 */
function cambiaFecha(){
    var selDiaDesde, selMesDesde, selAnyDesde;                              
    var selDiaHasta, selMesHasta, selAnyHasta;
    var dia,mes,any;
    var desde = null, hasta = null;
                    
    selDiaDesde = document.getElementById("campoDiaInicio");
    selMesDesde = document.getElementById("campoMesInicio");
    selAnyDesde = document.getElementById("campoAnyoInicio");
                    
    selDiaHasta = document.getElementById("campoDiaFin");
    selMesHasta = document.getElementById("campoMesFin");
    selAnyHasta = document.getElementById("campoAnyoFin");                                
    
    dia = selDiaDesde.selectedIndex != 0 ? parseInt( selDiaDesde.options[selDiaDesde.selectedIndex].value, 10 ) : null;
    mes = selMesDesde.selectedIndex != 0 ? parseInt( selMesDesde.options[selMesDesde.selectedIndex].value, 10 ) : null;
    any = selAnyDesde.selectedIndex != 0 ? parseInt( selAnyDesde.options[selAnyDesde.selectedIndex].value, 10 ) : null;
                                    
    if( dia != null && mes != null && any != null ){
        desde = new Date( any, mes, dia );
    }
                                    
    if( desde == null ){
        return;
    }
                                    
    dia = selDiaHasta.selectedIndex != 0 ? parseInt( selDiaHasta.options[selDiaHasta.selectedIndex].value, 10 ) : null;
    mes = selMesHasta.selectedIndex != 0 ? parseInt( selMesHasta.options[selMesHasta.selectedIndex].value, 10 ) : null;
    any = selAnyHasta.selectedIndex != 0 ? parseInt( selAnyHasta.options[selAnyHasta.selectedIndex].value, 10 ) : null;                                
    
    if( dia != null && mes != null && any != null ){
        hasta = new Date( any, mes, dia );
    }                                
    if( hasta != null ){
        if( hasta.compareTo(desde) < 0 ){
            marcarSelect( selDiaHasta, desde.getDate() );
            marcarSelect( selMesHasta, desde.getMonth() );
            marcarSelect( selAnyHasta, desde.getFullYear() );
        }
    }
}

/**
 * Objeto para gestionar los campos de tags.
 */
function TagsField( idInput, etiquetas ){
    this.etiquetas = etiquetas || new Array();
    this.idInput = idInput;
    
    /**
     * Método para actualizar las etiquetas según el valor del input.
     */
    this.actualizaEtiquetas = function(){
        
        var palabras = this.extraePalabras( this.idInput );
        
        this.desmarcaEtiquetas();
        
        for( var i=0; i<palabras.length; i++ ){
            
            for( var j in this.etiquetas ){
                
                // Si una palabra coincide parcialmente con una etiqueta la resaltamos también parcialmente.                
                if( this.etiquetas[j].toLowerCase().indexOf( palabras[i].toLowerCase() ) == 0 ){                    
                    this.marcaEtiquetaParcial( j, palabras[i].length );
                }
                
                if( palabras[i].toLowerCase() == this.etiquetas[j].toLowerCase() ){
                    this.insertaEtiqueta( j );
                }
            }
        }
    }
    
    /**
     * Borra una etiqueta del campo y desmarca su enlace.
     */
    this.borraEtiqueta = function( id ){
        var campo = document.getElementById( this.idInput );
        var texto = campo.value.toLowerCase();
        var etiqueta = this.etiquetas[id];
        var inicio;
        
        // Desmarcamos el enlace de la etiqueta.
        this.desmarcaEtiqueta( id );
        
        // Eliminamos la etiqueta del texto.
        if( ( inicio = texto.indexOf( etiqueta.toLowerCase() ) ) >= 0 ){
            if( this.palabraCompuesta( etiqueta ) ){
                campo.value = campo.value.substring( 0, inicio - 1 ) + campo.value.substring( inicio + etiqueta.length + 1 );
            }else{
                campo.value = campo.value.substring( 0, inicio ) + campo.value.substring( inicio + etiqueta.length );
            }
        }
        
        campo.value = this.limpiaTexto( campo.value );
    }
    
    /**
     * Desmarca una etiqueta.
     */
    this.desmarcaEtiqueta = function( id ){
        var anchor = document.getElementById(id);
        anchor.className = '';
        anchor.innerHTML = this.etiquetas[id];
    }
    
    /**
     * Desmarca todos los enlaces de etiquetas.
     */
    this.desmarcaEtiquetas = function(){
        for( var id in this.etiquetas ){
            this.desmarcaEtiqueta(id);
        }
    }
    
    this.escribeEtiquetas = function( id ){
        var texto, html;
        
        html = '<ul class="etiquetas">';
        
        for( var i in this.etiquetas ){
            texto = this.etiquetas[i];
            compuesta = this.palabraCompuesta(texto);
            html += '<li>';
            html += compuesta ? '<span>&quot;</span>' : '';
            html += '<a href="javascript:void(0);" onclick="tagsField.setEtiqueta(this);return false;" id="'+i+'">'+texto+'</a>';
            html += compuesta ? '<span>&quot;</span>' : '';
            html += '</li>';
        }
        
        html += '</ul>';
        
        document.write( html );
    }
    
    /**
     * Devuelve la etiqueta activa.
     * @param {int} id Identificador de etiqueta.
     * @return {boolean}
     */
    this.etiquetaActiva = function( id ){
        return document.getElementById(id).className == 'seleccionada';
    }
    
    /**
     * Extrae las palabras del campo.     
     * @return {Array}
     */
    this.extraePalabras = function(){
        var campo = document.getElementById( this.idInput );
        var palabras = new Array();
        var texto = campo.value;
        var inicio;
        var i;
        
        // Reducimos los espacios en blanco (por si hay mas dos seguidos o más).
        texto = this.limpiaTexto( texto );
        
        // Obtenemos las palabras compuestas.
        texto = this.extraePalabrasCompuestas( texto, palabras );
        
        texto = this.limpiaTexto( texto );
                
        this.extraePalabrasSimples( texto, palabras );        
        
        return palabras;
    }
    
    /**
     * Método recursivo para extraer las palabras compuestas.
     * @param {String} texto
     * @param {Array} palabras
     */
    this.extraePalabrasCompuestas = function( texto, palabras ){
        
        if( texto.length > 0 ){
            
            inicio = texto.indexOf('"');
            fin = texto.indexOf('"', inicio+1 );
            
            if( inicio >=0 && fin >= 0 ){
                palabras.push( this.limpiaTexto(texto.substring( inicio + 1, fin )) );
                return this.extraePalabrasCompuestas( texto.substring(0,inicio) + texto.substring(fin + 1), palabras );
            }
            
        }
        
        return texto;
    }
    
    /**
     * Método que extrae las palabras simples de un texto (aquellas separadas por espacios).
     * @param {String} texto
     * @param {Array} palabras
     */
    this.extraePalabrasSimples = function( texto, palabras ){
        
        if( texto.length > 0 ){
            var simples = texto.split(' ');
            for( var i=0; i<simples.length; i++ ){
                palabras.push( simples[i] );
            }
        }
        
        return texto;
    }
    
    /**
     * Inserta una nueva etiqueta en el campo y marca su enlace correspondiente.
     * @param {int} id
     */
    this.insertaEtiqueta = function( id ){
        var campo = document.getElementById( this.idInput );
        var texto = campo.value.toLowerCase();
        var etiqueta = this.etiquetas[id];
        
        this.marcaEtiqueta(id);
        
        // Añadimos la etiqueta al campo.
        if( texto.indexOf( etiqueta.toLowerCase() ) < 0 ){
            
            campo.value = this.limpiaTexto( campo.value );
            
            if( this.palabraCompuesta( etiqueta ) ){                                
                campo.value += ' "'+etiqueta+'"';
            }else{
                campo.value += ' '+etiqueta;
            }
            
            campo.value = this.limpiaTexto( campo.value );
        }
    }

    /**
     * Marca una etiqueta.
     */
    this.marcaEtiqueta = function( id ){
        // Marcamos el enlace de la etiqueta.
        document.getElementById(id).className = 'seleccionada';
    }
    
    this.marcaEtiquetaParcial = function( id, longitud ){
        var anchor = document.getElementById(id);
        var etiqueta = this.etiquetas[id];
        var texto = anchor.firstChild.nodeValue;
        if( longitud <= etiqueta.length ){
            anchor.innerHTML = "<strong>"+etiqueta.substring(0,longitud)+"</strong>"+etiqueta.substring(longitud);
        }else{
            anchor.innerHTML = this.etiquetas;
        }
    }

    /**
     * Método para eliminar los espacios en blanco al comienzo y final de una cadena.
     * @param {String} texto
     * @return {String}
     */
    this.limpiaTexto = function( texto ){        
        return texto.replace( /^\s*/, "" ).replace( /\s*$/, "" ).replace( /\s+/g, " " ); 
    }
    
    /**
     * Devuelve true si una string está compuesto por más de una palabra.
     * @param {String} texto
     */ 
    this.palabraCompuesta = function( texto ){
        return ( this.limpiaTexto(texto).split(' ').length > 1 );
    }
    
    /**
     * Marca/desmarca una etiqueta.
     */
    this.setEtiqueta = function(oAnchor){
        var campo = document.getElementById(this.idInput);
        
    	// Obtenemos el objeto etiqueta del array de etiquetas
    	var etiqueta = this.etiquetas[oAnchor.id];
    	
    	// Fijamos el texto de la etiqueta en el input
    	if( !this.etiquetaActiva( oAnchor.id ) ){
    	    this.insertaEtiqueta(oAnchor.id);
    	}else{
    	    this.borraEtiqueta(oAnchor.id);            
    	}
    	
    	this.actualizaEtiquetas();
    	
    	campo.focus();
    }
    
    // Constructor
    this.escribeEtiquetas();
}

/*******************************************************************/
/** Despliega el texto completo de descripción de una publicación **/
/*******************************************************************/
/*
<!-- MAQUETA PARA LA DESCRIPCION 
<p id="descripcionPublicacion_i">
	caracteres (0..200)
	<span class="descripcionAmpliada">
		<span class="textoAmpliada">
			caracteres (200..end)
		</span>
		<a href="javascript:void(0)" id="descripcionPublicacion_184343Mostrar" onclick="desplegarTexto('descripcionPublicacion_184343')">mostrar todo</a>
		<a href="javascript:void(0)" id="descripcionPublicacion_184343iOcultar" onclick="desplegarTexto('descripcionPublicacion_i')">mostrar todo</a>
	</span>
</p>
-->

<!-- Donde i es el identificador de la publicación, o un contador, o lo que sea, pero que no se repita -->
*/

function desplegarTexto(idParrafoContenedor, nodoEnlace){
	
	var parrafo = document.getElementById(idParrafoContenedor);
	
	var enlaceOcultar = document.getElementById(idParrafoContenedor+'Ocultar');
	var enlaceMostrar = document.getElementById(idParrafoContenedor+'Mostrar');
	
//	if(parrafo.className == "extendido"){
	if (parrafo.className.indexOf('extendido') != -1){	
		parrafo.className = "resumen";
		enlaceMostrar.className = "";
		enlaceOcultar.className = "oculto";
		
	}else if(parrafo.className == 'resumen'){
		parrafo.className += " extendido";
		enlaceMostrar.className = "oculto";
		enlaceOcultar.className = "";
	}
	
}

/*************************/
/* Validador de formularios*/
/*************************/


function FormValidator(idFormulario){

	/* nodo del formulario */
	this.nForm =  document.getElementById(idFormulario);
        	
	/* array de objetos campo, con expresion regular y mensaje de error */
	this.arrFields = new Array();

	/* array de objetos campo, numeros aleatorios y mensaje de error */
	this.arrSpan = new Array();
	
	
	/* ARRAY DE CAMPOS QUE CUMPLEN LA VALIDACION */
	this.fieldsValidos = new Array();
	
	
	/* ARRAY DE CAMPOS QUE NO CUMPLEN LA VALIDACION */
	this.fieldsNoValidos = new Array();

	
	/* EXPRESIONES REGULARES */
	FormValidator.noVacio = /\w/;
	FormValidator.noCero = /[^0]/;
	FormValidator.eMail = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	
	
	/* Cadena de error */
	
	this.cadenaError = '';

	this.arrCheckGroups = new Array();
	
	this.arrCheckDependencies = new Array();
	
	this.arrRadioDependencies = new Array();
	
    this.arrSelectDependencies = new Array();
    
    this.arrMandatorySelects = new Array();
	
}

FormValidator.prototype.setAction = function(action){
	
	this.nForm.setAttribute("action",action );
}


FormValidator.prototype.addField = function(nomCamp,regExp,mensError){
	
	this.arrFields.push({name: nomCamp, expr: regExp, mensError: mensError});
	
}


FormValidator.prototype.addSpan = function(nomCamp,numeros,mensError){
	
	this.arrSpan.push({name: nomCamp, numeros: numeros, mensError: mensError});
	
}


FormValidator.prototype.addRadioDependencies = function(nameRadio, value, inputName, regExp, mensError){

	this.arrRadioDependencies.push({nameRadio: nameRadio, value: value ,name: inputName, regExp: regExp, mensError: mensError });

}

FormValidator.prototype.addCheckDependencies = function(checkName, inputName, regExp, mensError){
	
	this.arrCheckDependencies.push({nameCheck: checkName, nameInput: inputName, regExp: regExp, mensError: mensError});
	
}


FormValidator.prototype.addSelectDependencies = function(nameSelect, valueOption, inputName, regExp, regExpNegada, mensError){
// RegExpNegada se utiliza para validar campos que NO deben hacer match con la expresion regular pasada
    this.arrSelectDependencies.push({nameSelect: nameSelect, value: valueOption ,name: inputName, regExp: regExp, regExpNegada: regExpNegada, mensError: mensError });

}


FormValidator.prototype.addSelectMandatory = function(nameSelect, regExpValue, fieldName, regExpField, mensError){
	
	this.arrMandatorySelects.push({nameSelect: nameSelect, regExpSelect: regExpValue, fieldName: fieldName, regExpField: regExpField, mensError: mensError});
}

FormValidator.prototype.addCheckGroup = function(arrNamesCheck ,mensError, minCheck, maxCheck){
	
	this.arrCheckGroups.push({arrNames: arrNamesCheck, mensError: mensError , minimo: minCheck, maximo: maxCheck});
	
}



FormValidator.prototype.checkForm = function(){
	var radioButtons;
	
	this.resetValidation();
	

	// Validamos las dependencias de los radio Buttons
	if(this.arrRadioDependencies.length > 0){
		
		for (var i in this.arrRadioDependencies){
			
			//seleccionamos en el formulario el nodo Radio button
			radioButtons = this.nForm[this.arrRadioDependencies[i].nameRadio];
			
			// es un radio??
			for (var j=0; j<radioButtons.length; j++ ){
			
				if (radioButtons[j].checked == true ){
					
					if (this.arrRadioDependencies[i].value == radioButtons[j].value){
						this.validateField( {name: this.arrRadioDependencies[i].name, expr:  this.arrRadioDependencies[i].regExp, mensError:  this.arrRadioDependencies[i].mensError } );
					}			
				}
			}			
		}
	}
	
	// Validamos las dependencias de Selects
    if(this.arrSelectDependencies.length > 0){
        
        for (var i in this.arrSelectDependencies){
            
			// name del select 
			selectName = this.arrSelectDependencies[i].nameSelect;

			valorSeleccionado = this.nForm[selectName].options[this.nForm[selectName].selectedIndex].value;
			
            // Si el valor del option seleccionado es el que fuerza a validar un campo
            if (valorSeleccionado == this.arrSelectDependencies[i].value){
                this.validateField( {name: this.arrSelectDependencies[i].name, expr: this.arrSelectDependencies[i].regExp, regExpNegada: this.arrSelectDependencies[i].regExpNegada ,mensError: this.arrSelectDependencies[i].mensError});
            }
                        
        }
    }
    
    //this.arrMandatorySelects.push({nameSelect: nameSelect, regExpSelect: regExpValue, fieldName: fieldName, regExpField: regExpField, mensError: mensError});
    // Validamos los selects mandatorios (aquellos que fuerzan a rellenar otro campo)
    if(this.arrMandatorySelects.length > 0){
        
    	
        for (var i in this.arrMandatorySelects){
            
			// name del select 
			selectName = this.arrMandatorySelects[i].nameSelect;
			
			if (this.nForm[selectName]){
				valorSeleccionado = this.nForm[selectName].options[this.nForm[selectName].selectedIndex].value;	
			}
			
			
            // Si el valor del option seleccionado es el que fuerza a validar un campo (hace match con la regexp marcada para el select)
            if (valorSeleccionado.match(this.arrMandatorySelects[i].regExpSelect) != null){
                this.validateField( {name: this.arrMandatorySelects[i].fieldName, expr: this.arrMandatorySelects[i].regExpField, mensError: this.arrMandatorySelects[i].mensError});
            	//alert (this.arrMandatorySelects[i].fieldName);
            }
                        
        }
    }
	


	// Validamos los grupos de checkboxes
	if(this.arrCheckGroups.length > 0){
		
		for (var i in this.arrCheckGroups){
			numChecked = 0;
			
			// Buscamos los items que estan checkeados
			for (var j in this.arrCheckGroups[i].arrNames){
				
			
				if (this.nForm[this.arrCheckGroups[i].arrNames[j]].checked){
					numChecked += 1; 
				}
			
			}
			
			// Si hay menos checkeados que el minimo exigido
			if (numChecked < this.arrCheckGroups[i].minimo){
				
				this.fieldsNoValidos.push({name: this.arrCheckGroups[i].arrNames[0], expr: '', mensError: this.arrCheckGroups[i].mensError} );
				
			// Si se ha fijado un máximo
			}else if(this.arrCheckGroups[i].maximo){
				// Si hay más checkeados que el máximo permitido
				if(numCheked > this.arrCheckGroups[i].maximo ){
					this.fieldsNoValidos.push({name: this.arrCheckGroups[i].arrNames[0], expr: '', mensError: this.arrCheckGroups[i].mensError});
				}
			}
		}
	
	}
	
	if (this.arrCheckDependencies.length > 0){
		
		for(var i in this.arrCheckDependencies){
			if(this.nForm[this.arrCheckDependencies[i].nameCheck].checked == true){
				
				this.validateField({name: this.arrCheckDependencies[i].nameInput, expr: this.arrCheckDependencies[i].regExp, mensError: this.arrCheckDependencies[i].mensError });
			}
		}
		
		
	}
	
	
	if (this.arrFields.length > 0 ){
		// Resto de campos
		for(var i in this.arrFields){
			this.validateField(this.arrFields[i]);	
		}
	}

	
	
	if (this.arrSpan.length > 0 ){
		for(var i in this.arrSpan){
			this.validateField(this.arrSpan[i]);
		}
	}
	
	
	//alert ('campos que no han validado: '+this.fieldsNoValidos.length );
		
	// Obtenemos los mensajes de error de los campos no validos
	if (this.fieldsNoValidos.length > 0 ){
		for (var j in this.fieldsNoValidos){
			this.cadenaError += this.fieldsNoValidos[j].mensError + "\n";
		}
		
		alert (this.cadenaError);
	}else{
		
		
		this.nForm.submit();	
		
	}
	
}



FormValidator.prototype.validateField = function(oField){
		var valor = '';
		var valorRadio = '';
		// Si es un radio
		
		//alert (this.nForm[oField.name]);
		if ( oField.name != 'suma_valida') {
		if (this.nForm[oField.name].length>0 && this.nForm[oField.name][0].type == 'radio' ){
			
			for (l=0; l<this.nForm[oField.name].length; l++){
				if(this.nForm[oField.name][l].checked == true){
					var valor = this.nForm[oField.name][l].value;
				}
			}
	
		// Si es un select, su valor es el del option seleccionado
		}else if(this.nForm[oField.name].type == 'select-one'){
		
			valor = this.nForm[oField.name].options[this.nForm[oField.name].selectedIndex].value;
		// Si es de tipo texto, su valor viene en value
		}else{
			valor = this.nForm[oField.name].value;
		}
		
		// Obtenemos la expresion regular
		var regularExp = oField.expr;
		
		
		// Si tenemos en el objeto oField el parámetro que indica que la expresión regular ha de negarse,
		if(oField.regExpNegada == true){
			if (valor.match(regularExp) != null){
				this.fieldsNoValidos.push(oField);
			}
		}
		else{
			// Si el valor no concuerda con el patron, este campo no se ha introducido correctamente
			if (valor.match(regularExp) == null){
				this.fieldsNoValidos.push(oField);
			}else{
				this.fieldsValidos.push(oField);
			}	
		}
		}
		// Obtenemos los valores del antispan
		
		if ( oField.name == 'suma_valida') {
			var valor = this.nForm['resultado_suma'].value;
			var suma = parseInt(valor);
			var valoresSpan1 = parseInt(oField.numeros[0]);
			var valoresSpan2 = parseInt(oField.numeros[1]);
			if (suma == valoresSpan1 + valoresSpan2){
				this.fieldsValidos.push(oField);
			} else {
				this.fieldsNoValidos.push(oField);
			}
		}
		
		
}

// Resetea el array de fields validos y no validos y la cadena de error que saltará en el alert
FormValidator.prototype.resetValidation = function(){
	this.cadenaError = '';
	this.fieldsNoValidos = new Array();
	this.fieldsValidos = new Array();
	
}

/*******************************************************/
function playVideo(idVid){
    var container = document.getElementById('containerFlash');
    if (!container){
        return;
    }
    var str='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="450" height="385">\
            <param name="base" value="/design/images/f4/xat/" />\
            <param name="movie" value="/design/images/f4/xat/'+videos[idVid].arx+'" />\
            <param name="quality" value="high" />\
            <param name="bgcolor" value="#FFFFFF" />\
            <param name="wmode" value="transparent" />\
            <!--[if !IE]> <-->\
             <object data="/design/images/f4/xat/'+videos[idVid].arx+'" width="450" height="385" type="application/x-shockwave-flash">\
                <param name="base" value="/design/images/f4/xat/" />\
                <param name="quality" value="high" />\
                <param name="bgcolor" value="#FFFFFF" />\
                <param name="wmode" value="transparent" />\
            </object>\
            <!--> <![endif]-->\
        </object>';
    container.innerHTML = str;
    oVid1 = document.getElementById('video1');
    oVid2 = document.getElementById('video2');
    oVid1.className = idVid==1 ? 'videoOn':'videoOff';
    oVid2.className = idVid==2 ? 'videoOn':'videoOff';
    oVid1.innerHTML = videos[1].nom;
    oVid2.innerHTML = videos[2].nom;
}

function marcarTodos( str ){
    inputs = document.getElementsByTagName("input");    
    for( var i in inputs ){            
        if( inputs[i].type == "checkbox" && inputs[i].name.substr(0,str.length) == str ){
            inputs[i].checked = true;
        }
    }
}

function desmarcarTodos( str ){
    inputs = document.getElementsByTagName("input");
    for( var i in inputs ){
        if( inputs[i].type == "checkbox" && inputs[i].name.substr(0,str.length) == str ){
            inputs[i].checked = false;
        }
    }
}

/**
 * Función para escribir una dirección de email.
 */
function escribeMail( tit, nom, dom ){
	document.write( '<a hr'+'ef="mai'+'lto:'+nom+'@'+dom+'">'+tit+': '+nom+'@'+dom+'</a>' );
}



function ocultarLabel(){                
    var obj = document.getElementById('paraulaClau');
    obj.value = "";
}

