// ----------------------------------------------------------------------
//           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: You cannot leave this field blank."
var pPrompt = "Error: ";
var pAlphanumeric = "Enter a text containing only letters and/or numbers";
var pAlphabetic   = "Enter a text containing only letters, with no spaces";
var pInteger = "Enter a integer number";
var pNumber = "Enter a number";
var pPhoneNumber = "Enter a phone number";
var pEmail = "Enter a valid email address";
var pName = "Enter a text containing letters, numbers or spaces only";
var pColor = "Enter a valid hexadecimal colour code, with numbers and letters (a/A - f/F)";
var pFecha = "Enter a valid date in the format (yyyy/mm/dd) or (yyyy-mm-dd)";
var pHora = "Enter a valid time in the format  (HH:MM:SS)";
var pLibre = "Enter a text of your own choice, without restrictions";
var pRadio = "You must select an option";
var pNice = "You cannot use quotation marks here";

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=document.getElementById('hora_visita').value;
	if (hora.length>5) {
		$.blockUI({ message: '<div class="mensaje_error">You enter a string greater than 5 characters</div>', overlayCSS: { backgroundColor: '#333' } });
    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		return false;
	}
	if (hora.length!=5) {
		$.blockUI({ message: '<div class="mensaje_error">Format: HH:MM</div>', overlayCSS: { backgroundColor: '#333' } });
    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		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)) {
		$.blockUI({ message: '<div class="mensaje_error">The value you entered for HOUR is not valid enter a number between 00 and 23</div>', overlayCSS: { backgroundColor: '#333' } });
    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		return false;
	}
	if (d>5) {
		$.blockUI({ message: '<div class="mensaje_error">The value you entered for MINUTES is not valid enter a number between 00 and 59</div>', overlayCSS: { backgroundColor: '#333' } });
		$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		return false;
	}
	if (c!=':') {
		$.blockUI({ message: '<div class="mensaje_error">Enter the character : to separate the Hour and the Minutes</div>', overlayCSS: { backgroundColor: '#333' } });
		$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		return false;
	}
  
  return true;
}


function isLibre (s)
{   var i;

    if (isEmpty(s)) 
       if (isLibre.arguments.length == 1) return defaultEmptyOK;
       else return (isLibre.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()
	$.blockUI({ message: '<div class="mensaje_error">' + mMessage + '</div>', overlayCSS: { backgroundColor: '#333' } }); 
    $('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
    statBar(mMessage)
    return false
}

function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
	$.blockUI({ message: '<div class="mensaje_error">' + s + '</div>', overlayCSS: { backgroundColor: '#333' } });
    $('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
    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" ){
			$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
    		$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
			return false;
		}
	}
}

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

	if ( marcado == "no" ){
		$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		return false;
	}
}

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

	if ( marcado == "no" ){
		$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		return false;
	}
}

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

		if ( marcado == "no" ){
			$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
	    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
			return false;
		}
	} else {
		$.blockUI({ message: '<div class="mensaje_error">An error has taken place. Please, excuses the annoyances</div>', overlayCSS: { backgroundColor: '#333' } });
		$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		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" ){
		$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		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;
	} 
	$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
   	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
	return false;
}

function validarListaOtro(f,c,c2,msg) {
	if (c2 != null) {
		if (c2.selectedIndex > 0) {
			return true;
		}
	} else 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;
		}	
	} 
	$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
   	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
	return false;
}

function validarPassword(f,c1,c2,msg) {
	
	clave1=c1.value;
	clave2=c2.value;
	
	if (clave1 != clave2 ) {
		$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
	   	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
		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" ){
			$.blockUI({ message: '<div class="mensaje_error">' + msg + '</div>', overlayCSS: { backgroundColor: '#333' } });
	    	$('.blockOverlay').attr('title','Click to continue').click($.unblockUI); 
			return false;
		}
	}
}

