<?php
  include_once(_DIR_TO_ENGINE.'/admin/i_img_working.php') ;
  include_once(_DIR_TO_ENGINE.'/admin/i_XML_import_export.php') ;


//<button class=button cmd=export_obj_to_xml mode=give_file params="12,33">Далее</button>

 // ---------------------------------------------------------------------------------------------------------------------------------
 // функции генерации элементов списоков и свойств
 // ---------------------------------------------------------------------------------------------------------------------------------

 function generate_datepicker($el_name,$value="")
 { $id='datepicker_'.rand(1,10000) ;
   ?><!--<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
     <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
     <link rel="stylesheet" href="/resources/demos/style.css" />-->
     <input name="<?echo $el_name?>" type="text" class=text id="<?echo $id?>" value="<?echo $value?>">
     <?/*if (!$GLOBALS['is_js_declare']['datepicker'])
        { $GLOBALS['is_js_declare']['datepicker']=1 ;
           ?><script type="text/javascript" src="<?echo _PATH_TO_ADMIN_ADDONS?>/jquery-ui-1.9.2/jquery.ui.datepicker.min.js"></script>
             <script type="text/javascript" src="<?echo _PATH_TO_ADMIN_ADDONS?>/jquery-ui-1.9.2/jquery.ui.datepicker-ru.js"></script>
             <script type="text/javascript" src="<?echo _PATH_TO_ADMIN_ADDONS?>/jquery-ui-1.9.2/jquery-ui-timepicker-addon.js"></script>
             <script type="text/javascript" src="<?echo _PATH_TO_ADMIN_ADDONS?>/jquery-ui-1.9.2/jquery.ui.widget.min.js"></script>
             <script type="text/javascript" src="<?echo _PATH_TO_ADMIN_ADDONS?>/jquery-ui-1.9.2/jquery.ui.tabs.min.js"></script>
           <?
        }*/?>
     <script type="text/javascript">include_datapicker_script() ; $j(function(){$j("#<?echo $id?>" ).datepicker();});</script>
   <?
 }

 function generate_datetimepicker($el_name,$options=array())
 { $id='datepicker_'.rand(1,10000) ;
   /*?><link rel="stylesheet" href="<?echo _PATH_TO_ENGINE?>/AddOns/jquery-ui-timepicker-addon.css"/>
     <script src="<?echo _PATH_TO_ENGINE?>/AddOns/jquery-ui-timepicker-addon.js"></script>*/
   ?><input name="<?echo $el_name?>" type="text" class=text id="<?echo $id?>" <?if ($options['data-required']) echo 'data-required'?> value="<?echo $options['value']?>"><script type="text/javascript">$j(function(){$j("#<?echo $id?>" ).datetimepicker(<?echo $options['js_options']?>);});</script><?
 }

 function generate_select_object_from_array($el_name,$arr,$fname='',$options=array())
 { ?><select name="<?echo $el_name?>"><option></option><?
    if (_sizeof($arr)) foreach($arr as $id=>$rec)
    {  if (!is_array($rec)) {?><option value="<?echo $id?>"><?echo $rec?></option><?}
       else                 {?><option value="<?echo $id?>"><?echo $rec[$fname]?></option><?}
    }
   ?></select><?
 }


 // новая версия
 function generate_obj_text($reffer,$options=array())
 { if (!$reffer) return ;
   $obj_rec=select_db_ref_info($reffer,array('no_error_table_not_found'=>1,'debug'=>0)) ;
   return(generate_ref_obj_viewer($obj_rec,$options['only_name'],$options['show_img'])) ;
 }

 function generate_tr_td_field($rec,$fname,$title,$options=array())
 {
    list($text,$td_attr)=_CLSS($rec['clss'])->generate_field_text($rec,$fname,$options) ;
   ?><tr reffer="<?echo $rec['_reffer']?>"><td><?echo $title?></td><td <?echo $td_attr?>><?echo $text?></td></tr><?
 }

 // генерация элемента ввода
 function generate_element2($rec,$fname,$type,$options=array())
 { $tkey=$rec['tkey'] ;
   $pkey=$rec['pkey'] ;
   $clss=$rec['clss'] ;
   $size=$options['size'] ;
   return(generate_element($type,$size,$tkey,$clss,$pkey,$fname,$rec[$fname])) ;
 }

 // генерация элемента ввода
 function generate_element($type,$size,$tkey,$clss,$pkey,$fname,$value,$options=array())
 { $element_name="obj[".$tkey."][".$clss."][".$pkey."][".$fname."]" ;
   $text='' ;
   switch ($type)
    { case 'checkbox':  if ($value) $check='checked' ;
    					$text ='<input  name="'.$element_name.'" type="hidden" value=0 />' ;
    					$text.='<input  name="'.$element_name.'" type=checkbox value=1 '.$check.' />' ;
    					break ;
      case 'text':		$text='<input  name="'.$element_name.'" class="text '.$options['class'].'" type=text value="'.$value.'" size='.$size.' />' ;
       					break;
      case 'select':    $text='<select size="1" name="'.$element_name.'">' ;
       					break;
      case 'hidden':	$text ='<input  name="'.$element_name.'" type="hidden" value="'.$value.'" />' ;
    					break ;
   }
   return($text) ;
 }

 // генерация чекбокса для отметки элемента
 function generate_check($tkey,$clss,$pkey,$value='ON',$status='',$_tkey=0,$_clss=0,$_pkey=0,$_value='ON')
 {
   $name='check' ;
   $text='<input name="_'.$name.'['.$tkey.']['.$clss.']['.$pkey.']" type="checkbox"  value="'.$value.'" '.$status.'/>' ;

   $name='check_source' ;
   if ($_tkey) $text.='<input name="_'.$name.'['.$_tkey.']['.$_clss.']['.$_pkey.']" type="checkbox" value="'.$_value.'" class=hidden />' ;

   return($text);
 }


 // 0=>'&nbsp;',1=>'Input big',6=>'Input small',2=>'Memo',3=>'Checkbox',4=>'Drop-down Menu',5=>'Radio button'



