/**********************************************************************
* Sistema de Gestão de Matrículas 2009
**********************************************************************
* Funções em JavaScript para utilização genérica
* 
* Mário Pinto - 2009.06.24
*********************************************************************/

function change(id,v){
  document.getElementById(id).value = v;
}

function validate_required(field,alerttxt){
  with (field){
    if (value==null||value==""){
      alert(alerttxt);
      return false;
    } else {
      return true;
    }
  }
}

function validate_password(p1,p2){
  if ((p1.value != p2.value)){
    alert("As palavras-passe não coincidem."); return false;
  } else
  if (p1.value==null || p1.value=="" || p2.value==null || p2.value==""){
    alert("A palavra-passe não pode ser vazia."); return false;
  } else
  if (p1.value.length<6){
    alert("A palavra-passe tem que ter pelo menos 6 caracteres."); return false;
  } else{
    return true;
  }
}

function valid_email(field){
  with (field){
    apos=value.indexOf("@");
    dotpos=value.lastIndexOf(".");
    if (apos<1||dotpos-apos<2){
      return false;
    } else {
      return true;
    }
  }
}

function validate_form(step){
  
  switch(step){
    // Validar Dados Pessoais
    case '1':
      with (document.form){
        if (nome.value.length==''){
          alert("Não preencheu o Nome");
          nome.focus();
          return false;
        }
        if (bi.value.length<7){
          alert("Não preencheu correctamente o número do Bilhete de Identidade/Cartão de Cidadão");
          bi.focus();
          return false;
        }
        if (data_nascimento.value.length<8){
          alert("Não preencheu correctamente a Data de Nascimento");
          data_nascimento.focus();
          return false;
        }
        if (morada.value.length==''){
          alert("Não preencheu a Morada");
          morada.focus();
          return false;
        }
        if (cod_postal.value.length<7){
          alert("Não preencheu correctamente o Código Postal");
          cod_postal.focus();
          return false;
        }
        if (localidade.value.length==''){
          alert("Não preencheu a Localidade");
          localidade.focus();
          return false;
        }
        if (contacto.value.length<9){
          alert("Não preencheu correctamente o contacto");
          contacto.focus();
          return false;
        }
        if ((email.value != '')&&(!valid_email(email))){
          alert("O endereço de correio electrónico indicado não é válido");
          email.focus();
          return false;
        }
        
        
        
        
        // Validar EE
        if (ee_nome.value.length==0){
          alert("Não preencheu o Nome do Encarregado de Educação");
          ee_nome.focus();
          return false;
        }
        if (ee_morada.value.length==''){
          alert("Não preencheu a Morada do Encarregado de Educação");
          ee_morada.focus();
          return false;
        }
        if (ee_cod_postal.value.length<7){
          alert("Não preencheu correctamente o Código Postal do Encarregado de Educação");
          ee_cod_postal.focus();
          return false;
        }
        if (ee_localidade.value.length==''){
          alert("Não preencheu a Localidade do Encarregado de Educação");
          ee_localidade.focus();
          return false;
        }
        if (ee_contacto.value.length<9){
          alert("Não preencheu correctamente o contacto do Encarregado de Educação");
          ee_contacto.focus();
          return false;
        }
        if ((ee_email.value != '')&&(!valid_email(ee_email))){
          alert("O endereço de correio electrónico indicado não é válido");
          ee_email.focus();
          return false;
        }
        
        
        // Validar irmaos, transporte, ASE e NEE
        if ((irmaos_outra[0].checked)&&(irmaos_outra_nome_1.value == '')){
          alert("Indique os dados relativos aos irmãos a frequentar escolas oficiais");
          irmaos_outra_nome_1.focus();
          return false;
        }
        if ((irmaos_essb[0].checked)&&(irmaos_essb_nome_1.value == '')){
          alert("Indique os dados relativos aos irmãos candidatos a frequentar a Escola Secundária Soares Basto");
          irmaos_essb_nome_1.focus();
          return false;
        }
        if ((transporte[0].checked)&&(transporte_embarque.value == '')){
          alert("Indique o local de embarque para os Transportes Escolares");
          transporte_embarque.focus();
          return false;
        }
        if ((nee[0].checked)&&(nee_quais.value == '')){
          alert("Deverá indicar a natureza das necessidades e o tipo da deficiência");
          nee_quais.focus();
          return false;
        }
        

        // Validar opções de línguas e turmas
        if (le_56.value == ''){
          alert("Não indicou a Língua Estrangeira frequentada no 5º e 6º anos");
          le_56.focus();
          return false;
        }
        if ((le_789.value =='')&&((ultimo_ano.value > 2)||((ultimo_ano.value == 2)&&(aproveitamento.value==1)))){
          alert("Não indicou a Língua Estrangeira iniciada no 7º ano");
          le_789.focus();
          return false;
        }
        if ((le_10.value =='')&&((ultimo_ano.value > 5)||((ultimo_ano.value == 5)&&(aproveitamento.value==1)))){
          alert("Não indicou a Língua Estrangeira iniciada no 10º ano");
          le_789.focus();
          return false;
        }
        if ((turma.value == '')&&(outra_escola.value == '')){
          alert("Não indicou a Turma ou o Estabelecimento de Ensino frequentado");
          le_56.focus();
          return false;
        }
        


      }
      break;

    case '2': // Validar form 2
      with (document.form){
        // n_opcoes_a - checkbox opcoes_a_'$i'
        // n_opcoes_b - checkbox opcoes_b_'$i'
        if (typeof n_opcoes_a!="undefined"){
          opcoes_a = 0;
          for (i = 1; i<=n_opcoes_a.value; i++)
            if (document.getElementById('opcoes_a_'+i).checked)
              opcoes_a++;
          opcoes = opcoes_a;
          for (i = 1; i<=n_opcoes_b.value; i++)
            if (document.getElementById('opcoes_b_'+i).checked)
              opcoes++;
          if (opcoes_a < 1){
            alert("Deverá escolher sempre uma disciplina do grupo de opções A.")
            return false;
          }
          if (opcoes < 2){
            alert("Deverá escolher sempre duas das disciplinas de opção.")
            return false;
          }
          if (opcoes > 2){
            alert("Deverá escolher apenas duas das disciplinas de opção.")
            return false;
          }
        }
        // n_cursos - curso_opcao_'$i'
        // Contar número de cursos seleccionados

        if (typeof n_cursos!="undefined"){
          cursos = 0;
          for (i = 1; i<=n_cursos.value; i++)
            if (document.getElementById('curso_opcao_'+i).value!='')
              cursos++;
          if (cursos == 0){
            alert("Não indicou nenhum curso que pretende frequentar");
            document.getElementById('curso_opcao_1').focus();
            return false;
          }
        }
        // n_opcoes_x - x {ct,se,lh}
        // curso_opcao_1 - ct
        // curso_opcao_2 - se
        // curso_opcao_3 - lh
        if ((typeof curso_opcao_1!= "undefined") && (curso_opcao_1.value>0)){ // CT
          if (typeof n_opcoes_ct!="undefined"){
            opcoes_ct = 0;
            for (i = 1; i<=n_opcoes_ct.value; i++)
              if (document.getElementById('opcoes_ct_'+i).checked)
                opcoes_ct++;
            if (opcoes_ct != 2){
              alert('No Curso de Ciências e Tecnologias, deverá escolher duas disciplinas das opções.\nVocê escolheu '+opcoes_ct);
              curso_opcao_1.focus();
              return false;
            }
          }
        }
        if ((typeof curso_opcao_2!= "undefined") && (curso_opcao_2.value>0)){ // SE
          if (typeof n_opcoes_se!="undefined"){
            opcoes_se = 0;
            for (i = 1; i<=n_opcoes_se.value; i++)
              if (document.getElementById('opcoes_se_'+i).checked)
                opcoes_se++;
            if (opcoes_se != 2){
              alert('No Curso de Socio-Económicas, deverá escolher duas disciplinas das opções.\nVocê escolheu '+opcoes_se);
              curso_opcao_2.focus();
              return false;
            }
          }
        }
        if ((typeof curso_opcao_3!= "undefined") && (curso_opcao_3.value>0)){ // LH
          if (typeof n_opcoes_lh!="undefined"){
            opcoes_lh = 0;
            for (i = 1; i<=n_opcoes_lh.value; i++)
              if (document.getElementById('opcoes_lh_'+i).checked)
                opcoes_lh++;
            if (opcoes_lh != 2){
              alert('No Curso de Línguas e Humanidades, deverá escolher duas disciplinas das opções.\nVocê escolheu '+opcoes_lh);
              curso_opcao_3.focus();
              return false;
            }
          }
        }
      }
      break;
  }
  return true;
}

