// Funções de validação dos forms

function verificaData(campo,desc)

{
  var str = campo.value;
  var format=0;
  var month=0;
  var day=0;
  var year=0;
  var err=false;
  if(str == "")
  {
    alert("A "+desc+" é obrigatória.");
    campo.focus();
	  return false;
  }
  if(str.length<6  || str.length>10)
     err=true;

  if(str.length>=6  && str.length<=10 && err==false)
  {
   // formato dd-mm-yyyy 
   // formato yyyy-mm-dd 

    if(str.charAt(4) == "-" && str.charAt(7) == "-" && str.length == 10)
    {
      format=1;
   // Check that month is a number.
      for (var i = 5; i < 7; i++) 
		{ var ch = str.substring(i, i + 1); if(ch < "0" || "9" < ch) err=true; }
   // Check that day is a number.
      for (var i = 8; i < 10; i++) 
	    { var ch = str.substring(i, i + 1); if(ch < "0" || "9" < ch) err=true; }
   // Check that year is a number.
	  for (var i = 0; i < 4; i++) 
		{ var ch = str.substring(i, i + 1); if(ch < "0" || "9" < ch) err=true; }
   // Set variables
	  if(err==false)
	  { 
		month=eval(str.substring(5,7)); 
		day=eval(str.substring(8,str.length)); 
		year=eval(str.substring(0,4)); 
	  }
	}

    // formato Incorrecto.
    if(format !=1)
      var err=true;
  }

  // Check that month is between 1 &12.
  if((month<=0 || month>=13) && err==false)
    err=true;

  // Check that day is right depending on month.
  if( month==2 && ((year/4)==parseInt(year/4)) )
  { 
		if(day<=0 || day>29) 
			err=true; 
  }
  if( month==2 && ((year/4)!=parseInt(year/4)) )
  { 
		if(day<=0 || day>28) 
			err=true; 
  }
  if( month==4 || month==6 || month==9 || month==11 )
  { 
		if(day<=0 || day>30) 
			err=true;
  }
  if( month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 )
  { 
		if(day<=0 || day>31) 
			err=true; 
  }

  // Check that year is OK
  if ((year<=1940 || year>2020) && err==false)
  {
    alert("O ano da "+desc+" é inválido.");
    campo.focus();
    return false;
  }

  // If anything appears incorrect, display error message.
  if(err==true)
  {
    alert("A "+desc+" é inválida.");
    campo.focus();
    return false;
  }

   // If all is OK, return true.
  return true;

}

var popmail = null;
function NewWindow(mypage,myname,w,h,resize){
esqPosition = (screen.width) ? (screen.width-w)/2 : 0;
topoPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings = 'height='+h+',width='+w+',top='+topoPosition+',left='+esqPosition+',scrollbars=no,resizable='+resize+'';
popmail = window.open(mypage,myname,settings);
}

function NewWindowResize(mypage,myname,w,h){
esqPosition = (screen.width) ? (screen.width-w)/2 : 0;
topoPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings = 'height='+h+',width='+w+',top='+topoPosition+',left='+esqPosition+',scrollbars=yes,resizable=yes';
popmail = window.open(mypage,myname,settings);
}

function validadecimais(elemento)
{
	elemento.value=elemento.value.replace(/\./g,'');
	if (decimales(elemento.value)==false)
	{
		alert ("Valor Inválido");
		elemento.focus();
		return false;
	}
	ele=elemento.value;
	elemento2=ele.toString();
	posi = elemento2.indexOf(",");
	if (posi==-1)
	{
		return true;
	}
	numero = elemento.value;
	numero2 = numero.toString();
	lon = numero2.length;
	if (lon - posi > 3)
	{
		alert ("Valor só com 2 decimais");
		elemento.focus();
		return false;
	}
	return true;
}

function decimales (cadena)
{
   lg=cadena.length;
   for (i=0;i<lg;i++) {
        c=cadena.charAt(i);
        if ((c<'0' || c>'9') && c != ',')
           return false;
   }
   return true;
}

