<?
function FORM($options=array()){ if (!is_object($GLOBALS['FORM'])) $GLOBALS['FORM']=new i_form($options);return($GLOBALS['FORM']);}
class i_form extends i_megamenu_form {}
class i_megamenu_form
{   var $mode='V' ;
    var $def_col_count=2 ;
    var $def_col_count_title=2 ;
    var $col_count=2 ;
    var $col_count_title=2 ;
    var $update_mode='POST' ;
    var $row_separator='' ;
    var $page=null ;
    var $report=null ;
    var $post_array_name='' ;
    var $filter=array() ;
    var $label_position='' ; //  left top right* bottom*
    var $block_position='' ; //  inline row
    var $form_id='' ;
    var $autofocus_isset=0 ;

	// mode=V - элемент находится под title
	//     =H - элемент находится справа от title
	function __construct($options=array())
	{  	$this->page=(isset($options['page']))? $options['page']:_CUR_PAGE() ;
	    $this->col_count=($options['col_count'])? $options['col_count']:$this->def_col_count ;
		$this->col_count_title=($options['col_count_title'])? $options['col_count_title']:$this->def_col_count_title ;

	    $this->init($options) ;
	}

	// все сохранения параметров только через isset, так как init вызывается при form_open()
function init($options=array())
	{
       if (isset($options['form_id'])) $this->form_id=$options['form_id'] ;
       if (isset($options['filter'])) $this->filter=$options['filter'] ;
	   if (isset($options['page'])) $this->page=$options['page'] ;
	   if (isset($options['report'])) $this->report=$options['report'] ;
	   if (isset($options['mode'])) $this->mode=$options['mode'] ;
	   if (isset($options['col_count'])) $this->col_count=$options['col_count'] ;
	   if (isset($options['col_count_title'])) $this->col_count_title=$options['col_count_title'] ;
	   if (isset($options['row_separator'])) $this->row_separator=$options['row_separator'] ;
	   if (isset($options['update_mode'])) $this->update_mode=$options['update_mode'] ;
	   if (isset($options['label_position'])) $this->label_position=$options['label_position'] ;
	   if (isset($options['block_position'])) $this->block_position=$options['block_position'] ;
	   if ($options['is_report']==1)               $this->post_array_name='filter' ;
	   if (isset($options['post_array_name'])) $this->post_array_name=$options['post_array_name'] ;
	}



     // cmd
     // id
     // class
     // title
     // items
     var $selected_item_by_url ; // URL, элемент с которым необхомо включить

     function panel_mega_menu_item($url,$item)
     {  if (!is_array($item))  $item=array('title'=>$item) ;
        if (is_int($url)) $url='' ;
        $arr_url=parse_url($url) ;
        $class='' ;
        if ($arr_url['path']==_CUR_PAGE_DIR._CUR_PAGE_NAME) $class='class=current' ;
        if ($arr_url['path']==$this->selected_item_by_url) $class='class=current' ;

        $item_url=$url.$this->menu_url_params ;
        ?><li aria-haspopup="<?echo (_sizeof($item['items']))? 'true':'false'?>" <?echo $class?>>
            <a href="<?echo $item_url?>"  <? if ($item['no_link']) echo 'nolink' ?>
                    <? if (_sizeof($item)) foreach($item as $name=>$value) if ($name!='class' and $name!='title' and $name!='info_id')
                    { if ($name=='cmd') echo 'class=v2 cmd="'.$value.'"' ;
                      elseif ($name=='new_window') echo ' class="new_window" title="'.$value.'" ' ;
                      else              echo $name.'="'.$value.'"' ;
                    }
                    //if ($item['id']) echo 'id="'.$item['id'].'"' ;
                    //if ($item['cmd']) echo 'class=v2 cmd="'.$item['cmd'].'"' ;
                    ?>><i class="<?echo $item['class']?>"></i><?echo $item['title']?></a>
            <?if ($item['info_id'] or $item['info_value']){?><span class="info" id="<?echo $item['info_id']?>"><?echo $item['info_value']?></span><?}?>
            <?if (_sizeof($item['items'])){?><div class="grid-container4"><ul><?foreach($item['items'] as $url2=>$item2) $this->panel_mega_menu_item($url2,$item2);?></ul></div><?}?>
         </li>
       <?

     }

     function panel_main_menu()
     {
         if (MEMBER()->info['rol']!=1) $this->member_menu_check($this->menu) ; // удаляем из меню пункты, к которым нет доступа

         /*?><ul  id="panel_main_menu" class="sky-mega-menu sky-mega-menu-pos-left sky-mega-menu-response-to-icons sky-mega-menu-anim-scale"><?*/
         ?><ul id="panel_main_menu" class="sky-mega-menu sky-mega-menu-pos-left  sky-mega-menu-fixed  sky-mega-menu-anim-scale"><?
         if ($this->page->menu_show_logo_item){?><li class="logo"><img src="<?echo _LOGO_CAB?>" width="150" class="v2" cmd="aspmo/reboot"></li><?}
         // информация по текущему аккааунту
         $this->panel_main_menu_title() ;

         // текущее меню страницы
         if (_sizeof($this->menu)) foreach($this->menu as $url=>$item)  $this->panel_mega_menu_item($url,$item) ;

         // кнопка "закрыть страницу"
         if ($this->page->menu_show_close_item){?><li><a href="" class="close_window"><i class="fa fa-home"></i>Закрыть</a></li><?}
         ?></ul><?
     }

     function panel_main_menu_title()
     {   global $member ;
            if ($this->page->menu_show_account_item){?>
                <li aria-haspopup="true">
                                <a><?echo '<strong>'.$member->name.'</strong>' ;
                                    if (MEMBER()->from_AD) echo ' <span><i class="fa fa-windows" aria-hidden="true"></i></span>' ;
                                    echo '<br>'.$member->working?>
                                   <?if (MEMBER()->cur_group_name) echo '<br>Группа: <strong>'.MEMBER()->cur_group_name.'</strong>'?>
                                   <?if (MEMBER()->superreader) echo '<div class="red">Режим СУПЕРЧИТАТЕЛЯ</div>'?>
                                   <?if (MEMBER()->use_auch_as_smena) switch($member->_smena_status)
                                    {  case 'close':     echo '<br><br><div class="red">Смена не открыта</div>' ; break ;
                                       case 'unactive':  echo '<br><br><div class="red">Смена не открыта</div>' ; break ;
                                       case 'active':    echo '<br><br>Начало смены: <strong>'.date('d.m.Y H:i',$member->info['smena_in']).'</strong>' ; break ;
                                       case 'pause':     echo '<br><br><div class="red">Смена приостановлена</div>' ; break ;
                                       case 'out':       echo '<br><br><div class="red">Смена окончена</div>' ; break ;
                                       case 'block':  echo '<br><br><div class="red">Смена заблокирована</div>' ; break ;
                                    }
                                    ?></a>
                                <div class="grid-container3">
                                    <ul><?if (MEMBER()->rol==6){?><li><a href="/cab/client/setting/"><i class="fa fa-sliders"></i>Настройки аккаунта</a></li><?}
                                             else                  {?><li><a href="/cab/setting/member/<?echo MEMBER()->id?>/"><i class="fa fa-sliders"></i>Настройки аккаунта</a></li><?}
                                            ?>
                                        <? // для тех пользователей, которые работают по сменам
                                           if (MEMBER()->use_auch_as_smena)
                                            {   // номельная ситуация оконачания смены
                                                if ($member->_smena_status=='active') {?><li><a href="/cab/smenaout/"><i class="fa fa-sign-out"></i>Завершить смену</a></li><?}
                                                // приостановленая смена
                                                elseif ($member->_smena_status=='pause') {?><li><a href="" class="v2" cmd="aspmo/smena_resume"><i class="fa fa-sign-out"></i>Продолжить смену</a></li>
                                                                                                                      <li><a href="/cab/smenaout/"><i class="fa fa-sign-out"></i>Завершить смену</a></li><?}
                                                // принудительное начало смены, когда идет смена другого сотрудника
                                                elseif ($member->_smena_status=='unactive') {?><li><a href="" class="v2" cmd="aspmo/smena_in"><i class="fa fa-sign-out"></i>Начать смену</a></li><?}
                                            }
                                        ?>
                                        <li><a href="/" class="v2" cmd="account/account_logout"><i class="fa fa-sign-out"></i>Выход</a></li>
     <? // переход из админа в аккаунт другого пользователя
                                        if (MEMBER()->rol==1)
                                        {  $arr_rols=execSQL_line('select distinct(rol) from obj_site_account where rol!=1 and clss=210 and enabled=1 order by rol') ;
                                           ?><li><a href=""><i></i>Перейти в аккаунт</a><div class="grid-container3"><ul><?
                                                 if (_sizeof($arr_rols)) foreach($arr_rols as $rol_id) if (isset($_SESSION['ARR_roll'][$rol_id]))
                                                 { ?><li><a href="" class="v2" cmd="account/get_panel_login_as" rol_id="<?echo $rol_id?>"><i class=""></i><?echo $_SESSION['ARR_roll'][$rol_id]['obj_name']?></a></li><?}
                                         ?></ul></div></li><?
                                           ?><li><a href="" class="v2" cmd="account/get_panel_group_as"><i></i>Перейти в группу</a><div class="grid-container3"></div></li><?
                                        }
                                        elseif ($_SESSION['admin_login_id']) {?><li><a href="/" class="v2" cmd="account/account_login_as" member_id="<?echo $_SESSION['admin_login_id']?>"><i class="fa fa-sign-out"></i>Вернутся в аккаунт администратора</a></li><?}
                                        ?>

                                    </ul>
                                </div>
                </li><?}

     }