function confirm_del(msg,f){
  if (confirm(msg))
    submit_form(f);
}

function submit_form(f){
  document.getElementById(f).submit();
}

function show(id,classe){ // Change visibility using style.display on the stylesheet
  document.getElementById(id).className = classe;
}
function hide(id,classe){
  document.getElementById(id).className = classe;
}

function switch_visibility(id,show,hide){
  document.getElementById(id).className = (document.getElementById(id).className == hide) ? show : hide;
}

function count_chars(id_text,id_counter,max) {
  t = document.getElementById(id_text);
  c = document.getElementById(id_counter);
  if (t.value.length > max)
    t.value = t.value.substring(0, max);
  else
    c.value = max - t.value.length;
}

function data_input(d,m,mask){

  function valid_char(c){
    switch(c){
      case '0': case '1': case '2': case '3': case '4': case '5': case '6':
      case '7': case '8': case '9': case '-': return true; break;
      default: return false;
    }
  }
  
  d = document.getElementById(d);
  m = document.getElementById(m);

  l = d.value.length;
  
  if (!valid_char(d.value.charAt(l-1)))
    d.value = d.value.substring(0, l-1); // Apagar caracteres não válidos
  else
    m.value = mask.substring(l); // Com carácteres válidos, alterar a máscara
}


