/*
 * Handle resetting the user's password.
 */

var reset_message_id = 'resetpasswd-message'

var reset_passwd_dlg = null;

var reset_already = false;

// Holds the old notification id.  This is reset when the dialog is closed.
var rp_old_notification_id = null;

function login_reset_password_dialog() {
    rp_old_notification_id = notify_set_id(reset_message_id);

    $("#resetpasswddialog").dialog('open');
    $('#rp_email_address').focus();
}

$(document).ready(function() {
    var remove_style = function() {
        $('#resetpasswddialog').removeAttr('style');
    };

    var restore_notify = function() {
        notify_set_id(rp_old_notification_id);
        $('email_address').focus();
    };

    var close_dialog = function() {
        $("#resetpasswddialog").dialog('close');
    }

    var options = { modal : true,
                    title : 'Reset your password?',
                    width : '636px',
                    height : '350px',
                    autoOpen : false,
                    buttons: { "Reset Password": reset_password,
                               Cancel: close_dialog },
                    resizeStop : remove_style,
                    open: remove_style,
                    close: restore_notify,
                    overlay: {opacity: 0.7,
                              background: 'black' }};

    $("#resetpasswddialog").dialog(options);
});

function reset_password() {
    var email = $('#rp_email_address').val();
    if (email == '') {
        $('#rp_email_address').focus();
        notify_error('Enter an email address.');
        return;
    }

    if (reset_already) {
        notify_error('You have already reset your password.');
        return;
    }

    var postd = { email_address : email };

    $.post("/passwd/reset", postd, function (data, status) {
        if (status != "success") {
            notify_error('Server error has occurred.  Try later.');
            return;
        }

        data = eval('(' + data + ')');

        if (data.status != 'success') {
            notify_error(data.value);
        } else {
            notify_info('Password reset.  Please check your email.');
            reset_already = true;
        }
    });
}