(function( $ ) {

function blankAccountForm() {
    return {
        errors: [],
        data: {
            email: '',
            receiveNewsletter: true
        }
    };
}

$.widget( "ui.createAccount", {  
    options: {
        // Selectors
        createAccountTemplate: '#create-account-template'
    },

    _init: function() {
        var self = this;

        $.template('createAccount', $(this.options.createAccountTemplate));

        self.deferredCreate = null;

        self.element.dialog({
            modal: true,
            autoOpen: false,
            close: function (event, ui ) {
                if( self.deferredCreate ) {
                    self.deferredCreate.reject( {} );
                    self.deferredCreate = null;
                }
            }
        });

        this._renderForm(blankAccountForm());
    },

    _renderForm: function (accountForm) {
        var self = this;

        $.tmpl('createAccount', accountForm).appendTo(this.element.empty());
        this.element.find( 'form' ).submit( function () {
            var $form = $(this);
            $.post( $form.attr( 'action' ), $form.serialize() ).then(
                function (result) { // success
                    if (result.errors && result.errors.length) {
                        self._renderForm(result);
                    }
                    else {
                        self.deferredCreate.resolve(result);
                        self._close();
                    }
                },
                function () { // failure
                    self.deferredCreate.reject( {} );
                    self._close();
                }
            );

            return false;
        }); 
    },

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

        if( this.deferredCreate ) {
            this.deferredCreate.reject( {} );
            this.deferredCreate = null;
        }

        this.element
            .dialog( 'destroy' )
            .find( 'form' ).unbind( 'submit' );

        $( this.options.signUp ).unbind( 'click' );
    },

    signUp: function () {
        var self = this;

        if( !this.deferredCreate ) {
            this.deferredCreate = $.Deferred();
            this.deferredCreate.then(function (result) {
                self._trigger('signedUp', $.Event(), result);
            });

            this._open();
        }

        return this.deferredCreate.promise();
    },

    _open: function () {
        this.element.dialog( 'open' );
    },

    _close: function () {
        this.element.dialog( 'close' );
    }
}); 

})( jQuery );

