var test = true
var defaultEmptyOK = false

// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñüºª "
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ "
var whitespace = " \t\n\r";

// caracteres admitidos en nos de telefono
var phoneChars = "()-+ ";

// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar este espacio vacio"

// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = "ingrese un texto que contenga solo letras y/o numeros";
var pAlphabetic   = "ingrese un texto que contenga solo letras";
var pInteger = "ingrese un numero entero";
var pNumber = "ingrese un numero";
var pPhoneNumber = "ingrese un número de teléfono";
var pEmail = "ingrese una dirección de correo electrónico válida";
var pName = "ingrese un texto que contenga solo letras, numeros o espacios";
//var pNice = "no puede utilizar comillas aqui";

// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //


function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

// ---------------------------------------------------------------------- //
//                  CODIGO PARA FUNCIONES BASICAS                         //
// ---------------------------------------------------------------------- //


// s es vacio
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// s es vacio o solo caracteres de espacio
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;
}

// Quita todos los caracteres que que estan en "bag" del string "s" s.
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;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
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;
}

// Quitar todos los espacios en blanco de un string
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
}

// Quita todos los espacios que antecedan al string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// c es una letra del alfabeto espanol
function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// c es letra o digito
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

// ---------------------------------------------------------------------- //
//                          NUMEROS                                       //
// ---------------------------------------------------------------------- //

// s es un numero entero (con o sin signo)
function isInteger (s)
{   
	var i;
    if (isEmpty(s)) 
	{
		if (isInteger.arguments.length == 1) return defaultEmptyOK;
		else 
		{
			if (isInteger.arguments[1] == true)
			{
				return true;
			}
			else 
			{
				return false;
			}
		}
	}
    
	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;
}

// s es un numero (entero o flotante, con o sin signo)
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;
}

// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //

// s tiene solo letras
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;
}


// s tiene solo letras y numeros
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;
}

// s tiene solo letras, numeros o espacios en blanco
function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

// ---------------------------------------------------------------------- //
//                           FONO o EMAIL                                 //
// ---------------------------------------------------------------------- //

// s es numero de telefono valido
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 isMail(s) {
    if (! allValidChars(s)) 
	{  // check to make sure all characters are valid
	return warnInvalid(msg);
	}
    if (s.indexOf("@") < 1)
	{
		return false;
    } 
	else 
	if (s.lastIndexOf(".") <= s.indexOf("@")) 
	{  // last dot must be after the @
	return false;
	} 
	else 
	if (s.indexOf("@") == s.length) 
	{  // @ must not be the last character
		return false;
	} 
	else
	if (s.indexOf("..") >=0) 
	{ // two periods in a row is not valid
		return false;
	} else 
	if (s.indexOf(".") == s.length) 
	{  // . must not be the last character
		return false;
	}
    return true;
}

function allValidChars(email) 
{
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}
//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;
//}
// pone el string s en la barra de estado

function statBar (s)
{   window.status = s
}

// notificar que el campo theField esta vacio
function warnEmpty (s)
{   
	s.style.color="#b10000";
	//alert ('warnEmpty (s)' + s.name)
	test = false;
	return false;
}

