DNow.AccountDialog = Class.create( aw.ui.Dialog, {

    _form: null,

    initialize: function ( properties, events ) {

        this._form = null;

        this.inheritCSS = true;
        Object.extend( properties, {
            'title': 'Sign-up'
        });

        aw.ui.Dialog.prototype.initialize.apply( this, [properties, events] );

        if ((this.componentBus) && (this.componentBus.isSessionValidated() === true))
            this.setTitle('Account Information');
    },

    afterDraw: function ( ) {
        var am = this.componentBus.getComponentReferences( 'aw.AccountManager' );
        if ((am) && (am.length > 0))
            am = am[0];
        else
            return;

        am.retrieveAccountInfo( this._manifestReceived.bind( this ) );
    },

    draw: function ( ) {
        aw.ui.Dialog.prototype.draw.apply( this );

        var contents = this.canvas.down('div.contents');
        if (contents)
            contents.update( this._local_templates['ui'] );

        var form = this.canvas.down('div.form');
        if (form)
            form.update( 'Loading...' );

        var details = this.canvas.down('div.details');

        if ((this.componentBus) && (this.componentBus.isSessionValidated() === true)) {
            this._renderButton( 'Save', this._onSaveClick.bind( this ) );
            if (details)
                details.update( this._local_templates['accountdetails'] );
        } else {
            this._renderButton( 'Sign-up', this._onSignupClick.bind( this ) );
            if (details)
                details.update( this._local_templates['signupdetails'] );
        }

        this._renderButton( 'Cancel', this.close.bind( this ) );

        return this.canvas;
    },

    _manifestReceived: function ( manifest ) {
        if ((!manifest) || (!manifest.length > 0))
            return;

        var contents = this.canvas.down('div.form');
        if (!contents)
            return;

        contents.update( '' );

        this._form = new aw.ui.Form( );

        var category = null, categoryKey = null, categoryDOM, field = null;
        for (var i=0; category=manifest[i]; i++) {
            categoryKey = this.getId( );
            contents.insert( this._local_templates['category'].evaluate( { 'key': categoryKey, 'category': category.category } ) );
            categoryDOM = contents.down('div[key="' + categoryKey + '"]');

            for (var j=0; field=category.fields[j]; j++) {
                if ((field.type == 'text') || (field.type == 'password')) {
                    this._form.add( new aw.ui.Control.TextBox( { 'type': field.type, 'label': field.label + ((field.required === true) ? '*' : ''), 'name': field.name, 'value': field.defaultValue, 'container': categoryDOM } ) );

                    if (field.type == 'password') {
                        pwConfirm = field;
                        pwConfirm.name = 'passwordConfirm';
                        pwConfirm.label = 'Password Confirmation';
                        this._form.add( new aw.ui.Control.TextBox( { 'type': pwConfirm.type, 'label': pwConfirm.label + ((field.required === true) ? '*' : ''), 'name': pwConfirm.name, 'value': pwConfirm.defaultValue, 'container': categoryDOM } ) );
                    }
                } else if (field.type == 'select') {
                    field.values.unshift( { 'value': '', 'label': '-- Select One --' } );
                    var select = new aw.ui.Control.DropDown( { 'label': field.label + ((field.required === true) ? '*' : ''), 'name': field.name, 'options': field.values, 'container': categoryDOM } );
                    if ((field.defaultValue) && (field.defaultValue !== ''))
                        select.selectByValue( field.defaultValue );

                    this._form.add( select );
                }
            }
        }
    },

    _onSaveClick: function ( ) {
        if (!this._form)
            return;

        var am = this.componentBus.getComponentReferences( 'aw.AccountManager' );
        if ((am) && (am.length > 0))
            am = am[0];
        else
            return;

        var formValues = this._form.serialize();
        if ((formValues.password) && (formValues.password == '*-*-*-*-*'))
            delete formValues.password;

        if ((formValues.passwordConfirm) && (formValues.passwordConfirm == '*-*-*-*-*'))
            delete formValues.passwordConfirm;

        am.updateAccount( formValues, function ( status, message ) {
            if (status == 'failure') {
                new aw.ui.Dialog.Error({'title':'Error!', 'content': message});
            } else {
                new aw.ui.Dialog.Alert({'title':'Success!','content': message});
                this.close( );
            }
        }.bind( this ) );
    },

    _onSignupClick: function ( ) {
        if (!this._form)
            return;

        var am = this.componentBus.getComponentReferences( 'aw.AccountManager' );
        if ((am) && (am.length > 0))
            am = am[0];
        else
            return;

        var formValues = this._form.serialize();

        am.createAccount( formValues, function ( status, message ) {
            if (status == 'failure') {
                new aw.ui.Dialog.Error({'title':'Error!', 'content': message});
            } else {
                new aw.ui.Dialog.Alert({'title':'Success!','content': message});
                this.close( );
            }
        }.bind( this ) );
    },

    _local_templates: {
        'ui': '<div class="form"></div>' +
            '<div class="details"></div>' +
            '<div style="clear: both;"></div>',
        'category': new Template('<div class="category" key="#{key}"><h1>#{category}</h1><div class="fields"></div></div>'),
        'signupdetails': '<p>Welcome to DemographicsNow.  Please register for access to features such as reporting, mapping and list generation.</p>' +
            '<p>Please provide the required information on the left. Once your information is submitted, you will receive an email with instructions on how to activate your account.</p>' +
            '<p>If you need further assistance please contact us at:</p>' +
                'Javelin Group<br />' +
                '<a href="mailto:GeoSupport@javelingroup.com">GeoSupport@javelingroup.com</a><br />' +
                '+44(0) 207 961 1289',
        'accountdetails': '<p>Your account information can be changed by editing the fields on the left. Please note that if you change your email address your log in will also change.</p>' +
            '<p>If you need further assistance please contact us at:</p>' +
                'Javelin Group<br />' +
                '<a href="mailto:GeoSupport@javelingroup.com">GeoSupport@javelingroup.com</a><br />' +
                '+44(0) 207 961 1289'
    },

    /*
        Constant: CLASS_NAME
        The static class name of the <DNow.AccountDialog> class.
    */
    CLASS_NAME: 'DNow.AccountDialog'
});
