// ----------------------------------------------------------------------
//           validaform.js 
// ----------------------------------------------------------------------
// Rutinas para verificacion campos de formularios.
//
// isAlphabetic(string) Retorna verdadero si y solo sí el contenido de string sólo está compuesto por // letras (mayúsculas o minúsculas, caracteres españoles incluídos)
//
// isAlphanumeric(string) Retorna verdadero si y solo sí el contenido de string sólo está compuesto
// por letras (mayúsculas o minúsculas, caracteres españoles incluídos) o número
//
// isName(string) Retorna verdadero si y solo sí el contenido de string sólo está compuesto por letras
// (mayúsculas o minúsculas, caracteres españoles incluídos), números o espacios en blanco
//
// isInteger(string) Retorna verdadero si y solo sí el contenido de string representa un número 
// entero, con o sin signo
//
// isNumber(string) Retorna verdadero si y solo sí el contenido de string representa un número entero 
// o decimal, con o sin signo
//
// isEmail(string) Retorna verdadero si y solo sí el contenido de string tiene la forma de una 
// dirección de correo electrónica válida
//
// isPhoneNumber(string) Retorna verdadero si y solo sí el contenido de string tiene la forma de un 
// número de teléfono válido (se aceptan números, paréntesis, guiones y espacios)
//
// isColor(string) Retorna verdadero si y solo sí el contenido de string tiene la forma de un 
// valor de color valido (numeros o letras A a F) 
//
// isFecha(string) Retorna verdadero si y solo sí el contenido de string tiene la forma de un 
// valor de fecha valido (numeros o /-) y es una fecha valida 
//
// isHora(string) Retorna verdadero si y solo sí el contenido de string tiene la forma de un 
// valor de hora valido (numeros o :) y es una hora valida 
//
// isRadio(formulario,campo) Retorna verdadero si y solo sí se ha seleccionado una de las opciones
//
// ---------------------------------------------------------------------- 

var defaultEmptyOK = false
var checkNiceness = false;
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñüâêîôû_-"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑÂÊÎÔÛ_-"
var whitespace = " \t\n\rºª:.,;\\";
var phoneChars = "()-+ ";
var colores = "abcdefABCDEF#";
var horas = ":";
var fechaChars = "/";
var mMessage = "Error: no puede dejar campos obligatorios vacios."
var pPrompt = "Error: ";
var pAlphanumeric = "Introduzca un texto que contenga solo letras y/o numeros";
var pAlphabetic   = "Introduzca un texto que contenga solo letras, sin espacios";
var pInteger = "Introduzca un numero entero";
var pNumber = "Introduzca un numero";
var pPhoneNumber = "Introduzca un número de teléfono";
var pEmail = "Introduzca una dirección de correo electrónico válida";
var pName = "Introduzca un texto que contenga solo letras, numeros o espacios";
var pColor = "Introduzca un color hexadecimal valido sólo numeros y letras (a/A - f/F)";
var pFecha = "Introduzca una fecha valida y con formato (dd/mm/aaaa o dd-mm-aaaa)";
var pHora = "Introduzca una hora valida y con formato (HH:MM:SS)";
var pLibre = "Introduzca un texto a su elección sin restricciones";
var pRadio = "Debe seleccionar una de las opciones";
var pNice = "No puede utilizar comillas aqui";

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}


function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Buscar por el string, si el caracter no esta en "bag", 
    // agregarlo a returnString
    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}


function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}


function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

function isLetterColor (c)
{
    return( colores.indexOf( c ) != -1 ) 
}

function isLetterHora (c)
{
    return( horas.indexOf( c ) != -1 ) 
}

function isCharFecha (c)
{
    return( fechaChars.indexOf( c ) != -1 ) 
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}


function isNumber (s)
{   var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c)) return false;
        } else { 
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}

function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}


function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

function isPhoneNumber (s)
{   var modString;
    if (isEmpty(s)) 
       if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isPhoneNumber.arguments[1] == true);
    modString = stripCharsInBag( s, phoneChars );
    return (isInteger(modString))
}

function isEmail (s)
{
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;
    var i = 1;
    var sLength = s.length;
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isColor (s)
{   var i;

    if (isEmpty(s)) 
       if (isColor.arguments.length == 1) return defaultEmptyOK;
       else return (isColor.arguments[1] == true);

	if (document.getElementById('isColor.arguments[1]').selectedIndex==0)
	{
		return false;
	}	
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetterColor(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

function isHora (s)
{   var i;

    if (isEmpty(s)) 
       if (isHora.arguments.length == 1) return defaultEmptyOK;
       else return (isHora.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetterHora(c) || isDigit(c) ) )
        return false;
    }
	
	hora=s;
	if (hora.length>5) {
		alert("Introdujo una cadena mayor a 5 caracteres");
		return false;
	}
	if (hora.length!=5) {
		alert("Introducir HH:MM");
		return false;
	}
	a=hora.charAt(0) //<=2
	b=hora.charAt(1) //<4
	c=hora.charAt(2) //:
	d=hora.charAt(3) //<=5
	if ((a==2 && b>3) || (a>2)) {
		alert("El valor que introdujo en la Hora no corresponde, introduzca un digito entre 00 y 23");
		return false;
	}
	if (d>5) {
		alert("El valor que introdujo en los minutos no corresponde, introduzca un digito entre 00 y 59");
		return false;
	}
	if (c!=':') {
		alert("Introduzca el caracter ':' para separar la hora y los minutos");
		return false;
	}
  
  return true;
}


function isLibre (s)
{   var i;

    if (isEmpty(s)) 
       if (isColor.arguments.length == 1) return defaultEmptyOK;
       else return (isColor.arguments[1] == true);

    return true;
}

function isFecha (s)
{   var i;

    if (isEmpty(s)) 
       if (isFecha.arguments.length == 1) return defaultEmptyOK;
       else return (isFecha.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isCharFecha(c) || isDigit(c) ) )
        return false;
    }

	return true;
}

