﻿/***
 *
 *  This file contains JavaScript code which allows to detect when
 *  a user starts entering data in a field while thet Caps Lock is on.
 *
 *  Every input field on which Caps Lock detection is needed, must contain the following attribute:
 *      onkeypress="capsDetect(arguments[0]);"
 ******/
 
var ignoreCapsLock = false;

//  The following message is displayed to the user if Caps Lock is on
var capsError = 'Caps Lock is On <br>' +
                'Having Caps Lock on may cause you to enter your password incorrectly.';


/***
 *  This function determines if a key pressed by a user while the Caps Lock is on.
 *  This function should be invoked from the onKeyPress event on the Input field
 ******/       
function capsDetect( inputEvent ) 
{
    if (ignoreCapsLock)
        return;
        
        
    if( !inputEvent ) 
    {
        inputEvent = window.event; 
    } 
    
    if( !inputEvent ) 
    { 
        displayCapsLockWarning( false );
        return; 
    }
    
    
    //  Get the key that was pressed (keys are case sensitive in standard browsers)
    var theKey = inputEvent.which ? inputEvent.which : ( inputEvent.keyCode ? inputEvent.keyCode : ( inputEvent.charCode ? inputEvent.charCode : 0 ) );
    
    
    //  Determine if the shift key was pressed
    var theShift = inputEvent.shiftKey || ( inputEvent.modifiers && ( inputEvent.modifiers & 4 ) ); //bitWise AND
    
    
    //  If the input was in upper case, check if the shift key is NOT pressed.
    //  If the input is lower case, check if the shift IS pressed.
    var displayWarning = ( theKey > 64 && theKey < 91 && !theShift ) || ( theKey > 96 && theKey < 123 && theShift )
    displayCapsLockMessage( displayWarning );
}


//  This function displays a warning to the user
function displayCapsLockAlert( displayAlert ) 
{
    if( displayAlert ) 
    { 
        alert( capsError ); 
            
        //  The user has been informed, turn Caps Lock detection off
        ignoreCapsLock = true;
    }
}


function displayCapsLockMessage( displayMessage )
{
    var errCapsLockStyle = errCapsLock.style;
    
    if ( displayMessage )
    {
        errCapsLock.innerHTML = capsError;
        errCapsLockStyle.display = "block";
    }
    else
    {
        errCapsLockStyle.display = "none";
    }    
}


