lg_poll = new Class
({
    initialize: function (el)
    {
        this.poll = $(el);
        this.getElements();
    },

    getElements: function ()
    {
        this.form = this.poll.getElement('form');
        this.results = this.poll.getElement('.results a');

        if (this.form)
        {
            this.addEvents();
        }
    },

    addEvents: function ()
    {
        this.form.addEvent('submit', this.submitHandler.bindWithEvent(this));
        this.results.addEvent('click', this.resultsClickHandler.bindWithEvent(this));
    },

    submitHandler: function (event)
    {
        event.stop();

        var inputs = this.form.getElements('input[type=radio]');
        var checked = false;
        inputs.each
        (
            function (input)
            {
                if (input.get('checked'))
                {
                    checked = true;
                }
            }
        );

        if (checked)
        {
            this.sendForm();
        }
        else
        {
            alert('Please select an answer before submitting the form');
        }
    },

    resultsClickHandler: function (event)
    {
        event.stop();

        var request = new Request.HTML
        (
            {
                update: this.poll,
                url: this.results.get('href'),
                onRequest: this.sendHandler,
                onComplete: this.successHandler.bind(this)
            }
        );

        request.send();
    },

    sendForm: function ()
    {
        var form_request = new Form.Request
        (
            this.form,
            this.poll,
            {
                onSend: this.sendHandler,
                onSuccess: this.successHandler.bind(this)
            }
        );

        form_request.send();
    },

    sendHandler: function ()
    {
        $('loading').setStyle('display', 'block');
        $('loading').fade('hide');
        $('loading').fade('show');
    },

    successHandler: function ()
    {
        this.getElements();
    }
})

window.addEvent('domready', function() {
    new lg_poll('poll');
});