function isNice(s)
{
        var i = 1;
        var sLength = s.length;
        var b = 1;
        while(i<sLength) {
                if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
                i++;
        }
        return b;
}

function statBar (s)
{   window.status = s
}

function warnEmpty (theField)
{   theField.focus()
    alert(mMessage)
    statBar(mMessage)
    return false
}

function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(s)
    statBar(pPrompt + s)
    return false
}

function checkField (theField, theFunction, emptyOK, s)
{   
	var msg;
	
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 4) {
        msg = s;
    } else {
        if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        if( theFunction == isInteger ) msg = pInteger;
        if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
        if( theFunction == isName ) msg = pName;
		if( theFunction == isColor ) msg = pColor;
		if( theFunction == isFecha ) msg = pFecha;
		if( theFunction == isLibre ) msg = pLibre;
		if( theFunction == isHora ) msg = pHora;
    }
	
	if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
       	return warnEmpty(theField);

    if (checkNiceness && !isNice(theField.value))
    	return warnInvalid(theField, pNice);

	if (theFunction(theField.value) == true) 
        return true;
    else
       	return warnInvalid(theField,msg);
}

function validarBotonRadio(f,c,msg) {
	var marcado = "no";
	
	with (f) {
		for ( var i = 0; i < c.length; i++ ) {
			if ( c[i].checked ) {
				return true;
			}
		}
		if ( marcado == "no" ){
			alert(msg) ;
			return false;
		}
	}
}

function validarLista(f,c,msg) {
	var marcado = "no";
	
	if (c.selectedIndex > 0) {
		return true;
	}

	if ( marcado == "no" ){
		alert(msg) ;
		return false;
	}
}

function validarListaUnica(f,c,msg) {
	var marcado = "no";
	
	if (c.selectedIndex >= 0) {
		return true;
	}

	if ( marcado == "no" ){
		alert(msg) ;
		return false;
	}
}

function validarListaDesple(f,c,msg) {
	var marcado = "no";
	
	if (c !=null) {
		if (c.selectedIndex >= 0) {
			return true;
		}

		if ( marcado == "no" ){
			alert(msg) ;
			return false;
		}
	} else {
		alert("Se ha producido algún error. Disculpe las molestias") ;
		return false;	
	}
}


function validarListaCheck(f,c,msg,c2) {
	var marcado = "no";
	
	if (c.selectedIndex > 0) {
		return true;
	}
	
	if (marcado == "no" && c2.checked ) {
		return true;
	}

	if ( marcado == "no" ){
		alert(msg) ;
		return false;
	}
}

function validarListaCampo(f,c,c2,msg) {
	ptrim=c.value;
	ptrim=ptrim.replace(/^\s+/g,'');
	ptrim=ptrim.replace(/\s+$/g,'');
	//alert(ptrim.length);
	if (c2.selectedIndex > 0 || ptrim.length > 0) {
		return true;
	} 
	alert(msg) ;
	return false;
}

function validarListaOtro(f,c,c2,msg) {
	if (c != null) {
		ptrim=c.value;
		ptrim=ptrim.replace(/^\s+/g,'');
		ptrim=ptrim.replace(/\s+$/g,'');
		//alert(ptrim.length);
		if (ptrim.length > 0) {
			return true;
		}	
	} else if (c2 != null) {
		if (c2.selectedIndex > 0) {
			return true;
		}
	} 
	alert(msg) ;
	return false;
}

function validarPassword(f,c1,c2,msg) {
	
	clave1=c1.value;
	clave2=c2.value;
	
	if (clave1 != clave2 ) {
		alert(msg);
		c1.focus()
    	c1.select()
		return false;
	} else {
			
		return true;
	} 
}

function validarCheckBox(f,c,msg) {
	var marcado = "no";
	
	with (f) {
		if ( c.checked ) {
			return true;
		}
		if ( marcado == "no" ){
			alert(msg) ;
			return false;
		}
	}
}


