// JScript File

/* --- Trim de uma string --- */
function TrimString(sInString) {
  if ((sInString == null) || (sInString == ""))
    return "";
  sInString = sInString.replace( /^\s+/g, "" ); // strip leading
  return sInString.replace( /\s+$/g, "" );      // strip trailing
}
/* --- Verifica se uma String esta' vazia (apos fazer trim) --- */
function IsEmptyString(sInString) {
  sInString = TrimString(sInString);
  return ((sInString == null) || (sInString == ""));
}
/* --- Verifica se o valor dado e' tem numeros, letras, '-' e '_' --- */
function IsValidString(str) {
  var test = "0123456789-_abcdefghijklmnopqrstuvwxyz ";
  str = str.toLowerCase();
  for (i=0; i < str.length; i++) {
    if (test.indexOf(str.charAt(i)) == -1) return false;
  }
  return true;
  /* for javascript 1.2 */
  // return (str.match(/[a-zA-Z0-9\-\_]*/) != null) ? true : false; 
}
/* --- Verifica se o valor dado e' numerico (inteiro positivo) --- */
function IsNum(str) {
  var test = "0123456789";
  for (i=0; i < str.length; i++) {
    if (test.indexOf(str.charAt(i)) == -1) return false;
  }
  return true;
  /* for javascript 1.2 */
  /* return (str.match(/\d+/) != null) ? true : false; */
}
/* --- Verifica se os dados (dia, mes, ano) formam uma data valida (1753 - hoje)--- */
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
  return date;
}
function IsValidDate(day, mn, year) {
  if ((!IsNum(day)) || (!IsNum(mn)) || (!IsNum(year)))
    return false;
  var myDate = new Date(year + "/" + mn + "/" + day);
  // 0. Data valida => 1753 <= ano <= AnoActual
  var now = fixDate(new Date());
  if ( (year < 1753) || (year > now.getFullYear()) )
    return false;
  // 1. dia do mes (1 a 31)
  // 2. JavaScript começa a contagem do mes a partir de 0, ie, 0 => jan e 11 => dez 
  // 3. ano (aaaa)
  return ((myDate.getDate() == day) && (myDate.getMonth() == mn-1) && (myDate.getFullYear() == year));
}
/* --- Verifica se a partir os dados (dia, mes, ano) formam uma idade entre [18, 64[ --- */
function IsAgeBetween18and64(day, mn, year){
  if (IsValidDate(day, mn, year)){
    var oneYear = 1000 * 60 * 60 * 24 * 365.25; //colocar 1 Ano em milisegundos
    var today = fixDate(new Date());
    var myDate = new Date(year + "/" + mn + "/" + day);

    // calcular a diferenca entre as 2 datas e converter para anos
    //var age = Math.ceil((today.getTime() - myDate.getTime()) / oneYear)-1;
    var age = Math.round((today - myDate) / oneYear);

    // 18 anos(inclusive)  e  65 anos (exclusive)
    return ((age >= 18) && (age < 65))
  }
  return false;
}

/* Validacao de um nr de Telefone */
function IsValidTelephone(val) {
  val = TrimString(val);
  var objRegExp =/\d{9}/;
  return (objRegExp.exec(val) != null);
}
/* Validacao de um nr de Telemovel */
function IsValidCellphone(val) {
  return (IsValidTelephone(val) && (val.charAt(0) == '9') && ((val.charAt(1) == '1')||(val.charAt(1) == '3')||(val.charAt(1) == '6')));
}
/* Validacao de um Email */
function IsValidEmail(str) {
  var objRegExp =/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
  return (objRegExp.exec(TrimString(str)) != null);
}

