function confirm_action(displ_text){   //pede confirmacao da accao que se vai realizar
	msg="";
	if(displ_text != ""){
		msg = displ_text + "\n";
	}
    msg = msg + "Por favor, confirme que quer continuar.";
    return confirm(msg);
    }
    
   
function popup(url,nome,width,height,scroll){ /*FUNCION PARA ABRIR UN POPUP*/
 var w=width;
 var h=height;

 window.open (url,nome,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+scroll+',resizable=yes,top=100,left=100,width='+w+',height='+h+'')
}


/*************FCs de validacao para FORMS*****************/
/** Email Validation ******************************************/
function isValidEmail(emailStr) {	
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	var emailPat=/^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";
	
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		alert("O email não parece ser válido (verifique os @ e .'s)");
		return false;
	}
	
	var user=matchArray[1];
	var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("O username tem caracteres inválidos.");
			return false;
		}
	}
	
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("O domínio tem caracteres inválidos.");
			return false;
		}
	}
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {// user is not valid
		alert("O username não parece ser válido.");
		return false;
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("IP do destino é inválido.");
				return false;
			}
		}
		return true;
	}
	
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("O domínio não parece ser válido.");
			return false;
		}
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("O endereço deve terminar com um domínio conhecido ou com duas letras representativas de um país.");
		return false;
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		alert("Falta um host ao domínio escrito");
		return false;
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}

function verify_data(value2check, text2display){   //Verifica se o campos passado esta' vazio e nesse caso, avisa
	if(value2check==""){
		alert("Campo sem dados. " + text2display);
		return false;
      	}
	else
		return true;
}

/************* validacao onKeyPress dos campos ******************/
function KeyCheckNum(myfield,e){ //Verifica se os dados inseridos estao ente 1-0 //KeyCode=0 -> delete
	var keycode;
	if (window.event) 
		keycode = window.event.keyCode;
	else if (e) 
		keycode = e.which;
	else 
		return true;
	if (((keycode>47) && (keycode<58)) || (keycode==8) || (keycode==0))
		return true;
	else 
		alert("O dígito inserido não é válido.\nVerifique os seus dados.");
	return false;
}

function KeyCheckDate(myfield,e){ //Verifica se os dados inseridos estao ente 1-0 //KeyCode=0 -> delete //=45-> traco
	var keycode;
	if (window.event) 
		keycode = window.event.keyCode;
	else if (e) 
		keycode = e.which;
	else 
		return true;
		
	if (((keycode>47) && (keycode<58)) || (keycode==8) || (keycode==0) || (keycode==45))
		return true;
	else 
		alert("O dígito inserido não é válido.\nApenas são permitidos os dígitos de 0 a 9 e '-'.");
	return false;
}

function KeyCheckPhone(myfield,e){ //Verifica se os dados inseridos estao ente 1-0, (, ), space, +. //KeyCode=0 -> delete // 43=+, 40=(, 41=)
	var keycode;
	if (window.event) 
		keycode = window.event.keyCode;
	else if (e) 
		keycode = e.which;
	else 
		return true;

	if(keycode==43)
		if (getFreq(myfield.value, "+")>0){
			alert("Não pode repetir o indicador '+'.");
			return false;
		}
	if(keycode==40)
		if (getFreq(myfield.value, "(")>0){
			alert("Não pode repetir a abertura de prefixo internacional '('.");
			return false;
		}
	if(keycode==41)
		if (getFreq(myfield.value, ")")>0){
			alert("Não pode repetir o fecho de prefixo internacional ')'.");
			return false;
		}
	if(keycode==32)
		if (getFreq(myfield.value, " ")>0){
			alert("Não pode repetir o espaço entre o prefixo internacional e o nº telefone.");
			return false;
		}

	
	if (((keycode>47) && (keycode<58)) || (keycode==8) || (keycode==0) || (keycode==43) || (keycode==40) || (keycode==41) || (keycode==32))
		return true;
	else 
		alert("O caracter inserido não é válido.\nApenas são permitidos os dígitos de 0 a 9, e/ou o indicativo do país.");
				
	return false;
}


/**************************************************************
 getFreq: Returns a Long specifying the nr of times a one string within occurs inside another. If String1 or String2 are null, 0 is returned.
 Parameters:
      String1 = String expression being searched.
      String2 = String expression sought
 Returns: Integer >= 0
***************************************************************/
function getFreq(String1, String2){
	if (String1 == null || String1 == "" || String2 == null || String2 == "")
		return 0;

	String1 = String1.toLowerCase();
	String2 = String2.toLowerCase();

	var a = String1.split(String2);

	return a.length -1;
}


function isValidName(defaultName){   //Verifica se os campos seleccionados estao vazios e nesse caso, avisa
	var nome = Trim(document.forms[0].varNome.value)
	if(nome=="" || nome==defaultName){
		alert("O Nome do registo não está preenchido.");
		document.forms[0].varNome.focus();
		return false;
      	}
	return true;
}