    function header_open() {?><header><?}
    function header_close() {?></header><?}
    function footer_open() {?><footer><?}
    function footer_close() {?></footer><?}

	function form_open($options=array())
	{   $this->init($options) ;
	    $_attr=array() ;
		$_attr[]='method=POST' ;
		$_attr[]='update_mode='.$this->update_mode ;
		if ($options['class']) { $_attr[]='class="'.$options['class'].'"' ; $this->form_class=$options['class'] ; }
		if ($options['id']) $_attr[]='id="'.$options['id'].'"' ;
		if ($options['multipart']) $_attr[]='enctype="multipart/form-data"' ;
		if ($options['enctype']) $_attr[]='enctype="'.$options['enctype'].'"' ;
		if ($options['style']) $_attr[]='style="'.$options['style'].'"' ;
		if ($options['post_array_name']) $this->post_array_name=$options['post_array_name'] ;
		//if ($this->row_separator=='dashed') $_attr[]='m-form--group-seperator-dashed' ;
		?>
        <form <?echo implode(' ',$_attr)?>>
            <?if (defined('_CUR_REPORT_DIR')) {?>
                <input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
            <?}?>
        <?
	}
	function form_close(){ ?><script type="text/javascript">$j(this).find('[autofocus=1]').focus();</script> </form><?}
	function row_open($options=array()){ ?><div class="row <?echo $options['class']?>"><?}
    function row_close(){ ?></div><?}
	function section_open($options=array())
    { $col_count=(isset($options['col_count']))? $options['col_count']:$this->col_count ;
      ?><section  class="<?if ($col_count) echo 'col col-'.$col_count?>"><?
    }
	function section_close(){ ?></section><?}
	function fieldset_open(){ ?><fieldset><?}
	function fieldset_close(){ ?></fieldset><?}
	function col_open($n=0){ ?><section  class="<?if ($n) echo 'col col-'.$n?>"><?}
    function col_close(){ ?></section><?}
	function row_buttons(){ ?><div class=" align-items-center" id="panel_buttons"><?}
	function row_buttons_open(){ ?><div class=" align-items-center" id="panel_buttons"><?}
	function row_buttons_close(){ ?></div><?}



	function row_close_open(){ echo '</div><div class="row">' ; }

	function prepare_element_attr($type,&$options=array())
	{ $element_type=($options['type'])? $options['type']:$type ;
	  $element_name=($options['name'])? $options['name']:'element' ;
	  $post_subarray=($options['multiple'])? '[]':'' ;
	  $element_value='' ; $element_id='' ;
      $default='' ;
      if (isset($options['default_value'])) $default=$options['default_value'] ;
      if (isset($options['cur_value']) and $type!='radio' and $type!='checkbox') $options['value']=$options['cur_value'] ; // для radio cur_value - значение текущего фильтра
      if ($options['element_class']) $options['class']=$options['element_class'] ;
      if ($options['select_id_param'])  $element_id=$options['select_id_param'] ;
      if ($options['id'])               $element_id=$options['id'] ;
      if ($options['attr']['id'])       $element_id=$options['id'] ;
      if (!$element_id)                 $element_id=$element_type.'_'.safe_text_to_url($options['name']) ;
      $options['id']=$element_id ;


      //damp_array($options);
      $_class=array() ; $attr=array() ;


	  if ($type!='select' and $type!='textarea')
	  {   $attr['type']='type='.$element_type ;
          $filter_value=$this->filter[$element_name] ;
          // необходимо, если в отчете было вручную поставлено значение фильтра
          if (is_object($this->report) and isset($this->report->filter[$element_name])) $filter_value=$this->report->filter[$element_name];
          $element_value=(isset($options['value']))? htmlspecialchars($options['value']):(($filter_value)? htmlspecialchars($filter_value):$default) ;
          $attr['value']='value="'.$element_value.'"' ;
	  }

        // если указан FORM()->form_open([...,'filter'=>$this->filter,...]) то в компонент radio/checkbox не надо указывать cur_value
      if ($type=='radio' and ($options['value']==($filter_value? $filter_value:$options['cur_value']))) $attr['checked']='checked' ;
      if ($type=='checkbox' and ($options['value']==($filter_value? $filter_value:$options['cur_value']))) $attr['checked']='checked' ;

//	  if ($type=='radio' and $options['value']==$options['cur_value']) $attr['checked']='checked' ;
//	  if ($type=='checkbox' and $options['value']==$options['cur_value']) $attr['checked']='checked' ;

      if ($element_id)                  $attr['id']='id="'.$element_id.'"' ;


	  if ($options['class'])            { if (!is_array($options['class'])) $_class[]=$options['class'] ;
	                                      else foreach($options['class'] as $value) $_class[]=$value ;
	                                    }


	  // filter[] добавляется ранее при конфигурировании набора опций
	  if (strpos($element_name,'[')!==false)  $attr['name']='name="'.$element_name.$post_subarray.'"' ; // поддержка старой версии, когда подмассив POST задавался в имени элемента
	  elseif ($this->post_array_name)         $attr['name']='name="'.$this->post_array_name.'['.$element_name.']'.$post_subarray.'"' ;
	  elseif ($options['post_array_name'])    $attr['name']='name="'.$options['post_array_name'].'['.$element_name.']'.$post_subarray.'"' ;
	  else                                    $attr['name']='name="'.$element_name.$post_subarray.'"' ;

	  if ($options['auto_complete'])          $attr[]='SetAutoComplete cmd="'.$options['auto_complete'].'"' ;// autocomplete ЛК
	  if ($options['autocomplete'])           $attr[]='autocomplete="'.$options['autocomplete'].'"' ;        // autocomplete дефолтный по браузеру
	  if ($options['required'])               { $attr[]='data-required required' ; $_class[]='input_required' ; }
	  if ($options['disabled'])               $attr[]='disabled="1"' ;
	  if ($options['placeholder'])      $attr[]='placeholder="'.$options['placeholder'].'"' ;
	  if ($options['LANG'])             $attr[]='LANG='.$options['LANG'] ;
      if ($options['lang'])               $attr[]='lang="'.$options['lang'].'"' ;
	  if ($options['rows'])             $attr[]='rows='.$options['rows'] ;
	  if ($options['data-mask'])        $attr[]='data-mask="'.$options['data-mask'].'"' ;
	  if ($options['required'])         $attr[]='required' ;
	  if ($options['multiple'])         $attr[]='multiple=""' ;
      if ($options['read_only'])               $attr[]='readonly' ;
	  if ($options['case'])             $attr[]='case="'.$options['case'].'"' ;
	  if ($options['autofocus'])               $attr[]='autofocus=1' ;
	  if ($options['style'])            $attr[]='style="'.$options['style'].'"' ;
	  if ($options['onchange'])            $attr[]='onchange="'.$options['onchange'].'"' ;
	  if ($options['pattern'])            $attr[]='pattern="'.$options['pattern'].'"' ; // HTML5 Pattern Validation

	  if ($type!='hidden')
	  { $attr[]='autofocus_isset='.$this->autofocus_isset ;
	    if (!$this->autofocus_isset)        { $attr[]='autofocus=1' ;  $this->autofocus_isset=1 ;}
	  }

      if (_sizeof($_class))                    $attr['class']='class="'.implode(' ',$_class).'"' ;

	  if (isset($options['attr'])) { if (!is_array($options['attr'])) $attr[]=$options['attr'] ;
	  	                             else foreach($options['attr'] as $id=>$value) $attr[$id]=$id.'="'.$value.'"' ;
	  	                           }

	  //damp_array($options);
	  //damp_array($attr);
	  return($attr) ;
	}

