/**
 * Radio
 * 
 * Manages a group of radio buttons
 * Radio group: all radio input fields in same form with same name.
 * 
 * @require     MooTools
 * 
 * @author      Steffen Maechtel <s.maechtel@netzbewegung.com>
 * @version     1.00 alpha
 */

var Nb_Form_Radio = new Class({
    initialize: function(formElement, name, options) {
        options = options || {};
        
        this.original = {};
        this.original.radios = formElement.getElements('input[name=' + name + ']');
        
        this.checked = this.getChecked();
        
        // hide orginal radios
        this.hideOriginal();
        
        // create custom radios
        this.custom = this.getCustom();
        
        // add events
        this.addEvents();
    },
    getCustom: function()
    {
        /*
         *  Example:
         *  <div class="usercontrol-radio"></div>
         */
        
        var custom = {};
        custom.radios = [];
        
        this.original.radios.each(function(element, key)
        {
            var elementRadio = new Element('div', {'class': element.get('class')});
            
            if (key == this.checked)
            {
                elementRadio.addClass('radio-checked');
            }
            
            custom.radios.push(elementRadio);
            
            element.grab(elementRadio, 'after');
        }.bind(this));
        
        return custom;
    },
    addEvents: function()
    {
        this.custom.radios.each(function(element, key)
        {
            element.addEvent('click', this.onClick.create({bind: this, event: true, arguments: key}));
        }.bind(this));
    },
    onClick: function(event, key)
    {
        event.stop();
        
        if (key == this.checked)
        {
            return;
        }
        
        if (this.checked != null)
        {
            this.custom.radios[this.checked].removeClass('radio-checked');
            this.original.radios[this.checked].checked = false;
        }
        
        this.checked = key;
        
        this.custom.radios[this.checked].addClass('radio-checked');
        this.original.radios[this.checked].checked = true;
        
        
    },
    getChecked: function()
    {
        var checked = null;
        
        this.original.radios.each(function(element, key)
        {
            if (element.get('checked'))
            {
                checked = key;
            }
        });
        
        return checked;
    },
    hideOriginal: function()
    {
        this.original.radios.each(function(element)
        {
            element.setStyle('display', 'none');
            
        });
    }

});