function generate_select_object_from_table($tkey,$clss,$pkey,$fname,$options)
{
   //damp_array($options) ;
   if (!$options['select_from_table']) return ;
   $table_name=_DOT($options['select_from_table'])->table_name ;
   $usl_clss=($options['select_from_clss'])? ' and clss='.$options['select_from_clss']:'' ;
   $list_recs=execSQL('select * from '.$table_name.' where parent!=0 '.$usl_clss);

   $text='<select name=obj['.$tkey.']['.$clss.']['.$pkey.']['.$fname.']><option value=""></option>' ;
   if (_sizeof($list_recs)) foreach($list_recs as $rec) $text.='<option value='.$rec['_reffer'].'>'.$rec['obj_name'].'</option>' ;
   $text.='</select>' ;
   return($text) ;
   //damp_array($list_recs) ;
}

 // на удаление. Пока используетмя в модулях - будет болванка, потом удалить
 function show_standart_button($options=array()) {}

 function show_add_image_button($tkey,$pkey) {?><img class="in_text" src="<?_PATH_TO_ENGINE?>/admin/images/add_icon.png" width="16" height="17" alt="" border="0"> Добавить <a after_close_event="show_all_img" menu_id="structure_3" reffer="<?echo $tkey?>_<?echo $pkey?>" href="/admin/image_uploader.php?tkey=<?echo $tkey?>&amp;pkey=<?echo $pkey?>&amp;auto_close=1" id="image_upload_<?echo $pkey?>" onclick="return hs.htmlExpand(this, {objectType: 'iframe', width: 500, headingText: 'Загрузка изображений',wrapperClassName: 'titlebar' } )" class="  ">Фото</a><?}

 function show_ckeditor_hidden_panel($title,$fname,$cnt=0)
 {
    ?><h1><?echo $title?><span class=small><? if ($cnt) echo ' ['.$cnt.' знаков]'?></span></h1><div class=expand_panel>развернуть/свернуть панель</div><div class="panel hidden"><? show_window_ckeditor_v3($GLOBALS['obj_info'],$fname,200) ; ?><br><button class="button" cmd="save_list">Сохранить</button></div><?
 }

 function show_ckeditor_visible_panel($title,$fname,$cnt=0)
 {
    ?><h1><?echo $title?><span class=small><? if ($cnt) echo ' ['.$cnt.' знаков]'?></span></h1><div class="panel"><? show_window_ckeditor_v3($GLOBALS['obj_info'],$fname,200) ; ?><br><button class="button" cmd="save_list">Сохранить</button></div><?
 }



 function _show_window_ckeditor_v3($rec,$fname,$height=300,$use_element_name='')
 { $element_name=($use_element_name)? $use_element_name:"obj[".$rec['tkey']."][".$rec['clss']."][".$rec['pkey']."][".$fname."]" ;
   $element_id=($use_element_name)? $use_element_name:"obj_".$rec['tkey']."_".$rec['clss']."_".$rec['pkey']."_".$fname ;
   $cur_content=($fname)? $rec[$fname]:'' ;
   ?><textarea name="<?echo $element_name?>" class="ckeditor" id=<?echo $element_id?>><?echo $cur_content?></textarea><?
 }