// Validaciones de FORMULARIO desde PRODUCTOS
function valida_datos_producto() {
	if( checkField( document.fdetalle.date, isFecha, false ) && 
	    checkField( document.fdetalle.number_guest, isInteger, false ) ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de FORMULARIO desde GET IN TOUCH
function valida_fGetInTouch() {
	if( checkField( document.fGetInTouch.name, isLibre, false ) && 
	    checkField( document.fGetInTouch.phone, isPhoneNumber, false ) && 
	    checkField( document.fGetInTouch.email, isEmail, false ) && 
	    checkField( document.fGetInTouch.comments, isLibre, false ) ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de FORMULARIO de GRUPO
function valida_fGroupForm() {
	if( checkField( document.fGroupForm.product, isLibre, false ) && 
	    checkField( document.fGroupForm.date, isFecha, false ) && 
	    checkField( document.fGroupForm.number, isInteger, false ) && 
		checkField( document.fGroupForm.name, isLibre, false ) && 
		checkField( document.fGroupForm.phone, isPhoneNumber, false ) && 
	    checkField( document.fGroupForm.email, isEmail, false ) && 
	    checkField( document.fGroupForm.comments, isLibre, false ) ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de REGISTRO
function valida_datos_registro() {
	if( checkField( document.fregistro.nombre, isName, false ) &&
		checkField( document.fregistro.apellidos, isName, false ) && 
		checkField( document.fregistro.direccion, isLibre, false ) && 
		checkField( document.fregistro.cp, isAlphanumeric, false ) && 
		validarLista(document.fregistro,document.fregistro.id_pais,"You need to select a country") &&
		validarListaOtro(document.fregistro,document.fregistro.provincia_otro,document.fregistro.id_provincia,"You need to select or enter a county/state") &&
		validarListaOtro(document.fregistro,document.fregistro.poblacion_otro,document.fregistro.id_poblacion,"You need to select a town or enter one") &&
		//checkField( document.fregistro.usuario, isAlphanumeric, true ) &&
		checkField( document.fregistro.clave, isAlphanumeric, false ) &&
		validarPassword(document.fregistro,document.fregistro.clave,document.fregistro.rep_clave,"Password incorrect.\nCheck you have not mistyped your password.\nThe password cannot be empty.") &&
		checkField( document.fregistro.telefono, isPhoneNumber, false ) &&
		checkField( document.fregistro.email, isEmail, false ) &&
		validarCheckBox(document.fregistro,document.fregistro.acepto,"You must check legal notice.") ) {
			return true;
		} else {
			return false;
		}
}
function valida_datos_perfil () {
	if( checkField( document.fregistro.nombre, isName, false ) &&
		checkField( document.fregistro.apellidos, isName, false ) && 
		checkField( document.fregistro.direccion, isLibre, false ) && 
		checkField( document.fregistro.cp, isAlphanumeric, false ) && 
		validarLista(document.fregistro,document.fregistro.id_pais,"You need to select a country") &&
		validarListaOtro(document.fregistro,document.fregistro.provincia_otro,document.fregistro.id_provincia,"You need to select or enter a county/state") &&
		validarListaOtro(document.fregistro,document.fregistro.poblacion_otro,document.fregistro.id_poblacion,"You need to select a town or enter one") &&
		//checkField( document.fregistro.usuario, isAlphanumeric, false ) &&
		checkField( document.fregistro.ant_clave, isAlphanumeric, true ) &&
		checkField( document.fregistro.clave, isAlphanumeric, true ) &&
		checkField( document.fregistro.rep_clave, isAlphanumeric, true ) &&
		checkField( document.fregistro.telefono, isPhoneNumber, false ) &&
		checkField( document.fregistro.email, isEmail, false ) ) {
			return true;
		} else {
			return false;
		}
}
function valida_nueva_clave() {
	if( checkField( document.fnuevaclave.email_pass, isEmail, false ) ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de PEDIDOS
function valida_datos_pedido () {
	if( validarListaDesple(document.fcesta,document.fcesta.id_formapago,"You must select a payment method") &&
		validarCheckBox(document.fcesta,document.fcesta.acepto,"You must accept the conditions of purchase.") ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de LOGIN GALERÍA
function valida_clave_galeria() {
	if( checkField( document.facceso.clave, isAlphanumeric, false ) ) {
			return true;
		} else {
			return false;
		}
}

// Validaciones de SUSCRIPCION AL BOLETIN
function valida_fboletin () {
	if( checkField( document.fboletin.email, isEmail, false ) &&
		validarCheckBox(document.fboletin,document.fboletin.acepto,"You must accept the conditions.") ) {
		return true;
	} else {
		return false;
	}	
}
