<?php

/**
 * Třída pro generování HTML formulářů
 * @author milda
 * @copyright Milan Lempera 2009
 */

class Form {

/**
 * Obecné atributy
 * @var array
 */
  private $Arr = array ('id' => '',
                        'class' => '',
                        'title' => '',
                        'style' => '',
                        'dir' => '',
                        'lang' => '',
                        'xml:lang' => '',
                        'onfocus' => '',
                        'onblur' => '',
                        'onchange' => '',
                        'onselect' => '',
                        'onclick'  => '',
                        'ondblclick' => ''
	                    );

/**
 * Argumenty pro form
 * @var array
 */
  private $formArr = array (
                   'method' => 'post',
                   'action' => '',
                   'id' => 'mainForm',
                   'enctype' => 'multipart/form-data',
                   'accept' => '',
                   'onsubmit' => '',
                   'onreset' => '',
                   'accept-charset' => '',
                   'style' => ''
                   );
                   
/**
 * Argumenty pro input
 * @var array
 */
  private $inputArr = array ('text' => array ('type' => '',
  											  'value' => '',
                                              'name' => '',
                                              'alt' => '',
                                              'tabindex' => '',
                                              'accesskey' => '',
                                              'readonly' => '',
                                              'disabled' => '',
                                              'width' => '',
                                              'maxlength' => '',
                                              'size ' => ''),
                             'button' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => ''),
                             'hidden' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'disabled' => '',
                                               'size ' => ''),
                             'password' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'readonly' => '',
                                               'disabled' => '',
                                               'width' => '',
                                               'maxlength' => '',
                                               'size ' => ''),
                             'submit' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => ''),
                             'checkbox' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => '',
                                               'checked' => ''),
                             'radio' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => '',
                                               'checked' => '',
                                               'title' => ''),
                             'reset' => array ('type' => '',
  											   		   		   		   	 'name' => '',
                                               'class' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => '',
                                               'title' => ''),
                             'file' => array ('type' => '',
  											   										 'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => '',
                                               'accept' => '',
                                               'size ' => ''),
                             'image' => array ('type' => '',
  											   											'name' => '',
                                               'value' => '',
                                               'alt' => '',
                                               'tabindex' => '',
                                               'accesskey' => '',
                                               'disabled' => '',
                                               'src' => '',
                                               'usemap' => '',
                                               'ismap' => '')
                             );
                             
/**
 * Argumenty pro HTML
 * @var array
 */
  private $htmlArr = array ('br'	=> array (),
                            'caption' => array(),
                            'table'	=> array ('summary' => '',
                                              'cellapding' => '',
                                              'cellapding' => ''),
                            'tr'	=> array (),
                            'th'	=> array ('rowspan' => '',
                                              'colspan'	=> ''),
                            'td'	=> array ('rowspan' => '',
                                              'colspan' => '')
                            );
           
/**
 * Argumenty pro fieldset
 * @var array
 */
  private $fieldsetArr = array ();

/**
 * Argumenty pro legend
 * @var array
 */
  private $legendArr = array ('innerHTML' => '',
                              'for' => '');
  
/**
 * Argumenty pro label
 * @var array
 */
  private $labelArr = array ('for' => '');
  
/**
 * Argumenty pro textarea
 * @var array
 */
  private $textareaArr = array ('rows' => '',
                                'cols' => '',
                                'disabled' => '',
                                'readonly' => '',
                                'accesskey' => '',
                                'tabindex' => '',
                                'name' => '');
  
/**
 * Argumenty pro select
 * @var array
 */
  private $selectArr = array ('disabled' => '',
                              'multiple' => '',
                              'size' => '',
                              'name' => '');
  
/**
 * Argumenty pro options
 * @var array
 */
  private $optionArr = array ('disabled' => '',
                              'label' => '',
                              'selected' => '',
                              'value' => '');
/**
 * Argumenty pro optgroupArr
 * @var array
 */
  private $optgroupArr = array ('label'	=> '',
                              	'disabled' => '');

