/*
========== INSTALLATION AND USAGE =============
1.  Include the javascript file (passwordvalidator.js) in the head or body of your HTML page
	Example: <script language="javascript" src="passwordvalidator.js"></script>
2.  Place the following password calling code IMMEDIATELY after the password field you want to validate 
     and replace passwordid with the ID of the password field being validated. Keep the double qoutes.
	Example: <script language="javascript">
				createPasswordValidator("passwordid");
			 </script>
===============================================*/
// Validation settings
var minLength = 3;             // Minimum length of password
var maxLength = 20;            // Maximum length of password
var noSpecialChars = false;     // Sets if special characters (punctuation etc.) can be in password
var isPasswordRequired = false;  // Sets if the password is a required field
var showTip = true;             // Show a tip to users if their password is not perfect

// Custom strings for personalisation or i18n
var strRequired = "Requerido";     // Displays when nothing is entered & password is required
var strTooShort = "Senha muito curta";   // Displays when password is less than minLength 
var strTooLong = "Senha muito longa";      // Displays when password is too long
var strSpecialChars = "Caracteres especiais não são permitodos";     // Displays when user enters special chars
var strWeak = "Senha muito fácil";       // Displays when password is weak strength
var strMedium = "Serve, mas poderia ser melhor";   // Displays when password is medium strength
var strStrong = "Senha perfeita!";          // Displays when password is perfect

// UI settings
var BackgroundColor = "#FFFFFF";     // Background color of validator 
var TextColor = "#FF0000";           // Text color of validator 
var TextFontFamily = "Arial"; // Font Family
var TextSize = "smaller";               // Text font size
var TextBold = false;              // Is text bold?


/*************** End of user specified settings **********/
/*************** DO NOT EDIT BELOW THIS LINE ****************/


var tip = 'Dicas para criar a senha perfeita:\\n1.Deve ter tamanho entre '+minLength+' e '+maxLength+' letras \\n2.Não deve ser palavra de dicionário comum (muito fácil de adivinhar)\\n3.Deve ter pelo menos uma letra maiúscula, uma minúscula e um dígito.';

/************** Create the validator **************/
function createPasswordValidator(elementToValidate,Required)
	{	
		// Initialise display
		isPasswordRequired = Required;
		var validatorStyle = '<style type="text/css"> .pwdvalid { background-color:'+BackgroundColor+'; color:'+TextColor+'; font-family:'+TextFontFamily+'; font-size:'+TextSize+';';
		if(TextBold)
			validatorStyle += 'font-weight: bold;';
		validatorStyle +='}</style>';
		document.write(validatorStyle);
		
		// Get the element to validate
		var elm;
		if(!(elm = document.getElementById(elementToValidate)))
		{
			alert('Password Validator could not find your password field identified by id='+elementToValidate);
			return;
		}
		
		// Create visual output
		var output = '<div id="_pwdvalid'+elementToValidate+'" class="pwdvalid">&nbsp;</div>';
		document.write(output);
		
		// Register event handlers
		// Use quirksmode idea for flexible registration by copying existing events
		// onKeyUp
		var oldEventCode = (elm.onkeyup) ? elm.onkeyup : function () {};
		elm.onkeyup = function () {oldEventCode(); validatePassword(elm.id)};
		// onmouseout
		oldEventCode = (elm.onmouseout) ? elm.onmouseout : function () {};
		elm.onmouseout = function() {oldEventCode(); validatePassword(elm.id)};		
		// onblur
		oldEventCode = (elm.onblur) ? elm.onblur : function () {};
		elm.onblur = function() {oldEventCode(); validatePassword(elm.id)};		
	}
	
function validatePassword(elementToValidate) 
	{
		var elm;
		if(!(elm = document.getElementById(elementToValidate)))
		{
			return;
		}
		var passwordDiv = document.getElementById("_pwdvalid"+elementToValidate);
		var passwordString = elm.value;
		if(passwordString.length == 0 )
		{
			if(  isPasswordRequired ) {
				passwordDiv.innerHTML = strRequired;
				return;
			} else {
				passwordDiv.innerHTML = "";
				return;
			}
		}
		if(passwordString.length < minLength)
		{
			passwordDiv.innerHTML = strTooShort;
			return;
		}
		if(passwordString.length > maxLength)
		{
			passwordDiv.innerHTML = strTooLong;
			return;
		}
		// Match special characters
		if(passwordString.match(/\W/) && noSpecialChars)
		{
			passwordDiv.innerHTML = strSpecialChars;
			return;
		}			
		var strength = 0;
		// Match upper case characters
		if(passwordString.match(/[a-z]/))
		{
			strength++;
		}
		// Match lower case characters
		if(passwordString.match(/[A-Z]/))
		{
			strength++;
		}
		// Match digits
		if(passwordString.match(/\d/))
		{
			strength++;
		}		
		switch(strength)
		{
			case 1: passwordDiv.innerHTML = strWeak;
					displayTip(passwordDiv);
					break;
			case 2: passwordDiv.innerHTML = strMedium;
					displayTip(passwordDiv);
					break;
			case 3: passwordDiv.innerHTML = strStrong;
					break;
		}				
	}
		
	function displayTip(div)
	{		
		// Show tip
		if(showTip)		
			div.innerHTML += '&nbsp;'+'<a href="javascript:alert(\''+tip+'\');" style="font-size:smaller; text-decoration: none">Dica</a>';
	}

							
							 
		
	
