<?php
/**
 * @author krku
 */

function smarty_function_formField($params, &$smarty) {

	$errorList = $smarty->get_template_vars('errorList');
	if (isset($params['value'])) {
		$value = $params['value'];
	} else if (isset($params['obj']) && $smarty->get_template_vars($params['obj']) && is_object($smarty->get_template_vars($params['obj'])) && isset($params['func'])) {
		$func = $params['func'];
		$value = $smarty->getTemplateVars($params['obj'])->$func();
	} else {
		$value = Request::GetPost($params['name']);
	}

	if (isset($params['obj'])) {
		unset($params['obj']);
	}

	if (isset($params['func'])) {
		unset($params['func']);
	}

	if (!$value) {
		$value = '';
	}

	if (!isset($params['type'])) {
		trigger_error('Parametr `type` jest wymagany.');
	}

	if (!isset($params['name'])) {
		trigger_error('Parametr `name` jest wymagany.');
	}

	$tagParameters = '';
	foreach ($params as $tag => $val) {
		if ($val != 'textarea') {
		$tagParameters .= $tag . '="' . $val . '" ';
		}
	}

	if ($params['type'] == 'textarea') {
		$ret = '<textarea ' . $tagParameters . '>' . $value . '</textarea>';
	} else if ($params['type'] == 'radio' || $params['type'] == 'checkbox') {
		$ret = '<input ' . $tagParameters . '" ' . ($value ? 'checked="checked"' : '') . ' />';
	} else {
		$ret = '<input ' . $tagParameters . ' value="' . $value . '" />';
	}

	//$ret .= '<br />';

	$ret .= '<div ' . (isset($params['errorClass']) ? 'class="' . $params['errorClass'] . '" ' : '') . 'id="' . $params['name'] . 'Error"> ';

        if(is_countable($errorList)) {
            if (sizeof($errorList)) {
                    foreach ($errorList as $k => $v) {
                            if ($v['field'] == $params['name']) {
                                    $ret .= $v['msg'].' ';
                            }
                    }
            }
        
        }
	
	$ret .= ' </div>';

	return $ret;
}
?>
