﻿/*
Script: Password Strength Indicator
Author: Luke Phillips
*/

function charCount(string) {
    var l, u, n, s;
    l = u = n = s = 0;
    var reCharLower = /^[a-z]$/;
    var reCharUpper = /^[A-Z]$/;
    var reNum = /^[0-9]$/;
    var reSpec = /^[!£$%^&*?.<>]$/;
    for (var i = 0; i < string.length; i++) {
        if (reCharLower.test(string.charAt(i))) l += 1;
        if (reCharUpper.test(string.charAt(i))) u += 1;
        if (reNum.test(string.charAt(i))) n += 1;
        if (reSpec.test(string.charAt(i))) s += 1;
    }
    var count = new Array(l, u, n, s);
    return count;
}

function strength(string) {
    var score = 0;
    var count = charCount(string);
    // password length
    if (string.length <= 4 && string.length != 0) score += 5;
    else if (string.length >= 5 && string.length <= 6) score += 10;
    else if (string.length >= 7) score += 25;
    // password uppercase and lowercase letters
    if (count[0] == 0 && count[1] == 0) score += 0;
    else if (count[0] != 0 && count[1] == 0) score += 10;
    else if (count[0] != 0 && count[1] != 0) score += 20;
    // password number
    if (count[2] == 0) score += 0;
    else if (count[2] >= 1 && count[2] <= 2) score += 10;
    else if (count[2] >= 3) score += 20;
    // password special characters
    if (count[3] == 0) score += 0;
    else if (count[3] == 1) score += 10;
    else if (count[3] > 1) score += 20;
    // passord bonus
    if (count[0] != 0 && count[1] == 0 && count[2] != 0 && count[3] == 0) score += 2;
    else if (count[0] != 0 && count[1] == 0 && count[2] != 0 && count[3] != 0) score += 3;
    else if (count[0] != 0 && count[1] != 0 && count[2] != 0 && count[3] != 0) score += 5;
    return score;
}

function indicator(input, id, txtStrenght) {
    var color;
    var newText;
    var string = input.value;
    var indicator = document.getElementById(id);
    var theText = document.getElementById(txtStrenght);
    var score = strength(string);
    if (score >= 90) {
        color = '#5bc405';
        newText = 'Password strength: <b>Great!</b>';
        score = 90;
    }
    else if (score >= 80) {
        color = '#ace000';
        newText = 'Password strength: <b>Great!</b>';
    }
    else if (score >= 70) {
        color = '#ffdf00';
        newText = 'Password strength: <b>Good</b>';
    }
    else if (score >= 60) {
        color = '#ffa100';
        newText = 'Password strength: <b>Ok</b>';
    }
    else if (score >= 50) {
        color = '#ff6300';
        newText = 'Password strength: <b>Could be better</b>';
    }
    else if (score >= 25) {
        color = '#ff2500';
        newText = 'Password strength: <b>Bad</b>';
    }
    else if (score >= 0) {
        color = '#ff0000';
        newText = 'Password strength: <b>Bad</b>';
    }
    indicator.style.background = color;
    indicator.style.width = score + 'px';
    theText.innerHTML = newText;
}
