	// Vamos a determinar el estilo del campo para saber si se ha modificado o no

  function eliminarcamposocultos(pform) {
    // Recorrer todos los elementos del formulario y aquellos que estén ocultos
    // los eliminamos
    // No confundir un campo oculto (el stylo es none) con un campo de tipo hidden

    /*
	  var elementos = Form.getElements(pform);     // Esto es de prototype!!
      alert("uee");
	  for (var i=0; i<elementos.length; i++) {
	  	if (elementos[i].style.display == "none")
			Element.remove(elementos[i]);
    }
    */

    var elementos = pform.elements;
    if (elementos) {
        for (var i=(elementos.length-1); i>=0; i--) {
          if (elementos[i].style.display == "none") {
            padre = elementos[i].parentNode;
            padre.removeChild(elementos[i]);
          }
        }
    }
  }

	function limiteSizeEditorHTML(nombreCampo, pDescripcion, pSize) {
    var texto;

    if (FCKeditorAPI.GetInstance(nombreCampo)) {
      texto = FCKeditorAPI.GetInstance(nombreCampo).GetHTML();

  		if (texto.length > pSize) {
	  		if (confirm("El campo " + pDescripcion + " es mayor de " + pSize + " caracteres\nEl texto se recotará.\n\n¿Desea continuar?") == true) {
          texto = texto.substr(0, pSize);

          // Pendiente de limppiza código html que se haya quedado a mitad
          pos_ini = texto.lastIndexOf("<");
          pos_fin = texto.lastIndexOf(">");

          //alert(pos_ini + " - " + pos_fin);
          if (pos_ini > pos_fin) {
            texto = texto.substr(0, pos_ini);
          }

          // Lo asignamos
          FCKeditorAPI.GetInstance(nombreCampo).SetHTML(texto);

  				return true;
        }
        else {
  				return false;
	  		}
			}
    }
    return true;
	}

  function limiteSize(pCampo, pDescripcion, pSize) {
		if (pCampo.value.length > pSize) {
			if (confirm("El campo " + pDescripcion + " es mayor de " + pSize + " caracteres\nEl texto se recotará.\n\n¿Desea continuar?") == true) {
				pCampo.value = pCampo.value.substr(0, pSize);
				return true;
			}
			else {
				return false;
			}

		}
		else {
			return true;
		}
	}
	
	function Estilo(f){
		var campo_origen, valor, aValores, iguales;

    var browser_ie = !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1);