// notificar que el campo theField es invalido
function warnInvalid (s)
{   
	s.style.color="#b10000";
	//alert ('warninvalid (s)' + s.name)
	test = false
	return false;
}
function returnOK(s)
{   
	s.style.color="black";
	return true;
}
function validate_form()
{
	test=true
	var	aux
	if (document.getElementById("INCSOL_TIPUSER").value=='NRE')
	{
		validate_requiredbyOption(getOptionValue("INCSOL_FJO"),document.getElementById("lblINCSOL_FJO"))
		if (getOptionValue("INCSOL_FJO")!= 'F')
		{
			checkField (document.getElementById("INCSOL_RAOSOCIAL"),isAlphanumeric, false, document.getElementById("lblINCSOL_RAOSOCIAL"))
		}
		else
		{
			checkField (document.getElementById("INCSOL_NOM"),isAlphabetic, false, document.getElementById("lblINCSOL_NOM"))
			checkField (document.getElementById("INCSOL_COGNOM1"),isAlphabetic, false, document.getElementById("lblINCSOL_COGNOM1"))
		}
		
		//checkField (document.getElementById("INCSOL_DNI"),isAlphanumeric, false, document.getElementById("lblINCSOL_DNI"))
		//if (checkField (document.getElementById("INCSOL_DNI"),isAlphanumeric, false, document.getElementById("lblINCSOL_DNI")))
		{
			//isValidDNI(document.getElementById("INCSOL_DNI").value,document.getElementById("lblINCSOL_DNI"))
		}
		//checkField (document.getElementById("INCSOL_COGNOM2"),isAlphanumeric, false, document.getElementById("lblINCSOL_COGNOM2"))
		checkField (document.getElementById("INCSOL_EMAIL"),isMail, false, document.getElementById("lblINCSOL_EMAIL"))
		//if (checkField (document.getElementById("INCSOL_TEL1"),isInteger, false, document.getElementById("lblINCSOL_TEL1")))
		{
			//isValidLength (document.getElementById("INCSOL_TEL1"),document.getElementById("lblINCSOL_TEL1"),"9")
		}
		//checkField (document.getElementById("INCSOL_TEL2"),isInteger, true, document.getElementById("lblINCSOL_TEL2"))
		//checkField (document.getElementById("INCSOL_CP"),isInteger, true, document.getElementById("lblINCSOL_CP"))
	}

	//checkField (document.getElementById("INCSOL_FAX"),isInteger, true, document.getElementById("lblINCSOL_FAX"))
	//validate_requiredbyOption(getOptionValue("INCSOL_ONVIUS"),document.getElementById("lblINCSOL_ONVIUS"))
	if(validate_requiredbyOption(getOptionValue("INCSOL_IDTIPINC"),document.getElementById("lblINCSOL_IDTIPINC")))
	{
		if (getOption("INCSOL_IDTIPINC") == 'Suggerència')
		{
			//validate_requiredbyOption(getOptionValue("INCSOL_IDTEMSUG"),document.getElementById("lblINCSOL_IDTEMSUG"))
		}
  		if (getOption("INCSOL_IDTIPINC") == 'Queixa')
		{
			//validate_requiredbyOption(getOptionValue("INCSOL_IDMOTQUE"),document.getElementById("lblINCSOL_IDMOTQUE"))
		}
	}
	checkField (document.getElementById("INCSOL_LREFCAD"),isInteger, true, document.getElementById("lblINCSOL_LREFCAD"))
	checkField (document.getElementById("INCSOL_LRUSPOL"),isInteger, true, document.getElementById("lblINCSOL_LRUSPOL"))
	checkField (document.getElementById("INCSOL_LRUSPAR"),isInteger, true, document.getElementById("lblINCSOL_LRUSPAR"))
	checkField (document.getElementById("INCSOL_LUTMX"),isInteger, true, document.getElementById("lblINCSOL_LUTMX"))
	checkField (document.getElementById("INCSOL_LUTMY"),isInteger, true, document.getElementById("lblINCSOL_LUTMY"))
	checkField (document.getElementById("DetalleQS"),isNotEmpty, false, document.getElementById("lblDetalleQS"))	
	
	
	if (getOption("INCSOL_IDTIPINC") != 'Altres')
	{
		  
	}
		
	if (!test)
	{
		alert ("Per favor, repassi els camps marcats en vermell");
	}
	/*
	if((document.getElementById('strCAPTCHA').value=="")&&(test)){
		alert("El camp de codi és obligatori");
		document.getElementById('strCAPTCHA').focus();
		test = false;
	}
	*/
	return test;
}

function checkField (theField, theFunction, emptyOK, lblfield)
{   
    var msg;
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
        msg = lblfield;
    
    if ((emptyOK == true) && (isEmpty(theField.value)))
	{
		return returnOK(lblfield)	
	}
    if ((emptyOK == false) && (isEmpty(theField.value))) 
		return warnEmpty(lblfield);

//    if ( checkNiceness && !isNice(theField.value))
//        return warnInvalid(theField, pNice);

    if (theFunction(theField.value) == true) 
		return returnOK(lblfield);	
	else
		return warnInvalid(msg);

}
function isNotEmpty(field, lblfield)
{
		return true;
}



function isValidDNI (dni,lblfield)
{
	cadena="TRWAGMYFPDXBNJZSQVHLCKET";
	numbers = dni.substring (0, 8);
	inputletter = dni.substring (8, 9);
	inputletter =	inputletter.toUpperCase();
	position = numbers % 23;
	letter = cadena.substring(position,position+1);

	if (dni.length == 9 && cadena.match(inputletter)!=null)
	{	
		if (letter == inputletter)
		{
			return returnOK(lblfield);
		}
		else
		{
			return warnInvalid(lblfield);
		}
	}
	else
	{
		return warnEmpty(lblfield);
	}
	return returnOK(lblfield);

}
function validate_requiredbyOption(field,lblfield)
{
		if (field=="NULL"||field==""||field=="0")
			return warnInvalid(lblfield)
		return returnOK(lblfield);
		
}

function isValidLength (field,lblfield,length)
{
	if (field.value.length  == length)
		return returnOK(lblfield);
	else
		return warnInvalid(lblfield);
}

