// Function taken from Mozilla Code:
// http://lxr.mozilla.org/seamonkey/source/security/manager/pki/resources/content/password.js
function getPasswordStrength(pwdID, textID, barID)
{
  // Here is how we weigh the quality of the password:
  // 1. number of characters
  // 2. numbers
  // 3. non-alpha-numeric chars
  // 4. upper and lower case characters

  var pwd = document.getElementById(pwdID).value.replace(/^\s*([^\s]+)?\s*$/, "$1");
  var text = document.getElementById(textID);
  var bar = document.getElementById(barID);
  
  var pwdLength = pwd.length;
  if (pwdLength > 5) pwdLength = 5;

  if (pwd.length > 0)
  {
    // use of numbers in the password
    var numbers = pwd.replace(/[0-9]/g, "");
    var numOfNumbers = pwd.length - numbers.length;
    if (numOfNumbers > 3) numOfNumbers = 3;
  
    // use of symbols in the password
    var symbols = pwd.replace(/\W/g, "");
    var numOfSymbols = pwd.length - symbols.length;
    if (numOfSymbols > 3) numOfSymbols = 3;
  
    // use of uppercase in the password
    var upper = pwd.replace(/[A-Z]/g, "");
    var numOfUpper = pwd.length - upper.length;
    if (numOfUpper > 3) numOfUpper = 3;
  
    // calculate and return a strength number
    var strength = pwdLength * 10 - 20 + numOfNumbers * 10 + numOfSymbols * 15 + numOfUpper * 10;
    if (strength < 0) strength = 0; // make sure we're give a value between 0 and 100
    if (strength > 100) strength = 100;
  }
  else
    strength = -1;
  
  // get a text and color rating based on the strength rating
  var rating, color;
  if (strength == -1)
  {
    strength = 0;
    rating = "Not Rated";
    color = "black";
  }
  else if (strength <= 25)
  {
    rating = "Very Weak";
    color = "red";
  }
  else if (strength <= 50)
  {
    rating = "Weak";
    color = "orange";
  }
  else if (strength <= 75)
  {
    rating = "Medium";
    color = "blue";
  }
  else
  {
    rating = "Strong";
    color = "green";
  }
  
  // set the element related styles and values
  text.innerHTML = '<span style="color:' + color + ';">' + rating + '</span>';
  bar.style.width = strength + "px";
  bar.style.backgroundColor = color;
  
  // if any additional fields are passed, set their value(s) to the strength rating
  for (var i=3; i<arguments.length; i++)
  {
    var fld = document.getElementById(arguments[i]);
    if (fld) fld.value = strength;
  }
}

function validatePassword(frm, flds)
{
  frm = $(frm);
  if (frm.validate(flds))
  {
    if (frm.hidStrength.value <= 50)
    {
      alert("Weak passwords cannot be accepted.");
      return false;
    }
    return true;
  }
  return false;
}
