<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OrdaSoft CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;

if( !class_exists("os_libMain") ){
    try{
        $ss = new os_libMain();
    }catch( Exception $e ){
        die("Please reinstall OrdaSoft Joomla CCK Package!");
    }
}
class Category
{
  static function listCategories($option, $lid = 0, $Itemid = 0){  
    global $app,$os_cck_configuration, $db, $user, $acl, $moduleId, $input, $layouts_type, $doc;
    $db = new os_cckDb();
    $input = $app->input;
    
    $currentcat = NULL;
    $session = JFactory::getSession();
    if(!$moduleId){
        if($Itemid == 0){
            $Itemid = intval($input->get('Itemid'));
        }
      // Params(cck component menu)
      if (version_compare(JVERSION, '3.0', 'ge')) {
        $menu = new JTableMenu($db->_db);
        $menu->load($Itemid);
        $params = new JRegistry;
//        var_dump($menu->params);
        if($menu->params){
            $params->loadString($menu->params);
        }
      } else {
        $app = JFactory::getApplication();
        $menu = $app->getMenu();
        $params = new JRegistry;
        $params = $menu->getParams( $Itemid );
      }//end
    }else{
      $menu = $app->getMenu();
      $mod_row =  JTable::getInstance ( 'Module', 'JTable' );//load module tables and params
      if (! $mod_row->load ( $moduleId )) {
        throw new Exception($mod_row->getError (), 500);
      }
      //module params
      if (version_compare(JVERSION, '3.0', 'ge')) {
        $params = new JRegistry;
        $params->loadString($mod_row->params);
      } else {
        $params = new JRegistry($mod_row->params);
      }//end
      //itemId
      $query = "SELECT id  FROM #__menu WHERE menutype like '%menu%'"
                      . "\n AND link LIKE '%option=com_os_cck%'"
                      . "\n AND params LIKE '%back_button%'"
                      . "\n AND params LIKE '%allcategories_layout%'"
                      . "\n AND published = 1";
      $db->setQuery($query);
      
      if($Itemid == 0){
          $Itemid = $db->loadResult();
          if($params->get('ItemId'))$Itemid=$params->get('ItemId');
      }
         
    }
    
    $allcategories_layout = new os_cckLayout($db->_db);
    $category_layout = new os_cckLayout($db->_db);
    //(expression ? true_value : false_value)
    if($lid){
      $allcategories_layout->load($lid);
    }else{
      $allcategories_layout->load($params->get('layout')?$params->get('layout') : $params->get('allcategories_layout'));
    }
    if ((($allcategories_layout->type != 'all_categories' && $allcategories_layout->type != 'all_categories_pdf') || $allcategories_layout->fk_eid <= 0) ){
        if(!$params->get('layout'))//component or module
            JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ALLCATEGORY_LAYOUT"), 'warning');
        else
            JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_MODULE_ALLCATEGORY_LAYOUT"), 'warning');
        return;    
    }
    //load category layout params
    $fields_from_params = $all_cat_params=unserialize($allcategories_layout->params);
    $entity_id = $allcategories_layout->fk_eid;
    
    if(!isset($fields_from_params['views']['category_layout']) || $fields_from_params['views']['category_layout'] == -1){//we set default lyout
        $defaultCategoryLayout = $category_layout->getDefaultLayout($entity_id, 'category');
        if($defaultCategoryLayout){
            $category_layout->load(intval($defaultCategoryLayout));
            $fields_from_params = unserialize($category_layout->params);
        }else{
            JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
            return;   
        }
    }else{
        $category_layout->load($fields_from_params['views']['category_layout']);
        $fields_from_params = unserialize($category_layout->params);
    }
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$category_layout->fk_eid/custom.css");
    //end category layout params
    $header = $params->get('layout') ? "" : set_header_name_cck($menu, $Itemid);
    $params->def('header', $header);
    $params->def('pageclass_sfx', '');
    $params->def('show_search', '1');
    $params->def('back_button', $app->getCfg('back_button'));
        $custom_sql_where = '';
      if(isset($all_cat_params['views']['request_layout_sql_show']) && !empty($all_cat_params['views']['request_layout_sql_show'])){
          foreach ($all_cat_params['views']['request_layout_sql_show'] as $temp_lid => $request_layout){
              foreach($request_layout as $sql_show){
                  if(isset($all_cat_params['views']['sql_where_type'][$temp_lid]) && $all_cat_params['views']['sql_where_type'][$temp_lid] == 'PHP'){
                      eval($sql_show);
                      $custom_sql_where .= ' ' . $sql_where_string . ' ';
                  }else{
                      $custom_sql_where .= ' ' . $sql_show . ' ';
                  }

              }
          } 
      }
//    $custom_sql_where = '';
//    if(isset($all_cat_params['views']['request_layout_sql_show']) && !empty($all_cat_params['views']['request_layout_sql_show'])){
//        foreach ($all_cat_params['views']['request_layout_sql_show'] as $request_layout){
//            foreach($request_layout as $sql_show){
//                $custom_sql_where .= ' ' . $sql_show . ' ';
//            }
//        } 
//    }
    $lang_where = '';
    $lang = JFactory::getLanguage();
      
      if(JLanguageMultilang::isEnabled()){
          if($allcategories_layout->language != '' && $allcategories_layout->language != '*'){
              if($allcategories_layout->language != $lang->getTag()){
                  $layout_assoc_list = unserialize($allcategories_layout->associate_layout);
                  if(isset($layout_assoc_list[$lang->getTag()])){
                      $lid = $layout_assoc_list[$lang->getTag()];
                      $allcategories_layout->load($lid);
                  }
              }
              $lang_where = " and ( c.language = '".$lang->getTag()."' or c.language like '*' or c.language like '' "
                 . " or c.language is null) ";
         
          }
          
      }
//    $lang = $allcategories_layout->language;
//    if($lang != '' && $lang != '*'){
//        $lang_where = " AND(c.language='$lang' || c.language='' || c.language='*' )";
//    }else{
//        $lang_where = "";
//    }
    $ordering = (isset($all_cat_params['views']['request_layout_categories_sort']))? $all_cat_params['views']['request_layout_categories_sort'] : 'ordering';

    $query = "SELECT c.*,(SELECT COUNT(ccc.fk_eiid) FROM #__os_cck_categories_connect AS ccc "
                            . "\n INNER JOIN #__os_cck_entity_instance AS cei ON ccc.fk_eiid=cei.eiid "
                            . "\n INNER JOIN #__os_cck_layout AS ley ON ley.lid = cei.fk_lid "
                            . "\n WHERE ccc.fk_cid=c.cid AND ley.type = 'add_instance' AND cei.fk_eid = '".$allcategories_layout->fk_eid."') AS items, '0' as display "
                            . "\n FROM  #__os_cck_categories AS c "
                            . "\n WHERE c.section='com_os_cck' "
                            . "\n AND c.published = '1' $custom_sql_where $lang_where "
                            . "\n ORDER BY c.".$ordering;
    $db->setQuery($query);
    $cat_all = $db->loadObjectList('cid');
    foreach ($cat_all as $key => $cat){
        
        if($cat->fk_eid == $allcategories_layout->fk_eid || $cat->fk_eid == '0'){
            $cat_temp[$key] = $cat;
        }
    }
    $cat_all = $cat_temp;
    
    // for ($i = 0; $i < count($cat_all); $i++) {
    foreach($cat_all as $key => $cat){
      if (os_cck_site_controller::is_exist_curr_and_subcategory_items($cat->cid, $allcategories_layout->fk_eid, $cat_all, false )) {
        $cat_all[$key]->display = 1;
        if($fields_from_params['views']['sub_category_level'] == 0 && $cat->parent_id > 0 && isset($cat->display))
            $cat_all[$key]->display = 0;
      }
    }

    $user = JFactory::getUser();
    $categories= array();
    foreach($cat_all as $key => $cat){
//    for ($i = 0; $i < count($cat_all); $i++) {
      if (($cat->params !== implode(',',array_diff(explode(',',$cat->params),$user->groups)))
          || $cat->params == 1) {
          $categories[]=$cat_all[$key];
      }
    } 
    
    if (empty($categories))
        JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_NOCAT_ALLCATEGORY_LAYOUT"), 'warning');
    $currentcat = new stdclass();
    $currentcat->header = $params->get('header');
    // page description
    $currentcat->descrip = cck_lang_text("COM_OS_CCK_DESC");
    // used to show table rows in alternating colours
    $tabclass = array('sectiontableentry1', 'sectiontableentry2');
    $params->set('all_cat_layout_params',$all_cat_params);
    $params->set('cat_layout_params',$fields_from_params);
    $layout_params = unserialize($allcategories_layout->params);
    $layout_params['custom_fields'] = unserialize($allcategories_layout->custom_fields);
    $layout_params['all_cat_layout_params'] = $fields_from_params;
    $bootstrap_version = $session->get( 'bootstrap','2');
    $allcategories_layout->layout_html = $allcategories_layout->getLayoutHtml($bootstrap_version);
    if(isset($layout_params['attachedModuleIds'])){
      $layout_params['attachedModule'] = explode('|_|',$layout_params['attachedModuleIds']);
      $mids = array();
      foreach ($layout_params['attachedModule'] as $attachedModuleId) {
        if($attachedModuleId){
          $mids[] = $attachedModuleId;
        }
      }
      if($mids){
        $mids = str_replace('m_', '', $mids);
        $mids = implode(',', $mids);
        $query = "SELECT id, title, module as type FROM #__modules WHERE id IN (" . $mids . ")";
        $db->setQuery($query);
        $layout_params['attachedModule'] = $db->loadObjectList('id');
      }
    }

    if($allcategories_layout->type == 'all_categories'){
      ViewCategory::showCategories($option, $categories ,$allcategories_layout , $layout_params, $Itemid, $cat_all, $params, $menu, $category_layout);
    }elseif($allcategories_layout->type == 'all_categories_pdf'){
        os_cck_site_controller::displayCckPdf($categories, array(), $allcategories_layout, $layout_params);
    }
  }


