<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/


class HTML_QuickForm2_Renderer_LabSmarty extends HTML_QuickForm2_Renderer_Default
{

    protected function exportMethods()
    {
        return array(
            'reset',
            'setTemplateForClass',
            'setTemplateForId',
            'setErrorTemplate',
            'setGroupedTemplateForClass',
			'toArray'
        );
    }
	
	/**
	* Renders a generic element
	*
	* @param    HTML_QuickForm2_Node    Element being rendered
	*/
    public function renderElement(HTML_QuickForm2_Node $element)
    {
        $elTpl = $this->prepareTemplate($this->findTemplate($element), $element);
		$html=str_replace(array('{element}', '{id}'),
                    array($element, $element->getId()), $elTpl);
		
        $this->html[count($this->html) - 1][] = $html;

		$name=$element->getName();
   
		$names=explode('[', str_replace(']', '', $name));
		
		$container=&$this->objects['items'];
		
		foreach($names as $key)
		{
			//имена полей вида name[] разрешены,
			//но валидация полей при этом работать не будет
			if ($key=='')
			{
				if (empty($container)) {
					$key = 0;
				}
				else
				{
					$keys  = array_keys($container);
					$key = end($keys);
					while (isset($container[$key]))
					{
						$key++;
					}
				}
			}
			$container=&$container[$key];
		}
		
		$container=$element->getAttributes();
		$container['id']     = $element->getId();
		$container['isRequired'] = $element->isRequired();
		$container['error'] = $element->getError();
		$container['label'] = $element->getLabel();
		$container['frozen']= $element->toggleFrozen();
		$container['html'] = $html;
	}
	
	/**
	* Renders a hidden element
	*
	* @param    HTML_QuickForm2_Node    Hidden element being rendered
	*/
    public function renderHidden(HTML_QuickForm2_Node $element)
    {
		$this->hiddenHtml .= $element->__toString();
    }
	
	public function finishForm(HTML_QuickForm2_Node $form)
	{
		$this->objects['id'] = $form->getId();
		$this->objects['frozen'] = $form->toggleFrozen();
		$this->objects['attributes'] = $form->getAttributes(true);
		$this->objects['items']['hiddenHtml'] = $this->hiddenHtml;
		parent::finishForm($form);
	}
	
	public function toArray()
	{
		$this->objects['html'] = $this->__toString();
		return $this->objects;
	}
}