function IsNumeric(ObjVal){
  return /^\d+$/.test(ObjVal);
}

function validate_nif(nif_n,val,valid,invalid){
  var nif = document.getElementById(nif_n).value;
  var c;
  var checkDigit = 0;
  
  if(nif != null && IsNumeric(nif) && nif.length == 9){
    //Get the first number of NIF
    c = nif.charAt(0);
    //Check firt number is (1, 2, 5, 6, 8 or 9)
    if(c == '1' || c == '2' || c == '5' || c == '6' || c == '8' || c == '9'){
      //Perform CheckDigit calculations
      checkDigit = c * 9;
      var i = 0;
      for(i = 2; i <= 8; i++)
        checkDigit += nif.charAt(i-1) * (10-i);
      checkDigit = 11 - (checkDigit % 11);
      //if checkDigit is higher than ten set it to zero
      if(checkDigit >= 10)
        checkDigit = 0;
      //Compare checkDigit with the last number of NIF
      //If equal the NIF is Valid.
      if(checkDigit == nif.charAt(8)){
        document.getElementById(val).value = valid;
        return true;
      }
    }
  } else{
    document.getElementById(val).value = invalid;
    return false;
  }
}

function validate_bi(bi_n,bi_d,val,valid,invalid){
  var bi = document.getElementById(bi_n).value;
  var digit = parseInt(document.getElementById(bi_d).value);
  var sum=0;
  var i=0;
  
  while (bi.length < 8)
    bi = '0' + bi;
  
  for (i=0;i<8;i++)
    sum = sum + (9-i)*bi.charAt(i);
  sum = sum + digit;

  if (sum%11==0){
    document.getElementById(val).value = valid;
    return true;
  }
  else {
    document.getElementById(val).value = invalid;
    return false;
  }
}
















function SHA1 (msg) {
/**
*
*  Secure Hash Algorithm (SHA1)
*  http://www.webtoolkit.info/
*
**/
  
  function rotate_left(n,s) {
      var t4 = ( n<<s ) | (n>>>(32-s));
      return t4;
  };

  function lsb_hex(val) {
      var str="";
      var i;
      var vh;
      var vl;

      for( i=0; i<=6; i+=2 ) {
          vh = (val>>>(i*4+4))&0x0f;
          vl = (val>>>(i*4))&0x0f;
          str += vh.toString(16) + vl.toString(16);
      }
      return str;
  };

    function cvt_hex(val) {
        var str="";
        var i;
        var v;

        for( i=7; i>=0; i-- ) {
            v = (val>>>(i*4))&0x0f;
            str += v.toString(16);
        }
        return str;
    };


    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for( i=0; i<msg_len-3; i+=4 ) {
        j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
        msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
        word_array.push( j );
    }

    switch( msg_len % 4 ) {
        case 0:
            i = 0x080000000;
        break;
        case 1:
            i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
        break;

        case 2:
            i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
        break;

        case 3:
            i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8    | 0x80;
        break;
    }

    word_array.push( i );

    while( (word_array.length % 16) != 14 ) word_array.push( 0 );

    word_array.push( msg_len>>>29 );
    word_array.push( (msg_len<<3)&0x0ffffffff );


    for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {

        for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
        for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for( i= 0; i<=19; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=20; i<=39; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=40; i<=59; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=60; i<=79; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}