/**
 * Check if the given element's value meets these requirements
 * A new password (given elements value) is required when:
 * - filling out a form for a new user (no element with the 'old_password' id)
 * - filling out a form for an existing user and the 'old_password' element is
 *   filled (user wants to change his/her password)
 */
/* TODO Implement a validator in PHP and JS */
function checkPasswords(elem)
{
    var passwordElem = elem
    var oldPasswordElem = document.getElementById('old_password');
    
    // Do not check the password if the old password is not given.
    if(oldPasswordElem && !oldPasswordElem.value.length > 0) {
        return true;
    }
    return (passwordElem.value.length > 0);
}

// A cache of user name's that were checked
var _usernamesCache = new Hash();

var newUsernameValidator=function()
{
    this.inprogress_error = 'Checking...';
    this.unique_error = 'Username already exists';
    this.field_id = null;
    return true;
}

newUsernameValidator.prototype.execute=function(value)
{
    if(_usernamesCache.hasOwnProperty(value)) {
        // Still waiting. Check again later
        if(_usernamesCache[value] == this.inprogress_error) {
            setTimeout('checkField($("'+ this.field_id +'"))', 5000);
        }
        return _usernamesCache[value];
    }
    
    var error = this.unique_error;
    var url = '/user/update?username=' + value;
    _usernamesCache[value] = this.inprogress_error;
    
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(transport) {
            _usernamesCache[value] = false;
        },
        on404: function(transport) {
            // 404 Means the request was malformed (no check was performed)
            _usernamesCache[value] = 'Malformed request';
        },
        on409: function(transport) {
            _usernamesCache[value] = error;
        }
    });
    setTimeout('checkField($("'+ this.field_id +'"))', 5000);
    return this.inprogress_error;
}