/**
 * povolené typy pro validaci
 * @var array
 */
  private $jsValidatetype = array('required' => false,
                                  'remote'   => true,
                                  'minlength' => false,
                                  'maxlength' => false,
                                  'rangelength' => false,
                                  'min'   => false,
                                  'max'   => false,
                                  'range' => false, // [2, 5]                              
                                  'email' => false,
                                  'url'	  => false,
                                  'date'  => false, // 30/30/2009
                                  'dateISO' => false, // 2009-20-20
                                  'dateDE'  => false, // 30.30.2009
                                  'number'	  => false, //123.14
                                  'numberDE'  => false, //123,14
                                  'digits'	  => false, //123
                                  'accept'	  => true,  // "jpg|jpeg"
                                  'equalTo'	  => true,  // "#identifikator"
                                  'creditcard' => false,  // 446-667-651                               
                                  );
                                  
/**
 * povolené typy pro validaci pouze na straně serveru
 * @var array
 */
  private $phpValidatetype = array('telefon' => true,
                                   'url_bezw' => true     
                                  );

/**
 * chybové zprávy pro validaci
 * @var array
 */
  private $validatemessage = array('required' => 'Pole %name nesmí být prázdné', 
                                  'remote'   => 'Pole %name neprošlo validací', 
                                  'minlength' => 'Pole %name musí mít minimálně %val znaků',
                                  'maxlength' => 'Pole %name může mít maximálně %val znaků',
                                  'rangelength' => 'Pole %name musí mít délku v rozsahu %val znaků',
                                  'min'   => 'Pole %name nesmí obsahovat hodnotu menší než %val',
                                  'max'   => 'Pole %name nesmí obsahovat hodnotu větší než %val',
                                  'range' => 'Pole %name musí být v rozsahu %val',                             
                                  'email' => 'Pole %name musí obsahovat validní e-mail',
                                  'url'	  => 'Pole %name musí obsahovat validní URL adresu',
                                  'date'  => 'Pole %name musí obsahovat validní datum např.(10/10/2009)',
                                  'dateISO' => 'Pole %name musí obsahovat validní datum např.(2009-10-10)',
                                  'dateDE'  => 'Pole %name musí obsahovat validní datum např.(1.12.2008)',
                                  'number'	  => 'Pole %name musí obsahovat validní číslo (k oddělení desetin použijte tečku)',
                                  'numberDE'  => 'Pole %name musí obsahovat validní číslo (k oddělení desetin použijte čárku)',
                                  'digits'	  => 'Pole %name musí obsahovat celé číslo',
                                  'accept'	  => 'Pole %name může obsahovat pouze následující soubory %val', // "jpg|jpeg"
                                  'equalTo'	  => 'Pole %name musí být stejné jako %legend',  // "#identifikator"
                                  'creditcard' => 'Pole %name musí obsahovat platné číslo kreditní karty',  // 446-667-651
  								  							'telefon'	   => 'Pole %name musí obsahovat platné telefonní číslo (např.&nbsp;777123123,&nbsp;nebo&nbsp;+420777123)'                               
                                  );

/**
 * Atributy formuláře
 * @var boolean
 */
  private $formAttrib = array();
  
/**
 * stav formuláře
 * @var boolean
 */
  private $formOpen = false;
  
/**
 * HTML kód formuláře
 * @var array
 */
  private $formHTML = array ();

/**
 * argumenty pro aktuální element
 * @var array
 */
  private $formElementArr = array ();
  
/**
 * argumenty pro aktuální atribut
 * @var array
 */  
  private $formAttributeArr = array ();

/**
 * povolení JS validace
 * @var bool
 */  
  private $jsValidate = true;

/**
 * pole s validačními pravidly
 * @var array
 */  
  private $formValidate = array();

/**
 * pole s nastavením validace (pouze pro JS)
 * @var array
 */  
  private $validateSettings = array();

/**
 * pole s názvy polí (legend)
 * @var array
 */  
  private $legend = array();  

