(function( $ ) {
/*
 * The account manager is initialized on a page change.  It must be passed the new page params.
 */
$.widget( "ui.accountManager", {  

    options: {
        // The url of the content html fragment
        url: null,

        // The url parameters of the address
        params: null,

        // Selectors
        accountTemplate: '#account-template',
        account: '.account',
        songListItemTemplate: '#song-list-item-template',
        songsContainer: '.songs',
        songs: '.songs ul',
        deletePanel: '.delete-panel'
    },

    _init: function() {
        var self = this,
            renderAccountUpdateForm,
            renderSongs,
            submitForm,
            loadPage,
            onLoad;

        function getAccountUpdateForm() {
            var href = $(self.options.account).data('href');
            return $.ajax({
                url: href,
                dataType: 'json'
            });
        }

		if( !this.options.params ) {
            throw "The account manager must be initialized with a set of parameters.";
        }

        if( !this.options.url ) {
            throw "The account manager must be initialized with a url.";
        }

        renderAccountUpdateForm = function (accountUpdateForm) {
            var $account = $(self.options.account);

            $.tmpl('account', accountUpdateForm).appendTo($account.empty());

            $account.find('form').bind('submit', function (event) {
                event.preventDefault();

                submitForm($(this)).then(
                    function (result) {
                        renderAccountUpdateForm(result);
                    },
                    function (xhr) {
                        throw 'updateError';
                    }
                );
            });
        };

        renderSongs = function (songs) {
            var songListView = new BS.view.AccountSongListView({
                el: self.options.songsContainer,
                model: songs
            });

            songListView.render();
        };

        submitForm = function ($form) {
            var updateUrl = $form.attr('action'),
                serializedForm = $form ? $form.serialize() : null;

            return $.ajax({
                url: updateUrl,
                type: 'POST',
                data: serializedForm
            });
        };

        loadPage = function () {
            self.element.empty().load( self.options.url, onLoad );
        };

        onLoad = function (responseText, textStatus, xhr) {
            switch (xhr.status) {
                case 401:
                    $( '#page' ).loginManager( 'login' ).then( loadPage );
                    break;
                default:
                    getAccountUpdateForm().then(
                        function (result) {
                            var $account = $(self.options.account),
                                userProfile = $.user.fromData(result),
                                artist = userProfile.artist,
                                songs;

                            if (artist) {
                                songs = new BS.domain.SongList([], {url: artist.links.songs});
                                songs.fetch().then(function () {
                                    renderSongs(songs);
                                });
                            }

                         //   renderAccountUpdateForm(result);

                            $account.accountUpdateForm({model: result});
                        },
                        function (xhr) {
                            throw 'error getting account update form';
                        }
                    );

                    //$(self.options.accountTemplate).template('account');
                    $('#account-song-list-template').template('accountSongList');
                    $(self.options.songListItemTemplate).template('songListItem');
            }
        };

        loadPage();
    },

    destroy: function() {
        $.Widget.prototype.destroy.apply(this, arguments);

        $( this.options.userProfile ).undelegate( 'submit' );
        this.element.empty();
    }
}); 

})( jQuery );

