var SearchResponses = {
    available: function(result) {
        return '';
    },
    taken: function(result) {
        return 'That name is already taken:<br/>'
            + '<dl>'
            + '<dt>Name</dt><dd>' + result.name + '</dd>'
            + '<dt>Number</dt><dd>' + result.number + '</dd>'
            + ((result.status) ? '<dt>Status</dt><dd>' + result.status + '</dd>' : '')
            + '</dl><br style="clear: both;"/>';
    }
};

var CompanySearch = new Class({
    Binds: ['onChangeClick', 'onFormSubmit', 'onRequestFailure', 'onRequestSuccess'],
    
    initialize: function() {
        this.form = $('companySearch');
        this.fieldset = this.form.getElement('fieldset');
        
        /* 
         * Dynamically create the dropdown since we don't want screenreaders
         * picking this up.
         */
        this.dropdown = new Element('div', {'class': 'dropdown'});
        this.dropdown.grab(new Element('div', {
            'class': 'close',
            'events': {
                'click': function(e) { this.dropdownFx.dissolve(); }.bind(this)
            }
        }));
        this.dropdown.grab(new Element('h2'));
        this.dropdown.grab(new Element('p'));
        this.dropdown.inject(this.fieldset);
        this.dropdown.fade('hide');
        this.dropdownFx = new Fx.Reveal(this.dropdown);
        
        this.selected = false;
        this.request = new Request.JSON({
            url: '/search/company'
        });
        this.request.addEvent('failure', this.onRequestFailure);
        this.request.addEvent('success', this.onRequestSuccess);
        
        this.searchSpan = this.fieldset.getElement('span');
        this.button = this.fieldset.getElement('button');
        this.input = this.fieldset.getElement('input');
        this.select = this.fieldset.getElement('select');

        this.button.addEvent('click', this.onFormSubmit);
        this.input.addEvent('keypress', this.onFormSubmit);
    },
    
    showDropdown: function(title, message) {
        this.dropdown.getElement('h2').set('text', title);
        this.dropdown.getElement('p').set('html', message);
        this.dropdownFx.reveal();
    },
    
    switchForm: function() {
        if (!this.selected) {
            // Remove the search form from the DOM.
            this.searchSpan.dispose();
            this.input.dispose();
            this.select.dispose();
            this.button.dispose();
            
            if (!this.selectedSpan) {
                this.selectedSpan = new Element('span', {
                    text: 'Your chosen company name is '
                });
                this.companyName = new Element('span', {
                    'class': 'companyName'
                }).inject(this.selectedSpan);
                this.change = new Element('a', {text: 'Change...'});
                this.change.addEvent('click', this.onChangeClick);
            }
            this.companyName.set('text', this.input.get('value'));
            this.fieldset.adopt(this.selectedSpan, this.change);
            this.selected = true;
        } else {
            // Remove the other elements from the form.
            this.selectedSpan.dispose();
            this.change.dispose();
            
            // Add in the search form again.
            this.fieldset.adopt(this.searchSpan, this.input, this.select, this.button);
            this.selected = false;
        }
    },
    
    onChangeClick: function(e) {
        this.switchForm();
    },
    
    onFormSubmit: function(e) {
        if (e.key && e.key != 'enter') return;
        e.stop();
        this.request.post({
            'company_name': this.input.get('value'),
            'added': this.select.get('value')
        });
    },
    
    onRequestFailure: function(xhr) {
        this.showDropdown('Error', 'Unfortunately there was an error whilst performing the search.');
    },
    
    onRequestSuccess: function(result) {
        if (result.available) {
            this.switchForm();
        } else {
            this.showDropdown('Search Results', SearchResponses.taken(result));
        }
    }
});
/*
window.addEvent('domready', function(e) {
    var search = new CompanySearch();
});*/