/**
 * pole s otevřenými emementy
 * @var array
 */  
  private $openElement = array();
  
/**
 * dočasné parametry
 * @var array
 */  
  private $templateParam = array(); 
  
/**
 * hodnoty formuláře
 * @var array
 */  
  private $form_value = array(); 
  
/**
 * zdroj hodnot
 * @var array
 */  
  private $form_value_from = 'post';
  
/**
 * počítadlo optionů
 * @var array
 */  
  private $option_count = 0;
   
/**
 * reference na entitnu
 * @var array
 */  
  private $entita = NULL; 
  
  public function setEntitaRef($entita) {
    $this->entita  = $entita;
  }
  
  public function setValue(array $array) {
    $this->form_value_from  = 'var';
    $this->form_value  = $array;
  }

/**
 * Vložení úvodní značky elementu form 
 * @param $id
 * @param $action
 * @param $method
 * @param $args
 */
                   
  public function __construct ($id = 'myForm', $action = '', $method = 'post',array $args = array(), $validate = true) {

    if (empty($action)) {
      $action = URL.Application::myController('URL');

      if (substr($action,-1) != DIRSEP) {
        $action .= DIRSEP;
      }
      
      if (!strstr($action,SEND)) {
      	$action .= SEND;
      }
    }

    $possible = array_merge ($this->Arr, $this->formArr);

    $args['id']     = $id;
    $args['action'] = $action;
    $args['method'] = $method;
    $this->form_value_from  = $method;
    $this->formAttrib = $args;

    $this->jsValidate = $validate;
    if ($validate) {
      $this->setJSvalidate();
    }

    $this->formHTML['formOpen'] = '<form';
    foreach ($possible as $key => $val) {
      
      if (!empty($args[$key])) {
        $this->formHTML['formOpen'] .= ' '.$key.'="'.$args[$key].'"';
      }
      elseif (!empty($val)) {
        $this->formHTML['formOpen'] .= ' '.$key.'="'.$val.'"';
      }

    }
    $this->formHTML['formOpen'] .= '>';
    $this->formOpen = true;

  }

/**
 * Nastavení defaultních parametrů pro JS validaci
 * @return unknown_type
 */
  private function setJSvalidate() {

    $this->validateSettings['errorPlacement'] = 'function(error, element) {
	   			error.insertAfter( element.get(0) );
	   		}';
    $this->validateSettings['errorElement'] = '"span"';
  }


/**
 * Ukončení elementu form 
 * Metodu není nutné volat, při volání form->get je metoda volána automaticky
 */
  public function closeForm() {

    if ($this->formOpen == true) {
      $this->formHTML['formClose'] = '</form>';
      $this->formOpen = false;
      
      if ($this->jsValidate) {

        $js_validate = array();
        $mess = array();
        $rule = array();
        foreach($this->formValidate as $id=>$my_rules) {
          $my_rule = array();
          $my_mess = array();

          foreach($my_rules as $key=>$value) {

            if (!isset($this->jsValidatetype[$key])) {
              if (isset($this->phpValidatetype[$key])) {
                $php_validate[] = $key.': '.$value;
                continue;
              }
              else {
                die(__METHOD__.': neznámý typ '.$key);
              }
            }
            
            if ($key == 'equalTo') {
              $my_rule[] = $key.': "#'.$value.'"';
              $m_mess = $key.': "'.$this->validatemessage[$key].'"';
              $m_mess = str_replace('%name', '<b>'.$this->legend[$id].'</b>', $m_mess);
              $m_mess = str_replace('%legend', '<b>'.$this->legend[$value].'</b>', $m_mess);
              $my_mess[] = $m_mess;
              continue;
            }

            if ($this->jsValidatetype[$key] == false) {
              $my_rule[] = $key.': '.$value;
            }
            else {
              $my_rule[] = $key.': "'.$value.'"'; 
            }
            $m_mess = $key.': "'.$this->validatemessage[$key].'"';
            
            if ($key == 'range' OR $key == 'rangelength') {
  	          $value = substr($value, 1);
  	          $value = substr($value, 0, -1);
  	          $va = explode(',', $value);
  	          if ($va[0] == $va[1]) {
  	            $value = $va[0];
  	          }
  	          else {
  	            $value = $va[0].' až '.$va[1];
  	          }
  	        }

            $m_mess = str_replace('%name', '<b>'.@$this->legend[$id].'</b>', $m_mess);
            $m_mess = str_replace('%val',  '<b>'.$value.'</b>', $m_mess);
            $my_mess[] = $m_mess;
          }
          
          $rule[] = $id.': {'.implode(','.NEWLINE,$my_rule).'}';
          $mess[] = $id.': {'.implode(','.NEWLINE,$my_mess).'}';
        }
        $js_validate[] = 'rules: {'.NEWLINE.implode(','.NEWLINE,$rule).NEWLINE.'}';

        $js_validate[] = 'messages: {'.NEWLINE.implode(','.NEWLINE,$mess).NEWLINE.'}';

        foreach($this->validateSettings as $key=>$value) {
          $js_validate[] = $key.': '.$value;
        }

        $ret = implode(','.NEWLINE,$js_validate);

        $registry = Registry::getInstance();
        $registry->jscript->addFile('jquery.validate.min.js');
        $registry->jscript->addJqFunction('"#'.$this->formAttrib['id'].'"', 'validate', $ret, 'validator', false, true, false, 'document_ready');
      }
    }

  }