//    alert(browser_ie);
		
		with(f.form) {
			// alert("document." + f.form.name + "." + f.name + "_orig");
			campo_origen = eval("document." + f.form.name + "." + f.name + "_orig");
			
			valor = "";
			if (f.type == "select-multiple") {
				// Revisamos todos los elementos para ver los que están seleccionados
				for (i=0; i<f.length; i++) {
					if (f.options[i].selected == true) {
						if (valor.length > 0) { valor += ","; }
						valor = valor + f.options[i].value;
					}
				}
			}
			else {
				valor = f.value;
			}

			//alert(eval("document." + f.form.name + "." + f.name + "_orig.value"));
			iguales = true;
			aValores = valor.split(",");
			for (i=0; i<aValores.length; i++) {
				if(campo_origen) {
				if (campo_origen.value.indexOf("," + aValores[i] + ",") == -1) {
					iguales = false;
					break;
				}
                }
			}


			if (iguales == false) {
        /*if (!(browser_ie)) {
          f.className = "cambio";
        }*/
        if (f.className) f.className = "cambio";

        if ( (f.type == "select-multiple") ||
          (f.type == "select-one") ) {
          for (var i=0; i< f.length; i++) {
            f.options[i].className = "cambio";
          }
        }

        var campo_modificado = document.getElementById("_MG_MODIFICADO");
        if (campo_modificado) {
          campo_modificado.value = "S";
        }
			}
			else {
        /*if (!(browser_ie)) {
          f.className = "nocambio";
        } */
        if (f.className) f.className = "cambio";

        if ( (f.type == "select-multiple") ||
          (f.type == "select-one") ) {
          for (var i=0; i< f.length; i++) {
            f.options[i].className = "nocambio";
          }
        }


			}		
		}
	}

  function confirmarCambios(form) {
    if ($('_MG_MODIFICADO')) {
      if ($('_MG_MODIFICADO').value != "S") {
        if (confirm("Ha realizado cambios, ¿está seguro que desea abandonar esta ventana?")) {
          return true;
        }
      }
    }
    else {
      alert("No existe el campo");
    }
    return false;
  }

	function ContieneExtension(campo, extension) {
			var i, iTam = extension.length, extensionactual;

			if (campo.value.length == 0) { return true; }
			
			i = campo.value.lastIndexOf(".");
			if (i > -1) {
				extensionactual = campo.value.substr(i+1);
				
				if (extensionactual.toUpperCase() == extension.toUpperCase()) {
					return true;
				}
				else {
					return false;
				}
			}
			else {
				if (campo.value.toUpperCase() == extension.toUpperCase()) {
					return true;
				}
				else {
					return false;
				}
			}
	}


  function limpiezaBasicaHTML(contenido) {
    contenido = contenido.replace(/<br>/ig, '');

    return contenido;
  }

  function ObligatorioEditorHTML(nombrecampo, descripcion, idioma) {
    var texto;
    var bVacio=true, bDebeEnfocarse=true;

    if (FCKeditorAPI.GetInstance(nombrecampo)) {
        texto = FCKeditorAPI.GetInstance(nombrecampo).GetHTML();
        texto = limpiezaBasicaHTML(texto);
        if (texto != "") {
          bVacio = false;
				}
    }

    if (bVacio == true) {
			// ** Idioma **
			if (idioma == "V") alert("És obligatori emplenar l´apartat:\n" + descripcion);
			else alert("Es obligatorio rellenar el campo:\n" + descripcion);

			if (bDebeEnfocarse == true) {
        if (FCKeditorAPI.GetInstance(nombrecampo)) {
  				FCKeditorAPI.GetInstance(nombrecampo).Focus();
        }
			}
			return false;
		}
		return true;
  }

	function Obligatorio(campo, descripcion, idioma) {
		var i, bVacio=true, bDebeEnfocarse=false;
		
		if (campo.type == undefined) {
			if (campo.length > 1) {
				for (i=0; i <campo.length; i++) { 
					if ((campo[i].type == "checkbox") || (campo[i].type == "radio") ) {
						if (campo[i].checked == true) {
							bVacio = false;
							break;
						}
					}
				}
			}
		}
		else {
			if ((campo.type == "checkbox") || (campo.type == "radio") ) {
				if (campo.checked == true) {
					bVacio = false;
				}
			}
			else if (campo.value != "") {
				bVacio = false;
				DebeEnfocarse = true;
			}
		}
			
		
		if (bVacio == true) {
			// ** Idioma **
			if (idioma == "V") alert("És obligatori emplenar l´apartat:\n" + descripcion);
			else alert("Es obligatorio rellenar el campo:\n" + descripcion);
			if (bDebeEnfocarse == true) {
				campo.focus();
			}
			return false;
		}
		return true;
	}
	
	// En los campos FILE obligamos a método POST y codificación multipart/form-data
	function esFormularioMultiParte(campo) {

//		if ((campo.form.encoding != "multipart/form-data") || (campo.form.method != "post")) {
//			alert("No se han definido correctamente método (" + campo.form.method + ") o codificación (" + campo.form.encoding + ") del formulario\n" +
//				"Debe ser método POST y codificación multipart/form-data");
//		}

		// Por el momento lo cambiamos y dejamos que continúe
		campo.form.encoding = "multipart/form-data"
		campo.form.method = "POST";
		return true;
	}
	
	// GESTIÓN DE FECHAS
	var kseparador= "/";
	var kminAnyo=1900;
	var kmaxAnyo=2100;
	
	function besEntero(sNumero){
		var i;
	    for (i = 0; i < sNumero.length; i++){   
	        var c = sNumero.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }
	    return true;
	}
	
	function filtrarTexto(campo) {
		if (campo.value=="") return(true);
		
		campo.value = campo.value.replace(/'/gi, "´");
		campo.value = campo.value.replace(/\"/gi, "´"); 	   
	}
	
   function esMoneda(campo, descripcion, idioma) {
//      alert("uoo");
      if (campo.value=="") return(true);
		//var objRegExp = /^-?[0-9]+(\,[0-9][0-9]){0,1}$/;
		var objRegExp = /^-?[0-9]+(\,[0-9]{1,2}){0,1}$/;

    var expunto = /\./;
 	  if (expunto.test(campo.value)) {
      if (idioma=="V") msgConfirmacion = "El número introduït es convertirà en " + campo.value.replace(/\./gi, "") +
        ", se n'ha eliminat el punt.\nVoleu continuar?";
			else msgConfirmacion = "El número introducido se convertirá en " + campo.value.replace(/\./gi, "") +
        " (se ha eliminado el punto) \n ¿Desea continuar?";

      var res = confirm(msgConfirmacion);
      if (!res) {return false;};

      campo.value = campo.value.replace(/\./gi, "");
    }

 	  if (!(objRegExp.test(campo.value))) {
	        // ** Idioma **
			if (idioma == "V") alert("Introduïu un valor correcte en euros en l´apartat:\n" + descripcion + ".");
		    else alert("Introducir cantidad en euros correcta en el campo:\n" + descripcion + ".");
			campo.focus();
			return false;
    }
  }


 /**
   * Comprueba si un campo tiene un valor decimal o no
   */
   function esDecimal(campo, descripcion, idioma) {
      if (campo.value=="") return(true);
	  campo.value = campo.value.replace(/\./gi, ",");
	  var objRegExp = /^-?[0-9]+(\,[0-9]+){0,1}$/;

 	  if (!(objRegExp.test(campo.value))) {
	     // ** Idioma **
		 if (idioma == "V") alert("Introduïu un valor decimal correcte en l´apartat:\n" + descripcion + ".");
		 else alert("Introduzca una cantidad decimal correcta en el campo:\n" + descripcion + ".");
		 campo.focus();
		 return(false);
 	  }
	  return (true);
   }

	
   function esEntero(campo, descripcion, idioma) {
		if (besEntero(campo.value) == false) {
		    // ** Idioma **
			if (idioma=="V") alert("Introduïu un valor numeric en l'apartat:\n" + descripcion + ".");
			else alert("Introduzca un valor numérico correcto en el campo:\n" + descripcion + ".");
			campo.focus();
			return false;
		}
	}
	

   function eliminarCaracter(pCadena, pCaracterEliminar){
		var i;
	   var sCadena = "";

	   for (i = 0; i < pCadena.length; i++){   
	        var c = pCadena.charAt(i);
	        if (pCaracterEliminar.indexOf(c) == -1) sCadena += c;
	   }
	   return sCadena;
	}
	
	
   function esFecha(campo, descripcion, idioma) {
   		if (campo.value.length == 0) {
   				return (true);
   		}
   		
     re = new RegExp("^([0-9]{1,2})/([0-1]{0,1}[0-9]{1})/([0-9]{2,4})$");
	 // ** Idioma **
     if (idioma=="V") msgError = "Introduïu una data correcta (dd/mm/aaaa)";
	 else msgError = "Introduzca una fecha correcta (dd/mm/aaaa)";
	 
     if (!re.test(campo.value)) {      
		alert(msgError);
 	    campo.focus();
        return (false);
     }
     else {  // El formato es correcto, hay que comprobar que la fecha exista
        fechaAux = new Date (parseInt(RegExp.$3,10), parseInt(RegExp.$2,10) - 1, parseInt(RegExp.$1,10))
        if ((parseInt(RegExp.$2,10)-1) != fechaAux.getMonth() || (parseInt(RegExp.$1,10) != fechaAux.getDate())) {
           //alert(msgError);
		   alert(msgError+' '+fechaAux);
		   campo.focus();
           return (false);
        }
        return (true);
     }
  } 
  
	function esURL(campo, descripcion, idioma) {
		var url = "https://www.ua.es";
		var hosts = "http,https,ftp";
		var allowQS = true, hostOptional = false;
		
		var front = "^(?:(" + hosts.replace( /\,/g, "|" ) + ")\\:\\/\\/)";
		var end   = ( Boolean( allowQS ) == true ) ? "(\\?.*)?$" : "$";
		
		if ( Boolean( hostOptional ) == true ) front += "?";
		var regex = new RegExp( front + "([\\w\\d-]+\\.?)+" + end );
		
		if (idioma=="V") msgError = "El formato de la URL es iconrrecto. Los formatos aceptado son:\n· http://...\n· https://...\n· ftp://...\n";
		else msgError = "El formato de la URL es iconrrecto. Los formatos aceptado son:\n· http://...\n· https://...\n· ftp://...\n";
		
		if ( !regex.test( url ) ) {
			alert(msgError);
		   campo.focus();
         return (false);
       }
       return (true);
	}

   function esCorreo(campo, descripcion, idioma) {
		// Los campos vacios los damos por válidos (si son obligatorios ya los comprobará su función correspondiente)
		if (campo.value.length == 0) return (true);

		var msgError;
		if (idioma=="V") msgError = "Debe introducir una dirección de correo electrónica correcta en el campo:\n" + descripcion + ".";
			else msgError = "Debe introducir una dirección de correo electrónica correcta en el campo:\n" + descripcion + ".";

		var emailPattern = /^\w[\w\d]+(\.[\w\d]+)*@\w[\w\d]+(\.[\w\d]+)*\.[a-z]{2,7}$/i;
		if ( ! emailPattern.test( campo.value ) ) {
			alert(msgError);
			campo.focus();
			return false;
		}
		return true;
	}

    var cargadocalendario = false;
    try {
        // Para la gestión de los calendarios. Nos creamos un objeto que nos permita la gestión
        var calendarObjForForm = new DHTMLSuite.calendar({minuteDropDownInterval:10,numberOfRowsInHourDropDown:5,callbackFunctionOnDayClick:'getDateFromCalendar',isDragable:false,displayTimeBar:false});
        calendarObjForForm.setCallbackFunctionOnClose('myOtherFunction');

        DHTMLSuite.commonObj.loadCSS("/tools/Formularios/css/calendar.css", false);

        cargadocalendario = true;
    }
    catch(er) {
        //alert("1 - " + er.message);

        var includescalendario = Array("dhtmlSuite-common.js", "dhtmlSuite-calendar.js", "dhtmlSuite-dragDropSimple.js");

        for (var i=0; i < includescalendario.length; i++) {
            document.write('<'+'script');
	        document.write(' language="javascript"');
	        document.write(' type="text/javascript"');
    	    document.write(' src="/tools/Formularios/js/'+ includescalendario[i] +'">');
	        document.write('</'+'script'+'>');
        }
    }

/*
    if (cargadocalendario == false) {
       try {
          // Para la gestión de los calendarios. Nos creamos un objeto que nos permita la gestión
          var calendarObjForForm = new DHTMLSuite.calendar({minuteDropDownInterval:10,numberOfRowsInHourDropDown:5,callbackFunctionOnDayClick:'getDateFromCalendar',isDragable:true,displayTimeBar:false});
          calendarObjForForm.setCallbackFunctionOnClose('myOtherFunction');

          DHTMLSuite.commonObj.loadCSS("/tools/Formularios/css/calendar.css", false);

          cargadocalendario = true;
        }
        catch(er) {
            //alert("2 - " + er.message);
        }
    }
*/
    //alert(cargadocalendario);

    // Funciones propias del calendario
  	function myOtherFunction() {
  	}

    function pickDate(buttonObj, idinputObject)
  	{
          var inputObject = $(idinputObject);

          if (!(inputObject)) {
              return;
          }

  		calendarObjForForm.setCalendarPositionByHTMLElement(inputObject,0,inputObject.offsetHeight+2);	// Position the calendar right below the form input
  		//calendarObjForForm.setInitialDateFromInput(inputObject,'yyyy-mm-dd hh:ii');	// Specify that the calendar should set it's initial date from the value of the input field.
          calendarObjForForm.setInitialDateFromInput(inputObject,'dd/mm/yyyy');	// Specify that the calendar should set it's initial date from the value of the input field.
  		calendarObjForForm.addHtmlElementReference('myDate',inputObject);	// Adding a reference to this element so that I can pick it up in the getDateFromCalendar below(myInput is a unique key)
  		if(calendarObjForForm.isVisible()){
  			calendarObjForForm.hide();
  		}else{
  			calendarObjForForm.resetViewDisplayedMonth();	// This line resets the view back to the inital display, i.e. it displays the inital month and not the month it displayed the last time it was open.
  			calendarObjForForm.display();
  		}
  	}

    function getDateFromCalendar(inputArray)
  	{
   	  var references = calendarObjForForm.getHtmlElementReferences(); // Get back reference to form field.
      references.myDate.value = inputArray.day + '/' + inputArray.month + '/' + inputArray.year;
      if (references.myDate.onchange) {
        references.myDate.onchange();
      }
  		calendarObjForForm.hide();
    }


