﻿

function RadioButtonGroup(iId, iCount)
{
    var This = this;

    // Data members
    This.Buttons = [];
    This.ActiveButtonIndex = null;
    This.Name = null;
    This.Value = null;

    // Events
    This.OnActivated = new EventHandler();

    // Methods
    This.GetName = function()
    { return This.Name; }    

    This.GetValue = function()
    { return This.Value; }

    This.SetValue = function(iValue)
    {
        if (iValue != null)
        {
            for (var i = 0; i < This.Buttons.length; i++)
            {
                if (This.Buttons[i].Value == iValue)
                    return This.Activate(i);
            }
        }
        else
            This.Reset();
    }

    This.Reset = function()
    {
        for (var i = 0; i < This.Buttons.length; i++)
            This.Buttons[i].Deactivate();
        This.ActiveButtonIndex = null;
        This.Value = null;
    }

    This.Add = function(iRadioButton)
    {
        iRadioButton.Group = This;
        iRadioButton.Index = This.Buttons.length;
        if (iRadioButton.Value == null)
            iRadioButton.Value = iRadioButton.Index;
        This.Buttons.push(iRadioButton);

        if (!This.Name)
            This.Name = iRadioButton.GetElement().name;
    }

    This.Activate = function(iIndex)
    {
        if (iIndex != This.ActiveButtonIndex)
        {
            if (This.ActiveButtonIndex != null)
                This.Buttons[This.ActiveButtonIndex].Deactivate();

            This.ActiveButtonIndex = iIndex;
            if (This.ActiveButtonIndex != null)
            {
                This.Value = This.Buttons[This.ActiveButtonIndex].Value;
                This.Buttons[This.ActiveButtonIndex].Activate();
                This.OnActivated.Invoke(This.Value);
            }
            else
                This.Value = null;
        }
    }    

    // Initialize
    {
        if (iCount)
        {
            for (var i = 0; i < iCount; i++)
                This.Add(new RadioButton(iId + '-' + i));
        } 
    } 
}

function RadioButton(iId)
{
    var This = this;

    // Implements
    Implements(This, Button, iId);

    // Data members
    This.Group = null;
    This.Index = null;
    This.Value = null;

    // Events
    This.OnActivate = new EventHandler();
    This.OnDeactivate = new EventHandler();    

    // Methods
    This.Activate = function()
    {
        This.SetStyle('active');
        This.GetElement().checked = true;
        This.OnActivate.Invoke();
    }

    This.Deactivate = function()
    {
        This.SetStyle(null);
        This.GetElement().checked = false;
        This.OnDeactivate.Invoke();
    }

    // Initialize
    {
        This.OnClick.Add(function() { This.Group.Activate(This.Index); });
        This.Value = This.GetElement().value;
    }
}