/**
 * Vložení úvodní značky elemetnu fieldset
 * @param $legend
 * @param $arrArgs
 */
  
  public function openFieldset($legend = '', $class = '',array $args = array ()) {

    $possible = array_merge($this->Arr, $this->fieldsetArr);

    $cpt = count ($this->formElementArr);
    $args['class'] = $class;
    $this -> formElementArr[$cpt]['fieldset'] = $args;

    $elHTML = '<fieldset';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '>';

    $this->formHTML['elements'][$cpt] = $elHTML;
    $this->openElement[] = 'fieldset';

    if (!empty($legend)) {
      $this->addLegend($legend);
    }
  }

/**
 * Ukončovací značka fieldset
 */
  public function closeFieldset() {

    $cpt = count ($this->formElementArr);
    $this -> formElementArr[$cpt]['/fieldset'] = array ();
    $elHTML = '</fieldset>';
    $this -> formHTML['elements'][$cpt] = $elHTML;
    unset($this->openElement[count($this->openElement)-1]);

  }

  private function getArgs($possible, $args) {
    $elHTML = array();
    $elHTML[] = '';
    foreach ($possible as $key => $val) {
      
      if (!empty($args[$key])) {
        $elHTML[] = $key.'="'.$args[$key].'"';
      }
      elseif (!empty($val)) {
        $elHTML[] = $key.'="'.$val.'"';
      }
    }
    return implode(' ',$elHTML);
  }

