﻿// VALIDACIONES:
// Funcion que comprueba que lo introducido es numérico.
function esnumero(s) {
	var reg= new RegExp("^[0-9]+$");
	if (!reg.test(s))
		return false;
	return true;
}
// Funcion que comprueba si un campo esta vacio
function vacio(strAux){
	var re= new RegExp("^\\s+$");
	if ( (strAux == null) || (strAux == "") || (re.test(strAux)) ) return true;
	return false;
}
// Validación de los campos obligatorios
function valObligatorio(object,name)
{
   var msg = "";
   var valor = "";

   //alert(object.name + "="+object.value);
   if (object.type=='text' || object.type=='textarea' || object.type=='password')
      valor = object.value;
   else if (object.type=='select-one')
      valor = object.options[object.selectedIndex].value;

   if(vacio(valor))
   {
      msg = "El campo '"+name+"' es obligatorio \n";
   }
   return msg;
}
// Validación de los campos fecha formateados (dd/MM/aaaa)
function valFecha(object,name)
{
   var msg = "";
   var valor = "";

   //alert(object.type);
   if (object.type=='text')
      valor = object.value;
   else if (object.type=='select-one') // borrar ?
      valor = object.options[object.selectedIndex].value;

   if(!esFechaValida(valor))
   {
      msg = "El campo '"+name+"' no es una fecha válida \n";
   }
   return msg;
}

function esFechaValida(fecha)
{
	var isValida=true;
	var fechaAux=fecha.split("/");
	var dia=fechaAux[0];
	var mes=fechaAux[1];
	var anyo=fechaAux[2];

	isValida=((!isNaN(dia))&&(!isNaN(mes))&&(!isNaN(anyo))&&(dia>0)&&(dia<32)&&(mes>0)&&(mes<13)&&(anyo>1500));

	//Comprobamos ahora que nada cambie en relación al objeto date.Así controlamos por ejemplo los años bisiestos
	if(isValida)
	{
		dia=parseInt(dia,10);
		mes=parseInt(mes,10);
		anyo=parseInt(anyo,10);

		var fechaDate=new Date(formatearFechaDate(fecha));

		var mes1=fechaDate.getMonth()+1;
		if((dia!=fechaDate.getDate())||(mes!=mes1)||(anyo	!=fechaDate.getFullYear()))
			isValida=false;
	}

	return isValida;
}

// Comprueba si un email está bien construido
function isEmail(value,msg) {

  	var valido = true;

	invalidChars = " /:,;";
	if (value=="") valido = false;

	for (i=0; i<invalidChars.length;i++) {
	   badChar = invalidChars.charAt(i);
	   if (value.indexOf(badChar,0) != -1) valido = false;
	}

	atPos = value.indexOf("@",1);
	if (atPos == -1) valido = false;
	if (value.indexOf("@", atPos + 1) != -1) valido = false;

	periodPos = value.indexOf(".", atPos);
	if (periodPos == -1) valido = false;

	if (periodPos+3 > value.length) valido = false;

	if(valido==false)
      return msg;

     return "";

}


//Pasa una fecha(String) del tipo dd/mm/aaaa a mm/dd/aaaa que es el que maneja javascript
function formatearFechaDate(fecha)
{
	fechaAux=fecha.split("/");
	dia=fechaAux[0];
	mes=fechaAux[1];
	anyo=fechaAux[2];
	return mes+"/"+dia+"/"+anyo;
}//formatearFechaDate(fecha)

function formatearFecha(obj)
{
  if (obj.value!="" && esnumero(obj.value))
  {
      fechaParser = obj.value.split("/");
      dia = fechaParser[0];
      mes = fechaParser[1];
      anio = fechaParser[2];
      if (dia==null || mes==null || anio==null)
      {
         fecha = obj.value;
         obj.value = obj.value.substring(0,2) + "/" + obj.value.substring(2,4) + "/" + obj.value.substring(4,8);
      }
  }
}

// Función para lanzar las validaciones
function validarFormulario(f)
{
   var errores = "";
   if (obligatorios!=null)
   {
       for (i=0; i<obligatorios.length; i++)
       {
          errores += valObligatorio (f.elements[obligatorios[i][0]],obligatorios[i][1]);
       }
   }
   if (fechas!=null && errores=="")
   {
       for (i=0; i<fechas.length; i++)
       {
          errores += valFecha (f.elements[fechas[i][0]],fechas[i][1]);
       }
   }

   if (errores !="")
   {
      alert(errores);
      return false;
   }
   else
      return true;
}



// cuenta atras de caracteres
function calCar(maxLong,campo,contador,nameForm)
{
   var maxLongitud = maxLong;
   var libres = maxLong;
   f = document.forms[nameForm];
   if (f.elements[campo].value.length > maxLongitud)
   {
      f.elements[campo].value = f.elements[campo].value.substring(0,maxLongitud)
      libres = 0
      alert("¡Ha superado el límite!\nRecuerde que dispone de\n" + maxLongitud + " caracteres")
   }
   else
   {
      libres = maxLongitud - f.elements[campo].value.length
   }
   f.elements[contador].value = libres
}


// abrir ventana
function Popup(url,w,h,x,y,name)
{
  strWin1='width='+w+',height='+h+',top='+y+',left='+x;
  strWin2=',directories=0,location=0,status=0,scrollbars=1,toolbar=0,menubar=0,resizable=0';
  win=strWin1+strWin2;
  eval("open(\'" + url + "\',\'" + name + "\',\'" + win + "\')");
}

/* busqueda de ambitos:
*  variables para paso de datos: formActivo, nameCampo, idCampo.
*/
function buscaAmbito()
{

  var posX = (screen.availWidth - 400)/2;
  var posY = (screen.availHeight - 300)/2;
  f=document.forms[formActivo];
  if (f.claveAmbito.value=="")
  {
     alert("Debe indicar la clave para buscar el CONVOCANTE");
     f.claveAmbito.focus();
     return false;
  }
  else
     Popup('/buscaConvocante.do?clave='+f.claveAmbito.value,400,300,posX,posY,'buscar');
}

function selectedAll (s)
{
   for (i=0;i<s.length;i++)
      s.options[i].selected=true;
}

function preguntarBorrar(url)
{
   if(confirm("¿Esta seguro de borrar la opción seleccionada?"))
      window.location.href=url;
}

function disabledFalse(f)
{
   msg="";
   for (i=0;i<f.length;i++)
   {
      if (f.elements[i].disabled==true)
	  {
	    //msg += f.elements[i].name + "\n";
	  	f.elements[i].disabled=false;
      }
   }
   //alert(":--habilitados--:\n"+msg);
}
function disabledAll(f)
{
   msg="";
   for (i=0;i<f.length;i++)
   {
	    msg += f.elements[i].name + "\n";
	  	f.elements[i].disabled=false;
	  	f.elements[i].readonly=true;
   }
   alert(":--deshabilitados--:\n"+msg);
}