function validaNumero(elemento)
{
	var strNumero = elemento.value;
    if (elemento.value!= '' &&
	   elemento.value != null)
    {
		for ( var i = 0; i < strNumero.length; i++)
		{
			var ch = strNumero.substring(i,i + 1);
			if (ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && 
					ch != '7' && ch != '8' && ch != '9' && ch != '0')
			{
				alert('O campo contém caracteres inválidos');
				elemento.focus();
				return false;
			}
		}
		return true;
	}
	return true;
}

function FormataNum(numf,milh,decim){
	if (milh==""){alert('Falta o separador dos milhões.')}
	if (decim==""){alert('Falta o separador decimal.')}
	if (decim==milh){alert('Os separadores são iguais.')}
	var tam=0;
	var pos=0;
	var dec="";
	var forma="";
	var expd= new RegExp("\\"+decim)
	var expm= new RegExp("\\"+milh,"g")
	var ok=false;
	var num;
	if (isNaN(numf)){
		num=numf.toString();
		if (isNaN(num.replace(expm,'').replace(expd,'.'))){
			return (num);
		}
		else{num=numf.replace(expm,''); var ok=true;}
	}
	else{
		num=numf.toString();
		num=num.replace(/\./,decim);
		ok=true;
	}
	if(ok){
		tam=num.length;
		pos=num.search(expd);
		//alert(num+"-"+pos);

		if (pos>0){
			dec=num.substr(pos+1);
			//alert(dec);

			num=num.substr(0,pos);
			tam=num.length;
		}
		while (num!="" || num==null){

			tam=num.length;
			pos=tam-3
			if (pos>0){
				
				if (tam>3){
					forma=milh+num.substr(pos)+forma;
				}
			}
			else{
			if (dec!=""){
				forma=num+forma+decim+dec;
				}
				else{	
				forma=num+forma;//+decim+"00";
	
			}	
		}
	num=num.substr(0,pos);	
	}
	}
	return (forma);
}

function validaTamanhoTextArea(maxChar,campo,descricao)
{
   if (campo.value.length > maxChar) {
        diff=campo.value.length - maxChar;
        if (diff>1)
            diff = diff + " caractéres";
        else
            diff = diff + " caractére";
            
        alert("O tamanho máximo do campo "+descricao+" são " + maxChar + " caracteres\n" + "Deverá reduzir o texto em " + diff);
        campo.focus();
		return false;
    }
	else
	{
		return true;
	}
}

function isEmpty(field, msg) {
	if (field.value.length == 0) {
		if (msg.length > 0) {
			alert(msg);
			field.focus();
			field.select();
		}
		return true;
	}
	return false;
}

 // Verifica se o Email está correctamente formatado
function checkEmail(field, msg) {
 	var exclude = /[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
	var check = /@[\w\-]+\./;
	var checkend = /\.[a-zA-Z]{2,3}$/;
	
	if (field.value != "") {
		if (((field.value.search(exclude) != -1) || (field.value.search(check)) == -1) || (field.value.search(checkend) == -1)) {
			alert(msg);
			field.focus();
			field.select();
			return false;
		}
	}
	return true;
}

function validarLogin(formulario)
{
	if (isEmpty(formulario.login, 'Por favor introduza o Login') || !checkEmail(formulario.login,'Login com formato inválido'))
		return false;
	else if (formulario.pwd.value.length < 7)
	{
		alert('A Password deverá ter pelo menos 7 caractéres');
		formulario.pwd.focus();
		return false;
	}
	formulario.submit();
	return true;
}

function DisableRightClick()
{
	var but=window.event.button;
	if (but==2)
	{
		alert('O acesso ao botão direito do rato, não é permitido.');
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function validateNIF(num) {

  numNIF = num.replace(/\D/g, '');

  if(numNIF.length != 9 || numNIF == '123456789' || numNIF == '000000000') return false;
  return checkmod(numNIF);
}

function checkmod(num) {
  val=0;
  for (pos=0; pos<num.length-1; ++pos) {
	val += (1 * num.charAt(pos)) * (9 - pos);
  }
  ctl = val % 11 ? (11 - val % 11) % 10 : 0;

  return ctl == (1 * num.charAt(pos));
}