  static function showCategory($option, $catid, $lid,$parent_layout_params = 0, $mod_type = 0, $return = false, $Itemid = 0, $layout_html = '', $cat_all1 = false, $params = false, $menu = false){ 

    global $app, $db, $acl, $user, $doc, $session, $cck_entity_configuration, $entityFieldLists;
    global $os_cck_configuration, $limit, $total, $limitstart,$moduleId ,$session;

    $db = new os_cckDb();
    $app = JFactory::getApplication();
    $input = $app->input;
    // var_dump($catid);
    
    $moduleId =(($moduleId == 0
                 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    $category = new os_cckCategory($db->_db);
    $category->load($catid);
    
    
    $task = $input->get('view', '', 'STRING');
    
    $currentcat = NULL;
    
    if(!$params){
        if(!$moduleId){
          
            if($Itemid == 0){
                $Itemid = intval($input->get('Itemid', 0, 'INT'));
            }
          // Params(cck component menu)
          $menu = new JTableMenu($db->_db);
          $menu->load($Itemid);
          $params = new JRegistry;
          if($menu->params){
              $params->loadString($menu->params);
          }
        }else{

          $mod_row =  JTable::getInstance ( 'Module', 'JTable' );//load module tables and params

          if (! $mod_row->load ( $moduleId )) {
            throw new Exception($mod_row->getError (), 500);
          }
          //module params
          $params = new JRegistry;
          $params->loadString($mod_row->params);
          //itemId


          $value = ($params->get('layout_type') == 'category')?
                                  'category_layout' : 'map_category_layout';

          $query = "SELECT id  FROM #__menu WHERE menutype like '%menu%'"
                          . "\n AND link LIKE '%option=com_os_cck%'"
                          . "\n AND params LIKE '%back_button%'"
                          . "\n AND params LIKE '%".$value."%'"
                          . "\n AND published = 1";
          $db->setQuery($query);
          if($Itemid == 0){
              $Itemid = $db->loadResult();
               if($params->get('ItemId'))$Itemid=$params->get('ItemId');
          }
        }
    }

    
    $entity_layout = new os_cckLayout($db->_db);
    $category_layout = new os_cckLayout($db->_db);

    
    if(!is_object($lid) && (!$lid || $lid == -1)){
      if($params->get('allcategories_layout') || $params->get('layout_type') == 'all_categories'){
        $all_category_layout = new os_cckLayout($db->_db);
        $all_category_layout->load($params->get('layout')?
                                   $params->get('layout') : $params->get('allcategories_layout'));
        $fields_from_params = unserialize($all_category_layout->params);
        $entity_id = $all_category_layout->fk_eid;
        if($fields_from_params['views']['category_layout'] == -1){//we set default lyout
          if($category_layout->getDefaultLayout($entity_id, 'category')){
            $category_layout->load(intval($category_layout->getDefaultLayout($entity_id, 'category')));
            $fields_from_params = unserialize($category_layout->params);
          }else{
            JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
            return;   
          }
        }else{
          $category_layout->load($fields_from_params['views']['category_layout']);
          if(!$category_layout->lid){
            JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
            return;
          }
          $fields_from_params = unserialize($category_layout->params);
        }
      }//end all_cat menu
      //from category menu
      
      if($params->get('layout') || $params->get('layout_type') == 'category' || $params->get('category_layout') ){
        
        $category_layout->load($params->get('layout')?$params->get('layout') : $params->get('category_layout'));
        
        if(!$category_layout->published){
            JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
            return;
        }
        if($category_layout->params){
          $fields_from_params = unserialize($category_layout->params);
        }else{
          $fields_from_params = array();
        }
        $entity_id = $category_layout->fk_eid;
        if (!$entity_id){
          if(!$params->get('layout'))//component or module
              JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_CATEGORY_LAYOUT"), 'warning');
          else
              JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_MODULE_CATEGORY_LAYOUT"), 'warning');
          return;
        }
        if($catid == 0){
           $catid = $params->get('layout')?$params->get('item') : $params->get('category');
           if(!$catid) $catid = $params->get('category');
        }
        if($catid < 1){
          if(isset($cck_entity_configuration[$entity_id]['redirect_missing_category']) && $cck_entity_configuration[$entity_id]['redirect_missing_category'] != ''){
            if(stripos($cck_entity_configuration[$entity_id]['redirect_missing_category'], 'http://') != false || stripos($cck_entity_configuration[$entity_id]['redirect_missing_category'], 'https://') != false){
              $redirect_url = $cck_entity_configuration[$entity_id]['redirect_missing_category'];
            }else{
              $redirect_url = JUri::root() . $cck_entity_configuration[$entity_id]['redirect_missing_category'];
            }
  
            $app->redirect($redirect_url);
          }
          if(!$params->get('layout'))//component or module
              JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_CATEGORY"), 'warning');
          else
              JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_MODULE_CATEGORY"), 'warning');
          return;
        }
        $category->load($params->get('category'));
        // var_dump($params->get('category'));
        // if($params->get('category_layout'))
        //     $category->load($params->get('category'));
        // else
        //     $category->load($params->get('item'));
      }//end category menu
      //var_dump($_REQUEST); exit;
      $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$category_layout->fk_eid/custom.css");
      $catid = ($catid == 0) ? $params->get('category') : $catid;
      $search_layout = new os_cckLayout($db->_db);
      $search_layout->load($entity_layout->getDefaultLayout($entity_id, 'search'));
      if($search_layout->published == 0){
          $params->def('show_search','0');
      }else{
          $params->def('show_search','1');
      }//end show serch
    }else{
      if(is_object($lid)){
        $category_layout = $lid;
      }else{
        $category_layout->load($lid);
      }
      if($category_layout->params){
        $fields_from_params = unserialize($category_layout->params);
      }else{
        $fields_from_params = array();
      }
      $entity_id = $category_layout->fk_eid;
    }
    
//    var_dump($category);
    if(isset($cck_entity_configuration[$category_layout->fk_eid]['meta_title_source']) && $cck_entity_configuration[$category_layout->fk_eid]['meta_title_source'] === '0'){
        $doc->setTitle('');
    }elseif(isset($cck_entity_configuration[$category_layout->fk_eid]['meta_title_source']) && $cck_entity_configuration[$category_layout->fk_eid]['meta_title_source'] === '2'){
        if($category->meta_title != ''){
            $doc->setTitle($category->meta_title);
        }elseif($category->title != ''){
            $doc->setTitle($category->title);
        }else{
            $doc->setTitle('');
        }
    }

    if(isset($cck_entity_configuration[$category_layout->fk_eid]['meta_description_source']) && $cck_entity_configuration[$category_layout->fk_eid]['meta_description_source'] === '0'){
        $doc->setDescription('');
    }elseif(isset($cck_entity_configuration[$category_layout->fk_eid]['meta_description_source']) && $cck_entity_configuration[$category_layout->fk_eid]['meta_description_source'] === '2'){
        $doc->setDescription($category->meta_description);
    }

    if(isset($cck_entity_configuration[$category_layout->fk_eid]['meta_keywords_source']) && $cck_entity_configuration[$category_layout->fk_eid]['meta_keywords_source'] === '0'){
        $doc->setMetaData('keywords','');
    }elseif(isset($cck_entity_configuration[$category_layout->fk_eid]['meta_keywords_source']) && $cck_entity_configuration[$category_layout->fk_eid]['meta_keywords_source'] === '2'){
        $doc->setMetaData('keywords',$category->meta_keywords);
    }
    
    $lang_where = '';
      if(JLanguageMultilang::isEnabled()){
          $category_layout = setLayoutLangCCK($category_layout);
          $lang_where = getCCKLangWhere();
          
      }

      
    if($category_layout->type != 'all_categories' && $category_layout->type != 'category' && $category_layout->type != 'category_pdf'){
      JFactory::getApplication()->enqueueMessage("Layout type load error Category | All Category layout ID: ".$category_layout->lid, 'warning');
      return;
    }
    $category_layout->layout_html = $category_layout->getLayoutHtml('2');
      $lay_html = urldecode($category_layout->layout_html);
      
      
      $limit = (isset($fields_from_params['views']['pagenator_limit']) && strpos($lay_html,"{|f-joom_pagination|}")) ? $fields_from_params['views']['pagenator_limit'] : 0;
//    $limit = (isset($fields_from_params['views']['pagenator_limit'])) ? $fields_from_params['views']['pagenator_limit'] : 0;

    if(isset($fields_from_params['views']['limit'])){
        $max_items = $fields_from_params['views']['limit'];
    }else{
        $max_items = 0;
    }

    
    if(isset($catid) && !empty($catid)){ //is not isset category (skip access checking)

      $db->setQuery("SELECT * FROM `#__os_cck_categories` e WHERE e.`cid` = {$catid}");
      $carCatParams =$db->loadObjectList();
      if(!$carCatParams){
        JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_CATEGORY"), 'warning');
        return;
      }


      $carCatParams = $carCatParams[0];
      //user access to category
      $user = JFactory::getUser();
      if (($carCatParams->params == implode(',',array_diff(explode(',',$carCatParams->params),$user->groups)))
          && $carCatParams->params != 1) {
          JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_CATEGORY"), 'warning');
          return;
      }//end  
    }

    if($category_layout->fk_eid){
        $entity_name = $category_layout->fk_eid;
    }else{
        return;
    }
    
if($input->get('option', '') == 'com_os_cck'){
    //creating order by list
    $fields_from_params = getOrderByOptions('category_order_by', $fields_from_params, $entity_id, $mod_type, $category_layout->lid);

    $header = $params->get('layout') ? "$category_layout->title" : set_header_name_cck($menu, $Itemid);
    $params->def('header', $header);
    $params->def('pageclass_sfx', '');
    $params->def('category_name', $category->name);
}
    //alfabetical pagination

    $sp = 0;
    if (array_key_exists("sp", $_REQUEST)){
      $sp = JFactory::getApplication()->input->getInt('sp', 0);
    }
    $where = '';
    $list_str = array();
    if (array_key_exists("letindex", $_REQUEST)) {
        $search = JFactory::getApplication()->input->getCmd("letindex",'');

        if(isset($_REQUEST['now_indexed']) && $search != 'all'){

          if($sp == 1 && $_REQUEST['now_indexed'] == $fields_from_params["views"]["selected"]){
            $where = " AND LOWER(instance." . $_REQUEST['now_indexed'] . ") LIKE '$search%' ";
          }else{
            $where = '';
          }
        }
    }
//    foreach ($fields_from_params as $par){
//        var_dump($par);
//    }
    
//    $custom_sql_where = '';
//    if(isset($fields_from_params['views']['request_layout_sql_show']) && !empty($fields_from_params['views']['request_layout_sql_show'])){
//        foreach ($fields_from_params['views']['request_layout_sql_show'] as $request_layout){
//            foreach($request_layout as $sql_show){
//                $custom_sql_where .= ' ' . $sql_show . ' ';
//            }
//        } 
//    }
    $custom_sql_where = '';
    if(isset($fields_from_params['views']['request_layout_sql_show']) && !empty($fields_from_params['views']['request_layout_sql_show'])){
        foreach ($fields_from_params['views']['request_layout_sql_show'] as $temp_lid => $request_layout){
            foreach($request_layout as $sql_show){
                if(isset($fields_from_params['views']['sql_where_type'][$temp_lid]) && $fields_from_params['views']['sql_where_type'][$temp_lid] == 'PHP'){
                    eval($sql_show);
                    $custom_sql_where .= ' ' . $sql_where_string . ' ';
                }else{
                    $custom_sql_where .= ' ' . $sql_show . ' ';
                }

            }
        } 
    }
    //user access
    if($entity_id > 0 && isset($cck_entity_configuration[$entity_id]) && $cck_entity_configuration[$entity_id]['check_access_instances'] == 0){
        $access_where = '';
    }else{
        $access_where = ' AND (' . getWhereUsergroupsConditionCCK('ei') . " or ei.access='' OR " . getWhereUsergroupsConditionWithoutLikeCCK('ei') . ") ";
    }

    if(isset($fields_from_params["views"]["child_instancies_sub_category_level"]) && $fields_from_params["views"]["child_instancies_sub_category_level"] == 1){
        $where_cat = " AND (c.cid={$catid} OR c.parent_id={$catid})";
    }else{
        $where_cat = " AND c.cid={$catid} ";
    }
    
    if(isset($fields_from_params["views"]["selected"]) && strstr($fields_from_params["views"]["selected"], 'text_textfield') !== false){

       $query = " SELECT DISTINCT UPPER(SUBSTRING(instance.".$fields_from_params["views"]["selected"].", 1,1)) AS symb FROM  #__os_cck_entity_instance AS ei "
          . "\n LEFT JOIN #__os_cck_categories_connect AS ccc ON ccc.fk_eiid=ei.eiid "
           . "\n LEFT JOIN #__os_cck_categories AS c ON ccc.fk_cid=c.cid "
          . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid=ei.fk_lid "
          . "\n LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
          . "\n LEFT JOIN `#__os_cck_content_entity_$entity_name` as instance ON instance.`fk_eiid` = ei.eiid "
          . "\n WHERE ei.published='1' "
          . "\n AND ei.approved='1' "
          . "\n AND lay.type='add_instance' "
          . "\n $where_cat "
          . "\n AND ei.fk_eid='" . $entity_id . "' $access_where $custom_sql_where $lang_where GROUP BY ei.eiid ORDER BY symb"; 
  
        $db->setQuery($query);
        $tmp_arr = $db->loadObjectList();
        
        if(count($tmp_arr)>1){

          $symb_list_str = '<ul>';
          foreach($tmp_arr as $symbol){

            if(empty($symbol->symb)){
              continue;
            }

          $symb_list_str.= '<li><a href="index.php?option=' . $option . 
          '&view=category&letindex=' . $symbol->symb . '&sp=1&Itemid=' . $Itemid . 
            '&now_indexed=' . $fields_from_params["views"]["selected"] . '&catid=' . $catid . '">' . 
          $symbol->symb . '</a></li> ';
            
          }

          //check string not empty
          $temp_var =  strip_tags($symb_list_str) ;
          if(!empty($temp_var) ){
            $symb_list_str.= '<li><a href="index.php?option=' . $option . 
            '&view=category&letindex=all&sp=1&Itemid=' . $Itemid . 
            '&now_indexed=' . $fields_from_params["views"]["selected"] . '">all</a></li> ';
          }
          
          $symb_list_str.= "</ul>";
          $list_str['symbol_list'] = $symb_list_str;
        }else{
          $list_str['symbol_list'] = false;
        }
    }else{
      $list_str['symbol_list'] = false;
    }

    //end alfabetical pagination

     //$layout_params = unserialize($layout->params);
     $featured = (isset($layout_params['views']['featured'])?$layout_params['views']['featured']:'0');

        //check featured layout or not
      if ( (isset($featured) && $featured != 0)  ){
        $where .= " AND ( ei.featured_clicks > 0 || ei.featured_shows > 1 ) ";
      } 
      

    $query = " SELECT COUNT(DISTINCT ei.eiid) FROM  #__os_cck_entity_instance AS ei "
            . "\n LEFT JOIN #__os_cck_categories_connect AS ccc ON ccc.fk_eiid=ei.eiid "
             . "\n LEFT JOIN #__os_cck_categories AS c ON ccc.fk_cid=c.cid "
            . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid=ei.fk_lid "
            . "\n LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
            . "\n LEFT JOIN `#__os_cck_content_entity_$entity_name` as instance ON instance.`fk_eiid` = ei.eiid "
            . "\n WHERE ei.published='1' "
            . "\n AND ei.approved='1' "
            // . "\n AND ei.featured_clicks!='0' "
            // . "\n AND ei.featured_shows!='0' "
            . "\n AND lay.type='add_instance' "
            . "\n $where_cat "
            . "\n AND ei.fk_eid='" . $entity_id . "' $where $access_where $custom_sql_where $lang_where";
    $db->setQuery($query);
    $total = $db->loadResult();

    if($max_items != '0' && $max_items < $total ) {
      if($limit > $max_items )$limit = $max_items;
      $total = $max_items;
    }


//var_dump($fields_from_params);
//     if( isset($fields_from_params['views']['selected']) && 
//         ( !isset( $fields_from_params['fields']['order_by_fields_category_order_by'] ) || !is_array( $fields_from_params['fields']['order_by_fields_category_order_by'] ) ||
//          ( is_array( $fields_from_params['fields']['order_by_fields_category_order_by'] ) && !in_array($fields_from_params["views"]["selected"],$fields_from_params['fields']['order_by_fields_category_order_by'])
//          ) 
//         )
//        )
//     {
//
//        $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_category_order_by"])?$fields_from_params["fields"]["indexed_category_order_by"]:'';
//    }
    // var_dump()
    $pageNav = new os_libPagination($total, $limitstart, $limit);
    $query = " SELECT ei.eiid FROM  #__os_cck_entity_instance AS ei "
            . "\n LEFT JOIN #__os_cck_categories_connect AS ccc ON ccc.fk_eiid=ei.eiid "
             . "\n LEFT JOIN #__os_cck_categories AS c ON ccc.fk_cid=c.cid "
            . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid=ei.fk_lid "
            . "\n LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
            . "\n LEFT JOIN `#__os_cck_content_entity_$entity_name` as instance ON instance.`fk_eiid` = ei.eiid "
            . "\n WHERE ei.published='1' "
            . "\n AND ei.approved='1' "
            . "\n AND lay.type='add_instance' "
            . "\n $where_cat "
            . "\n AND ei.fk_eid='" . $entity_id . "' $where $access_where $custom_sql_where $lang_where ";
        if(isset($fields_from_params["fields"]["indexed_category_order_by"])){ // if selected sortable field
            
            $orderby = (!empty($fields_from_params["views"]["sortType_category_order_by"])) ? $fields_from_params["views"]["sortType_category_order_by"] : 'ASC';
            if($orderby != 'RAND()') {
                if (isset($fields_from_params["views"]["selected"]) && !empty($fields_from_params["views"]["selected"])) {

                    $index = 0;
                    if (isset($fields_from_params['views']['show_request_layout'])) {

                        foreach ($fields_from_params['views']['show_request_layout'] as $key => $val) {
                            $request_layout = new os_cckLayout($db->_db);
                            $request_layout->load($key);
                            $request_layout_fields_params = unserialize($request_layout->params);
                            $views_selected = $fields_from_params["views"]["selected"] . '_average';
                            if ($request_layout->type == 'instance' && $index == 0) {

                                if ($fields_from_params["views"]["selected"] == 'title') {
                                    $query .= " GROUP BY ei.eiid ORDER BY ei.title $orderby ";
                                } elseif ($fields_from_params["views"]["selected"] == 'hits') {

                                    $query .= " GROUP BY ei.eiid ORDER BY ei.hits $orderby";
                                } elseif ($fields_from_params["views"]["selected"] == 'last_review') {

                                    $query .= " GROUP BY ei.eiid ORDER BY ei.last_review $orderby";
                                }elseif ($fields_from_params["views"]["selected"] == 'custom_order') {
                                    $query .= ' GROUP BY ei.eiid ' . $fields_from_params['views']['custom_order_by'][0] . " $orderby ";
                                } elseif (stripos($fields_from_params["views"]["selected"], 'pricefield_number_') !== false) {

                                    $query .= " AND price.fk_fid = " . str_replace('pricefield_number_', '', $fields_from_params["views"]["selected"]) . " GROUP BY ei.eiid ORDER BY price.price_value $orderby";
                                } elseif (stripos($fields_from_params["views"]["selected"], 'rating_field') !== FALSE && isset($request_layout_fields_params['fields'][$views_selected]) && $request_layout_fields_params['fields'][$views_selected] == 'on') {
                                    $query = "SELECT  ei.eiid,ccc.fk_cid,AVG(instance2.`" . $fields_from_params['views']['selected'] . "`) as rating FROM  #__os_cck_entity_instance AS ei "
                                        . "\n LEFT JOIN #__os_cck_categories_connect AS ccc ON ccc.fk_eiid=ei.eiid "
                                        . "\n LEFT JOIN #__os_cck_categories AS c ON ccc.fk_cid=c.cid "
                                        . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid=ei.fk_lid "
                                        . "\n LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
                                        . "\n LEFT JOIN `#__os_cck_content_entity_$entity_name` as instance ON instance.`fk_eiid` = ei.eiid "
                                        . "\n LEFT JOIN #__os_cck_child_parent_connect AS cpc ON cpc.fid_parent=ei.eiid "
                                        . "\n LEFT JOIN `#__os_cck_content_entity_$entity_name` as instance2 ON instance2.`fk_eiid` = cpc.fid_child "
                                        . "\n WHERE ei.published='1' "
                                        . "\n AND ei.approved='1' "
                                        . "\n AND lay.type='add_instance' "
                                        . "\n AND $where_cat "
                                        . "\n AND ei.fk_eid='" . $entity_id . "' $where $access_where $custom_sql_where $lang_where "
                                        . "\n GROUP BY ei.eiid "
                                        . "\n ORDER BY rating $orderby";

                                } else {
                                    $query .= " GROUP BY ei.eiid ORDER BY instance.`{$fields_from_params["views"]["selected"]}` $orderby ";
                                }
                                $index++;
                            }

                        }
                    } else {
                        $query .= " GROUP BY ei.eiid ";
                    }
                } elseif ($fields_from_params["fields"]["indexed_category_order_by"] == 'eid') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.eiid $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_category_order_by"] == 'title') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.title $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_category_order_by"] == 'hits') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.hits $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_category_order_by"] == 'last_review') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.last_review $orderby ";
                }elseif (stripos($fields_from_params["fields"]["indexed_category_order_by"], 'pricefield_number_') !== false) {

                    $query .= " AND price.fk_fid = " . str_replace('pricefield_number_', '', $fields_from_params["fields"]["indexed_category_order_by"]) . " GROUP BY ei.eiid ORDER BY price.price_value $orderby";
                } elseif ($fields_from_params["fields"]["indexed_category_order_by"] == 'custom_order') {
                    $query .= ' GROUP BY ei.eiid ' . $fields_from_params['views']['custom_order_by'][0] . " $orderby ";
                } else { // for other fields
                    $query .= " GROUP BY ei.eiid ORDER BY instance.`{$fields_from_params["fields"]["indexed_category_order_by"]}` $orderby ";
                }
            }else{
                $query .= " ORDER BY $orderby ";
            }
        }else{
            $query .= " GROUP BY ei.eiid ";
        }
    $session = JFactory::getSession();
    $session->set( 'queryItemIds', $query );//need for pagination in instances//we save our query to know how to sort ourinstance//
    $query_no_limit = $query;
    $query .= " LIMIT $pageNav->limitstart, $pageNav->limit ";
  //  print_r($query); //exit;
    $db->setQuery($query);

