// Recorre todos los forms de la página y los valida
var g_aErroneos;
var g_aMensajes;
var g_nErrores;
var g_fnPresentacion;

function validarPagina(bPasoAPaso, bSetFocus, fnPresentacion) {
  var nForms = document.forms.length;
  var i=0;
  var bRdoPagina = true;
  g_aErroneos = new Array();
  g_aMensajes = new Array();
  g_nErrores = 0;
  g_fnPresentacion = null;
  
  if (fnPresentacion != null)
    g_fnPresentacion = fnPresentacion;
  
  for (i=0; i<nForms; i++) {
    var bRdoForm = validarForm(document.forms[i], bPasoAPaso);
    if (bRdoPagina && !bRdoForm)
      bRdoPagina = false;
  }
  if (!bRdoPagina) {
    if (bPasoAPaso) {
      Presentar(g_aMensajes[0]);
    } else {
      var i=0;
      var szMensajon = "Errores:";
      for (i=0; i<g_aErroneos.length; i++)
        szMensajon += "\n·" + g_aErroneos[i].name + ": " + g_aMensajes[i];
      Presentar(szMensajon);
    }
    if (bSetFocus) {
      var erroneo = g_aErroneos[0];
      var tipo = erroneo.type;
      erroneo.focus();
      if (tipo == "text" || tipo == "textarea")
        g_aErroneos[0].select();
    }
  }
  return bRdoPagina;
}

// Recorre los elementos de cada form y valida los que incluyen un atributo 'regexp'
function validarForm(elForm, bPasoAPaso) {
  var nElements = elForm.elements.length;
  var i=0;
  var bRdo;
  var bRdoForm = true;
  var bSeguir = true;
  var msg;
  for (i=0; (i<nElements) && bSeguir; i++) {
    var elem = elForm.elements[i];
    if (elem.regexp != null) {
        bRdo = validarElementoRegExp(elem);
        if (!bRdo) {
          if (bRdoForm) // Si puede empeorar
            bRdoForm = false;
          msg = elem.message;
          if (msg != null) {
            g_aMensajes[g_nErrores] = msg;
          } else {
            g_aMensajes[g_nErrores] = "<Error desconocido>";
          }
          if (bPasoAPaso) {
            bSeguir = false;
          }
          g_aErroneos[g_nErrores] = elem;
          g_nErrores++;
        } 
    }
  }
  return bRdoForm;
}

// Valida un elemento con atributo 'regexp', de momento no soportamos 'radio' ni 'checkbox'
function validarElementoRegExp(elem) {
  var tipo = elem.type;
  var valor = "<valor>";
  var regexp = elem.regexp;
  var bTipoOk = false;
  var bRdo = true;

  if (tipo == "text") {
    bTipoOk = true;
    valor = elem.value;
    bRdo = cumpleCondiciones(valor, regexp);
  }
  if (tipo == "select-one") {
    bTipoOk = true;
	if (elem.options.selectedIndex != -1)
    	valor = elem.options[elem.options.selectedIndex].value;
    else
		valor = "";
    bRdo = cumpleCondiciones(valor, regexp);
  }
  if (tipo == "select-multiple") {
    // Inicialmente TRUE. Si alguno seleccionado no cumple pasa a FALSE
    // Si no hay selección, aplica la regla sobre una cadena en blanco
    bTipoOk = true;
    var i=0;
    var nOptions = elem.options.length;
    var bHaySeleccion = false;
    bRdo = true;
    for (i=0; (i<nOptions) && bRdo; i++) {
      var opt = elem.options[i];
      if (opt.selected) {
        bHaySeleccion = true;
        bRdo = cumpleCondiciones(opt.value, regexp);
      }
    }
    if (!bHaySeleccion)
      bRdo = cumpleCondiciones("", regexp);
  }
  if (tipo == "textarea") {
    bTipoOk = true;
    valor = elem.value;
    bRdo = cumpleCondiciones(valor, regexp);
  }
  if (tipo == "password") {
    bTipoOk = true;
    valor = elem.value;
    bRdo = cumpleCondiciones(valor, regexp);
  }
  if (tipo == "file"){
      bTipoOk = true;
	  valor = elem.value;
      bRdo = cumpleCondiciones(valor, regexp);
  }
  
  if (!bTipoOk)
    alert("validador.js: Tipo '" + tipo + "' no soportado.");

  return bRdo;
}

function cumpleRegExp(value, exp) {
  var bCumple = false;
  var regexp = new RegExp(exp);
  bCumple = regexp.test(value);
  return bCumple;
}

function Presentar(szTexto) {
  if (g_fnPresentacion != null)
    g_fnPresentacion(g_aErroneos, g_aMensajes);
  else
    alert(szTexto);
}

function fechaCorrecta(day, month, year)
{
month = month - 1;  // pq los meses en Javascript van de 0-11
var temp = new Date(year, month, day);
if ( (year == temp.getFullYear()) && (month == temp.getMonth()) && (day == temp.getDate()) )
	return true;
else
	return false;
}


function cumpleCondiciones(valor, validador)
{

var regexpEMail = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
var resultado = true;

// Los más comunes al principio por eficiencia
if (validador == "_email")
	resultado = cumpleRegExp(valor, regexpEMail);

else
	resultado = cumpleRegExp(valor, validador);
return resultado;

}

function validarTodoDeGolpe()
{
return validarPagina(false, true);
}

function validarTodo()
{
return validarPagina(true, true);
}