	// внимание! $options - набор атрибутов кнопки, которые передаются в массие id=value
	// на выходе должен получиться массив [id="value"]
	// одним из элементов $options может быть class, тогда его надо убрать из attr и обработать отдельно
	function prepare_button_attr($type,$options=array())
	{ $_class=array() ; $attr=array() ;
	  $arr_attr=$options ; unset($arr_attr['class']) ;

      $_class[]='button' ;
      //if (!$options['to_right']) $_class[]='easy' ; \\ float: none; display: inline;margin: 0 10px - мешает
      if ($options['cmd']!='cancel') $_class[]=($options['cmd_method'])?  $options['cmd_method']:'v2' ;
      else { $_class[]='cancel' ; unset($options['cmd']) ; }

      if ($options['class'])            { if (!is_array($options['class'])) $_class[]=$options['class'] ;
	                                      else foreach($options['class'] as $value) $_class[]=$value ;
	                                    }
      $attr[]='class="'.implode(' ',$_class).'"'  ;
      $attr['type']='type="'.$type.'"' ;


      if ($options['cmd']) $attr[]='cmd="'.$options['cmd'].'"' ;
      if ($options['button_apply_id']) $attr['id']='id="'.$options['button_apply_id'].'"' ;

      //damp_array($attr,1,-1);
      if (is_array($arr_attr) and _sizeof($arr_attr)) foreach($arr_attr as $id=>$value) $attr[$id]=$id.'="'.$value.'"' ;

	  return($attr) ;
	}

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	//
	// вывод блочного элемента
	//
	// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    // вывод блочного элемента section
	function section($html_element,$options=array())
	{ $element_title=(isset($options['title']))? $options['title']:'' ;
	  $col_count=(isset($options['col_count']))? $options['col_count']:$this->col_count ;
	  $col_count_title=($options['col_count_title'])? $options['col_count_title']:$this->col_count_title ;
	  $comment_style=($options['comment_style'])? $options['comment_style']:'m-form__help' ; // text-muted, help-block
	  //damp_array($options);
      $form_class=($options['form_class'])? $options['form_class']:$this->form_class ;
	  switch($form_class)
	  { case 'form-horizontal': $this->row_open();
	                            ?><section  class="<?if ($col_count_title) echo 'col col-'.$col_count_title?>" id="section_<?echo $options['id']?>"><?
                                if ($element_title){?><label class="label title" <?if ($options['id']){?>for="<?echo $options['id']?>"<?}?>><?echo $element_title?></label><?}
                                ?></section><?
                                ?><section  class="<?if ($col_count) echo 'col col-'.$col_count?>"><?
                                ?><label class="<?echo $options['label_class']?>"><?echo $html_element?></label><?
                                if ($options['comment']){?><span class="<?echo $comment_style?>"><?echo $options['comment']?></span><?}
                                ?></section><?
                                $this->row_close();
                                break ;
        case 'form-horizontal2':?><section  id="section_<?echo $options['id']?>"><?
                                if ($element_title){?><label class="label" <?if ($options['id']){?>for="<?echo $options['id']?>"<?}?>><?echo $element_title?></label><?}
                                ?><label class="<?echo $options['label_class']?>"><?echo $html_element?></label><?
                                if ($options['comment']){?><span class="<?echo $comment_style?>"><?echo $options['comment']?></span><?}
                                ?></section><?
                                break ;
        case 'form-inline':     ?><div class="form-group"><?
                                if ($element_title){?><label class="mr-1" <?if ($options['id']){?>for="<?echo $options['id']?>"<?}?>><?echo $element_title?></label><?}
                                echo $html_element ;
                                ?></div><?
                                break ;
       default:                 ?><section  class="<?if ($col_count) echo 'col col-'.$col_count?>"  id="section_<?echo $options['id']?>"><?
                                if ($element_title){?><label class="label" <?if ($options['id']){?>for="<?echo $options['id']?>"<?}?>><?echo $element_title?></label><?}
                                ?><label class="<?echo $options['label_class']?>"><?echo $html_element?></label><?
                                if ($options['comment']){?><span class="<?echo $comment_style?>"><?echo $options['comment']?></span><?}
                                ?></section><?
	  }
	}


	// вывод строки таблицы
	function table_tr($html_element,$options=array())
	 {  $element_title=($options['title'])? $options['title']:'Заголовок элемента' ;
        ?><tr><td class="left"><?echo $element_title?></td><td class="<?echo $options['label_class']?>" style="text-align:left"><?
            echo $html_element ;
         ?></td></tr><?
	 }

	 function element($html_element,$options=array())
	 {
	   ?><label class="<?echo $options['label_class']?>"><?echo $html_element?></label><?
	 }


	// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	//
	// просто текст
	//
	// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

	function element_text($options=array()) {$options['section']=1 ; $this->text($options);}
	function section_text($options=array()) {$options['section']=1 ; $this->text($options);}
	function tr_text($options=array())      {$options['table']=1 ; $this->text($options);}

	function text($options=array())
	{  $attr=$this->prepare_element_attr('input',$options) ;
	   $html_element='<span '.implode(' ',$attr).'>'.$options['value'].'</span>' ;
	   $options['label_class']='text_element' ;
	   if ($options['table'])        $this->table_tr($html_element,$options) ;
	   elseif ($options['section'])  $this->section($html_element,$options) ;
	   else                          $this->element($html_element,$options) ;
	}

	// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	//
	// checkbox radio
	//
	// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------


	function element_radio_button($options=array())
	{ $element_title=($options['title'])? $options['title']:'Заголовок элемента' ;
	  $col_count=($options['col_count'])? $options['col_count']:$this->col_count ;
	  $col_count_title=($options['col_count_title'])? $options['col_count_title']:$this->col_count_title ;
	  $cur_value=$options['value'] ;
	  $option['value']=1 ;
	  $attr=$this->prepare_element_attr('radio',$options) ;
	  $recs=($options['recs'])? $options['recs']:array() ;

	  if ($this->mode=='H'){?><label class="col-lg-<?echo $col_count_title?> col-form-label"><?echo $element_title?>:</label><?}
	  ?><div class="col-lg-<?echo $col_count?>">
		    <?if ($this->mode=='V'){?><label><?echo $element_title?>:</label><?}?>
			<div class="m-radio-inline">
			<?if (_sizeof($recs)) foreach($recs as $id=>$title)
				{?><label class="m-radio m-radio--solid"><input <?echo implode(' ',$attr)?> <?if ($cur_value==$id) echo 'checked="1"'?> value="<?echo $id?>"><?echo $title?><span></span></label><?}?>
		    </div>
            <?if ($options['comment']){?><span class="m-form__help"><?echo $options['comment']?></span><?}?>
        </div>
	  <?
	}

	// $mode=default, success, info, warning, danger, brand, primary
	function panel_alert($text,$mode='default',$options=array())
	{
	  ?><div class="m-alert m-alert--icon m-alert--outline alert alert-<?echo $mode?> alert-dismissible fade show" role="alert">
			<div class="m-alert__icon"><i class="la la-<?echo $mode?>"></i></div>
			<div class="m-alert__text"><?echo $text?></div>
		</div>
	  <?
	}