/**************************************************************
 LTrim: Returns a String containing a copy of a specified string without leading spaces 
 Parameters:
      String = The required string argument is any valid string expression. If string contains null, false is returned
 Returns: String
***************************************************************/
function LTrim(String){
	var i = 0;
	var j = String.length - 1;

	if (String == null)
		return (false);

	for (i = 0; i < String.length; i++)	{
		if (String.substr(i, 1) != ' ' &&
		    String.substr(i, 1) != '\t')
			break;
	}

	if (i <= j)
		return (String.substr(i, (j+1)-i));
	else
		return ('');
}

/**************************************************************
 RTrim: Returns a String containing a copy of a specified string without trailing spaces 
 Parameters:
      String = The required string argument is any valid string expression. If string contains null,  false is returned
 Returns: String
***************************************************************/
function RTrim(String){
	var i = 0;
	var j = String.length - 1;

	if (String == null)
		return (false);

	for(j = String.length - 1; j >= 0; j--)	{
		if (String.substr(j, 1) != ' ' &&
			String.substr(j, 1) != '\t')
		break;
	}

	if (i <= j)
		return (String.substr(i, (j+1)-i));
	else
		return ('');
}

/**************************************************************
 RTrim: Returns a String containing a copy of a specified string without both leading and trailing spaces 
 Parameters:
      String = The required string argument is any valid string expression. If string contains null, false is returned
 Returns: String
***************************************************************/
function Trim(String){
	if (String == null)
		return (false);

	return RTrim(LTrim(String));
}

/**************************************************************
 roundNumber: Arredonda um nr, X casas decimais
 Parameters:
      decLength = the number of decimals to round
      myNumber = nr to round
 Returns: Rounded Nr
***************************************************************/
function roundNumber(decLength, myNumber) {
	if (decLength==null || isNaN(decLength))
		decLength = 0;
		
	return Math.round(myNumber*Math.pow(10,decLength))/Math.pow(10,decLength);
}

/**************************************************************
 allDigits
***************************************************************/
function allDigits(str){
	return inValidCharSet(str,"0123456789");
}

/**************************************************************
 inValidCharSet
***************************************************************/
function inValidCharSet(str,charset){
	var result = true;

	// Note: doesn't use regular expressions to avoid early Mac browser bugs	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0){
			result = false;
			break;
		}
	
	return result;
}

/**************************************************************
 isValidDate
***************************************************************/
function isValidDate(dateValue){
	var result = true;

  	if (result){
 		var elems = dateValue.split("-");
 		
 		result = (elems.length == 3); // should be three components
 		
 		if (result){
  			var day = parseInt(elems[0],10);
 			var month = parseInt(elems[1],10);
 			var year = parseInt(elems[2],10);
 			
			result = allDigits(elems[1]) && (day > 0) && (day < 32) &&
			            allDigits(elems[0]) && (month > 0) && (month < 13) &&
			            allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
 		}
	} 
	
	return result;
}

/**************************************************************
 IsDate: Returns a Boolean (true) if the date is true, false if not
 Parameters:
	- DateStr: String date in format (DD/MM/YYYY or DD-MM-YYYY)
 Returns: Boolean
***************************************************************/
function isDate(dateStr){
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat)
	if (matchArray == null)
		return false;

	day = matchArray[1]
	month = matchArray[3]
	year = matchArray[4]
	
	if (month < 1 || month > 12)
		return false;

	if (day < 1 || day > 31)
		return false;	
		
	if ((month==4 || month==6 || month==9 || month==11) && day==31)
		return false;

	if (month == 2)
		if (day>29 || (day==29 && !isLeapYear(year)))
			return false;
	return true;
}

/**************************************************************
 LeapYear: Return a Boolean if the speficied Year is a Leap Year
 Parameters:
      Year = Numeric expression that represents the Year.
 Returns: Boolean
***************************************************************/
function isLeapYear(Year){    
	return (Year % 4 == 0 && Year % 100 != 0 || Year % 400 ==0);
}

/**************************************************************
 isValidTime
***************************************************************/
function isValidTime(timeValue){
	var result = true;

	var elems = timeValue.split(":");
 		
	result = (elems.length == 2); // should be three components
 		
	if (result){
		var hour = parseInt(elems[0],10);
		var minutes = parseInt(elems[1],10);
 			
		result = allDigits(elems[0]) && (hour > 0) && (hour < 25) &&
		            allDigits(elems[1]) && (minutes >= 0) && (minutes < 60) ;
 	} 
	
	return result;
}


/**************************************************************
makeDate: formato DD-MM-AAAA; nao verifica pois assume q já verificoi a validade de data
***************************************************************/
function makeDate(dateValue){
	var result = true;
	var myDate = new Date();
	

 	var elems = dateValue.split("-");
 		 		
 	if (result){
 		var day = parseInt(elems[0],10);
 		var month = parseInt(elems[1],10);
 		var year = parseInt(elems[2],10);
 		
 		myDate.setDate(day);
 		myDate.setMonth(month-1);
 		myDate.setYear(year);

 	}
	
	return myDate;
}

