var SharePostModal = 
{
    form_view_helper: null,
    el: 
    {
        form: null
    },
    
    init: function()
    {
        this.observe();
    },

    observe: function(parent_el)
    {
        var elements;
        var selector = 'a.modal_share';
        if (typeof(parent_el) == 'undefined')
            elements = $$(selector);
        else
            elements = parent_el.select(selector);
            
        elements.invoke('observe', 'click', this.show.bind(this));
    },
    
    show: function(e)
    {
        var a = Event.element(e);      
        
        // not the best way to do this. Should probably be done with a var called role_class
        if (a.href.match(/#nogo$/))
        {
            alert('You must be logged in to share this post.');
        }
        else
        {
            $$('div.flash_chart object').invoke('hide');
            Modalbox.show(a.href, { title: a.title, width: 600, 'afterLoad':this.afterLoad.bind(this), 'afterHide':this.afterHide });
        }
        Event.stop(e);
    },
    
    afterLoad: function()
    {
        this.form = $('modal_form');
        this.form_view_helper = new FormViewHelper(this.form);
        this.form.observe('submit', this.submitForm.bind(this));
    },

    afterHide: function()
    {
        $$('div.flash_chart object').invoke('show');
    },
            
    submitForm: function(e)
    {
        new Ajax.Request(this.form.action, 
        {
            method: 'post',
            postBody: Form.serialize(this.form),
            onSuccess: function(t) 
            {
                this.form_view_helper.clearInputErrors();
    
                var response = t.responseJSON;
                if ('success' === response.status)
                {
                    Effect.Fade(this.form, { duration: 0.3 });
                    setTimeout(function() 
                    { 
                        this.form_view_helper.showSuccessMessage(response.status_message); 
                        Modalbox.resizeToContent(); 
                        setTimeout(function()
                        {
                            Modalbox.hide();
                        }.bind(this), 1000);
                    }.bind(this), 500);
                }
                else
                {
                    this.form_view_helper.showInputErrors(response.input_errors);
                    this.form_view_helper.showMessage(response.status_message, response.status);
                    Modalbox.resizeToContent();
                }
            }.bind(this)
        });
        Event.stop(e);
    }
};