﻿function ValidateField()
{
document.getElementById("ctl00_cphHomePage_lblMsg").innerHTML="";

//vou buscar os valores dos tres campos
  var valorUsername=document.getElementById("ctl00_cphHomePage_txtUsername").value;
  var valorPassword=document.getElementById("ctl00_cphHomePage_txtPassword").value;
  var valorNif=document.getElementById("ctl00_cphHomePage_txtNif").value;
  var nifValido =IsValidNIF(valorNif);
  //  alert(nifValido);
    //alert(sValidNIF(valorNif)== true);
    //alert(valorUsername!="");
    //alert(valorPassword !="");
   // alert(valorNif!="");
   
  //se todos os campos estiverem preenchidos coloco enable senão disable
  if(valorNif!="" && valorPassword !="" && valorUsername!="" && IsValidNIF(valorNif)== true){
    document.getElementById("ctl00_cphHomePage_btLogin").disabled = false;
    }
    else{
     document.getElementById("ctl00_cphHomePage_btLogin").disabled = true;
    }
 }


//
function IsValidNIF(nif)
{
    var c;
    var checkDigit = 0;
    
    //Check if is not null, is numeric and if has 9 numbers
    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))
                return true;            
        }        
    }
    return false;
}

function IsNumeric(ObjVal)
{
return /^\d+$/.test(ObjVal);
}

