/**
 * Encrypt passwords in either a new user registration form or a password change form
 *
 * (c) Mark Pearson 2008
 */


mujs = {}

// Hard coded password regex for the moment because its easier than trying to grab
// a regex defined on the server.
mujs.passwordRegex = /^[a-zA-Z0-9]+$/

// If any of the following fields are found, process the contents so that what gets
// submitted to the server is only MD5 hashes and scrambled plain text passwords.
mujs.encryptPasswords = function(form) {
    mujs.processField(form, 'password');
    mujs.processField(form, 'oldPassword');
    mujs.processField(form, 'newPassword');
    mujs.processField(form, 'confirmPassword');
}

// If the form contains a text input with the given name then generate an MD5 hash of the
// value it contains and store that in the hidden field with the name "_<fieldName>".
mujs.processField = function(form, fieldName) {
    if (form[fieldName] && mujs.passwordRegex.test(form[fieldName].value)) {
        mujs.encryptPassword(form[fieldName], form['_' + fieldName]);
        mujs.scramblePassword(form[fieldName]);        
    }
}

mujs.encryptPassword = function(inEl, outEl) {
    outEl.value = hex_md5(inEl.value);
}

mujs.randomString = function(length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var s = '';
    for (var i=0; i<length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        s += chars.substring(rnum,rnum+1);
    }
    
    return s;
}
    
// Scramble a plain text password typed in by the user without visually jarring by 
// just emptying the field. The new value serves no purpose other making it seem
// (in terms of watching the HTML form) that the password is just submitted as is).
mujs.scramblePassword = function(textField) {
    var length = textField.value.length;
    textField.value = mujs.randomString(length);
}

window.onload = function() {
    var form = document.getElementById('pwdform');
    if (!form) {
        form = document.getElementById('regform');
    }
    
    form.onsubmit = function() { mujs.encryptPasswords(form); }
}