    $items = (version_compare(JVERSION, "3.0.0", "lt")) ? $db->loadResultArray() : $db->loadColumn();

    $db->setQuery($query_no_limit);
    $no_limit_items = $db->loadObjectList();

    $no_limit_items_arr = $session->get('no_limit_items_arr', array());

//      foreach($fields_from_params['views']['show_request_layout'] as $show_request_layout_lid => $show_request_layout){
        $no_limit_items_arr[$category_layout->lid] = $no_limit_items;
//      }
    $session->set( 'no_limit_items_arr', $no_limit_items_arr );
//    $session->set( 'last_overall_layout.', $lid );
//    $query .= " LIMIT $pageNav->limitstart, $pageNav->limit ";
//    $db->setQuery($query); 
//    $items = (version_compare(JVERSION, "3.0.0", "lt")) ? $db->loadResultArray() : $db->loadColumn();
    $instancies = array();
    // var_dump($items);
    foreach ($items as $item) {
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($item);
        $instancies[] = $instance;
    }
    
    //////////////////////////////////////////////////////////////////
    if(!$cat_all1){
        $query = " SELECT c.*, (SELECT COUNT(ccc.fk_cid) "
                . "\n FROM #__os_cck_categories_connect AS ccc WHERE ccc.fk_cid=c.cid) AS items, '0' AS display "
                . "\n FROM  #__os_cck_categories AS c FORCE INDEX (section_ordering) WHERE section='com_os_cck' ORDER BY ordering ";
        $db->setQuery($query);
        $cat_all1 = $db->loadObjectList('cid');
    }
    