// Validaciones de INSCRIPCIONES
function valida_inscripciones () {
	if( validarLista(document.finscripcion,document.finscripcion.id_torneo,"Debe seleccionar un torneo") &&
	    checkField( document.finscripcion.dni, isLibre, false ) &&		
		checkField( document.finscripcion.nombre, isLibre, false ) &&
		checkField( document.finscripcion.apellidos, isLibre, false ) &&
		checkField( document.finscripcion.direccion, isLibre, false ) &&
		checkField( document.finscripcion.cp, isNumber, false ) &&
        validarLista(document.finscripcion,document.finscripcion.id_pais,"Debe seleccionar un pais") &&
		validarListaOtro(document.finscripcion,document.finscripcion.provincia_otro,document.finscripcion.id_provincia,"Debe seleccionar una provincia o introducir una") &&
		validarListaOtro(document.finscripcion,document.finscripcion.poblacion_otro,document.finscripcion.id_poblacion,"Debe seleccionar una población o introducir una") &&
		checkField( document.finscripcion.fec_nacimiento, isFecha, false ) &&
		checkField( document.finscripcion.telefono, isPhoneNumber, false ) &&
		checkField( document.finscripcion.email, isEmail, false ) &&
		validarCheckBox(document.finscripcion,document.finscripcion.mayor18,"Debe certificar que es mayor de 18 años") &&		
		validarLista(document.finscripcion,document.finscripcion.id_tipopago,"Debe seleccionar una forma de pago") ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de INSCRIPCIONES
function valida_inscripciones_v2 () {
	if( validarLista(document.finscripcion,document.finscripcion.id_torneo,"Debe seleccionar un torneo") &&
	    validarLista(document.finscripcion,document.finscripcion.id_tipopago,"Debe seleccionar una forma de pago") ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de CLIENTES
function valida_clientes () {
	if( checkField( document.fcliente.usuario, isAlphanumeric, false ) &&
		checkField( document.fcliente.clave_1, isAlphanumeric, false ) &&
		validarPassword(document.fcliente,document.fcliente.clave_1,document.fcliente.clave_2,"Clave incorrecta.\nRevise que ha tecleado la misma clave 2 veces.\nLa clave no puede ser vacia.") &&
		checkField( document.fcliente.dni, isLibre, false ) &&
		checkField( document.fcliente.nombre, isLibre, false ) &&
		checkField( document.fcliente.apellidos, isLibre, false ) &&
		checkField( document.fcliente.fec_nacimiento, isFecha, false ) &&
		validarCheckBox(document.fcliente,document.fcliente.mayor18,"Debe confirmar su mayoría de edad.") &&
		checkField( document.fcliente.email, isEmail, false ) &&
		checkField( document.fcliente.direccion, isLibre, false ) &&
		checkField( document.fcliente.cp, isNumber, false ) &&
        validarLista(document.fcliente,document.fcliente.id_pais,"Debe seleccionar un pais") &&
		validarListaOtro(document.fcliente,document.fcliente.provincia_otro,document.fcliente.id_provincia,"Debe seleccionar una provincia o introducir una") &&
		validarListaOtro(document.fcliente,document.fcliente.poblacion_otro,document.fcliente.id_poblacion,"Debe seleccionar una población o introducir una") &&
        checkField( document.fcliente.telefono, isPhoneNumber, false ) ) {
			return true;
		} else {
			return false;
		}
}
function valida_modifica_clientes () {
	if( checkField( document.fcliente.dni, isLibre, false ) &&
	    checkField( document.fcliente.nombre, isLibre, false ) &&
		checkField( document.fcliente.apellidos, isLibre, false ) &&
		checkField( document.fcliente.fec_nacimiento, isFecha, false ) &&
		validarCheckBox(document.fcliente,document.fcliente.mayor18,"Debe confirmar su mayoría de edad.") &&
		checkField( document.fcliente.email, isEmail, false ) &&
		checkField( document.fcliente.direccion, isLibre, false ) &&
		checkField( document.fcliente.cp, isNumber, false ) &&
        validarLista(document.fcliente,document.fcliente.id_pais,"Debe seleccionar un pais") &&
		validarListaOtro(document.fcliente,document.fcliente.provincia_otro,document.fcliente.id_provincia,"Debe seleccionar una provincia o introducir una") &&
		validarListaOtro(document.fcliente,document.fcliente.poblacion_otro,document.fcliente.id_poblacion,"Debe seleccionar una población o introducir una") &&
        checkField( document.fcliente.telefono, isPhoneNumber, false ) ) {
			return true;
		} else {
			return false;
		}
}
function valida_conexion_clientes () {
	if( checkField( document.fcliente.usuario, isAlphanumeric, false ) &&
		checkField( document.fcliente.clave_1, isAlphanumeric, false ) &&
		validarPassword(document.fcliente,document.fcliente.clave_1,document.fcliente.clave_2,"Clave incorrecta.\nRevise que ha tecleado la misma clave 2 veces.\nLa clave no puede ser vacia.") &&
		checkField( document.fcliente.email, isEmail, false ) ) {
			return true;
		} else {
			return false;
		}
}
function valida_pass_clientes () {
	if( checkField( document.fcliente.email, isEmail, false ) ) {
			return true;
		} else {
			return false;
		}
}