function show_window_ckeditor_v3($rec,$fname,$height=300,$options=array())
 { $style_file=($options['style_file'])? $options['style_file']:'/style.css' ;
   $use_element_name=(!is_array($options))?  $options:$options['use_element_name'] ;
   if (!is_array($options)) $options=array() ;
   $element_name=($use_element_name)? $use_element_name:"obj[".$rec['tkey']."][".$rec['clss']."][".$rec['pkey']."][".$fname."]" ;
   $element_id=($use_element_name)? $use_element_name:"obj_".$rec['tkey']."_".$rec['clss']."_".$rec['pkey']."_".$fname ;
   $cur_content=($fname)? $rec[$fname]:'' ;
   if ($options['content']) $cur_content=$options['content'] ;
   // если отдаем текст в редактор и там вообще нет <тегов> - заменяем переносы строк на абзац
   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);


   ?><textarea name="<?echo $element_name?>" id=<?echo $element_id?>><?echo $cur_content?></textarea>
     <script type="text/javascript">
       $j(document).ready(function()
       {config=
        {   height: <?echo $height?>,
            contentsCss : "<?echo $style_file?>",
            <?if ($options['editor_config']) echo $options['editor_config'].','?>
            <?if ($_SESSION['CK_editor_toolbar']) echo $_SESSION['CK_editor_toolbar'].','?>
            EnterMode:'p'
        };
        editor = CKEDITOR.replace( '<?echo $element_id?>', config);
       }) ;
       </script>
      <?
 }

 function show_preview_site()
    { global $obj_info ;
      $clss_info=_DOT($obj_info['tkey'])->list_clss_ext[$obj_info['clss']] ;
      $cnt=preg_match_all('#\#(.*?)\##i',$clss_info['page_pattern'],$arr) ;
      //damp_array($arr) ;
      if ($arr[0][0])
       { $page_href=str_replace($arr[0][0],$obj_info[$arr[1][0]],$clss_info['page_pattern']) ;
         //echo $site_patch.$page_href ;
         ?><div style='margin:5px;'>Адрес: <input class='text' name='adress' type='text' value='<?echo _PATH_TO_SITE.'/'.$page_href ?>' size=100></div><?
         ?><iframe src="<?echo _PATH_TO_SITE.'/'.$page_href ?>" name='fra_prev' id=fra_prev  scrolling=auto frameborder=1 width=100% height=600>&nbsp;</iframe><?
       }
    }


  function panel_obj_images()
  {

  }