    if (count($cat_all1) > 0) {
        foreach ($cat_all1 as $cat_item1) {
            $categories[] = $cat_item1;
        }

        foreach($categories as $key => $cat){
          if (os_cck_site_controller::is_exist_curr_and_subcategory_items($cat->cid, $entity_id, $cat_all1, false)) $categories[$key]->display = 1;
        }
    } else $categories = array();
//var_dump($mod_type);
    os_cck_site_controller::cck_constructPathway($category, 'category', $mod_type);
    $params->def('show_rating', 1);
    $params->def('hits', 1);
    $params->def('back_button', $app->getCfg('back_button'));
    $currentcat = new stdclass();

    $currentcat->descrip = $category->description;
    // page image
    $currentcat->img = null;
    $path = JURI::root() . 'images/os-cck/';
    // var_dump(file_exists(JPATH_SITE . '/images/os-cck/' .$category->image));
    if ($category->image != null && $category->image != '' && file_exists(JPATH_SITE . '/images/os-cck/' .$category->image)) {
        $currentcat->img = $path . $category->image;
        $currentcat->align = $category->image_position;
    }
    $currentcat->header = $params->get('header');
    $currentcat->header = $currentcat->header . ": " . $category->title;
    $currentcat->title = $category->title;
    $currentcat->inst_count = getInstanceCountInCategory($category->cid, $category_layout->fk_eid);


