
// DEFINE VARIABLES


var fileinc = "fileinc"; //serve para verificar se o ficheiro foi incluido.
// whitespace characters
var whitespace = " \t\n\r";


function replaceAll (s, fromStr, toStr)
{
	var new_s = s;
	for (i = 0; i < 100 && new_s.indexOf (fromStr) != -1; i++)
	{
		new_s = new_s.replace (fromStr, toStr);
	}
	return new_s;
}

/****************************************************************/

/* PURPOSE:  Since we are using the single tick mark as the
	string delimiter to construct our SQL queries, a string with
	a tick mark in it will cause a SQL error.  Therefore we replace
	all "'" with "''", which eliminates the possibility of a SQL error.
*/

function sqlSafe (s)
{
	var new_s = s;
	new_s = replaceAll (new_s, "'", "|");
	new_s = replaceAll (new_s, "|", "''");
	new_s = replaceAll (new_s, "\"", "|");
	new_s = replaceAll (new_s, "|", "''");
	return new_s;
}

/****************************************************************/

function makeSafe (i)
{
	i.value = sqlSafe (i.value);
}

/****************************************************************/

// Check whether string s is empty.

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

/****************************************************************/

// Returns true if string s is empty or
// whitespace characters only.

function isWhitespace (s)
{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through strings characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
		// Check that current character isn't whitespace.
		var c = s.charAt(i);

		if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

/****************************************************************/


// isEmail (STRING s [, BOOLEAN emptyOK])
//
// Email address must be of form a@b.c ... in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s))
       if (isEmail.arguments.length == 1) return true;
       else return (isEmail.arguments[1] == true);

    // is s whitespace?
    //if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

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

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

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

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function ForceEmail(objField, FieldName)
{
	var strField = new String(objField.value);
	if(!isEmail (strField)){
		//alert("\"" + FieldName + "\" tem que ser um endereço de e-mail válido.\n\nExemplo: nome@endereco.pt");
		objField.focus();
		return false;
	}
	else
		return true;
}


function ForceLettersNumbers(objField, FieldName)
{
	var strField = new String(objField.value);
	//alert('strField:'+strField)
	var reg = /[^a-zA-Z0-9]/ig;

	if(reg.test(strField)){
		//alert("O campo \"" + FieldName + "\" só permite letras e números. Não são permitidos espaços.");
		objField.focus();
		return false;
	}else{
		return true;
	}
}

/*
para além dos números permite o caracter passado por paramentro
CUIDADO: COM os caracteres especiais
*/
function ForceCustomChars(objField, FieldName)
{
	var strField = new String(objField.value);

	var reg = /[^a-zA-Z0-9._-]/ig;

	if(reg.test(strField)){
		//alert("O campo \"" + FieldName + "\" só permite letras, números, \"-\" , \"_\" e \".\" . Não são permitidos espaços.");
		objField.focus();
		return false;
	}else{
		return true;
	}
}

/****************************************************************/

// Checks to see if a required field is blank.  If it is, a warning
// message is displayed...

function ForceEntry(objField, FieldName)
{
	var strField = new String(objField.value);
	if (isWhitespace(strField)) {
		//alert("É necessário preencher o campo \"" + FieldName + "\"" );
		objField.focus();
		objField.select();
		return false;
	}

	return true;
}

/****************************************************************/

// Returns true if the string passed in is a valid number
//  (no alpha characters), else it displays an error message

function ForceNumber(objField, FieldName)
{
	var strField = new String(objField.value);

	if (isWhitespace(strField)) return true;

	var i = 0;

	for (i = 0; i < strField.length; i++)
		if (strField.charAt(i) < '0' || strField.charAt(i) > '9') {
			//alert("\"" + FieldName + "\" é um campo númerico.\nÉ necessário preencher o campo só com dígitos.\n\nExemplo: 123");
			objField.focus();
			return false;
		}

	return true;
}




/****************************************************************/

// Returns true if the string passed in is a valid money
//  (no alpha characters except a decimal place),
//   else it displays an error message

function ForceMoney(objField, FieldName)
{
	var strField = new String(objField.value);

	if (isWhitespace(strField)) return true;

	var i = 0;
	var contavirgula = 0;
	var virgulalocation = 0;
	for (i = 0; i < strField.length; i++){
		if ((strField.charAt(i) < '0' || strField.charAt(i) > '9') && strField.charAt(i) != ',' ) {
			//alert("\"" + FieldName + "\" é necessário ser um número e separado por uma vírgula ( 1000,50 ).");
			objField.focus();
			return false;
		}
/**/
		if(strField.charAt(i) == ','){
			virgulalocation = i;
			contavirgula++;
			if(contavirgula > 1){
				//alert("\"" + FieldName + "\"é necessário ser um número válido e separado por uma vírgula ( 1000,50 ).\nNão é permitido usar mais do que uma vírgula.");
				objField.focus();
				return false;
			}
		}
//*/
	}

/**/
	if(virgulalocation > 0){
		var x = strField.substring(virgulalocation+1);
		if(x.length>2){
			//alert("O número introduzido no campo \""+FieldName+"\" só pode ter duas casas décimais");
			objField.focus();
			return false;
		}

	}//*/

	return true;
}


/****************************************************************/

// Right trims the string...  Useful for SQL datatypes of CHAR

function RTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0;

	for (i = str.length; i >= 0 && endpos == 0; i = i - 1) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			endpos = i;
	}

	return str.substring(0,endpos+1);
}


