<?php

class Tag_Radio extends Tag
{
	protected $inline = false; // Whether or not to display radio buttons side by side or rendered in blocks.

	public function __construct($name=NULL, $options=NULL, $attributes=NULL)
	{
		if( is_array($attributes) && array_key_exists('inline',$attributes) && ((bool)$attributes['inline']) )
		{
			$this->inline = true;
			unset($attributes['inline']);
		}
		parent::__construct('div', $attributes);
		$this->addClass('radioset');
		$this->addClass('input');
		$this->attr('name',$name);
		$this->setOptions($options);
		if( isset($attributes['value']) )
			$this->attr('value',$attributes['value']);
	}

	public function setOptions($options, $option_attributes=NULL, $label_attributes=NULL)
	{
		// Validate Attributes Parameter
		$option_attributes = is_array($option_attributes) ? $option_attributes : array() ;
		$label_attributes = is_array($label_attributes) ? $label_attributes : array() ;

		// Add all Options as Children
		if( is_array($options) && count($options) > 0 )
		{
			$name = $this->attr('name');
			$i = 1;
			foreach($options as $key => $label)
			{
				$id = $name.'-option-'.$i;

				$input_tag = new Tag_Input($name, $option_attributes);
				$input_tag->attr('type','radio');
				$input_tag->attr('id',$id);
				$input_tag->attr('value',$key);

				$label_tag = new Tag_Label('','',$label_attributes);
				$label_tag->text($label);
				$label_tag->attr('for',$id);
				$label_tag->addClass('radio');

				$div_tag = new Tag('div');
				$div_tag->addChild($input_tag, $label_tag);

				if( $this->inline )
					$div_tag->attr('style', 'display: inline');

				$this->addChild($div_tag);
				$i++;
			}
		}
	}

	public function attr($name, $value=NULL)
	{
		if( $name == 'value' )
		{
			// First layer of children are "DIV" tags - look at the setOptions function, you'll see
			foreach($this->children as $child_div)
			{
				// Second Layer is where you find the <option> tags
				foreach($child_div->children as $tag)
				{
					if( is_null($value) )
					{
						// Retrieve the Value for a "get" call
						if( $tag instanceof Tag_Input && $tag->attr('checked') == 'checked' )
						{
							return $tag->attr('value');
							break;
						}
					}
					else
					{
						// Set the New Value for a "set" call
						$tag->attr('checked','');
						if( $tag->attr('value') == $value )
						{
							$tag->attr('checked','checked');
							break;
						}
					}
				}
			}
		}
		else
		{
			return parent::attr($name, $value);
		}
	}

	public function value($value=NULL)
	{
		if( is_null($value) )
			return $this->attr('value');
		else
			$this->attr('value',$value);
	}
}