    $tabclass = array('sectiontableentry1', 'sectiontableentry2');
    if(!$instancies && isset($layout_params['views']['subcategories_layout']) && $layout_params['views']['subcategories_layout'] == -1 && !os_cck_site_controller::is_exist_curr_and_subcategory_items($catid,$entity_id,$cat_all1, false)){
        echo '<div style="text-align:center"><h2>'.cck_lang_text("COM_OS_CCK_CATEGORY_IS_EMPTY").'</h2></div>';
    }
    $layout_params = unserialize($category_layout->params);
    $layout_params['custom_fields'] = unserialize($category_layout->custom_fields);
    $layout_params['cat_layout_params'] = $fields_from_params;
    $bootstrap_version = $session->get( 'bootstrap','2');
    if(!property_exists($category_layout, 'layout_html')){
        $category_layout->layout_html = $category_layout->getLayoutHtml($bootstrap_version);
    }
    $layout_params['parent_layout_params'] = $parent_layout_params;
    $layout_params['catid'] = $catid;
    
    if(isset($layout_params['attachedModuleIds'])){
      $layout_params['attachedModule'] = explode('|_|',$layout_params['attachedModuleIds']);
      $mids = array();
      foreach ($layout_params['attachedModule'] as $attachedModuleId) {
        if($attachedModuleId){
          $mids[] = $attachedModuleId;
        }
      }
      if($mids){
        $mids = str_replace('m_', '', $mids);
        $mids = implode(',', $mids);
        $query = "SELECT id, title, module as type FROM #__modules WHERE id IN (" . $mids . ")";
        $db->setQuery($query);
        $layout_params['attachedModule'] = $db->loadObjectList('id');
      }
    }
    //var_dump($layout_params['views']); exit;
    if(isset($layout_params['views']['subcategories_layout']) && $layout_params['views']['subcategories_layout'] == -1){
        
        $layout =  new os_cckLayout($db->_db);
        $layout_params['views']['subcategories_layout'] = $layout->getDefaultLayout($entity_id, 'category_pdf');
        
    }
    $is_exist_sub_categories = os_cck_site_controller::is_exist_curr_and_subcategory_items($catid, $entity_id, $cat_all1, false); 

