// 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 hmac_calc(data){
	return hex_hmac_sha1("966000100102140760003", data);
}

var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

/*
 * Perform a simple self-test to see if the VM is working
 */
function sha1_vm_test()
{
  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}

/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}

/*
 * Calculate the HMAC-SHA1 of a key and some data
 */
function core_hmac_sha1(key, data)
{
  var bkey = str2binb(key);
  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
  return core_sha1(opad.concat(hash), 512 + 160);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert an 8-bit or 16-bit string to an array of big-endian words
 * In 8-bit function, characters >255 have their hi-byte silently ignored.
 */
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
  return bin;
}

/*
 * Convert an array of big-endian words to a string
 */
function binb2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
  return str;
}

/*
 * Convert an array of big-endian words to a hex string.
 */
function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of big-endian words to a base-64 string
 */
function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

////////////////////////////
function textCounter(field,cntfield,maxlimit) 
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		cntfield.value = maxlimit - field.value.length;
}

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 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));
}

function validateBI(num, cd) {
  if(7 > num.length || num.length > 8) return false;
  if(cd.length != 1) return false;
  num += cd;                             // join num and check digit
  if (num.length == 8) num = "0" + num;  // left pad with 0, if needed
  return checkmod(num);
}

function validateNIF(num) {

  numNIF = num.replace(/\D/g, '');

  if(numNIF.length != 9 || numNIF == '123456789' || numNIF == '000000000') return false;
  if (numNIF == '800200200')
	  return true;
  else
	return checkmod(numNIF);
}

function validateNIB(num) {
  if(num.length != 21) return false;

  // last digit is the check digit; put it aside
  ctl = num.charAt(20);
  num = num.substring(0, 20);     // 20 digits now

  val = 0;
  for (i=0; i<20; ++i) {
	// I prefer (1 * x) to parseInt(x, 10)
// and ... num is all digits already :)
	val = ((val + (1 * num.charAt(i))) * 10) % 97;
  }

  return (98 - val) == ctl;
}

function validateCC(num) {
  // check number length
  if (num.length < 7 || 19 < num.length) {
	retval = false;
  } else {
	// reverse the number
	for (i = 0, num2 = ''; i < num.length; ++i)
	  num2 = num.charAt(i) + num2;
	num = num2;

	even = true;
	for (i = 0, sum = 0; i<num.length; ++i) {
	  c = (num.charAt(i)) * 1;
	  if (even = !even) {  // swap and test even
		c *= 2;
		if (c > 9) c -= 9;
	  }
	  sum += c;
	}
	retval = !(sum % 10);
  }
  return retval;
}

function validate() {
  // get input; erasing all non-numbers
  // I know this does not work in Opera :(, but document.all.BInumber gave me errors too
  numBI = BInumber.value.replace(/\D/g, '');
  numBIC = BIcheck.value.replace(/\D/g, '');
  numNIF = NIFnumber.value.replace(/\D/g, '');
  numNIB = NIBnumber.value.replace(/\D/g, '');
  numCC = CCnumber.value.replace(/\D/g, '');

  if (numBI != '' && numBIC != '')
	this.valBI.innerHTML = validateBI(numBI, numBIC)?"number OK":"invalid number";
  if (numNIF != '')
	this.valNIF.innerHTML = validateNIF(numNIF)?"number OK":"invalid number";
  if (numNIB != '')
	this.valNIB.innerHTML = validateNIB(numNIB)?"number OK":"invalid number";
  if (numCC != '')
	this.valCC.innerHTML = validateCC(numCC)?"number OK":"invalid number";
}

function IsText(texto) {
  var re = new RegExp(/^[a-z\d\s\-\ã\á\â\à\À\Ã\Á\Â\õ\Õ\ó\Ó\í\Í\,\.\ú\ü\Ú\Ü\é\É]{3,40}$/i);
  if (re.test(texto)){
    return true;
  }
  else{
    return false;
  }
}

function validaPesq()
{
	if (document.pesquisa.campo.value=='' || document.pesquisa.campo.value.toLowerCase()=='digite texto'){
		alert('Por favor introduza o texto a pesquisar.');
		document.pesquisa.campo.focus();
		return false;
	}
	else
	{
		if (document.pesquisa.campo.value.length<3 || document.pesquisa.campo.value.length>30){
			alert('O texto a pesquisar deverá ter entre 3 e 40 caracteres.');
			document.pesquisa.campo.focus();
			return false;
		}
		else
		{
			if (IsText(document.pesquisa.campo.value) == true)
			{
				document.pesquisa.action="/include/pesquisa.php";
				document.pesquisa.submit();
				return true;
			}
			else
			{
				alert('Só são permitidos caracteres alfanuméricos');
				return false;
			}
		}
	}
}

function validaPesq2()
{
	if (document.pesquisa.marca.value==0){
		alert('Por favor seleccione a marca a pesquisar.');
		document.pesquisa.marca.focus();
		return false;
	}
	else
	{
		document.pesquisa.campo.value = document.pesquisa.marca.value;
		document.pesquisa.action="/include/pesquisa.php?campo="+document.pesquisa.marca.value;
		document.pesquisa.submit();
	}
}

function validaEmail(form1) {
   if (!isEmpty(form1.mailNews, 'Por favor introduza o Email') && checkEmail(form1.mailNews,'Email com formato inválido')) {
	   if (confirm('Confirma a subscrição do email?')){
			form1.action="/include/news_submit.php";
			form1.submit();
			return true;
	   }
		else 
			return false;
	}
	else 
		return false;
}
