(function( $ ) {

// A component for managing the account login/logout/create buttons.
// This is a wrapper for those controls into a single grouping.  Other code can
// interact by either binding to events or calling public methods.
$.widget( "ui.accountUtils", {  

    options: {
        // Selectors
        loggedInPanel: '.logged-in',
        notLoggedInPanel: '.not-logged-in',
        loginButton: '.login',
        createAccountButton: '.create-account',
        logoutButton: '.logout',
        accountLink: '.account-link'
    },

    _init: function () {
        var self = this;

        this._initializeLoggedInPanel()
            ._initializeNotLoggedInPanel()
            ._initializeButton(this.options.loginButton, 'loginToAccount')
            ._initializeButton(this.options.createAccountButton, 'createAccount')
            ._initializeButton(this.options.logoutButton, 'logoutFromAccount');

        this._getUser().then(
            function (profile) {
                self.userIsLoggedIn(profile);
            },
            function () {
                self.userIsNotLoggedIn();
            }
        );

    },

    _getUser: function () {
        return $.user.currentIfAny();
    },

    _initializeLoggedInPanel: function () {
        var self = this,
            panel = this._createPanel(this.options.loggedInPanel),
            parentShow = panel.show,
            thisShow = function (profile) {
                self.element.find(self.options.accountLink).text(profile.user.email);
                parentShow.apply(this);
            };

        panel.show = thisShow;
        panel.hide();

        this.loggedInPanel = panel;
        return this;
    },

    _initializeNotLoggedInPanel: function () {
        this.notLoggedInPanel =  this._createPanel(this.options.notLoggedInPanel);
        this.notLoggedInPanel.hide();

        return this;
    },

    _createPanel: function (panelSelector) {
        var $panel = this.element.find(panelSelector);

        return {
            show: function () {
                $panel.show();
            },
            hide: function () {
                $panel.hide();
            }
        };
    },

    _initializeButton: function (buttonSelector, name) {
        var self = this;

        this.element.find(buttonSelector)
            .click(function (event) {
                self._trigger(name, event, []);
                return false;
            });

        return this;
    },

    userIsLoggedIn: function (profile) {
        this.isLoggedIn = true;
        this._displayLoggedInPanel(profile);
    },

    userIsNotLoggedIn: function () {
        this.isLoggedIn = false;
        this._displayNotLoggedInPanel();
    },

    _displayLoggedInPanel: function (profile) {
        this.notLoggedInPanel.hide();
        this.loggedInPanel.show(profile);
    },

    _displayNotLoggedInPanel: function () {
        this.loggedInPanel.hide();
        this.notLoggedInPanel.show();
    }
});

})(jQuery)