    $layout = $category_layout;
    
    if($layout->type == 'category'){
        $type = 'category';
        require getLayoutPathCCK::getLayoutPathCom($option, $type);
    }elseif($layout->type == 'category_pdf'){
        if(!$return){
            os_cck_site_controller::displayCckPdf($category, $instancies, $layout, $layout_params);
        }else{
            return array('instancies' => $instancies, 'layout' => $layout, 'layout_params' => $layout_params);
        }
    }
  }
  
  static function showSearch($option, $catid,$lid = 0, $Itemid = 0){ 

    global $app, $db, $acl, $user, $os_cck_configuration, $limit, $total, $limitstart,$moduleId,$entityFieldLists,$entities_type, $input, $doc;
    $db = new os_cckDb();

    $moduleId =(($moduleId == 0|| empty($moduleId)) 
                  && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    $session = JFactory::getSession();
    if(!$moduleId){
        if($Itemid == 0){
            $Itemid = $input->get('Itemid', 0, 'INT');//id our menu
        }
      // Params(cck component menu)
      $menu = new JTableMenu($db->_db);
      $menu->load($Itemid);
      $params = new JRegistry;
      if($menu->params){
        $params->loadString($menu->params);
      }
    }else{
      $mod_row =  JTable::getInstance ( 'Module', 'JTable' );//load module tables and params
      if (! $mod_row->load ( $moduleId )) {
        throw new Exception($mod_row->getError (), 500);
      }
      //module params
      $params = new JRegistry;
      $params->loadString($mod_row->params);
      //itemId
      $query = "SELECT id  FROM #__menu WHERE menutype like '%menu%'"
                      . "\n AND link LIKE '%option=com_os_cck%'"
                      . "\n AND params LIKE '%search_layout%'"
                      . "\n AND link LIKE '%show_search%'"
                      . "\n AND published = 1";
      $db->setQuery($query);
      if($Itemid == 0){
        $Itemid = $db->loadResult();
        if($params->get('ItemId'))$Itemid=$params->get('ItemId');
      }
      if(!$Itemid){
          $Itemid = $input->get('Itemid', 0, 'INT');//id our menu
      }
    }
    $layout = new os_cckLayout($db->_db);
    $category_layout = new os_cckLayout($db->_db);
    $fromSearch = 1;
    //end params
    
    if(!$lid){
      if($params->get('layout') || $params->get('layout_type') == 'search' || $params->get('search_layout') ){
        $layout->load($params->get('layout')?$params->get('layout') : $params->get('search_layout'));
        if(!$layout->lid || !$layout->published){
          JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_SEARCH_LAYOUT"), 'warning');
          return;   
        }
      }//end search menu
    }else{
      $layout->load($lid);
    }
    if (!$layout->lid){
      JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_SEARCH_LAYOUT"), 'warning');
      return;
    }
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$layout->fk_eid/custom.css");
    $layout_params = unserialize($layout->params);
    $layout_params['custom_fields'] = unserialize($layout->custom_fields);
    $bootstrap_version = $session->get( 'bootstrap','2');
    $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
    $layout_params['catid'] = $catid;
    if(isset($layout_params['attachedModuleIds'])){
      $layout_params['attachedModule'] = explode('|_|',$layout_params['attachedModuleIds']);
      $mids = array();
      foreach ($layout_params['attachedModule'] as $attachedModuleId) {
        if($attachedModuleId){
          $mids[] = $attachedModuleId;
        }
      }
      if($mids){
        $mids = str_replace('m_', '', $mids);
        $mids = implode(',', $mids);
        $query = "SELECT id, title, module as type FROM #__modules WHERE id IN (" . $mids . ")";
        $db->setQuery($query);
        $layout_params['attachedModule'] = $db->loadObjectList('id');
      }
    }
    
    $ids = array();
    foreach($layout_params['search_params'] as $key => $var){
      if(isset($var["fid"]))$ids[] = $var["fid"];
    }
    
    $price_field = false;
    foreach($ids as $key => $row){
        if($row == 'price_search'){
            unset($ids[$key]);
            $price_field = true;
        }
    }
    

    $fields = $entityFieldLists[$layout->fk_eid];
//$entityFieldLists
  

    $type = 'show_search';
    require getLayoutPathCCK::getLayoutPathCom($option, $type);
    
  }

  static function show_attached_layout($option, $lid, $eiid, $category_params,$show_type = 0, $button_name = '', $catid = 0,$instancies = array(),$button_style='', $recursive_count = 10, $Itemid = 0, $params = false, $menu = false){
    global $db, $os_cck_configuration, $doc, $moduleId, $entityFieldLists, $entities_type, $input;
    $db = new os_cckDb();

    $moduleId =(($moduleId == 0
                 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    if(!$params){
        if(!$moduleId){
            $Itemid = intval($input->get('Itemid', 0, 'INT'));


        }else{

          $mod_row =  JTable::getInstance ( 'Module', 'JTable' );//load module tables and params

          if (! $mod_row->load ( $moduleId )) {
            throw new Exception($mod_row->getError (), 500);
          }
          //module params
          $params = new JRegistry;
          $params->loadString($mod_row->params);
          //itemId
          $query = "SELECT id  FROM #__menu WHERE menutype like '%menu%'"
                          . "\n AND link LIKE '%option=com_os_cck%'"
                          . "\n AND params LIKE '%back_button%'"
                          . "\n AND published = 1";
          $db->setQuery($query);

          $Itemid = $db->loadResult();
          if($params->get('ItemId'))$Itemid=$params->get('ItemId');

        }
    }
    
    $includes_instance = '1';
    $session = JFactory::getSession();
    $bootstrap_version = $session->get('bootstrap','2');
    
    if(!is_object($lid)){
        $layout =  new os_cckLayout($db->_db);
        $layout->load($lid);
        if($layout->lid && !property_exists($layout, 'layout_html')){
            $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
        }
    }else{
        $layout =  $lid;
        $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
    }
    $jinput = JFactory::getApplication()->input;
    if(!$layout->lid){
      JFactory::getApplication()->enqueueMessage("Layout ID:".$lid." doesn't exists!", 'warning');
      return;
    }
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$layout->fk_eid/custom.css");
    
    if($layout->type == 'instance' || $layout->type == 'all_instance'){

      $layout_html = urldecode($layout->layout_html);
      if($recursive_count < 1) return;
      $recursive_count = $recursive_count -1;
      $empty_layout = true;
      if(stripos($layout_html, '{|f-') !== false || stripos($layout_html, '{|l-') !== false
              || stripos($layout_html, '{|m-') !== false || stripos($layout_html, '{|e-p-ch-') !== false){
                  $empty_layout = false;
      }

      if(empty($instancies) ){
        print_r("<h3 class='cck-nothing-found'>".cck_lang_text("COM_OS_CCK_LABEL_SEARCH_NOTHING_FOUND") . " </h3>");
      }

      foreach ($instancies as $key => $instance) {   

        //!isset($instance->fk_eid) - as example: when do import users layouts, but haven't so users
        if($empty_layout || !isset($instance->fk_eid) ){continue;}

        $layout_params = unserialize($layout->params);
        $layout_params['custom_fields'] = unserialize($layout->custom_fields);
        // $layout_params['views']['show_navigation'] = 0;
        $layout_params['has_price'] = 0;

        $layout_params['nextInstId'] = 0;
        $layout_params['prevInstId'] = 0;
        
        $layout->field_list = $entityFieldLists[$instance->fk_eid];
        foreach ($layout->field_list as $field) {
          $html = urldecode($layout->layout_html);
          if(strpos($html,"{|f-".$field->fid."|}")){
            $layout_fields = $layout_params['fields'];
            if($field->field_type == 'decimal_textfield' && $layout_params['has_price'] == 0){
              if(isset($layout_fields[$field->db_field_name.'_field_type']) && $layout_fields[$field->db_field_name.'_field_type'] == 'price'){
                $layout_params['has_price'] = 1;
              }
            }
          }
        }
        if($layout->type == 'all_instance'){
          $catid = $instance->cat_id;
        }
        
        $category = new os_cckCategory($db->_db);
//        if ($catid > 0) {
//            $category->load($category);
//        }
        
        
        if ($catid > 0) {
          if(!isset($GLOBALS['categories'][$catid] )){
              $query = "SELECT * FROM #__os_cck_categories WHERE cid='{$catid}'";
              $db->setQuery($query);
              $category = $db->loadObjectList();
              $GLOBALS['categories'][$catid] = $category;
          }else{
              $category = $GLOBALS['categories'][$catid];
          }
        } else {    
            if($entities_type[$instance->fk_eid] == 'os_cck_entity'){
              $query = "SELECT * FROM #__os_cck_categories AS cc "
                      . "\n LEFT JOIN #__os_cck_categories_connect AS ccc ON cc.cid=ccc.fk_cid "
                      . "\n WHERE ccc.fk_eiid=" . $instance->eiid . ""
                      . "\n LIMIT 0,1";

              $db->setQuery($query);
              $category = $db->loadObjectList();
            }
        }
        
        if($category && is_array($category))
          $category = $category[0];
        
        
        if(isset($category_params['views']['link_field'])){
          $layout_params['views']['link_field'] = $category_params['views']['link_field'];
        }
        
//        if($category_params['views']['instance_layout'] == '-1'){
//          $layout_params['views']['instance_layout'] = $layout->getDefaultLayout($instance->fk_eid, 'instance');
//        }else{
//          $layout_params['views']['instance_layout'] = $category_params['views']['instance_layout'];
//        }
        if(isset($layout_params['attachedModuleIds'])){
          $layout_params['attachedModule'] = explode('|_|',$layout_params['attachedModuleIds']);
          $mids = array();
          foreach ($layout_params['attachedModule'] as $attachedModuleId) {
            if($attachedModuleId){
              $mids[] = $attachedModuleId;
            }
          }
          if($mids && $mids[0] != 'undefined'){
            $mids = str_replace('m_', '', $mids);
            $mids = implode(',', $mids);
            $query = "SELECT id, title, module as type FROM #__modules WHERE id IN (" . $mids . ")";
            $db->setQuery($query);
            $layout_params['attachedModule'] = $db->loadObjectList('id');
          }
        }
        $entityInstance = $instance;
        $type = 'instance';
        //var_dump($category_params['parent_layout_params']['all_cat_layout_params']);
        //if(!isset($category_params['parent_layout_params']['all_cat_layout_params'])){
        
          require getLayoutPathCCK::getLayoutPathCom($option,$type);

        //}
          
      }
    }elseif($layout->type == 'search'){

      $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
      $layout_params = unserialize($layout->params);
      $layout_params['custom_fields'] = unserialize($layout->custom_fields);
      $layout_fields = $layout_params['fields'];
      $layout->parent_eiid = $eiid;
      if($show_type){
        $layout_params['show_type'] = $show_type;
      }
      $layout_params['button_name'] = $button_name;
      $layout_params['catid'] = $catid;

      //05.05.26 andrew: not understend worum use Category::showSearch, we need in Search layout "$layout_params" from parent layout!!!!! 
      // Category::showSearch($option, $catid,$layout->lid, $Itemid);
     ViewCategory::showSearch($option, $layout, $layout_params, $button_style);

      
    }elseif($layout->type == 'add_instance' || $layout->type == 'request_instance'){
      $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
      $layout_params = unserialize($layout->params);
      $layout_params['custom_fields'] = unserialize($layout->custom_fields);
      $layout_fields = $layout_params['fields'];
      $layout->parent_eiid = $eiid;
      $entityInstance = new os_cckEntityInstance($db->_db);
      $entityInstance->fk_eid = $layout->fk_eid;
      $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
      if($show_type){
        $layout_params['show_type'] = $show_type;
      }
      $extra_fields_list = $entityFieldLists[$layout->fk_eid];
      if (count($extra_fields_list) < 1) {
          

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_FIELD"), 'warning');
        return;  
      }
//      $layout_params['categories_list'] = $clist;
//      $layout_params['layout_type'] = $layout_type;
      $layout_params['extra_fields_list'] = $extra_fields_list;
      $layout_params['button_name'] = $button_name;
      $layout_params['catid'] = $catid;
      if(isset($layout_params['attachedModuleIds'])){
        $layout_params['attachedModule'] = explode('|_|',$layout_params['attachedModuleIds']);
        $mids = array();
        foreach ($layout_params['attachedModule'] as $attachedModuleId) {
          if($attachedModuleId){
            $mids[] = $attachedModuleId;
          }
        }
        if($mids && $mids[0] != 'undefined'){
          $mids = str_replace('m_', '', $mids);
          $mids = implode(',', $mids);
          $query = "SELECT id, title, module as type FROM #__modules WHERE id IN (" . $mids . ")";
          $db->setQuery($query);
          $layout_params['attachedModule'] = $db->loadObjectList('id');
        }
      }
      
      $type = $layout->type;
      require getLayoutPathCCK::getLayoutPathCom($option,$type);
    }elseif($layout->type == 'category'){

      Category::showCategory($option, $catid,$layout,$category_params, 0, false, $Itemid, '', $instancies, $params, $menu);
//      static function showCategory($option, $catid, $lid,$parent_layout_params = 0, $mod_type = 0, $return = false, $Itemid = 0, $layout_html = ''){ 
    }
  }
}