/**
 * Přidání elementu legend
 * @param $legend
 * @param $for_id
 * @param $args
 */
  public function addLegend($legend, $for_id = '',array $args = array ()) {

    $possible = array_merge($this->Arr, $this->legendArr);

    if (!empty($for_id)) {
      $this->legend[$for_id] = $legend;
    }

    $cpt = count ($this->formElementArr);
    $args['for']    = $for_id;
    
    $this -> formElementArr[$cpt]['legend'] = $args;

    $elHTML = '<legend';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '>'.$legend.'</legend>';
    $this -> formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * Přidání elementu label
 * @param $legend
 * @param $for_id
 * @param $args
 */
  public function addLabel ($label, $for_id = '', array $args = array (), $help = '') {

  	if ($label == MY AND !empty($for_id)) {
  		$label = $this->entita->label[$for_id];
  	}
  	
    $possible = array_merge($this->Arr, $this->legendArr);

    if (!empty($for_id)) {
      $this->legend[$for_id] = $label;
    }
    
    if (!empty($help)) {
      $help = '<acronym class="f_l" title="'.$help.'"><img src="'.URL.'image/ico/24_pomoc.png" widht="20" height="20" alt="???" /></acronym>';
    }
    
    if (isset($args['class']) AND $args['class'] == 'after_input') {

    }
    else {
    	$label .= ':';
    }

    $cpt = count ($this->formElementArr);
    $args['for']    = $for_id;
    
    $this -> formElementArr[$cpt]['legend'] = $args;

    $elHTML = '<label';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '>'.$help.$label.'</label>';
    $this -> formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * Přidání elementu input
 * @param $type
 * @param $id
 * @param $ivalue
 * @param $attrib
 * @param $validate
 * @param $help
 */
  public function addInput($type, $id, $value = '', array $args = array(), $validate = array(), $br = false, $help = '') {

    if ($validate == MY AND !empty($id)) {
  		$validate = $this->entita->validate[$id];
  	}

    $possible = array_merge($this->Arr, $this->inputArr[$type]);

    $cpt = count($this->formElementArr);
//    $args['legend'] = $legend;  $legend je vložena do tagu přímo
    $args['id']    = $id;
    if (empty($args['name'])) {
      $args['name'] = $args['id'];
    }
    $args['type']  = $type;
    
    if ($value == MY) {
      if ($this->form_value_from == 'post') {
        $value = @$_POST[$id];
      }
      elseif ($this->form_value_from == 'var') {
        $value = @$this->form_value[$id];
      }
      elseif ($this->form_value_from == 'get') {
        $value = @$_GET[$id];
      }
    }
    
    if (($args['type'] == 'checkbox') AND !empty($value)) {
      $args['checked'] = 'checked';
    }
    else {
      $args['value'] = @htmlspecialchars($value);
    }
    
    $this->formElementArr[$cpt][$type] = $args;
    
    $elHTML = '<input';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '/>';
    if ($br) {
      $elHTML .= '<br />';
    }
    
    $this->formHTML['elements'][$cpt] = $elHTML;
    
    if (count($validate) > 0) {
      $this->validate($id, $validate);
    }

    if (!empty($help)) {
      $this->getHelp($help);
    }
    
  }

/**
 * vložení nápovědy
 * @param $help
 */
  public function getHelp($help) {
    
    $cpt = count($this->formElementArr);
    $this -> formElementArr[$cpt]['help'] = $help;
    $elHTML = '<acronym title="'.$help.'"><img src="/image/ico/24_pomoc.png" alt="help" /></acronym>';
    $this -> formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * vložení validačních pravidel
 * @param $id
 * @param $validate
 */
  public function validate($id, $validate) {

    $this->formValidate[$id] = $validate;

  }

/**
 * vložení libovolného nepárového tagu
 * @param $tag
 * @param $args
 */
  public function addTag($tag, array $args = array(), $check_tag = true) {

    $cpt = count($this->formElementArr);
    $elHTML = '<'.$tag;

    if ($check_tag) {
      $possible = $this->Arr;
      $elHTML .= $this->getArgs($possible, $args);
      $elHTML .= ' />';
    }
    else {
      $elHTML = '<'.$tag;

      foreach ($args as $key => $val) {
       
        if (!empty($key)) {
          $elHTML .= ' '.$key.'="'.$args[$key].'"';
        }

      }

      $elHTML .= ' />';

    }

    
    $this->formElementArr[$cpt]['html'] = $elHTML;
    $this->formHTML['elements'][$cpt]   = $elHTML;

  }

/**
 * Vložení úvodní značky tagu
 * @param $tag
 * @param $args
 */
  public function openTag($tag, array $args = array()) {

    $cpt = count($this->formElementArr);
    
    $elHTML = '<'.$tag;
    foreach ($args as $key => $val) {
      
      if (!empty($args[$key])) {
        $elHTML .= ' '.$key.'="'.$args[$key].'"';
      }
      elseif (!empty($val)) {
        $elHTML .= ' '.$key.'="'.$val.'"';
      }

    }
    $elHTML .= '>';
    
    $this->formElementArr[$cpt]['html'] = $elHTML;
    $this->formHTML['elements'][$cpt]   = $elHTML;
    $this->openElement[] = $tag;

  }

/**
 * Vložení ukončovací značky tagu
 * @param $tag
 */
  public function closeTag($tag = '') {

  	if (empty($tag)) {
      $tag = $this->openElement[count($this->openElement)-1];
    }

    $cpt = count($this->formElementArr);
    $elHTML = '</'.$tag.'>';
    
    $this->formElementArr[$cpt]['html'] = $elHTML;
    $this->formHTML['elements'][$cpt]   = $elHTML;
    unset($this->openElement[count($this->openElement)-1]);
    $this->openElement = Tools::arrayRecount($this->openElement);

  }
  
/**
 * Vložení libovolného obsahu
 * @param $tag
 */
  public function addInnerHTML($innerHTML) {

    $cpt = count($this->formElementArr);
    
    $this->formElementArr[$cpt]['html'] = $innerHTML;
    $this->formHTML['elements'][$cpt]   = $innerHTML;

  }

/**
 * Vložení elementu textarea
 * @param $innerHTML
 * @param $special_chars
 * @param $args
 */
  public function addTextarea($id, $innerHTML, $special_chars = true, array $args = array (), $validate = array(), $help = '') {

    if ($validate == MY AND !empty($id)) {
  		$validate = $this->entita->validate[$id];
  	}

    $possible = array_merge($this->Arr, $this->textareaArr);
    $args['id']    = $id;
    if (empty($args['name'])) {
      $args['name'] = $args['id'];
    }

    $cpt = count($this->formElementArr);

    if ($innerHTML == MY) {
      if ($this->form_value_from == 'post') {
        $innerHTML = @$_POST[$id];
      }
      elseif ($this->form_value_from == 'var') {
        $innerHTML = @$this->form_value[$id];
      }
      elseif ($this->form_value_from == 'get') {
        $innerHTML = @$_GET[$id];
      }
    }

    if ($special_chars) {
      $innerHTML = htmlspecialchars($innerHTML);
    }
    $this -> formElementArr[$cpt]['textarea']['innerHTML'] = $innerHTML;

    $elHTML = '<textarea ';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '>'.$innerHTML.'</textarea>';
    $this -> formHTML['elements'][$cpt] = $elHTML;

    if (count($validate) > 0) {
      $this->validate($id, $validate);
    }

    if (!empty($help)) {
      $this->getHelp($help);
    }

  }

/**
 * Vložení úvodní značky elementu select
 * @param $arrArgs
 */
  public function openSelect($id, $value = '', array $args = array (), $validate = array (), $help = '') {

    if ($validate == MY AND !empty($id)) {
  		$validate = $this->entita->validate[$id];
  	}

  	$this->option_count = 0;
    $possible = array_merge($this->Arr, $this->selectArr);
    $cpt = count($this->formElementArr);

    $args['id']    = $id;
    if (empty($args['name'])) {
      $args['name'] = $args['id'];
    }

    if ($value == MY) {
      if ($this->form_value_from == 'post') {
        $value = @$_POST[$id];
      }
      elseif ($this->form_value_from == 'var') {
        $value = @$this->form_value[$id];
      }
      elseif ($this->form_value_from == 'get') {
        $value = @$_GET[$id];
      }
    }
    
    if (count($validate) > 0) {
      $this->validate($id, $validate);
    }

    $this->templateParam['value'] = $value;

    $this->formElementArr[$cpt]['select'] = $args;

    $elHTML = '<select ';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '>';
    $this->formHTML['elements'][$cpt] = $elHTML;

      if (!empty($help)) {
      $this->getHelp($help);
    }

  }

/**
 * Ukončení elementu select
 */
   public function closeSelect($br = false) {

   	if ($this->option_count == 0) {
   		$this->addOption('není', 'Neexistují žádné hodnoty','','');
   	}
   	$this->option_count = 0;

    $cpt = count($this->formElementArr);
    $this->formElementArr[$cpt]['/select'] = array ();
    $this->templateParam = array();

    $elHTML = '</select>';
    if ($br) {
      $elHTML .= '<br />';
    }
    
    $this->formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * vložení elementu option
 * @param $value
 * @param $txt
 * @param $arrArgs
 */
  public function addOption($value, $txt, $selected = '', $id = '', array $args = array ()) {

  	$this->option_count++;
    $possible = array_merge($this->Arr, $this->optionArr);
    $cpt = count ($this->formElementArr);
    
    if (!empty($value)) {
      $args['value'] = $value;
      $v = '';
    }
    else {
      $v = ' value="0"';
    }

    if (!empty($id)) {
      $args['id'] = $id;
    }
    
	if ($selected == true) {
      $args['selected'] = 'selected';
    }
    
    if ($value == $this->templateParam['value']) {
        $args['selected'] = 'selected';  
    }

    $this->formElementArr[$cpt]['option']['innerHTML'] = $txt;

    $elHTML = '<option';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= $v.'>'.$txt.'</option>';
    $this->formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * Vložení úvodního tagu optgroup
 * @param $label
 * @param $arrArgs
 */
  public function openOptgroup($label, array $args = array ()) {

    $possible = array_merge($this->Arr, $this->optgroupArr);
    $cpt = count($this->formElementArr);

    $args['label'] = $label;
    $this->formElementArr[$cpt]['optgroup']['innerHTML'] = $args;

    $elHTML = '<optgroup';
    $elHTML .= $this->getArgs($possible, $args);
    $elHTML .= '>';
    $this->formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * Ukončení elementu optgroup
 */
  public function closeOptgroup() {

    $cpt = count ($this -> formElementArr);
    $this->formElementArr[$cpt]['/optgroup'] = array ();

    $elHTML = '</optgroup>';
    $this->formHTML['elements'][$cpt] = $elHTML;

  }

/**
 * Převod objektu na text vrací HTML kód formuláře
 * @return string
 */
  public function __toString() {
    return $this->get();
  }
  
  public function get() {

	$formHTML = ''; //<div id="form">
	
	if (isset ($this -> formHTML['formOpen'])) {
	  if ($this->formOpen == true) {
	    $this->closeForm();
	  }
	  $formHTML .= $this->formHTML['formOpen'];
		if (isset ($this->formHTML['elements']) && !empty ($this -> formHTML['elements'])) {
		  foreach ($this->formHTML['elements'] as $key => $value) {
		    if (isset ($this->formHTML['anything'][$key])) {
			  	$formHTML .= $this->formHTML['anything'][$key];
      	}
      	$formHTML .= $value;
			}
	  }
	  $formHTML .= $this->formHTML['formClose'];
	}
	$formHTML .= ''; //</div>

	return $formHTML;
  }
  
  public function stateSelect(& $entita, $new = false, $default = 1) {

    if ($new AND (count($entita->stavy) == 0)) {
      $entita->newStates();

      if (!empty($default)) {
        if ($default == MY) {
          if ($this->form_value_from == 'post') {
            $default = @$_POST['stav'];
          }
          elseif ($this->form_value_from == 'var') {
            $default = @$this->form_value['stav'];
          }
        }

        $entita->stav = $default;

      }
    }

    if (count($entita->stavy) > 0) {
    	$stav = $default;
      if (!empty($default)) {
        if ($default == MY) {
          if ($this->form_value_from == 'post') {
            $stav = @$_POST['stav'];
          }
          elseif ($this->form_value_from == 'var') {
            $stav = @$this->form_value['stav'];
          }
        }
        else {
        	$stav = @$entita->stav;
        }
      }
      $this->openSelect('stav', $stav, array('title' => @$entita->stavy[$entita->stav]['popis']));
      foreach($entita->stavy as $key=>$value) {
        $this->addOption($key, $value['nazev'], '', '', array('title' => $value['popis']));
      }
      $this->closeSelect();
      return true;
    }
    else {
      $this->addInnerHTML($entita->my_stav);
      return false;
    }
  }

}
?>