// A utility function that returns true if a string contains only 
// whitespace characters.
function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verify(f)
{
    var msg;
    var empty_fields = "";
    var errors = "";


    // Loop through the elements of the form, looking for all 
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // then verify that they are numbers and that they are in the right range.
    // Put together error messages for fields that are wrong.

	 for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
		   if (((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional) {
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + e.name;
                continue;
            }
            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) { 
                var v = parseFloat(e.value);
                if (isNaN(v) || 
                    ((e.min != null) && (v < e.min)) || 
                    ((e.max != null) && (v > e.max))) {
                    errors += "- The field " + e.name + " must be a number";
                    if (e.min != null) 
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null) 
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".\n";
                }
            }
        }
    }
   

    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted. 
    // Otherwise return true.
    if (!empty_fields && !errors) return true;

    msg  = "______________________________________________________\n\n"
    msg += "There are errors in your form.\n";
    msg += "Please correct them.\n";
    msg += "______________________________________________________\n\n"

    if (empty_fields) {
        msg += "- The following mandatory fields are empty :" 
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

// função que determina se uma string tem caracteres que não são admissíveis numa password
function has_inv_letters(s)
{
	var itHas,c;
	var strRef;
	var res;
	
    strRef = "AaÂâÁáààãÃBbCcÇçddEeÉéÊêÈèfFgGHhIiÍÍììjJkKLlMmnNOoÓóÒòÕõpPqQRrSsTtUuúÚÙúVvXxYyWwZz_.0123456789";
		
	itHas = false;
	
	for (var i = 0; i < s.length; i++) {
        c = s.charAt(i);
		
		res = strRef.indexOf(c,0);
		if (res == -1)
			itHas = true;
	}
	
	return itHas;
}

// função para validar o form de alteração de dados de acesso. Sim eu sei que é específico e não devia estar aqui...

function validate_login_data(f)
{
	var e1,e2, ve1,ve2, errors, msg;
	var invLetters;
	
	errors = "";
	
	if (! verify(f))  // verifica se há campos obrigatórios nulos
	  return false;
	
	e1 = f.elements[1];
	ve1 = e1.value;
	
	e2 = f.elements[2];
	ve2 = e2.value;
	
	if ((f.elements[0].value.length > 0) && (f.elements[0].value.length < 6))
		errors += "O campo " + f.elements[0].name + " não tem o comprimento mínimo exigido (6 caracteres)!\n";
					
	if (ve1.length < 6)
		errors += "O campo " + e1.name + " não tem o comprimento mínimo exigido (6 caracteres)!\n";
		
	if (ve2.length < 6)
		errors += "O campo " + e2.name + " não tem o comprimento mínimo exigido (6 caracteres)!\n";
		
	// verifico se não há letras proíbidas
	
	if (f.elements[0].length != 0)
		invLetters = has_inv_letters (f.elements[0].value);
	
	if (invLetters) {
		errors += "O campo " + f.elements[0].name + " tem caracteres que não são permitidos.\n";
		errors += "Por favor use apenas letras, dígitos, '.' ou '_' .\n";
	}
	
	invLetters = has_inv_letters (ve1);
	
	if (invLetters) {
		errors += "O campo " + e1.name + " tem caracteres que não são permitidos.\n";
		errors += "Por favor use apenas letras, dígitos '.' ou '_'.\n";
	}
		
	invLetters = has_inv_letters (ve2);
	
	if (invLetters) {
		errors += "O campo " + e2.name + " tem caracteres que não são permitidos.\n";
		errors += "Por favor use apenas letras, dígitos '.' ou '_'.\n";
	}
	
	// verifico se as versões das passwords são iguais
	
	if (ve1 != ve2) {
		errors += "A palavra chave é diferente da palavra chave repetida.\n";
		errors += "Por favor indique duas palavras chave iguais.\n";
	}
	
	if (!errors)			
		return true;
		
	msg  = "______________________________________________________\n\n"
    msg += "O formulário não foi submetido por conter erros.\n";
    msg += "Corrija-os, por favor.\n";
    msg += "______________________________________________________\n\n"	
	
	msg += "\n" + errors;
	alert(msg);
	return false;
}

function validate_and_confirm(f,msg)
{
	if (! verify(f))  // verifica se há campos obrigatórios nulos
	  return false;
	  
	return confirm(msg);  
}

function isValidDate(f,strDate){  // também escreve os valores no form
   var s;                                //Declare variable.
   
   var myDay,myMonth,myYear, ndays;
   var re = new RegExp("\/|-"); //Regular expression pattern
  
               //String to be searched.
   var arr = re.exec(strDate);               //Perform the search.
   
   if (arr=null) 
   	  return "";
	
	myDay = Number(RegExp.leftContext)
	strDate = RegExp.rightContext
	
   var arr = re.exec(strDate);               //Perform the search.
   
   if (arr=null) 
   	  return "";
  
   myMonth = Number(RegExp.leftContext)
   myYear = Number(RegExp.rightContext)
   
  
   
   // ja os tenho, testo valores
   
   if ((myDay <0) || (myMonth<0) || (myYear < 0))
   	  return false;
	  
   if ((myYear <1900) || (myYear > 2030))
   	return false;
	
	 
	switch (myMonth) {
	
		case 1:
		case 3:
		case 5: 
		case 7:
		case 8:
		case 10:
		case 12:
					ndays = 31;
					break;
		case 4:
		case 6:
		case 9:
		case 11:
					ndays = 30;
					break;
		case 2:
			if ( (((myYear % 4) == 0) && (myYear % 100 != 0)) || (myYear % 400 == 0) )
				ndays = 29;
			else
				ndays = 28;
				
			break;
		default:
			return false;
	}
	
	// so falta validar os dias
	
	if (myDay <= ndays) {
		
		f.Dia.value = myDay;
		f.Mes.value = myMonth;
		f.Ano.value = myYear;
			return true;
	}
	
	else
		return false;
	
	
}

function validate_and_checkdate(f)
{
	if (! verify(f))  // verifica se há campos obrigatórios nulos
	  return false;

	if (isValidDate(f,f.SubmissionDate.value))
		res = true;
	else {
	   res = false;
	   
	   alert('The Submission Date is not valid');
	}

	return (res);  
}

