/*
* This notice must be untouched at all times.

============= META ==================
@name : passwordvalidator.js  
@version : 0.9 
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 10/06/2005
@url : http://sarat.xcelens.co.uk
@latest-version-url : http://sarat.xcelens.co.uk/2005/06/10/password-validator/
======================================

============== DESCRIPTION =============
This code snippet creates an dynamic password validator for a password fields in a form resembling the functionality provided by ASP.Net.
=========================================

========== 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>
==========================================

And thats it! You have your own password field validator.

============= FEATURES ==================
- Editable validation settings to create a custom password field
- i18n support for strings
- Customisable UI
- Use on any number of password fields
============================================

============= FUTURE PLANS ==================
- Allow validator to block all submits until field is validated
- Allow automatic addition of validator to all password fields by just including
- Create XML markup tag syntax to enable designers to create validator as in .NET
==============================================

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

/************** OPTIONAL EDIT BELOW THIS LINE  ***********************/
/************** User specified settings *******************/
// Validation settings
var minLength = 8;             // Minimum length of password
var maxLength = 255;            // Maximum length of password
var noSpecialChars = true;     // Sets if special characters (punctuation etc.) can be in password
var isPasswordRequired = true;  // 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 = "<table width=200 border=0 cellspacing=0 cellpadding=0>" + "  <tr>" + 
"    <td width=33% align=center class=passwordBlank>Weak</td>" + 
"    <td width=33% align=center class=passwordBlank>Medium</td>" + 
"    <td width=33% align=center class=passwordBlank>Strong</td>" + 
"  </tr>" + 
"</table>";     // Displays when nothing is entered & password is required
var strTooShort = "<table width=200 border=0 cellpadding=0 cellspacing=0>" + 
"  <tr>" + 
"    <td align=left class=passwordError1>Password is too short</td>" + 
"  </tr>" + 
"</table>";   // Displays when password is less than minLength 
var strTooLong = "<table width=200 border=0 cellpadding=0 cellspacing=0>" + 
"  <tr>" + 
"    <td align=left class=passwordError1>Password too long</td>" + 
"  </tr>" + 
"</table>";      // Displays when password is too long
var strSpecialChars = "<table width=200 border=0 cellpadding=0 cellspacing=0>" + 
"  <tr>" + 
"    <td align=left class=passwordError1>Special characters not allowed</td>" + 
"  </tr>" + 
"</table>";     // Displays when user enters special chars
var strWeak = "<table width=200 border=0 cellspacing=0 cellpadding=0>" + 
"  <tr>" + 
"    <td width=33% align=center class=passwordWeak>Weak</td>" + 
"    <td width=33% align=center class=passwordBlank>&nbsp;</td>" + 
"    <td width=33% align=center class=passwordBlank>&nbsp;</td>" + 
"  </tr>" + 
"</table>";       // Displays when password is weak strength
var strMedium = "<table width=200 border=0 cellspacing=0 cellpadding=0>" + 
"  <tr>" + 
"    <td width=33% align=center class=passwordMedium>&nbsp;</td>" + 
"    <td width=33% align=center class=passwordMedium>Medium</td>" + 
"    <td width=33% align=center class=passwordBlank>&nbsp;</td>" + 
"  </tr>" + 
"</table>";   // Displays when password is medium strength
var strStrong = "<table width=200 border=0 cellpadding=0 cellspacing=0>" + 
"  <tr>" + 
"    <td width=33% align=center class=passwordStrong>&nbsp;</td>" + 
"    <td width=33% align=center class=passwordStrong>&nbsp;</td>" + 
"    <td width=33% align=center class=passwordStrong>Strong</td>" + 
"  </tr>" + 
"</table>";          // Displays when password is perfect

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


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


var tip = 'Tips on creating the right password\\n1.Should be between '+minLength+' and '+maxLength+' characters \\n2.Should not be a word from the common dictionary. These passwords are easiest to guess and internet robots can figure them out.\\n3.Should have atleast one uppercase letter, one lowercase letter and one digit.';

/************** Create the validator **************/
function createPasswordValidator(elementToValidate)
	{	
		// Initialise display
		var validatorStyle = '';
		if(TextBold)
			validatorStyle += '';
		validatorStyle +='';
		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)};		
	}
	
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)
		{
			passwordDiv.innerHTML = strRequired;
			return;
		}
		if(passwordString.length < minLength)
		{
			passwordDiv.innerHTML = strTooShort;
			return;
		}
		if(passwordString.length > maxLength)
		{
			passwordDiv.innerHTML = strTooLong;
			return;
		}
		// Match special characters
		if(passwordString.match(/\W/))
		{
			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">Tip</a>';
	}

							
							 
		
	