//-----------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------
// Журнальные таблицы
//-----------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------

 // показ истории по заданному условию
 function show_history($usl_show,$options=array())
  {  $order=($options['order'])? $options['order']:'c_data' ;
     _CLSS(40)->show_list_items(TM_LOG_EVENTS,$usl_show,array('debug'=>0,'default_order'=>$order,'read_only'=>1,'no_check'=>1,'no_icon_edit'=>1,'no_table_header'=>0,'all_enabled'=>1,'no_htmlspecialchars'=>1,'no_view_field'=>'reffer')) ;
  }

 function show_link()
 { global $obj_info ;
   _CLSS(102)->show_list_items(TM_LINK,'',array('cur_obj'=>$obj_info)) ;
 }

 function show_SEO()
 { global $obj_info ;
   $options['no_extended_info']=1 ;
   include_class(36) ;
   //$system=$_SESSION['list_created_sybsystems'][$obj_info['tkey']] ;
   //if ($system and is_object($_SESSION[$system])) damp_array($_SESSION[$system]) ;
     //damp_array($obj_info) ;
   //$meta_info=execSQL('select * from '.$TM_sitemap.' where url like "%'.$obj_info['url_name'].'" and enabled=1 order by url',2) ;
   $url='' ;
   if ($obj_info['__href'])
   {  $url=str_replace(_MAIN_PROTOCOL,'',$obj_info['__href']) ;
      $_usl[]='url="'.$url.'"' ;
   }
   $_usl[]='obj_reffer="'.$obj_info['_reffer'].'"' ;
   $_usl[]='enabled=1' ;
   //damp_array($_usl) ;
   $meta_info=execSQL_van('select * from '.TM_SITEMAP.' where  '.implode(' and ',$_usl).' order by url limit 1') ;
   ?><input type=hidden name=cur_sitemap_page_id value=<?echo $meta_info['pkey']?>><?

   //$this->get_url_item($obj_info) ;

   if (!_sizeof($meta_info))
   { //echo 'Создаем запись для данной страницы в SEO' ;
     adding_rec_to_table_fast(TM_SITEMAP,array('parent'=>1,'clss'=>36,'obj_reffer'=>$obj_info['_reffer'],'url'=>$url),array('debug'=>0)) ;
     $meta_info=execSQL_van('select * from '.TM_SITEMAP.' where obj_reffer="'.$obj_info['_reffer'].'" and enabled=1 order by url limit 1') ;
   }
   // $SEO_info - все страницы связынные с текущим объектом
   $SEO_info=execSQL('select * from '.TM_SITEMAP.' where obj_reffer="'.$obj_info['_reffer'].'" order by url') ;
   unset($SEO_info[$meta_info['pkey']]) ;

   // показываем свойства главной записи в SEO
   _CLSS($meta_info['clss'])->show_props($meta_info,$options) ;

   ?><button class="button" cmd="sitemap_delete_id_reffer_from_rec" params="<?echo $meta_info['pkey']?>" script="ext/sitemap/map_func.php">Удалить связь этой страницы с текущим объектом</button><?


   //$SEO_info=execSQL('select * from '.TM_SITEMAP.' where url like "lux-time.com.ua/catalog/watch/AudemarsPiguet/%" order by url',2) ;
   if (_sizeof($SEO_info))
   { ?><br><br><h1>Другие страницы, связанные с текущим объектом</h1><?
     _CLSS(36)->show_list_items($SEO_info) ;
     //show_standart_button() ; //   show_standart_button - более не используется
     ?><button class="button" cmd="sitemap_delete_check_reffer_from_rec" script="ext/sitemap/map_func.php">Удалить связь отмеченных страниц с текущим объектом</button><?
     ?><button class="button" cmd="sitemap_copy_tags_to_main_page" script="ext/sitemap/map_func.php">Скопировать теги в основную страницу объекта</button><?
   }
 }

 function show_SEO_small()
 { global $obj_info ;
   $options['edit_list']=_CLSS(36)->view['small'] ;
   $options['no_header']=1 ;
   $options['no_extended_info']=1 ;

   $SEO_info=execSQL('select * from '.TM_SITEMAP.' where obj_reffer="'.$obj_info['_reffer'].'" order by url',array('no_indx'=>1)) ;
   if (!_sizeof($SEO_info))
   { //echo 'Создаем запись для данной страницы в SEO' ;
     $new_id=adding_rec_to_table_fast(TM_SITEMAP,array('parent'=>1,'clss'=>36,'obj_reffer'=>$obj_info['_reffer']),array('debug'=>0)) ;
     $SEO_info=execSQL('select * from '.TM_SITEMAP.' where pkey="'.$new_id.'"',array('no_indx'=>1)) ;
   }

   // показываем свойства главной записи в SEO
   _CLSS($SEO_info[0]['clss'])->show_props($SEO_info[0],$options) ;

   if (_sizeof($SEO_info)>1)
   { ?><br><br><h1>Другие страницы, связанные с текущим объектом</h1><?
     unset($SEO_info[0]) ;
     //print_2x_arr($SEO_info) ;
     _CLSS(36)->show_list_items($SEO_info) ;
   }
 }

 function show_db_info()
 { global $obj_info ;
   damp_array($obj_info,1,-1) ;
 }


 //**************************************************************************************************************************************************
 //
 // функции с генерируемыми данными
 //
 //**************************************************************************************************************************************************

  // возвращает путь текущего объекта
  // переделана 27.08.11 на основе функции get_obj_parents_name
  function get_obj_patch(&$rec)
  {  //  $options['include_root_name'] - включать в итоговый массив имя корня дерева, по умолчанию выключена, пока не научимся определять опцию  $_SESSION['init_options']['XXX']['no_root_dir']=1 ;
     $patch=get_obj_parents_name($rec['_reffer'],array('include_root_name'=>1)) ;
     $arr=array() ;
     if (_sizeof($patch)) foreach($patch as $reffer=>$name) $arr[]='<a href="'.get_url_window_object($reffer).'">'.$name.'</a>' ;
     $str=implode(' / ',$arr) ;
     return($str) ;
  }

  // 27.08.11
  // возвращает url окна редактирования объекта
  function get_url_window_object($reffer)
  { global $php_source ;
    list($pkey,$tkey)=explode('.',$reffer) ;
    $url=_PATH_TO_ADMIN.'/'.$php_source.'?tkey='.$tkey.'&pkey='.$pkey.'&rn='.rand(0,1) ;
    return($url) ;
  }

?>