	function section_begin($title,$comment='')
	{
		?><div class="m-section"><h3 class="m-section__heading"><?echo $title?></h3><?
	    if ($comment) {?><span class="m-section__sub"><?echo $comment?></span><?}
	    ?><div class="m-section__content"><?
	}

	function section_end($style='')
	{	?></div></div><?
	    if ($style) {?><div class="m-separator m-separator--<?echo $style?>"></div><?}
	}

	function label($text,$col_count)
	{
	    ?><label class="label <?if ($col_count) echo 'col col-'.$col_count?>"><?echo $text?></label><?
	}

	function hidden_var($var_name,$value)
	{  $options=[] ;
	   $options['name']=$var_name ;
	   $options['value']=$value ;
	   $attr=$this->prepare_element_attr('hidden',$options) ;
	   echo '<input '.implode(' ',$attr).'>' ;
	}

    function element_ios7_switch($rec,$fname,$options=[])
    { $_attr=[] ;
      $_attr[]='type="checkbox"' ;
      $_attr[]=($options['name'])?:'name="'.$fname.'['.$rec['pkey'].']"' ;
      $_attr[]='value="1"' ;
      if ($rec[$fname]) $_attr[]='checked' ;
      if ($options['ajax_cmd']) { $_attr[]='class="v2"' ; $_attr[]='cmd="'.$options['ajax_cmd'].'"' ; }
      if ($options['ajax_params']) foreach ($options['ajax_params'] as $id=>$value) $_attr[]=$id.'="'.$value.'"' ;
      $attr=implode(' ',$_attr) ;

      ?><label class="ios7-switch" style="font-size: 15px;">
             <input type="hidden" name="<?echo $fname?>[<?echo $rec['pkey']?>]" value="0">
             <input <?echo $attr?>><span class="switch"></span>
        </label>
      <?
    }


	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	 //
	 // SELECT
	 //
	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    // старый метод для вывода элементов фильтра отчетов
    // регулярка для поиска вызовов функции с параметрами типа $element_name=filter[name]:
    // $this->filter_section_select('term[parent]',
    // filter_section_select\('(.+?)\[(.+?)\]',
	function filter_section_select($element_name,$element_title,$col_count,$recs,$options=array())
     {  if (!_sizeof($recs) and !$options['view_clear_select']) return ; // возникает путаница если массив пустой
        if (isset($options['value'])) $options['cur_value']=$options['value'] ;
        $cur_value=(isset($options['cur_value']))? $options['cur_value']:$this->filter[$element_name] ;
        //echo '$cur_value='.$cur_value.'<br>' ;
        //damp_array($options,1,-1);

        $options['name']=$element_name ;
        $options['title']=$element_title ;
        $options['col_count']=$col_count ;
        $options['value']=$cur_value ;
        $options['recs']=$recs ;


        $this->section_select($options) ;
     }


     function filter_section_select_multiple($element_name,$element_title,$col_count,$recs,$options=array())
     {
        if (!_sizeof($recs)) return ;
        if (!isset($options['cur_values']) and is_array($this->filter[$element_name]) and _sizeof($this->filter[$element_name])) $options['cur_values']=array_keys($this->filter[$element_name]) ;
        else if (isset($options['cur_values']) and is_string($options['cur_values'])) $options['cur_values']=explode(',',$options['cur_values']) ;

        $options['name']=$element_name ;
        $options['title']=$element_title ;
        $options['col_count']=$col_count ;
        $options['recs']=$recs ;
        $options['multiple']=1 ;


        $this->section_select($options) ;
     }

    function filter_section_select_search($element_name,$recs,$options=array())
    {
        $id_element = ($options['id']) ? $options['id'] : $element_name.'_select2';
        $class = ($options['class']) ? $options['class'] : '';
        $width = ($options['width']) ? $options['width'] : '280px';
        ?>
        <select name="<?=$element_name?>" class="<?=$class?>" id="<?=$id_element?>">
            <?if (!$options['nospace_element']){?><option value="0"></option><?}
            foreach ($recs as $id=>$rec) {?>
                <option value="<?=$id?>" <?if ($options['value']==$id) echo 'selected' ?>><?=$rec?></option>
            <?}?>
        </select>
        <script>
            $j("#<?=$id_element?>").select2({
                width: "<?=$width?>"
            });
        </script>
    <?}

     // старый метод для вывода элементов настроек системы, переменные передавались в $_POST['setting']
    function form_element_select($element_title,$comment,$element_name,$recs=array(),$options=array())
     {  if (!_sizeof($recs)) return ;

         if ($comment) $element_title.='<div class="comment">'.$comment.'</div>' ;
         $el_name=(strpos($element_name,'[')!==false)? $element_name:'setting['.$element_name.']' ; // оставлено пока для совместмости
         if (isset($options['value'])) $options['cur_value']=$options['value'] ;
         $cur_value=(isset($options['cur_value']))? $options['cur_value']:$GLOBALS[$element_name] ; // оставлено пока для совместмости

        $options['name']=$el_name ;
        $options['title']=$element_title ;
        $options['value']=$cur_value ;
        $options['recs']=$recs ;
        //print_r($recs) ;

        $this->tr_select($options) ;
     }

