jscape.account = jscape.account || {};

/** @class */
jscape.account.AccountSettingsApplication = jscape.Application.extend(
    /** @lends {jscape.account.AccountSettingsApplication.prototype} */
{
    onLogout: function() {
        jscape.API.logout();
    },

    /** @override */
    onReady: function() {
        this._forceStartModule("password-compliance");
        this._forceStartModule("account-inactivity");
        this.view.show(this);
    },

    /** @override */
    _createView: function() {
        this._super();
        this.view = new jscape.account.AccountSettingsView();
    },

    /** @override */
    _destroy: function() {
        this._forceStopModule("account-inactivity");
        this._forceStopModule("password-compliance");
        this._super();
    }
});

/** @class */
jscape.account.AccountSettingsView = jscape.DashboardView.extend(
    /** @lends {jscape.account.AccountSettingsView.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#dashboard[role=tablist]"));

        this.modules.tabs({
            fit: true,
            tabPosition: "left",
            headerWidth: 200,
            onSelect: $.proxy(this._onSelect$Tab, this)
        });
        this.modules.find("div[role=tablist]")
                .filter(function () { return $(this).parents("div.dialog").length == 0; })
                .each($.proxy(function (_, tablist) {
                          $(tablist).tabs({border: false, onSelect: $.proxy(this._onSelect$Tab, this)});
                      }, this));
        this.modules.find(">div.tabs-header>div.tabs-wrap")
                .hover(
                    function () { $(this).css({overflowY: "auto", overflowX: "hidden"}); },
                    function () { $(this).css({overflowY: "", overflowX: ""}); }
                );
    },

    show: function() {
        this._super.apply(this, arguments);
        this.modules.tabs("unselect", 0).tabs("select", 0);
    }
});

/** @class */
jscape.account.PasswordComplianceModule = jscape.ApplicationModule.extend(
    /** @lends {jscape.account.PasswordComplianceModule.prototype} */
{
    onStart: function() {
        this.view = new jscape.account.PasswordComplianceView();
        this.view.show(this);
    },

    onStop: function() {
        this.view.destroy();
        this.view = null;
    }
});

/** @class */
jscape.account.PasswordComplianceView = Class.extend(
    /** @lends {jscape.account.PasswordComplianceView.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.holder = $("#logininfo");
        var reminder = $("#password-reminder");

        if (this.holder.length && reminder.length) {
            this.holder.tooltip({
                content: reminder.html(),
                showEvent: "none",
                hideEvent: "none",
                onShow: $.proxy(function() {
                    this.holder.tooltip("tip")
                            .addClass("tooltip-tip-black")
                            .one("click", $.proxy(function () { this.holder.tooltip("destroy"); }, this));
                    this.holder.tooltip("reposition");
                }, this),
                onHide: function() { $(this).tooltip("destroy"); }
            });
        }
    },

    show: function() {
        if (this.holder.length) {
            this.holder.tooltip("show");
            $(window).on("resize.password_reminder", $.proxy(function() {
                this.holder.tooltip("reposition");
            }, this));
        }
    },

    destroy: function() {
        if (this.holder.length) {
            this.holder.tooltip("destroy");
            $(window).off("resize.password_reminder");
        }
    }
});

/** @class */
jscape.account.ChangePasswordController = Class.extend(
    /** @lends {jscape.account.ChangePasswordController.prototype} */
{
    deferred: null,

    start: function(username) {
        this.username = username;
        this.deferred = $.Deferred();
        this._setupDialog().show(this);
        return this.deferred.promise();
    },

    onSubmit: function(dialog) {
        var password = dialog.getPassword();
        dialog.destroy();

        jscape.API.changeUserPassword(this.username, password)
                .done($.proxy(this._showPasswordChangedMessage, this))
                .done($.proxy(function() { this.deferred.resolve(); this.deferred = null; }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    },

    onCancel: function(dialog) {
        dialog.destroy();
        this.deferred.reject();
        this.deferred = null;
    },

    _setupDialog: function() {
        var dialog = new jscape.account.ChangePasswordDialog();
        dialog.setUsername(this.username);
        return dialog;
    },

    _showPasswordChangedMessage: function () {
        $.messager.alert(window.R.string.USER_CHANGE_PASSWORD_TITLE,
                         window.R.string.USER_CHANGE_PASSWORD_MESSAGE,
                         "info");
    }
});

/** @class */
jscape.account.ChangePasswordDialog = Class.extend(
    /** @lends {jscape.account.ChangePasswordDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.dialog = $("#d-user-changepwd").clone().attr("id", "");
        this.dialog.dialog({
            width: 530, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK || "Ok", handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL || "Cancel", handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).show();

        this.fieldset = $("fieldset[name=userpasswordfields]", this.dialog);

        var id = "newpwd_" + $.now().toString(36);
        this.password = $("input[name=password]", this.fieldset).textbox({validType: "pi_password_compliance", delay: 700, width: "70%"});
        this.password.textbox("textbox")
                .on("input", $.proxy(function() { this.confirmPassword.textbox({required: this.password.textbox("textbox").val().length != 0}); }, this))
                .attr("id", id);

        this.confirmPassword = $("input[name=confirmpwd]", this.fieldset).textbox({validType: "pi_password_confirm['#" + id + "']", missingMessage: window.R.string.USER_ERROR_CONFIRM_PWD, width: "70%"});
    },

    getPassword: function() {
        return this.password.textbox("getValue");
    },

    setUsername: function(value) {
        this._adjustPasswordRequirements(value);
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.password.textbox("textbox").focus();
    },

    hide: function () {
        if (!this._closed()) {
            this.closing = true;
            this.dialog.dialog("close");
            this.fieldset.form("disableValidation");
            this.closing = false;
        }
    },

    destroy: function() {
        this.dialog.dialog("destroy");
    },

    _adjustPasswordRequirements: function(username) {
        var compliant = new jscape.Validator().isSatisfied("pi_password_compliance", "", username);
        var options = this.password.textbox("textbox").validatebox("options");
        options.validType = "pi_password_compliance" + (username ? "['" + username + "']" : "");
        options.required = !compliant;
    },

    _onSubmit: function () {
        if (this.fieldset.form("validate")) {
            this.listener.onSubmit(this);
        }
    },

    _onCancel: function () {
        this.hide();
        this.listener.onCancel(this);
    },

    _closed: function () {
        return !!this.dialog.dialog("options").closed;
    }
});