/****************************************************************/

// Displays an alert box with the passed in string...

function PromptErrorMsg(Field,strError)
{
	//alert('A data que preencheu no campo "' + strError + '" não é válida. \nO formato da data é AAAA-MM-DD (ano-mês-dia).');
	Field.focus();
	Field.select();
	return false;
}


/****************************************************************/

// This function determines if the string passed in is a valid
// Portugal zip code.  It accepts either ####-###.  If the
// string is valid, it returns true, else false.

function isZipcode(strZip)
{
	var s = new String(strZip);

	if (s.length != 8)
		// inappropriate length
		return false;

	for (var i=0; i < s.length; i++)
		if ((s.charAt(i) < '0' || s.charAt(s) > '9') && s.charAt(i) != '-')
			return false;

	return true;
}

function ForceZipcode(objField, FieldName)
{
	var strField = new String(objField.value);
	if(!isZipcode (strField)){
		//alert("O campo \"" + FieldName + "\" tem que ser um Código Postal do tipo ####-###.\n\nExemplo: 2134-678");
		objField.focus();
		return false;
	}
	else
		return true;
}

/****************************************************************/

// This function ensures that a field is less than or equal to the
// Length passed in.  You must call this function with the element
// name in your form (for example: "ForceLength(document.forms[0].txtElement)"
// as opposed to "ForceLength(document.forms[0].txtElement.value)"
// If the field's value is too large, an error message is displayed
// and false is returned, else true is returned.

function ForceLength(objField, nLength, strWarning)
{
	var strField = new String(objField.value);

	if (strField.length > nLength) {
		//alert(strWarning);
		objField.focus();
		objField.select();
		return false;
	} else
		return true;
}


////////////////////////////////////////////////////////////////////////////////////////
// DATE VALIDATION

// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(objField,Field){
	var dtStr = objField.value;
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(pos2+1)
	strYr=strYear

	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){

		PromptErrorMsg(objField,Field);
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("O mês introduzido não é válido");
		objField.focus();
		objField.select();
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("O dia introduzido não é válido");
		objField.focus();
		objField.select();
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("O ano tem que ter 4 digitos e estar entre os valores "+minYear+" e "+maxYear);
		objField.focus();
		objField.select();
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		PromptErrorMsg(objField,Field);
		objField.focus();
		objField.select();
		return false
	}
return true
}

function isHour(objField,Field)
{
	var hourStr = objField.value;

	//alert('str: '+hourStr+' field :'+ Field);

	var pos = hourStr.indexOf(":");
	//alert(pos);
	//alert(hourStr.length);

	if(pos != 2 || hourStr.length < 5)
	{
		//alert("O formato da hora do campo \""+Field+"\" tem que ser do tipo HH:MM \nExemplo: 00:59");
		objField.focus();
		objField.select();
		return false;
	}


	if(hourStr.charAt(0) < "0" ||  hourStr.charAt(0) > "2"){
		//alert("A Hora do campo \""+Field+"\" tem que ser entre 00 e 23");
		objField.focus();
		objField.select();
		return false;
	}

	if(hourStr.charAt(1) < "0" ||  hourStr.charAt(1) > "9"){
		//alert("A Hora do campo \""+Field+"\" tem que ser entre 00 e 23");
		objField.focus();
		objField.select();
		return false;
	}

	if(hourStr.charAt(0) == 2 && hourStr.charAt(1) > "3")
	{
		//alert("A Hora do campo \""+Field+"\" tem que ser entre 00 e 23");
		objField.focus();
		objField.select();
		return false;
	}

	if(hourStr.charAt(3) < "0" ||  hourStr.charAt(3) > "5"){
		//alert("Os Minutos do campo \""+Field+"\" tem que ser entre 00 e 59");
		objField.focus();
		objField.select();
		return false;
	}

	if(hourStr.charAt(4) < "0" ||  hourStr.charAt(4) > "9"){
		//alert("Os Minutos campo \""+Field+"\" tem que ser entre 00 e 59");
		objField.focus();
		objField.select();
		return false;
	}

	return true;


}