    function form_element_autocomplete($element_name,$rec_id,$recs=array(),$options=array())
    {  $element_id = ($options['element_id']) ? $options['element_id'] : $element_name;
        $input_name = ($options['name_input']) ? $options['name_input'] : 'input'.$element_name;
        $input_id = ($options['input_id']) ? $options['input_id'] : $input_name;
        $data_required = ($options['data_required']) ? 'data-required' : '';
        ?>
        <div class="ui-widget">
            <select id="<?echo $element_id?>" name="<?echo $element_name?>" style="display: none;" <?echo $data_required?>><option value="0" selected></option>
                <? foreach($recs as $id=>$name) {?><option value="<?echo $id?>" <?if ($rec_id==$id) echo 'selected'?>><?echo $name?></option><?}?>
            </select>
        </div>
        <script>
            $j( function() {
                let data_req = "<?echo $data_required?>";
                $j.widget( "custom.<?echo ($element_id)?$element_id:$element_name?>", {
                    _create: function() {
                        this.wrapper = $j( "<span>" )
                            .addClass( "custom-combobox" )
                            .insertAfter( this.element );
                        // this.element.hide();
                        // this.element.attr("hidden", true);
                        this._createAutocomplete();
                        this._createShowAllButton();
                    },

                    _createAutocomplete: function() {
                        var selected = this.element.children( ":selected" ),
                            value = selected.val() ? selected.text() : "";
                        this.input = $j('<input name="<?echo $input_name?>" id="<?echo $input_id?>" '+data_req+' >')
                            .appendTo( this.wrapper )
                            .val( value )
                            .attr( "title", "" )
                            // .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
                            .addClass( "custom-combobox-input ui-widget ui-widget-content ui-corner-left" )
                            .autocomplete({
                                delay: 0,
                                minLength: 0,
                                source: $j.proxy( this, "_source" )
                            })
                            .tooltip({
                                classes: {
                                    "ui-tooltip": "ui-state-highlight"
                                }
                            });
                        this._on( this.input, {
                            autocompleteselect: function( event, ui ) {
                                ui.item.option.selected = true;
                                this._trigger( "select", event, {
                                    item: ui.item.option
                                });
                            },
                            autocompletechange: "_removeIfInvalid"
                        });
                    },

                    _createShowAllButton: function() {
                        var input = this.input,
                            wasOpen = false;
                        $j( "<a>" )
                            .attr( "tabIndex", -1 )
                            .attr( "title", "Show All Items" )
                            .tooltip()
                            .appendTo( this.wrapper )
                            .button({
                                icons: {
                                    primary: "ui-icon-triangle-1-s"
                                },
                                text: false
                            })
                            .removeClass( "ui-corner-all" )
                            .addClass( "custom-combobox-toggle ui-corner-right" )
                            .on( "mousedown", function() {
                                wasOpen = input.autocomplete( "widget" ).is( ":visible" );
                            })
                            .on( "click", function() {
                                input.trigger( "focus" );
                                // Close if already visible
                                if ( wasOpen ) {
                                    return;
                                }
                                // Pass empty string as value to search for, displaying all results
                                input.autocomplete( "search", "" );
                            });
                    },

                    _source: function( request, response ) {
                        var matcher = new RegExp( $j.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( this.element.children( "option" ).map(function() {
                            var text = $j( this ).text();
                            if ( this.value && ( !request.term || matcher.test(text) ) ){
                                $j('select#<?echo $element_id?>').removeClass('error');
                                $j('#<?echo $input_id?>, #<?echo $input_id?> + a.ui-button').removeClass('ui-widget-error');
                                $j('#<?echo $element_id?>-error').remove();
                                return {
                                    label: text,
                                    value: text,
                                    option: this
                                };
                            }
                            //else if (data_req!=''){
                            //    $j('#<?//echo $element_id?>//-error').remove();
                            //    $j('select#<?//echo $element_id?>//').addClass('error').after('<label id="<?//echo $element_id?>//-error" class="error" for="<?//echo $element_id?>//">Это поле необходимо заполнить.</label>');
                            //    $j('#<?//echo $input_id?>//, #<?//echo $input_id?>// + a.ui-button').addClass('ui-widget-error');
                            //}
                        }) );
                    },


                    _removeIfInvalid: function( event, ui ) {
                        // Selected an item, nothing to do
                        if ( ui.item ) {
                            $j('select#<?echo $element_id?>').removeClass('error');
                            $j('#<?echo $input_id?>, #<?echo $input_id?> + a.ui-button').removeClass('ui-widget-error');
                            $j('#<?echo $element_id?>-error').remove();
                            return;
                        }
                        // Search for a match (case-insensitive)
                        var value = this.input.val(),
                            valueLowerCase = value.toLowerCase(),
                            valid = false;
                        this.element.children( "option" ).each(function() {
                            if ( $j( this ).text().toLowerCase() === valueLowerCase ) {
                                this.selected = valid = true;
                                return false;
                            } //если совпадений не найдено, устанавливаем val(0) для возможности добавления новой организации
                            else $j('select#<?echo $element_id?>').val(0);
                        });
                        // Found a match, nothing to do
                        if ( valid ) {
                            return;
                        }
                        // Remove invalid value
                        // this.input
                        //     .val( "" )
                        //     // .attr( "title", value + " не найдено" )
                        //     .tooltip( "open" );
                        // this.element.val( "" );
                        this._delay(function() {
                            // this.input.tooltip( "close" ).attr( "title", "" );
                        }, 2500 );
                        this.input.autocomplete( "instance" ).term = "";
                        //if (data_req!=''){
                        //$j('#<?//echo $element_id?>//-error').remove();
                        //$j('select#<?//echo $element_id?>//').addClass('error').after('<label id="<?//echo $element_id?>//-error" class="error" for="<?//echo $element_id?>//">Это поле необходимо заполнить.</label>');
                        //$j('#<?//echo $input_id?>//, #<?//echo $input_id?>// + a.ui-button').addClass('ui-widget-error');
                        //}
                    },

                    _destroy: function() {
                        this.wrapper.remove();
                        this.element.show();
                    }
                });
                $j( "#<?echo $element_id?>" ).<?echo $element_id?>();
            } );
        </script>
        <?
    }

	function element_select($options=array()) { $this->select($options); }
	function section_select($options=array()) { $options['section']=1 ;  $this->select($options); }
	function tr_select($options=array())      { $options['table']=1 ; $this->select($options);}
	function element_select_multiple($options=array()) { $options['multiple']=1 ; $this->select($options); }
	function section_select_multiple($options=array()) { $options['section']=1 ;  $options['multiple']=1 ;  $this->select($options); }
	function tr_select_multiple($options=array())      { $options['table']=1 ; $options['multiple']=1 ;$this->select($options);}

    function select_multiple($options=array()){$options['multiple']=1 ;$this->select($options);}
	function select($options=array())
	 {
        if (!_sizeof($options['recs'])) return ;
        $element_value=$this->filter[$options['name']]? $this->filter[$options['name']]:($options['value']? $options['value']:0) ; // если не указан value в select([...,'value'=>$this->filter[$options[name]],...]), то value берётся из фильтра, иначе из указанного value, иначе value=0
        if (isset($this->filter[$options['name']]) and is_array($this->filter[$options['name']])) $options['cur_values']=array_keys($this->filter[$options['name']]) ; // был убран двумерный массив options['cur_values][]=$this->filter[$options['name']] и заменён на options['cur_values]=array_keys($this->filter[$options['name']]) (баг с незаписывающимися значениями)
        if (!isset($options['cur_values']) and is_array($this->filter[$options['name']]) and _sizeof($this->filter[$options['name']])) $options['cur_values']=array_keys($this->filter[$options['name']]) ;
        else if (isset($options['cur_values']) and is_string($options['cur_values'])) $options['cur_values']=explode(',',$options['cur_values']) ;
	    if (isset($options['cur_values'])) $options['check_values']=$options['cur_values'] ;
	    if (isset($options['class']) and !is_array($options['class'])) $options['class']=array($options['class']) ;
	    $options['class'][]='form-control' ;
	    if ($options['multiple'])
	    { $options['nospace_element']=1 ;
	      $options['class'][]='select2-multiple' ;
	    }
        if ($options['use_value_as_id']) $options['value_is_id']=1 ;

	    //$options['class'][]='select2-single' ;
	    //damp_array($options,1,-1);
	    //echo '$element_value='.$element_value.'<br>' ;

	 	$attr=$this->prepare_element_attr('select',$options) ;
	 	//damp_array($attr);
		$recs=($options['recs'])? $options['recs']:array() ;
        // определяем наличие групп в списке
        $arr_recs_by_group=[] ;
        $fname=($options['fname_label_optgroup'])?:'-' ;
        if (_sizeof($recs)) foreach($recs as $id=>$rec)
        {   $group_name=(isset($rec[$fname]) and $rec[$fname])? $rec[$fname]:'' ;
            $arr_recs_by_group[$group_name][$id]=$rec ;

        }

        if ($options['debug']) damp_array($arr_recs_by_group);


		ob_start() ;
		?><select <?echo implode(' ',$attr)?>>
                <? if ($options['placeholder']){?><option value="" disabled selected><?echo $options['placeholder']?></option><?}?>
                <? if (!$options['nospace_element']){?><option value="0"></option><?}
                         if (sizeof($arr_recs_by_group)) foreach($arr_recs_by_group as $group_name=>$recs)
						 {
                             if ($group_name) {?><optgroup label="<?echo addslashes($group_name)?>"><?}

                   if (_sizeof($recs)) foreach($recs as $id=>$value)
                    {   if ($options['value_is_id'] and !is_array($value)) $id=$value ;
                        $key=(is_array($value) and $options['key_fname'])?  $value[$options['key_fname']]:$id ;
                        $val=(is_array($value))?  (($options['title_fname'])? $value[$options['title_fname']]:$value['obj_name']):$value ;
                        if ($options['use_id_plus_1']) $key++ ;

                        //$selected=(isset($this->filter[$element_name][$id]))? 1:0 ;
                        if (isset($options['check_values'])) $selected=(in_array($key,$options['check_values']))? 1:0 ;
                        else                                 $selected=((string)$element_value==(string)$key)? 1:0; /// !!! не ставить тут ===, работает некорректго
                        if (!isset($options['match']) or ($options['match'] and preg_match_all($options['match'],$value,$matches,PREG_SET_ORDER)))
                                { $_option_attr=[] ;
                                  $_option_attr[]='value="'.$key.'"' ;
                                  if ($selected) $_option_attr[]='selected' ;
                                  if ($options['option_class']) $_option_attr[]='class="'.$options['option_class'].'"' ;
                                  $options_attr=implode(' ',$_option_attr) ;
                                  ?><option <?echo $options_attr?>><?echo $val?></option><?
                                }
                             }
                             if ($group_name) {?></optgroup><?}
                    }
                ?>
          </select><i></i>
          <?if ($options['comment'] && !$options['section']){?><span class="m-form__help"><?echo $options['comment']?></span><?}?>
		<?
		$html_element=ob_get_clean() ;
		$options['label_class']='select' ;
		if ($options['table'])          $this->table_tr($html_element,$options) ;
		elseif ($options['section'])    $this->section($html_element,$options) ;
		else                            $this->element($html_element,$options) ;
	 }

	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	 //
	 // INPUT TEXT
	 //
	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

	 //  старый вариант для элементов фильтра
     function filter_section_input_text($element_name,$element_title,$col_count,$options=array())
     {   $options['name']=$element_name ;
         $options['title']=str_replace(':','',$element_title) ;
         $options['col_count']=$col_count ;
         $options['section']=1 ;
         $this->input($options) ;
     }

     // старый вариант для редактора настроек
	function form_element_input($element_title,$comment,$element_name,$options=array())
    {   if ($comment) $element_title.='<div class="comment">'.$comment.'</div>' ;
        $el_name=(strpos($element_name,'[')!==false)? $element_name:'setting['.$element_name.']' ;
        if (isset($options['value'])) $options['cur_value']=$options['value'] ;
        $cur_value=(isset($options['cur_value']))? $options['cur_value']:$GLOBALS[$element_name] ; // оставлено пока для совместмости

        $options['name']=$el_name ;
        $options['title']=$element_title ;
        $options['value']=$cur_value ;

        $this->tr_input($options) ;
    }

    // новый вариант
    function element_input($options=array()) {$options['section']=0 ; $this->input($options);}
    function section_input($options=array()) {$options['section']=1 ; $this->input($options);}
    function tr_input($options=array())      {$options['table']=1 ; $this->input($options);}

    function input($options=array())
	{ if (!$options['type']) $options['type']='text' ;
	  $attr=$this->prepare_element_attr('input',$options) ;
	  $html_element='<input '.implode(' ',$attr).'>' ;
	  if ($options['view_as_h_m_s'])  $html_element.=ENGINE()->view_human_time_period($options['view_as_h_m_s'],$GLOBALS[$options['name']]) ;

	  $options['label_class']='input' ;

	  if ($options['table'])        $this->table_tr($html_element,$options) ;
	  elseif ($options['section'])  $this->section($html_element,$options) ;
	  else                          $this->element($html_element,$options) ;

	  if ($options['class']=='datetimepicker' and $this->page!=null) $this->page->use_datepicker=1 ;
	  if ($options['class']=='datepicker' and $this->page!=null) $this->page->use_datepicker=1 ;
	  if ($options['auto_complete'] and $this->page!=null) $this->page->use_auto_complete=1 ;
	}


	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	 //
	 // TEXTAREA
	 //
	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

     function filter_section_textarea($element_name,$element_title,$col_count,$options=array())
     {  $options['name']=$element_name ;
          $options['title']=str_replace(':','',$element_title) ;
          $options['col_count']=$col_count ;
          $options['section']=1 ;
          $this->textarea($options) ;
      }

     function form_element_textarea($element_title,$comment,$element_name,$options=array()) //$title,$comment,$var_name,$options=array())
     {  if ($comment) $element_title.='<div class="comment">'.$comment.'</div>' ;
        $el_name=(strpos($element_name,'[')!==false)? $element_name:'setting['.$element_name.']' ;
        if (isset($options['value'])) $options['cur_value']=$options['value'] ;
        $cur_value=(isset($options['cur_value']))? $options['cur_value']:$GLOBALS[$element_name] ; // оставлено пока для совместмости

        $options['name']=$el_name ;
        $options['title']=$element_title ;
        $options['value']=$cur_value ;
        $this->tr_textarea($options) ;
     }

        // новый вариант
     function element_textarea($options=array()) {$options['section']=1 ; $this->textarea($options);}
     function section_textarea($options=array()) {$options['section']=1 ; $this->textarea($options);}
     function tr_textarea($options=array())      {$options['table']=1 ; $this->textarea($options);}

     function textarea($options=array())
     {  $options['class']='form-control' ;
        //$options['style']='width:100%;height:50px;' ;

        $attr=$this->prepare_element_attr('textarea',$options) ;
	    $html_element='<textarea '.implode(' ',$attr).'>'.htmlspecialchars($options['value']).'</textarea>' ;

	    $options['label_class']='textarea' ;

	    if ($options['table'])        $this->table_tr($html_element,$options) ;
	    elseif ($options['section'])  $this->section($html_element,$options) ;
	    else                          $this->element($html_element,$options) ;
    }

     function textarea_ckeditor($name,$options=array())
	 { $style_file=($options['style_file'])? $options['style_file']:'/style.css' ;
	   //$use_element_name=(!is_array($options))?  $options:$options['use_element_name'] ;
	   $element_id='_'.ENGINE()->generate_UID() ; $cur_content='' ;
	   //$cur_content=($fname)? $rec[$fname]:'' ;
	   if ($options['content']) $cur_content=$options['content'] ;
	   if ($options['value']) $cur_content=$options['value'] ;
	   // если отдаем текст в редактор и там вообще нет <тегов> - заменяем переносы строк на абзац
	   //if (!preg_match('/<(.+?)>/is',$cur_content,$match)) $cur_content=preg_replace('~^(?![\r\n])(.*?)\r?\n?$~m','<p>$1</p>',$cur_content);
	   // аналог: for ($result = '',$i = 0,$a = explode("\r\n",$str),$s = _sizeof($a); $i < $s && ($result .= (!strlen($a[$i])?$a[$i]:'<p>'.$a[$i].'</p>')."\n") !== FALSE; ++$i);
	   $options['id']=$element_id ;
	   $options['name']=$name ;
	   $attr=$this->prepare_element_attr('input',$options) ;
	   //damp_array($attr) ;
	   ?><textarea <?echo implode(' ',$attr)?>><?echo $cur_content?></textarea>
	     <script type="text/javascript">

	       $j(document).ready(function()
	       {  editor=CKEDITOR.replace( '<?echo $element_id?>',
	             {  //height:700,
	                filebrowserBrowseUrl: '/AddOns/ckfinder/ckfinder.html',
                    filebrowserUploadUrl: '/AddOns/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
                    filebrowserWindowWidth: '1000',
                    filebrowserWindowHeight: '700',
                    contentsCss:'/1.css',
                    //extraPlugins:'timestamp',
                    extraPlugins:'autogrow',
                    // config.uiColor = '#AADC6E';

                    <?if ($options['no_toolbar']){?>toolbar: []<?}
                      else {?>
                    toolbar: [
                    			{ name: 'document', items: [ 'Source', '-', 'Print', '-', 'Templates' ] },
                    			{ name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
                    			{ name: 'editing', items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
                    			{ name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat' ] },
                    			{ name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
                    			{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
                    			{ name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak' ] },
                    			'/',
                    			{ name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
                    			{ name: 'colors', items: [ 'TextColor', 'BGColor' ] },
                    			{ name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
                    			{ name: 'about', items: [ 'About' ] }
                    		]<?}?>
                 } );

	       }) ;
	       </script>
	      <?
	      return($options['id']) ;
	 }

	 // Далее подключение CKEditor5 пока используем 4-й
     function textarea_ckeditor5($name,$options=array())
	 { $style_file=($options['style_file'])? $options['style_file']:'/style.css' ;
	   //$element_id='editor_'.ENGINE()->generate_UID() ;
	   $element_id='editor' ;
	   if ($options['content']) $cur_content=$options['content'] ;
	   if ($options['value']) $cur_content=$options['value'] ;
	   // если отдаем текст в редактор и там вообще нет <тегов> - заменяем переносы строк на абзац
	   //if (!preg_match('/<(.+?)>/is',$cur_content,$match)) $cur_content=preg_replace('~^(?![\r\n])(.*?)\r?\n?$~m','<p>$1</p>',$cur_content);
	   // аналог: for ($result = '',$i = 0,$a = explode("\r\n",$str),$s = _sizeof($a); $i < $s && ($result .= (!strlen($a[$i])?$a[$i]:'<p>'.$a[$i].'</p>')."\n") !== FALSE; ++$i);
	   $options['name']=$name ;
	   //$options['id']=$element_id ;
	   //$options['class']='document-editor__editable' ;
	   $options['style']='display:none' ;
	   $attr=$this->prepare_element_attr('textarea',$options) ;
	   //damp_array($attr) ;

	   ?><textarea <?echo implode(' ',$attr)?> id='textarea_<?echo $element_id?>'></textarea>
	   <!-- This container will become the editable. -->
	   <p>
	               <button id="comments-only-toggle">Toggle comments-only</button>
	           </p>
       <div class="document-editor">
           <div class="document-editor__toolbar"></div>
           <div id="container">
               <div class="document-editor__editable-container">
                   <div id="editor" class="document-editor__editable">
                       <?echo $cur_content?>
                   </div>
               </div>
               <div id="sidebar"></div>
               <div class="clear"></div>
           </div>
           <div class="clear"></div>
       </div>
	     <script type="text/javascript">
	       $j(document).ready(function()
	       {








               DecoupledDocumentEditor
                .create( document.querySelector( '#editor' ),
                {   toolbar: {
                       viewportTopOffset : 50,
                        items: [
                            'heading',
                            '|',
                            'fontSize',
                            'fontFamily',
                            '|',
                            'bold',
                            'italic',
                            'underline',
                            'strikethrough',
                            'highlight',
                            '|',
                            'alignment',
                            '|',
                            'numberedList',
                            'bulletedList',
                            '|',
                            'indent',
                            'outdent',
                            '|',
                            'todoList',
                            'link',
                            'blockQuote',
                            'imageUpload',
                            'insertTable',
                            'mediaEmbed',
                            '|',
                            'undo',
                            'redo',
                            'comment'
                        ]
                    },
                    language: 'ru',
                    image: {
                        toolbar: [
                            'imageTextAlternative',
                            'imageStyle:full',
                            'imageStyle:side'
                        ]
                    },
                    table: {
                        contentToolbar: [
                            'tableColumn',
                            'tableRow',
                            'mergeTableCells',
                            'tableProperties'
                        ]
                    },
                    licenseKey: '/cMdVlTzZiTMCrHzHkpZs241UMW4eS0u19DrNwx0YPRfdBgEcCIWCz4=',
                    //extraPlugins: [ CommentsAdapter ],
                    sidebar: {
                    container: document.querySelector( '#sidebar' )
                    },
                } )
                .then( editor => {
                    window.editor = editor;

                    // Set a custom container for the toolbar.
                    document.querySelector( '.document-editor__toolbar' ).appendChild( editor.ui.view.toolbar.element );
                    document.querySelector( '.ck-toolbar' ).classList.add( 'ck-reset_all' );


                     // Switch between the comments-only and editable mode when the user clicks the button.
                    const button = document.querySelector( '#comments-only-toggle' );

                    button.addEventListener( 'click', () => {
                    editor.plugins.get( 'CommentsOnly' ).isEnabled = !editor.plugins.get( 'CommentsOnly' ).isEnabled;
                    } );




                } )
                .catch( error => {
                    console.error( error );
                } );

	           /*
	           ClassicEditor
	           .create( document.querySelector( '#<?echo $element_id?>' ),
	           {    toolbar: [
	                    "undo", "redo", "bold", "italic", "blockQuote", "imageTextAlternative", "imageUpload", "heading", "imageStyle:full", "imageStyle:side", "link", "numberedList", "bulletedList", "mediaEmbed", "insertTable", "tableColumn", "tableRow", "mergeTableCells"
	                   ],
	                heading: {
	                       options: [
	                           { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
	                           { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
	                           { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }
	                       ]
	                   },

                   ckfinder:
                   {
                       // Upload the images to the server using the CKFinder QuickUpload command.
                       uploadUrl: '/AddOns/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&responseType=json'
                   },
                   language: 'ru',
                   height: 300,
                   toolbarCanCollapse: true,
	           } )
	           .then( newEditor => {
	                   CKeditor = newEditor;
	                   console.log( 'Editor was initialized', newEditor );
	                   console.log(Array.from( newEditor.ui.componentFactory.names() ));
	               })
	           .catch( err => {
	               console.error( err.stack );
	           } );*/

	           console.log(DecoupledDocumentEditor.builtinPlugins.map( plugin => plugin.pluginName ));

	       }) ;
	       </script>
	      <?
	      return($options['id']) ;
	 }


	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	 //
	 // CHECKBOX
	 //
	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------


    function form_checkbox($title,$comment,$var_name,$value=0,$check_value=1)
    {   if ($comment) $title.='<div class="comment">'.$comment.'</div>' ;
        $el_var_name=(strpos($var_name,'[')!==false)? $var_name:'setting['.$var_name.']' ;
        if (!$value and isset($GLOBALS[$var_name])) $value=$GLOBALS[$var_name] ;
        ?><tr><td class="left"><?echo $title?></td><td style="text-align:center">
            <input type="hidden" name="<?echo $el_var_name?>" value="0">
            <input type="checkbox" name="<?echo $el_var_name?>" value="<?echo $check_value?>" <?if ($value) echo 'checked'?>>
        </td></tr><?
    }

    function form_checkbox_left($title,$comment,$var_name,$value=0,$check_value=1)
    {   if ($comment) $title.='<div class="comment">'.$comment.'</div>' ;
        $el_var_name=(strpos($var_name,'[')!==false)? $var_name:'setting['.$var_name.']' ;
        if (!$value and isset($GLOBALS[$var_name])) $value=$GLOBALS[$var_name] ;
        ?><tr><td style="text-align:center">
            <input type="hidden" name="<?echo $el_var_name?>" value="0">
            <input type="checkbox" name="<?echo $el_var_name?>" value="<?echo $check_value?>" <?if ($value) echo 'checked'?>>
        </td><td class="left"><?echo $title?></td></tr><?
    }

    function form_checkbox_to_arr($title,$comment,$var_name,$var_name2)
    {   if ($comment) $title.='<div class="comment">'.$comment.'</div>' ;
        //$el_var_name=(strpos($var_name,'[')!==false)? $var_name:'setting['.$var_name.']' ;
        ?><tr><td class="left"><?echo $title?></td>
        <td style="text-align:center">
        <input type="hidden" name="setting[<?echo $var_name?>][<? echo $var_name2?>]" value="0">
        <input type="checkbox" name="setting[<?echo $var_name?>][<? echo $var_name2?>]" value="1" <?if ($GLOBALS[$var_name][$var_name2]==1) echo 'checked'?>>
        </td>
        </tr><?
    }

    function element_checkbox($options=array()) {$options['section']=1 ; $this->checkbox($options);}
    function section_checkbox($options=array()) {$options['section']=1 ; $this->checkbox($options);}
    function tr_checkbox($options=array())      {$options['table']=1 ; $this->checkbox($options);}

    function checkbox($options=array())
    {  $options['class']='form-check-input' ; // class для checkbox

       if (!$options['value']) $options['value']=1 ;
       $attr=$this->prepare_element_attr('checkbox',$options) ;
       $title=(isset($options['title']))? $options['title']:'Да' ;
       $html_element='<section><label class="checkbox"><input type="hidden" '.$attr['name'].' value="0"><input '.implode(' ',$attr).'><i></i><label class="form-check-label" for="'.$options['id'].'">'.$title.'</label></label></section>' ;

       $options['label_class']=($options['inline'])? 'inline-group':'section-group' ;
	   unset($options['id']) ;

	   if ($options['table'])        $this->table_tr($html_element,$options) ;
	   elseif ($options['section'])  $this->section($html_element,$options) ;
	   else                          $this->element($html_element,$options) ;
    }


    function checkbox_new($options=array())
    {  $options['class']='form-check-input' ; // class для checkbox

        $options['value']=1 ;
//        damp_array($options,1,-1);
       $attr=$this->prepare_element_attr('checkbox',$options) ;
       $label_text=($options['cur_value']==1)? 'да':'нет';
       $html_element='<div class="checkbox d-inline-flex"><input type="hidden" '.$attr['name'].' value="0"><input '.implode(' ',$attr).'><i></i></div>' ;

       $options['label_class']=($options['inline'])? 'inline-group':'section-group' ;
	   unset($options['id']) ;
	   if ($options['table'])        $this->table_tr($html_element,$options) ;
	   elseif ($options['section'])  $this->section($html_element,$options) ;
	   else                          $this->element($html_element,$options) ;
    }


     // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	 //
	 // RADIO
	 //
	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    function element_radio($options=array()) {$options['section']=1 ; $this->radio($options);}
    function section_radio($options=array()) {$options['section']=1 ; $this->radio($options);}
    function tr_radio($options=array())      {$options['table']=1 ; $this->radio($options);}

    function radio($options=array())
    {  $options['class']='form-check-input' ;

       $html_elements=array() ;
       if (_sizeof($options['recs'])) foreach($options['recs'] as $id=>$value)
       {   $options['value']=$id ;
           $options['id']=$options['name'].'_'.$options['value'] ;
           $attr=$this->prepare_element_attr('radio',$options) ;
           $html_elements[]='<section><label class="radio"><input '.implode(' ',$attr).'><i></i>'.$value.'</label></section>' ;
	   }
       $html_element=implode("\n",$html_elements) ;

       $options['label_class']=($options['inline'])? 'inline-group':'section-group' ;
	   unset($options['id']) ;

	   if ($options['table'])        $this->table_tr($html_element,$options) ;
	   elseif ($options['section'])  $this->section($html_element,$options) ;
	   else                          $this->element($html_element,$options) ;
    }


     // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	 //
	 // FILE
	 //
	 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    function element_file($options=array()) {$options['section']=1 ; $this->file($options);}
    function section_file($options=array()) {$options['section']=1 ; $this->file($options);}
    function tr_file($options=array())      {$options['table']=1 ; $this->file($options);}

    function file($options=array())
    {  $options['class']='form-check-input' ;

       $options['type']='file' ;
       $options['id']=$options['name'];
       $attr=$this->prepare_element_attr('file',$options) ;
       $html_element='<section><label class="file"><input '.implode(' ',$attr).'><i></i></label></section>' ;

       $options['label_class']=($options['inline'])? 'inline-group':'section-group' ;
	   unset($options['id']) ;

	   if ($options['table'])        $this->table_tr($html_element,$options) ;
	   elseif ($options['section'])  $this->section($html_element,$options) ;
	   else                          $this->element($html_element,$options) ;
    }



    // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    //
    // BUTTONS
    //
    // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    //УБРАНЫ КНОПКИ "Сохранить в документах", "PDF", "Excel", "Excel CSV" для роли 20 - Суперчитатель
     function panel_buttons($options=array())
         { $page_report=(is_object($this->report))? $this->report:_CUR_PAGE() ;
           ?><div id="panel_buttons"><input type="submit" class="button v2" data-testId="setFilter" cmd="set_filter" value="<?echo ($page_report->editing)? 'Получить данные':'Сформировать отчет'?>">&nbsp;&nbsp;<?
           if (!$page_report->editing)
           {?>
                                <?if (MEMBER()->rol!=20){?><button class="button v2" data-testId="createDoc" cmd="docs/doc_create">Сохранить в документах</button>&nbsp;&nbsp;<?}?>
                                <button class="button v2" cmd="report/view_as_html">HTML</button>&nbsp;&nbsp;
                                <?if (MEMBER()->rol!=20){?><button class="button v2" data-testId="pdf" cmd="report/view_as_pdf" mode="<?echo $page_report->PDF_master?>">PDF</button>&nbsp;&nbsp;<?}?>
                                <?if ($page_report->allow_export_to_excel and MEMBER()->rol!=20){?><button class="button v2" cmd="report/view_as_xls">Excel</button>&nbsp;&nbsp;<?}?>
                                <?if ($page_report->allow_export_to_csv and MEMBER()->rol!=20){?><button class="button v2" data-testId="csv" cmd="report/view_as_CSV">Excel CSV</button>&nbsp;&nbsp;<?}?>
                                <?if ($page_report->allow_export_to_docx and MEMBER()->rol!=20){?><button class="button v2" cmd="report/view_as_DOCX">Word</button>&nbsp;&nbsp;<?}?>
                                <?if ($page_report->allow_set_to_cron){?><button class="button v2" cmd="report/set_report_to_cron" report_code="<?echo $page_report->report_code?>">Планировщик</button>&nbsp;&nbsp;<?}?>
                                <!--<button class="button v2" cmd="report/to_print">Печать</button>&nbsp;&nbsp;-->
                                <?if (method_exists($page_report,'panel_report_buttons')) $page_report->panel_report_buttons($options);?>
                <?if ($GLOBALS['_SETTING']['plugins']['send_report']){?><button class="button v2" cmd="send_report/report_register" report_code="<?echo $page_report->report_code?>">Отправка по расписанию</button>&nbsp;&nbsp;<?}?>

                              <?}
           ?></div><?
         }


     function section_button($title,$cmd,$col_count,$options=array())
     {   ob_start() ;
         $this->button($title,$cmd,$options);
         $html_element=ob_get_clean() ;
         $options['title']='<span class=white>.</span>';
         $options['col_count']=$col_count ;
         $this->section($html_element,$options) ;
     }

     //function button($title,$cmd,$options=array())
     function element_button($options=array())
     {
        $this->button($options['title'],$options['cmd'],$options);
	 }

     function button($title,$cmd='',$options=array())
     {   //$page_report=(is_object($this->report))? $this->report:_CUR_PAGE() ;
         if (is_array($title)) $options=$title ;
         if (is_string($title) and !$options['title']) $options['title']=$title ;
         if (is_string($cmd) and !$options['cmd']) $options['cmd']=$cmd ;
         $attr=$this->prepare_button_attr('button',$options) ;
         //damp_array($attr) ;

         ?><button <?echo implode(' ',$attr)?>><?echo $options['title']?></button><?
     }

     function panel_button_apply($options=array())
     {   $page_report=(is_object($this->report))? $this->report:_CUR_PAGE() ;

         $_class=array() ; $_attr=array() ;
         $_class[]='button' ;

         if ($options['cmd']!='cancel') $_class[]=($options['cmd_method'])?  $options['cmd_method']:'v2' ;
         else { $_class[]='cancel' ; unset($options['cmd']) ; }

         $_attr[]='type="submit"'  ;
         $_attr[]='class="'.implode(' ',$_class).'"'  ;
         $_attr[]='data-testId="setFilter"'  ;
         $_attr[]='cmd="'.(($options['cmd'])?  $options['cmd']:'set_filter').'"' ;
         $_attr[]='value="'.(($page_report->editing)?  'Получить данные':'Применить').'"' ;
         if ($options['button_apply_id']) $_attr[]='id="'.$options['button_apply_id'].'"' ;

         // переносим в кнопку атрибуты типа event_id=
         unset($options['cmd'],$options['button_apply_id'],$options['cmd_method']) ;
         if (_sizeof($options)) foreach($options as $id=>$value) $_attr[]=$id.'="'.$value.'"' ;


         ?><div id="panel_buttons"><input <?echo implode(' ',$_attr)?>><?
         if (method_exists($page_report,'panel_report_buttons')) $page_report->panel_report_buttons($options);
         ?></div><?
     }

     function panel_buttons_action()
     { $page_report=(is_object($this->report))? $this->report:_CUR_PAGE() ;
       ?><div id="panel_buttons"><?
       if ($page_report->filter and !$page_report->editing)
       {?>
            <?if (MEMBER()->rol!=20){?><button class="button v2" cmd="docs/doc_create"><i class="fa fa-floppy-o"></i></button>&nbsp;&nbsp;<?}?>
            <button class="button v2" cmd="report/view_as_html"><i class="fa fa-file-text-o"></i></button>&nbsp;&nbsp;
            <?if (MEMBER()->rol!=20){?><button class="button v2" cmd="report/view_as_pdf" mode="<?echo $page_report->PDF_master?>"><i class="fa fa-file-pdf-o"></i></button>&nbsp;&nbsp;<?}?>
            <?if ($page_report->allow_export_to_excel and MEMBER()->rol!=20){?><button class="button v2" cmd="report/view_as_xls">Excel</button>&nbsp;&nbsp;<?}?>
            <?if ($page_report->allow_export_to_csv and MEMBER()->rol!=20){?><button class="button v2" cmd="report/view_as_CSV">Excel CSV</button>&nbsp;&nbsp;<?}?>
            <button class="button v2" cmd="report/to_print"><i class="fa fa-print"></i></button>&nbsp;&nbsp;
        <?
       }
       ?></div><?
     }

}
?>