/* --- Validação do NIF - nr de contrinbuinte (pelo Algoritmo CheckDigit) --- */
function ValidateNIF(contrib) {
 var s = contrib;
 if ((s.length != 9) || (!IsNum(s))) return false;
  //else
  var  c = s.charAt(0);
  if (c == '1' || c == '2' || c == '5' || c == '6' || c == '8' || c == '9') { //digitos iniciais válidos
    var checkDigit = (c - '0') * 9; // (c - '0') -> char to int

    for (var i = 2 ; i <= 8 ; i++)
      checkDigit += (s.charAt(i - 1) - '0') * (10 - i);

    checkDigit = 11 - (checkDigit % 11);

    if (checkDigit >= 10)
      checkDigit = 0;
      
    if (checkDigit == (s.charAt(8) - '0'))
      return true;
  }
  return false;
}
/* --- Validação do BI (pelo Algoritmo CheckDigit) --- */
function ValidateBI(numStr, cd) {
  // tem de ter 1 digito de controle
  if (cd.length != 1) return false;

  var lenBI = numStr.length;
  // pode ter 7 ou 8 digitos
  if ((lenBI < 6) || (lenBI > 8)) return false;
  // juntar NBI e dígito de controlo
   numStr += cd;
  // verificar se é um valor numerico 
  if (IsNum(numStr)) {
    // adicionar zero à esquerda de nbi se for de comprimento 7 (sem bit de controle)
    if (numStr.length == 8)
      numStr = "0" + numStr;

    // if (numStr.lenght != 9) return false; // no total tem de ter 9 digitos!!  

    /* verificação validade do numero (calculo pelo alg. checkdigit) checkmod: */  
    // 0. converter num (string) para inteiro
    // var num = parseInt(numStr, 10) // 10 -> base decimal
    
    var val = 0;
    var pos = 0;
    /* 1. computar soma de controlo */
    for (pos = 0; pos < numStr.length-1; ++pos) {
      val += (1 * numStr.charAt(pos)) * (9 - pos);   // (digito = parseInt(numStr.charAt(pos))
    }
    /* 2. verificar soma de controlo */
    var ctl = val % 11 ? (11 - val % 11) % 10 : 0;       // (soma mod 11 = 0) or (soma mod 11 = 10))
    /* 3. o valor resultante da soma calculada é = ao digito de controle? */
     // alert(pos + " char=" +(1 * numStr.charAt(pos)) + "=" + ctl + " ....... val = " + val + " - val % 11= " + (val % 1)+ " -> (11 - val % 11) % 10 " +((11 - val % 11) % 10));
    return ctl == (1 * numStr.charAt(pos)); 
    // ou simplesmente: return (sum % 11 and (11 - sum % 11) % 10) == parseInt(num.charAt(pos));
  }
}
function HelpBI(ctrlHelpTxt, ctrlVisible) {
	document.getElementById(ctrlHelpTxt).style.display = ctrlVisible ? 'block' : 'none';
}
function HelpBI1(ctrlHelpTxt1, ctrlVisible) {
	document.getElementById(ctrlHelpTxt1).style.display = ctrlVisible ? 'block' : 'none';
}
/* --------------------------------------------- */
/* Retorna o ctrl que: está a ser validado por um CustomValidator e cujo o nome começa por "validator2" */
function GetCtrlFromCustomValidator(source) {
  var ctrlV = document.getElementById(source.id.substring(source.id.indexOf("2")+1, source.id.length));
  if (ctrlV == null)
    return null;
  ctrlV.value = TrimString(ctrlV.value);
  return ctrlV;
}
/* Retorna o bloco com id="block..." (se existir) no qual o ctrl dado esta inserido */
function GetCtrlBlock(ctrl){
  var blockCtrl = ctrl.parentNode;
  while (blockCtrl != null){ 
  if (blockCtrl.id.indexOf("block") != -1) break;
    blockCtrl = blockCtrl.parentNode;
  }
  return blockCtrl;
}

/* Activa o block "outro..." associada 'a dropDownList dada */
function ClientSetVisibleOther(clientIdDropdownList, clientIdBlockOutro) {
  var dropDownList = document.getElementById(clientIdDropdownList);
  if (dropDownList == null)
    return;
  var val = dropDownList.options[dropDownList.selectedIndex].value.toLowerCase();
  document.getElementById(clientIdBlockOutro).style.display = (val.indexOf("outr") != -1) ? 'block' : 'none';
}
function ClientSetVisibleOther2(clientIdDropdownList, clientIdBlockOutro) {
  var dropDownList = document.getElementById(clientIdDropdownList);
  if (dropDownList == null)
    return;
  var val = dropDownList.options[dropDownList.selectedIndex].value.toLowerCase();
  document.getElementById(clientIdBlockOutro).style.display = (val.indexOf("outr") != -1) ? 'inline' : 'none';
}
/* Valida a caixa de texto "outro..." em funcao do bloco onde esta' inserido estar ou nao visible */
function ClientCheckEmptyFieldOther(source, args) {
  var ctrlV = GetCtrlFromCustomValidator(source);
  var blockCtrl = GetCtrlBlock(ctrlV);
  if ((ctrlV != null) && (blockCtrl != null) && (blockCtrl.style.display == 'block') && (ctrlV.value == ""))  // caixa existe, visivel e vazia
    args.IsValid = false;
  else
    args.IsValid = true;
  return args.IsValid;
}
/* Verifica (apos o event 'onchange' da dropDownList ter sido disparado) a validade do nr de identificacao  */
function ClientCheckNrDocId(clientIdDropdownList, clientNrId, validatorCtrl) {
  var dropDownList = document.getElementById(clientIdDropdownList);
  if (dropDownList == null)  return;
  var val = dropDownList.options[dropDownList.selectedIndex].value.toLowerCase();
  document.getElementById(clientNrId).style.display = (val.indexOf("_bi") != -1) ? 'inline' : 'none';
  if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); 
}

/* ------------------------------------------------------------------------- */
/* Activa os blocos de informacao do Conjuge -> APENAS VALIDO PARA O PASSO 1 */
function ClientSetVisibleBlockConjuge(clientIdLeftBlock, clientIdRightBlock) {
  document.getElementById(clientIdLeftBlock).style.display = (existeConjuge ? 'block' : 'none');
  document.getElementById(clientIdRightBlock).style.display = (existeConjuge ? 'block' : 'none');  
}

/* --------------------------------------------------------------------------------------------- */
/* Validação de Campos que pretencem ao Titular 2 (Conjuge) -> APENAS VALIDO PARA OS PASSO 2 e 3 */
function ClientValidateEmptyTitular2(source, args) {
  var ctrlV = GetCtrlFromCustomValidator(source);
  args.IsValid = ((ExistsTitular2() && (ctrlV != null)) ? !IsEmptyString(ctrlV.value) : true);
}
function ExistsTitular2() {
  var exist = document.getElementById("<%=existeConjuge.ClientID%>");
  if (exist != null)
    return (exist.value == "true")
  return false;
}

