<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright 2020 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 Instance{

    static function search($option, $catid, $mod_type = 0){
  
      global $app, $db, $user, $mosConfig_absolute_path, $doc, $session, $entities_type,
             $Itemid, $limit, $total, $limitstart, $search,$moduleId, $os_cck_configuration, $cck_entity_configuration, $entityFieldLists;

      $db = new os_cckDb();
      $Itemid = protectInjectionWithoutQuote('Itemid', 0, 'INT');
      $moduleId =(($moduleId == 0 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
      $instancies = $names = array();
      $search = "";
      $params="";
      $multiple_query ="";
      $layout="";
      $pageNav="";
      $currentcat = NULL;
      $comp_search = array();
      $comp_search_and = array();
      $where = array();
      $fild_name = array();
      $prices = array();
      $multiple_table_name = array();
      
      $input = $app->input;
      $session = JFactory::getSession();
      if(!$moduleId){
        // 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
        if (version_compare(JVERSION, '3.0', 'ge')) {
          $params = new JRegistry;
          $params->loadString($mod_row->params);
        } else {
          $params = new JRegistry($mod_row->params);
        }//end
      }
      $layout = new os_cckLayout($db->_db);
      $search_layout = new os_cckLayout($db->_db);
     //from os cck menu item(Search)
      if($params->get('search_layout') || $params->get('layout_type') == 'search'){
        $search_layout->load($params->get('layout')?$params->get('layout') : $params->get('search_layout'));
        if(!$search_layout->fk_eid){

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_REBILD_MENU"), 'warning');
          return;
        }
      }else{
        if(protectInjectionWithoutQuote('lid','')){
          $search_layout->load(protectInjectionWithoutQuote('lid'));
        }else{
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_SEARCH_LAYOUT"), 'warning');

          return;
        }
      }//end search layouts



      $entity_id = $search_layout->fk_eid;
      $fields_from_params = unserialize($search_layout->params);
//      var_dump($fields_from_params['views']['all_instance_layout']); exit;
      if(isset($fields_from_params['views']['search_in_reviews']) && $fields_from_params['views']['search_in_reviews'] == 'on'){
        $search_in_reviews = true;
      }else{
        $search_in_reviews = false;
      }
      // var_dump($fields_from_params['views']);
      // /home/vlados/public_html/joomla42/components/com_os_cck/files/entity_files_48
      $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$entity_id/custom.css");
      // var_dump($fields_from_params['views']['all_instance_layout']);
      
      if(!isset($fields_from_params['views']['all_instance_layout'] ) 
          || $fields_from_params['views']['all_instance_layout'] == -1){//we set default layout
        if($layout->getDefaultLayout($entity_id, 'all_instance')){
          $layout->load(intval($layout->getDefaultLayout($entity_id, 'all_instance')));
          $fields_from_params = unserialize($layout->params);

        }else{

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ALL_INSTANCE_LAYOUT"), 'warning');
          return;
        }
      }else{
        $layout->load($fields_from_params['views']['all_instance_layout']);
        if($layout->params){
          $fields_from_params = unserialize($layout->params);
        }else{
          $fields_from_params = array();
        }
      }


      if(empty($layout->lid)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ALL_INSTANCE_LAYOUT"), 'warning');
        return;
      }

      $limit = $fields_from_params['views']['pagenator_limit'];
      if(isset($fields_from_params['views']['limit'])){
      $max_items = $fields_from_params['views']['limit'];
      }else{
        $max_items = 0;
      }
      
      $header = $layout->title;
      $params->def('header', $header);
      $params->def('pageclass_sfx', '');
      $params->def('show_rating', 1);
      $params->def('hits', 1);
      $params->def('back_button', $app->getCfg('back_button'));
//      var_dump($_REQUEST);
//      var_dump($entity_id);
      if (array_key_exists("search", $_REQUEST)) {
        $search = urldecode(protectInjectionWithoutQuote('search','','STRING'));
        $search = addslashes($search);
      }
      //var_dump($_REQUEST); exit;
       ////////start create search request

      if (isset($_REQUEST['search_title'])) {
        $comp_search[] = "LOWER(c.title) LIKE '%$search%'";
      }
      $reaquest = protectInjectionWithoutQuote('request', array());
      $reaquest = $input->request->getArray(array(), null, 'raw');
      //maybe shit code below
      //var_dump($_REQUEST); //exit;
      $add_join = array();
      $child_where = array();
      $add_join_parent_child = array();
      
      foreach($reaquest AS $key => $var){
          
          if($entities_type[$entity_id] == 'joomla_user' && stripos($key, 'os_cck_search_') !== false){
              $subkey = str_replace('os_cck_search_', '', $key);
              $subkey = str_replace('_range_eventfrom', '', $subkey);
              $subkey = str_replace('_range_eventto', '', $subkey);
              $subkey = str_replace('_from', '', $subkey);
              $subkey = str_replace('_to', '', $subkey);
              $subkey_arr = explode('_', $subkey);
              $field = getJoomlaUserField($subkey, $entity_id);
              
              $prefix = '';
              if($subkey_arr[1] == 'standart'){
                  if($field->fid == 'register'){
                      $field_name = 'registerDate';
                  }elseif($field->fid == 'last_visit'){
                      $field_name = 'lastvisitDate';
                  }else{
                      $field_name = $field->fid;
                  }
                  $prefix = 'us.';
                if($field->field_type == 'datetime_popup' && 
                  (isset($_REQUEST['os_cck_search_' . $subkey.'_range_eventfrom']))){//date/time field


                        if(isset($_REQUEST['os_cck_search_' . $subkey.'_range_eventto'])){

                          if(!empty($_REQUEST['os_cck_search_' . $subkey.'_range_eventfrom']) 
                              && empty($_REQUEST['os_cck_search_' . $subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_' . $subkey.'_range_eventfrom','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "us." .$field_name. " BETWEEN '".($range_date_from)
                          ."' AND  '2067-01-01 00:00:00'";

                            //print_r($comp_search_and);

                          }

                          if(empty($_REQUEST['os_cck_search_'. $subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_' . $subkey.'_range_eventto'])){
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d')." 23:59:59";

                            $comp_search_and[] = "us." .$field_name. " BETWEEN '1967-01-01 00:00:00'". 
                            " AND  '".($range_date_to)."'";

                          }

                          if(!empty($_REQUEST['os_cck_search_' . $subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "us." .$field_name. " BETWEEN '".($range_date_from)
                            ."' AND  '".($range_date_to)."'";

                          }

                        }else{

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from_explode = explode(' ', $range_date_from);
                            if($range_date_from_explode[count($range_date_from_explode)-1] == 'undefined'){
                                $range_date_from = str_replace(' undefined', '', $range_date_from);
                                $range_date_from = date_create($range_date_from)->Format('Y-m-d');
                            }else{

                                $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            }
                            //var_dump($range_date_from); exit;
                            $comp_search_and[] = "us." .$field_name. " LIKE '%".($range_date_from)
                            ."%'";

                          }

                    }

                }elseif($field->field_type == 'text_textfield' && is_array($_REQUEST['os_cck_search_'.$subkey])){
                    $textfield_search = $input->get('os_cck_search_'.$subkey, array(), 'ARRAY()');
                    $textfield_search_array = array();
                    foreach ($textfield_search as $single_search){
                        if($single_search != 'all'){
                            $textfield_search_array[] = "LOWER(us." .$field_name. ") = '".($single_search)."'";
                        }
                    }
                    if(!empty($textfield_search_array)){
                        $comp_search[] = "(" . implode(' OR ', $textfield_search_array) . ')';
                    }
//                    var_dump($textfield_search); exit;
                }else{
                  $comp_search[] = "LOWER($prefix" .$field->fid. ") LIKE '%$search%'";
                }
              }elseif($subkey_arr[1] == 'profile'){
                  $prefix = 'prof.';
                  if(!isset($add_join['profile'])){
                      $add_join['profile'] = " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id ";
                  }
//                  var_dump($field->field_type == 'datetime_popup'); 
//                  var_dump(isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']));
                  if($field->field_type == 'datetime_popup' && 
                  (isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']))){//date/time field


                        if(isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "(prof.profile_key = 'profile.$field->fid' AND prof.profile_value BETWEEN '".($range_date_from)
                          ."' AND  '2067-01-01 00:00:00')";

                            //print_r($comp_search_and);

                          }

                          if(empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d')." 23:59:59";

                            $comp_search_and[] = "(prof.profile_key ='profile." .$field->fid. "' AND prof.profile_value BETWEEN '1967-01-01 00:00:00'". 
                            " AND  '".($range_date_to)."')";

                          }

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "(prof.profile_key ='profile." .$field->fid. "' AND prof.profile_value BETWEEN '".($range_date_from)
                            ."' AND  '".($range_date_to)."')";

                          }

                        }else{

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from_explode = explode(' ', $range_date_from);
                            if($range_date_from_explode[count($range_date_from_explode)-1] == 'undefined'){
                                $range_date_from = str_replace(' undefined', '', $range_date_from);
                                $range_date_from = date_create($range_date_from)->Format('Y-m-d');
                            }else{

                                $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            }
                            //var_dump($range_date_from); exit;
                            $comp_search_and[] = "prof.profile_key ='profile." .$field->fid. "' AND prof.profile_value LIKE '%".($range_date_from)
                            ."%'";

                          }

                    }

                }elseif($field->field_type == 'decimal_textfield' 
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_from']) 
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_to'])){

                  //print_r($multiple);exit;//NumberField field
                    $price_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_from',0, 'INT');
                    $price_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_to',0, 'INT');

                    if($price_to){

                      $comp_search_and[] = "prof.profile_key ='" .$field->fid. "' AND prof.profile_value BETWEEN ".($price_from)
                      .' AND '.($price_to) . ' ';

                    }
                }elseif($field->field_type == 'text_textfield' && is_array($_REQUEST['os_cck_search_'.$subkey])){
                    $textfield_search = $input->get('os_cck_search_'.$subkey, array(), 'ARRAY()');
                    $textfield_search_array = array();
//                    var_dump($textfield_search); exit;
                    foreach ($textfield_search as $single_search){
//                        "(prof.profile_key = 'profile.$field->fid' AND LOWER(prof.profile_value) = '$single_search') "
                        if($single_search != 'all'){
                            $textfield_search_array[] = "(prof.profile_key = 'profile.$field->fid' AND LOWER(prof.profile_value) = '$single_search') ";
                        }
                    }
                    if(!empty($textfield_search_array)){
                        $comp_search_and[] = "(" . implode(' OR ', $textfield_search_array) . ')';
                    }
//                    var_dump($comp_search); exit;
                }else{
                  $comp_search[] = "(prof.profile_key = 'profile.$field->fid' AND LOWER(prof.profile_value) LIKE '%$search%') ";
                }
              }else{
                  $prefix = 'val.';
                  if(!isset($add_join['custom_fields'])){
                      $add_join['custom_fields'] = " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                    . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
                  }
                  if($field->field_type == 'datetime_popup' && 
                  (isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']))){//date/time field


                        if(isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "(fi.name = '$field->fid' AND val.value BETWEEN '".($range_date_from)
                          ."' AND  '2067-01-01 00:00:00')";

                            //print_r($comp_search_and);

                          }

                          if(empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d')." 23:59:59";

                            $comp_search_and[] = "(fi.name ='" .$field->fid. "' AND val.value BETWEEN '1967-01-01 00:00:00'". 
                            " AND  '".($range_date_to)."')";

                          }

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "(fi.name ='" .$field->fid. "' AND val.value BETWEEN '".($range_date_from)
                            ."' AND  '".($range_date_to)."')";

                          }

                        }else{

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from_explode = explode(' ', $range_date_from);
                            if($range_date_from_explode[count($range_date_from_explode)-1] == 'undefined'){
                                $range_date_from = str_replace(' undefined', '', $range_date_from);
                                $range_date_from = date_create($range_date_from)->Format('Y-m-d');
                            }else{

                                $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            }
                            //var_dump($range_date_from); exit;
                            $comp_search_and[] = "fi.name ='" .$field->fid. "' AND val.value LIKE '%".($range_date_from)
                            ."%'";

                          }

                    }

                }elseif($field->field_type == 'decimal_textfield' 
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_from']) 
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_to'])){

                  //print_r($multiple);exit;//NumberField field
                    $price_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_from',0, 'INT');
                    $price_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_to',0, 'INT');

                    if($price_to){

                      $comp_search_and[] = "fi.name ='" .$field->fid. "' AND val.value BETWEEN ".($price_from)
                      .' AND '.($price_to) . ' ';

                    }
                }elseif($field->field_type == 'text_textfield' && is_array($_REQUEST['os_cck_search_'.$subkey])){
                    $textfield_search = $input->get('os_cck_search_'.$subkey, array(), 'ARRAY()');
                    $textfield_search_array = array();
//                    var_dump($textfield_search); exit;
                    foreach ($textfield_search as $single_search){
//                        "(prof.profile_key = 'profile.$field->fid' AND LOWER(prof.profile_value) = '$single_search') "
                        if($single_search != 'all'){
                            $textfield_search_array[] = "(fi.name = '$field->fid' AND LOWER(val.value) = '$single_search') ";
                        }
                    }
                    if(!empty($textfield_search_array)){
                        $comp_search_and[] = "(" . implode(' OR ', $textfield_search_array) . ')';
                    }
//                    var_dump($comp_search); exit;
                }else{
                  $comp_search[] = "(fi.name = '$field->fid' AND LOWER(val.value) LIKE '%$search%') ";
                }
                  
              }

          }
          if($entities_type[$entity_id] == 'custom_sql' && stripos($key, 'os_cck_search_') !== false){
              
              $subkey = str_replace('os_cck_search_', '', $key);
              $subkey = str_replace('_range_eventfrom', '', $subkey);
              $subkey = str_replace('_range_eventto', '', $subkey);
              $subkey = str_replace('_from', '', $subkey);
              $subkey = str_replace('_to', '', $subkey);
              
              foreach ($entityFieldLists[$entity_id] as $k => $field){
                  
                  if($k == 'custom_sql_id' || $k == 'custom_sql_title') continue;
//                    var_dump($k);
                  if($field->field_type == 'datetime_popup' && 
                  (isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']))){//date/time field


                        if(isset($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
//                            var_dump($k);
                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "t.$field->fid BETWEEN '".($range_date_from)
                          ."' AND  '2067-01-01 00:00:00'";

                            print_r($comp_search_and);

                          }

                          if(empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d')." 23:59:59";

                            $comp_search_and[] = "t.$field->fid BETWEEN '1967-01-01 00:00:00'". 
                            " AND  '".($range_date_to)."'";

                          }

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom']) 
                              && !empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventto'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventto','');
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            $range_date_to = date_create($range_date_to)->Format('Y-m-d H:i:s');

                            $comp_search_and[] = "t.$field->fid BETWEEN '".($range_date_from)
                            ."' AND  '".($range_date_to)."'";
                    
                          }

                        }else{

                          if(!empty($_REQUEST['os_cck_search_'.$subkey.'_range_eventfrom'])){
                            $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_range_eventfrom','');
                            $range_date_from_explode = explode(' ', $range_date_from);
                            if($range_date_from_explode[count($range_date_from_explode)-1] == 'undefined'){
                                $range_date_from = str_replace(' undefined', '', $range_date_from);
                                $range_date_from = date_create($range_date_from)->Format('Y-m-d');
                            }else{

                                $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                            }
                            //var_dump($range_date_from); exit;
                            $comp_search_and[] = "t.$field->fid LIKE '%".($range_date_from)
                            ."%'";

                          }

                    }

                }elseif($field->field_type == 'decimal_textfield' && $subkey != 'price_search'
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_from']) 
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_to'])){
                    
                  //print_r($multiple);exit;//NumberField field
                    $price_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_from',0, 'INT');
                    $price_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_to',0, 'INT');

                    if($price_to){

                      $comp_search_and[] = "t.$field->fid BETWEEN ".($price_from)
                      .' AND '.($price_to) . ' ';

                    }
                }elseif($field->field_type == 'pricefield_number' && $subkey == 'price_search'
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_from']) 
                  && isset($_REQUEST['os_cck_search_'.$subkey.'_to'])){
//                    var_dump($subkey);
                  //print_r($multiple);exit;//NumberField field
                    $price_from = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_from',0, 'INT');
                    $price_to = protectInjectionWithoutQuote('os_cck_search_'.$subkey.'_to',0, 'INT');

                    if($price_to){

                      $comp_search_and[] = "t.$field->fid BETWEEN ".($price_from)
                      .' AND '.($price_to) . ' ';

                    }
                }elseif($field->field_type == 'text_textfield' && isset($_REQUEST['os_cck_search_'.$subkey])){
                    $textfield_search = $input->get('os_cck_search_'.$subkey, array(), 'ARRAY()');
                    $textfield_search_array = array();
                    $search_key = str_replace('custom_sql_', '', $subkey);
//                    var_dump($textfield_search); exit;
                    if(is_array($textfield_search)){
                      foreach ($textfield_search as $single_search){
                    //                        "(prof.profile_key = 'profile.$field->fid' AND LOWER(prof.profile_value) = '$single_search') "
                          if($single_search != 'all'){
                              $textfield_search_array[] = "LOWER(t.$search_key) = '$single_search' ";
                          }
                      }
                    }
                    if(!empty($textfield_search_array)){
                        $comp_search_and[] = "(" . implode(' OR ', $textfield_search_array) . ')';
                    }
//                    var_dump($subkey); exit;
                }else{
                  $comp_search[] = "LOWER(t.$field->fid) LIKE '%$search%' ";
                }
              }
//              var_dump($var);
//              var_dump($key);
//              $fild_name = array_unique($fild_name);
//              var_dump($fild_name);
          }
          
//          var_dump($comp_search);
//          var_dump($comp_search_and);
          
          $short_key = '';
          
          if(stripos($key, '_e-p-ch-') !== false){
            
              $key_array = explode('-', $key);
              
              foreach($key_array as $row){
                  //$short_key .= '-' . $row;
                  if(strpos($row, '_') !== false){
                      //var_dump(is_numeric(explode('_', $row)[0]));
                      if(is_numeric(explode('_', $row)[0])){
                          $field_array = explode('_', $row);
                          continue;
                      }
                  }
              }
              
              $short_key = str_replace('_range_eventfrom', '', $key);
              $short_key = str_replace('_range_eventto', '', $short_key);
              $short_key = str_replace('_from', '', $short_key);
              $short_key = str_replace('_to', '', $short_key);
              $short_key = str_replace('_select+', '', $short_key);
              $short_key = str_replace('_select', '', $short_key);
              //var_dump($short_key);
              //$field_array = explode('_', end($key_array));
              if(!isset($add_join_parent_child[$field_array[0]])){
                  //LEFT JOIN #__os_cck_content_entity_".$entity_id." AS entcont ON c.eiid = entcont.fk_eiid
                $add_join[$field_array[0]] = " LEFT JOIN #__os_cck_content_entity_".$field_array[0]." AS parent_$field_array[0] ON cpc.fid_child = parent_$field_array[0].fk_eiid ";
                $add_join_parent_child[$field_array[0]] = array();
              }
              //var_dump($add_join); exit;
              $child_field = new os_cckEntityField($db->_db);
              $child_field->load($field_array[2]);
              //var_dump($short_key.'_range_eventfrom');
              
              if($child_field->field_type == 'text_single_checkbox_onoff' &&
                 $_REQUEST[$key] == 'on'){ //checkbox
                    // $comp_search_and[] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name." != '')";
                    $add_join_parent_child[$field_array[0]][] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name." != '')";
                }
                elseif($child_field->field_type == 'text_select_list' && 
                  $_REQUEST[$key] != 'all' 
                  && $_REQUEST[$key] != '' ){//list field
                    $like = $db->Quote(protectInjectionWithoutQuote($key));
                    $like = substr_replace($like, "'%\"", 0, 1);
                    $like = substr_replace($like, "\"%'", -1, 1);
                    //var_dump(substr_replace($like, "%'", -1, 1));
                    // $comp_search_and[] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") LIKE ".
                    //   $like;
                    $add_join_parent_child[$field_array[0]][] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") LIKE ".$like;


              //var_dump($comp_search_and);
                }
                elseif($child_field->field_type == 'text_radio_buttons'){//radioButton field
                    
                    if($db->Quote(protectInjectionWithoutQuote($key,'')) != "'0'"){

                    // $comp_search_and[] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") LIKE ".
                    // $db->Quote(protectInjectionWithoutQuote($key,''));
                      $add_join_parent_child[$field_array[0]][] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") LIKE ".
                      $db->Quote(protectInjectionWithoutQuote($key,''));
                    }
                    
                }
//                elseif($child_field->type == 'decimal_textfield' 
//                  && isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_from']) 
//                  && isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_to'])){
                elseif($child_field->field_type == 'decimal_textfield' 
                  && isset($_REQUEST[$short_key.'_from']) 
                  && isset($_REQUEST[$short_key.'_to'])){

                  //print_r($multiple);exit;//NumberField field
                    $price_from = protectInjectionWithoutQuote($short_key.'_from',0, 'INT');
                    $price_to = protectInjectionWithoutQuote($short_key.'_to',0, 'INT');

                    if($price_to){
                      if($price_from == 0){
                          // $comp_search_and[] = "((LOWER(parent_$field_array[0]." .$child_field->db_field_name. ")) IS NULL 
                          // OR (LOWER(parent_$field_array[0]." .$child_field->db_field_name. ")) <= " . $price_to . ")";
                          $add_join_parent_child[$field_array[0]][] = "((LOWER(parent_$field_array[0]." .$child_field->db_field_name. ")) IS NULL 
                          OR (LOWER(parent_$field_array[0]." .$child_field->db_field_name. ")) <= " . $price_to . ")";
                      }else{
                          // $comp_search_and[] = "(LOWER(parent_$field_array[0]." .$child_field->db_field_name. ")) BETWEEN ".($price_from)
                          //     .' AND '.($price_to);
                          $add_join_parent_child[$field_array[0]][] = "(LOWER(parent_$field_array[0]." .$child_field->db_field_name. ")) BETWEEN ".($price_from)
                          .' AND '.($price_to);
                      }


                    }
                }
                
                elseif($child_field->field_type == 'decimal_textfield' 
                  && (isset($_REQUEST[$short_key.'_select']) || isset($_REQUEST[$short_key.'_select+']))){
                    $more = '';
                    $plus = '';
                    if(isset($_REQUEST[$short_key.'_select+'])){
                        $more = '>';
                        $plus = '+';
                    }
                  //print_r($multiple);exit;//NumberField field
                    $number = protectInjectionWithoutQuote($short_key.'_select'.$plus);//may be necessary to improve the int number test later
                    $more = '';
                    if(isset($_REQUEST[$short_key.'_select+'])){
                        $more = '>';
                    }

                    if($number != 'none' && $number != ''){

                      // $comp_search_and[] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") $more= '$number'";
                      $add_join_parent_child[$field_array[0]][] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") $more= '$number'";

                    }
                }

                elseif($child_field->field_type == 'datetime_popup' && 
                  (isset($_REQUEST[$short_key.'_range_eventfrom']))){//date/time field


                    if(isset($_REQUEST[$short_key.'_range_eventto'])){

                      if(!empty($_REQUEST[$short_key.'_range_eventfrom']) 
                          && empty($_REQUEST[$short_key.'_range_eventto'])){
                        $range_date_from = protectInjectionWithoutQuote($short_key.'_range_eventfrom','');
                        $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');

                        // $comp_search_and[] = "parent_$field_array[0]." .$child_field->db_field_name. " BETWEEN '".($range_date_from)
                      // ."' AND  '2067-01-01 00:00:00'";
                      $add_join_parent_child[$field_array[0]][] = "parent_$field_array[0]." .$child_field->db_field_name. " BETWEEN '".($range_date_from)
                      ."' AND  '2067-01-01 00:00:00'";
                        //print_r($comp_search_and);

                      }

                      if(empty($_REQUEST[$short_key.'_range_eventfrom']) 
                          && !empty($_REQUEST[$short_key.'_range_eventto'])){
                        $range_date_to = protectInjectionWithoutQuote($short_key.'_range_eventto','');
                        $range_date_to = date_create($range_date_to)->Format('Y-m-d')." 23:59:59";

                        // $comp_search_and[] = "parent_$field_array[0]." .$child_field->db_field_name. " BETWEEN '1967-01-01 00:00:00'". 
                        // " AND  '".($range_date_to)."'";
                        $add_join_parent_child[$field_array[0]][] = "parent_$field_array[0]." .$child_field->db_field_name. " BETWEEN '".($range_date_from)
                      ."' AND  '2067-01-01 00:00:00'";

                      }

                      if(!empty($_REQUEST[$short_key.'_range_eventfrom']) 
                          && !empty($_REQUEST[$short_key.'_range_eventto'])){
                        $range_date_from = protectInjectionWithoutQuote($short_key.'_range_eventfrom','');
                        $range_date_to = protectInjectionWithoutQuote($short_key.'_range_eventto','');
                        $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                        $range_date_to = date_create($range_date_to)->Format('Y-m-d H:i:s');

                        // $comp_search_and[] = "parent_$field_array[0]." .$child_field->db_field_name. " BETWEEN '".($range_date_from)
                        // ."' AND  '".($range_date_to)."'";
                        $add_join_parent_child[$field_array[0]][] = "parent_$field_array[0]." .$child_field->db_field_name. " BETWEEN '".($range_date_from)
                        ."' AND  '".($range_date_to)."'";

                      }

                    }else{

                      if(!empty($_REQUEST[$short_key.'_range_eventfrom'])){
                        $range_date_from = protectInjectionWithoutQuote($short_key.'_range_eventfrom','');
                        $range_date_from_explode = explode(' ', $range_date_from);
                        if($range_date_from_explode[count($range_date_from_explode)-1] == 'undefined'){
                            $range_date_from = str_replace(' undefined', '', $range_date_from);
                            $range_date_from = date_create($range_date_from)->Format('Y-m-d');
                        }else{

                            $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                        }
                        //var_dump($range_date_from); exit;
                        // $comp_search_and[] = "parent_$field_array[0]." .$child_field->db_field_name. " LIKE '%".($range_date_from)
                        // ."%'";
                        $add_join_parent_child[$field_array[0]][] = "parent_$field_array[0]." .$child_field->db_field_name. " LIKE '%".($range_date_from)
                        ."%'";

                      }

                }

            }

            elseif($child_field->field_type == 'datetime_popup' && 
              (!empty($_REQUEST[$short_key.'_dateto']) || 
              !empty($_REQUEST[$short_key.'_datefrom']))){//date/time field

                if(!empty($_REQUEST[$short_key.'_datefrom']))
                {
                  $date_from = protectInjectionWithoutQuote($short_key.'_datefrom','');
                }
                 
                if(!empty($_REQUEST[$short_key.'_dateto'])){
                    $date_to = protectInjectionWithoutQuote($short_key.'_dateto','');
                }

            }elseif($child_field->field_type == 'text_textfield' && is_array($_REQUEST[$short_key])){
                    $textfield_search = $input->get($short_key, array(), 'ARRAY()');
                    $textfield_search_array = array();
//                    var_dump($field_array); exit;
                    
                   
                    foreach ($textfield_search as $single_search){
//                        "(prof.profile_key = 'profile.$field->fid' AND LOWER(prof.profile_value) = '$single_search') "
                        if($single_search != 'all'){
                            $textfield_search_array[] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") = '$single_search' ";
                        }
                    }
                    
                    if(!empty($textfield_search_array)){
                        // $comp_search_and[] = "(" . implode(' OR ', $textfield_search_array) . ')';
                        $add_join_parent_child[$field_array[0]][] = "(" . implode(' OR ', $textfield_search_array) . ')';
                        
                    }
//                    var_dump($comp_search_and); exit;
            }else{
            
                $comp_search[] = "LOWER(parent_$field_array[0]." .$child_field->db_field_name. ") LIKE '%$search%'";
            }
                // $add_join_parent_child[$field_array[0]] = "(" . implode(' OR ', $textfield_search_array) . ')';
              
              
              //var_dump($field_array); exit;
          }

          
          
          
          
        if(stripos($key, 'text_radio_buttons')){
            $key = substr($key, 0, strripos($key, '_'));
        }
        
        if(strpos($key, '_datefrom')===strlen($key)-9){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_datefrom','',
            str_replace('os_cck_search_', '', $key))));
        }elseif(strpos($key, '_dateto')===strlen($key)-7){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_dateto','',
            str_replace('os_cck_search_', '', $key))));

        }elseif(strpos($key, 'os_cck_search_price_search_from')!==FALSE){
         $prices['price_search_from'] = $var;
        }elseif(strpos($key, 'os_cck_search_price_search_to')!==FALSE){
          $prices['price_search_to'] = $var;
        }elseif($key ==  'os_cck_search_price_search' && $var = 'on'){
          $prices['price_search'] = $var;
        }elseif(strpos($key, '_from')===strlen($key)-5){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_from','',
            str_replace('os_cck_search_', '', $key))));
        }elseif(strpos($key, '_to')===strlen($key)-3){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_to','',
            str_replace('os_cck_search_', '', $key))));
        }elseif(strpos($key, '_range_eventfrom')===strlen($key)-16){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_range_eventfrom','',
            str_replace('os_cck_search_', '', $key))));

        }elseif(strpos($key, '_range_eventto')===strlen($key)-14){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_range_eventto','',
            str_replace('os_cck_search_', '', $key))));

        }elseif(strpos($key, '_select')===strlen($key)-7){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_select','',
            str_replace('os_cck_search_', '', $key))));

        }elseif(strpos($key, '_select+')===strlen($key)-8){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('_select+','',
            str_replace('os_cck_search_', '', $key))));

        }elseif(strpos($key, 'os_cck_search_') === 0){
          array_push($fild_name, 'fld.db_field_name='.$db->quote(str_replace('os_cck_search_', '', $key)));
        }
        
      }//end
      //var_dump($comp_search_and);
      $fild_name = array_unique($fild_name);
      //exit;
      //all names and types of tables/fields
      if($fild_name){
        $query = "SELECT fld.db_field_name, fld.field_type "
                  ."\n FROM #__os_cck_entity_field AS fld "
                  ."\n WHERE ".implode(' OR ', $fild_name)." ORDER BY fid";
        $db->setQuery($query);
        $fields = $db->loadAssocList();
      
        //end
        $allowed_values='';

        //$date_from = '0000-00-00';
        //$date_to = '0000-00-00';

             //print_r($fields);
            //       exit;
//            var_dump($fields); exit;
        foreach($fields as $field){

//            var_dump($field);
            if($field['field_type'] == 'text_single_checkbox_onoff' &&
             $_REQUEST['os_cck_search_'.$field['db_field_name']] == 'on'){ //checkbox
                $comp_search_and[] = "LOWER(entcont." .$field['db_field_name']." != '')";
            }
            //old search on select list
            elseif($field['field_type'] == 'text_select_list' && 
              $_REQUEST['os_cck_search_'.$field['db_field_name']] != 'all' 
              && $_REQUEST['os_cck_search_'.$field['db_field_name']] != '' 
              && !is_array($_REQUEST['os_cck_search_'.$field['db_field_name']]) ){//list field
                
                $like = $db->Quote(protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'], 0, 'INT'));
                $like = substr_replace($like, "'%\"", 0, 1);
                $like = substr_replace($like, "\"%'", -1, 1);
                //var_dump(substr_replace($like, "%'", -1, 1));
                $comp_search_and[] = "LOWER(entcont." .$field['db_field_name']. ") LIKE ".
                  $like;
          
          
//          var_dump($comp_search_and); exit;
            }
            //new search on select list
            elseif($field['field_type'] == 'text_select_list' && 
              is_array($_REQUEST['os_cck_search_'.$field['db_field_name']]) ){//list field
//                var_dump(protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'], array(), 'ARRAY')); exit;
                $select_search_array = $input->get('os_cck_search_'.$field['db_field_name'], array(), 'ARRAY');
//                var_dump($select_search_array);
//                var_dump($_REQUEST['os_cck_search_'.$field['db_field_name']]);
//                $like = $db->Quote(protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'], 0, 'INT'));
                $select_search_like = array();
                foreach ($select_search_array as $like){
//                    var_dump($like);
//                    $like = substr_replace($like, "'%\"", 0, 1);
//                    $like = substr_replace($like, "\"%'", -1, 1);
                    if($like != 'all'){
                        $like = "'%\"" . $like . "\"%'";
    //                    var_dump($like);
                        $select_search_like[] = "LOWER(entcont." .$field['db_field_name']. ") LIKE " . $like;
                    }
                }
//                var_dump($select_search_like);
                if(!empty($select_search_like)){
                    $comp_search_and[] = " ( " . implode(' OR ', $select_search_like) . ' ) ';
                }
                  
          
          
//          var_dump($comp_search_and); exit;
            }
            elseif($field['field_type'] == 'text_radio_buttons'){//radioButton field
                
                if($db->Quote(protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'],'')) != "'0'"){
                    
                $comp_search_and[] = "LOWER(entcont." .$field['db_field_name']. ") LIKE ".
                  $db->Quote(protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'],''));
                }
          
            }
            elseif($field['field_type'] == 'decimal_textfield' 
              && isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_from']) 
              && isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_to'])){

              //print_r($multiple);exit;//NumberField field
                $price_from = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_from',0, 'INT');
                $price_to = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_to',0, 'INT');
                
                if($price_to){
                    if($price_from == 0){
                        $comp_search_and[] = "((LOWER(entcont." .$field['db_field_name']. ")) IS NULL 
                          OR (LOWER(entcont." .$field['db_field_name']. ")) <= " . $price_to . ")";
                    }else {
                        $comp_search_and[] = "(LOWER(entcont." . $field['db_field_name'] . ")) BETWEEN " . ($price_from)
                            . ' AND ' . ($price_to);
                    }

                }
            }
            elseif($field['field_type'] == 'decimal_textfield' 
              && (isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_select'])
                    || isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_select+']))){
                $more = '';
                $plus = '';
                if(isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_select+'])){
                    $more = '>';
                    $plus = '+';
                }
              //print_r($multiple);exit;//NumberField field
                $number = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_select'.$plus);//may be necessary to improve the int number test later
                
                if($number != 'none' && $number != ''){

                  $comp_search_and[] = "LOWER(entcont." .$field['db_field_name']. ") $more= '$number'";

                }
            }

            elseif($field['field_type'] == 'datetime_popup' && 
              (isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventfrom']))){//date/time field


                if(isset($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventto'])){

                  if(!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventfrom']) 
                      && empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventto'])){
                    $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_range_eventfrom','');
                    $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');

                    $comp_search_and[] = "entcont." .$field['db_field_name']. " BETWEEN '".($range_date_from)
                  ."' AND  '2067-01-01 00:00:00'";

                    //print_r($comp_search_and);
                    
                  }

                  if(empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventfrom']) 
                      && !empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventto'])){
                    $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_range_eventto','');
                    $range_date_to = date_create($range_date_to)->Format('Y-m-d')." 23:59:59";

                    $comp_search_and[] = "entcont." .$field['db_field_name']. " BETWEEN '1967-01-01 00:00:00'". 
                    " AND  '".($range_date_to)."'";
                    
                  }

                  if(!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventfrom']) 
                      && !empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventto'])){
                    $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_range_eventfrom','');
                    $range_date_to = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_range_eventto','');
                    $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                    $range_date_to = date_create($range_date_to)->Format('Y-m-d H:i:s');

                    $comp_search_and[] = "entcont." .$field['db_field_name']. " BETWEEN '".($range_date_from)
                    ."' AND  '".($range_date_to)."'";
                    
                  }

                }else{

                  if(!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_range_eventfrom'])){
                    $range_date_from = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_range_eventfrom','');
                    $range_date_from_explode = explode(' ', $range_date_from);
                    if($range_date_from_explode[count($range_date_from_explode)-1] == 'undefined'){
                        $range_date_from = str_replace(' undefined', '', $range_date_from);
                        $range_date_from = date_create($range_date_from)->Format('Y-m-d');
                    }else{
                    
                        $range_date_from = date_create($range_date_from)->Format('Y-m-d H:i:s');
                    }
                    //var_dump($range_date_from); exit;
                    $comp_search_and[] = "entcont." .$field['db_field_name']. " LIKE '%".($range_date_from)
                    ."%'";
                    
                  }

                }

            }

            elseif($field['field_type'] == 'datetime_popup' && 
              (!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_dateto']) || 
              !empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_datefrom']))){//date/time field

                if(!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_datefrom']))
                {
                  $date_from = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_datefrom','');
                }
                 
                if(!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_dateto'])){
                    $date_to = protectInjectionWithoutQuote('os_cck_search_'.$field['db_field_name'].'_dateto','');
                }

            }elseif($field['field_type'] == 'text_textfield' && $_REQUEST['os_cck_search_'.$field['db_field_name']] != 'on' && is_array($_REQUEST['os_cck_search_'.$field['db_field_name']])){
//                var_dump($_REQUEST['os_cck_search_'.$field['db_field_name']]); exit;
                $text_select = array();
                foreach ($_REQUEST['os_cck_search_'.$field['db_field_name']] as $single_field){
                    if($single_field != 'all'){
                        $text_select[] =  "LOWER(entcont." .$field['db_field_name']. ") = '".$single_field."'";
                    }
                }
                if(!empty($text_select)){
                    $comp_search_and[] = '('.implode(' OR ', $text_select).')';
                }
//                var_dump($where); exit;
            }else
                $comp_search[] = "LOWER(entcont." .$field['db_field_name']. ") LIKE '%$search%'";//not multiple field
        }
      }
      
//      if(!empty($prices)){
//          
//      }

//var_dump(!empty($_REQUEST['os_cck_search_'.$field['db_field_name'].'_datefrom'])); exit;
      ////////creating database search request
      if($catid[0]!=0 && $catid[0]!=''){
          $k=0;
          $addwhere='';
          $subcat_search = $input->get('subcat_search', '', 'STRING');
          if($subcat_search == 'on'){
            $cats_with_child = cck_getSubCategories($catid);
            $catid = $cats_with_child;
          }
//          var_dump($cats_with_child);
          foreach($catid as $item){
            
            $k++;
            if($k==1)$addwhere.='(';
            if($k < count($catid))
                $addwhere.="categ.cid=".$item." OR ";
            else
                $addwhere.="categ.cid=".$item.")";
          }
          array_push($where, $addwhere);
          array_push($where, "(categ.published IS NULL OR categ.published ='1')");
      }
      if(JLanguageMultilang::isEnabled()){
          $lang = JFactory::getLanguage();
          $lang_tag = $lang->getTag();

          array_push($where, "( c.language='$lang_tag' OR c.language='*' OR c.language IS NULL) ");   
      }
      if(!empty($add_join_parent_child)){
        foreach($add_join_parent_child as $parent_eid => $parent_query_arr){
          if(!empty($parent_query_arr)){
            array_push($where, "EXISTS (SELECT * FROM #__os_cck_child_parent_connect AS cpc LEFT JOIN #__os_cck_content_entity_$parent_eid AS parent_$parent_eid ON cpc.fid_child = parent_$parent_eid.fk_eiid WHERE cpc.fid_parent = entcont.fk_eiid AND ".implode(' AND ', $parent_query_arr).")");
          }
        }
      }
      // var_dump($where); exit;
      array_push($where, "c.published='1'");
      array_push($where, "c.approved='1'");

      if($search_in_reviews && !empty($comp_search)){
        $reviev_search = array();
        foreach($comp_search as $comp_search_temp_string){
          $reviev_search[] = str_replace('entcont.', 'entcont_review.', $comp_search_temp_string);
        }
        // var_dump($reviev_search);
         $review_search_string = "(SELECT COUNT(ei_review2.eiid) FROM #__os_cck_entity_instance as ei_review
                                  LEFT JOIN #__os_cck_child_parent_connect as pc_review ON pc_review.fid_parent = ei_review.eiid
                                  LEFT JOIN #__os_cck_entity_instance as ei_review2 ON pc_review.fid_child = ei_review2.eiid
                                  LEFT JOIN #__os_cck_content_entity_$entity_id AS entcont_review ON ei_review2.eiid = entcont_review.fk_eiid 
                                  LEFT JOIN #__os_cck_layout as l_review ON l_review.lid = ei_review2.fk_lid
                                  WHERE pc_review.fid_parent=c.eiid AND l_review.type='review_instance' AND ei_review2.published = 1 AND ei_review2.approved = 1 AND (".implode(' OR ', $reviev_search).")) > 0";
         array_push($comp_search, $review_search_string);
      }

      $comp_search_str = implode(' OR ', $comp_search);
      if ($comp_search_str != '') {
          array_push($where, '(' . $comp_search_str . ')');
      }
      
      $comp_search_str_and = implode(' AND ', $comp_search_and);
      if ($comp_search_str_and != '') {
          array_push($where, '(' . $comp_search_str_and . ')');
      }
      
      array_push($where, "c.fk_eid=".$entity_id);
      
      array_push($where, "lay.type = 'add_instance'");
      
      
      $search_date_from = '0000-00-00 00:00:00';
      $search_date_until = '0000-00-00 00:00:00';
      if(isset($date_from)) $search_date_from = date_create($date_from)->Format('Y-m-d H:i:s');
      if(isset($date_to)) $search_date_until = date_create($date_to)->Format('Y-m-d H:i:s');
      $RentSQL = '';

      if($os_cck_configuration->get('rent_type') || $os_cck_configuration->get('by_time')){
          $sign = '=';      
      }else{
          $sign = '';
      }  
      //var_dump($date_from); //exit;
      if(isset($date_from) || isset($date_to)){
      $RentSQL = " entcont.fk_eiid NOT IN (select dd.fk_eiid from #__os_cck_rent AS dd
      where ((dd.rent_until >".$sign." '" . $search_date_from . "' and dd.rent_from <= '" . $search_date_from . "') or " .
          " (dd.rent_from <".$sign." '" . $search_date_until . "' and dd.rent_until >= '" . $search_date_until . "' ) or " .
          " (dd.rent_from >".$sign."'" . $search_date_from . "' and dd.rent_until <".$sign." '" . $search_date_until . "'))  AND dd.rent_return IS NULL) ";
  

      if (trim($RentSQL) != "")
          array_push($where, $RentSQL);
      }
//      var_dump($where); exit;
      if(!empty($prices)){
          //$base_price_fields = getBasePriceFields($entity_id);
          
          if(isset($prices['price_search_to']) && $prices['price_search_to']){
              $currency = cck_getCurrentCurrency();
              if($currency == ''){
                  $currency = cck_getCurrency($os_cck_configuration);
                  $currency = $currency[0]['sign'];
              }
              
              $search_currency = cck_getCurrency($os_cck_configuration);
              $search_currency = $search_currency[0]['sign'];
              
              if($currency == $search_currency){
                  $currency_price_search_from = $prices['price_search_from'];
                  $currency_price_search_to = $prices['price_search_to'];
              }else{
                  $entityInstance = new stdClass();
                  $entityInstance->instance_currency = $currency;
                  $currency_price_search_from = calculatedCurrency($entityInstance, $prices['price_search_from'], $search_currency);
                  $currency_price_search_from = $currency_price_search_from[1];
                  $currency_price_search_to = calculatedCurrency($entityInstance, $prices['price_search_to'], $search_currency);
                  $currency_price_search_to = $currency_price_search_to[1];
              }
              
              //$price_search_from = 
                  $price_search_string = "c.instance_price BETWEEN ".($currency_price_search_from)
                  .' AND '.($currency_price_search_to); 

                }elseif($prices['price_search']){
                      $price_search = (isset($reaquest['search'])) ? $reaquest['search'] : '';
                      
                      if(is_numeric($price_search)){
                          
                      
                          $currency = cck_getCurrentCurrency();
                          if($currency == ''){
                              $currency = cck_getCurrency($os_cck_configuration);
                              $currency = $currency[0]['sign'];
                          }

                          $search_currency = cck_getCurrency($os_cck_configuration);
                          $search_currency = $search_currency[0]['sign'];

                          if($currency == $search_currency){
                              $currency_price_search = $price_search;
                          }else{
                              $entityInstance = new stdClass();
                              $entityInstance->instance_currency = $currency;
                              $currency_price_search = calculatedCurrency($entityInstance, $price_search, $search_currency);
                              $currency_price_search = $currency_price_search[1];
                          }

                          $price_search_string = "c.instance_price = '$currency_price_search'";
                      }else{
                          $price_search_string = '';
                      }
                }
                
                array_push($where, $price_search_string);
      }
      
      //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 = ' (' . getWhereUsergroupsConditionCCK('c') . " or c.access='' OR " . getWhereUsergroupsConditionWithoutLikeCCK('c') . ") ";
          }
        array_push($where, $access_where);
        
        foreach($where as $key => $temp_where){
            if($temp_where == ''){
                unset($where[$key]);
            }
        }
        
      //query for paginator limit
        if($entities_type[$entity_id] == 'os_cck_entity'){
            $query = "SELECT COUNT(DISTINCT c.eiid) FROM #__os_cck_entity_instance as c "//items table
                //20.07.2022 VlaDOS
                //Ranshe mi vivodili instance stolko raz, v skolki kategoriyah on byl, vozmojno nujno dobavit nastroyku. Sey4as vivodim 1 raz
                //VlaDOS 20.07.2022
          //$query = "SELECT COUNT(DISTINCT c.eiid,catcon.fk_cid) FROM #__os_cck_entity_instance as c "//items table
            . "\n LEFT JOIN #__os_cck_content_entity_".$entity_id." AS entcont ON c.eiid = entcont.fk_eiid"//table for text field
            . "\n LEFT JOIN #__os_cck_categories_connect AS catcon ON c.eiid = catcon.fk_eiid"//need for conect entity and categories tables
            //. "\n LEFT JOIN #__os_cck_content_instances_price AS price ON c.eiid = price.fk_eiid"//for price search
            . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid = c.fk_lid";//need for conect entity and categories tables
            if(!empty($add_join)){
            $query .= "\n LEFT JOIN #__os_cck_child_parent_connect AS cpc ON cpc.fid_parent = entcont.fk_eiid";
            }
            $query .= $multiple_query . ' ' . implode(' ', $add_join) 
            . "\n LEFT JOIN #__os_cck_categories AS categ ON catcon.fk_cid = categ.cid"//category table
            .((count($where) ? "\nWHERE " . implode(' AND ', $where) : ""));
        }elseif($entities_type[$entity_id] == 'joomla_user'){
            $comp_search_and_str = '';
            if(!empty($comp_search_and)){
                $comp_search_and_str = implode(' AND ', $comp_search_and) . 'AND ';
            }
            $query = "SELECT COUNT(DISTINCT us.id) FROM #__users as us " . implode(' ', $add_join);
            $query .= " WHERE us.block=0 AND ".$comp_search_and_str." (".implode(' OR ', $comp_search).")";
        }elseif($entities_type[$entity_id] == 'custom_sql'){
            $entity = new os_cckEntity($db->_db);
            $entity->load($entity_id);
            
            $id_field = $entityFieldLists[$entity_id]['custom_sql_id'];
            $comp_search_and_str = '';
            if(!empty($comp_search_and)){
                $comp_search_and_str = implode(' AND ', $comp_search_and) . 'AND ';
            }
            $where_string = " WHERE $comp_search_and_str (".implode(' OR ', $comp_search).")";
//            var_dump($where_string); exit;
            $query = "SELECT COUNT(t.$id_field->fid) FROM ($entity->sql_select) as t $where_string";
        }
        // print_r($query);exit;
      $db->setQuery($query);
      $total = $db->loadResult();
      
//      var_dump($total); exit;
      if($max_items != '0' && $max_items < $total ) {
          $total = $max_items;
      }
      
      //creating order by list
      $fields_from_params = getOrderByOptions('all_instance_order_by', $fields_from_params, $layout->fk_eid, $mod_type, $layout->lid);

      $order_by_selected = $fields_from_params["views"]["selected"];
      
      
      // $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';
      
      $pageNav = new os_libPagination($total, $limitstart, $limit);
      //var_dump($fields_from_params["fields"]["sortType_all_instance_order_by"]);

      //serch query
      if($entities_type[$entity_id] == 'os_cck_entity'){

          if($order_by_selected != '') $order_by_selected .=  ' ' . $fields_from_params["fields"]["sortType_all_instance_order_by"];
          $orderby = $fields_from_params["fields"]["sortType_all_instance_order_by"];
          $query = "SELECT distinct c.eiid FROM #__os_cck_entity_instance as c "
          //20.07.2022 VlaDOS
          //Ranshe mi vivodili instance stolko raz, v skolki kategoriyah on byl, vozmojno nujno dobavit nastroyku. Sey4as vivodim 1 raz
          //VlaDOS 20.07.2022
          //$query = "SELECT distinct c.eiid,catcon.fk_cid FROM #__os_cck_entity_instance as c "
            . "\n LEFT JOIN #__os_cck_content_entity_".$entity_id." AS entcont ON c.eiid = entcont.fk_eiid"//table for text field
            . "\n LEFT JOIN #__os_cck_categories_connect AS catcon ON c.eiid = catcon.fk_eiid"//need for conect entity and categories tables
                  . "\n LEFT JOIN #__os_cck_content_instances_price AS price ON c.eiid = price.fk_eiid"//for price search
            . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid = c.fk_lid"//need for conect entity and categories tables
            . "\n LEFT JOIN #__os_cck_child_parent_connect AS cpc ON cpc.fid_parent = entcont.fk_eiid"
            . $multiple_query . ' ' . implode(' ', $add_join) 
            . "\n LEFT JOIN #__os_cck_categories AS categ ON catcon.fk_cid = categ.cid"//category table
            // .$RentSQL_JOIN_1 . $RentSQL_JOIN_2 
            . ((count($where) ? "\nWHERE " . implode(' AND ', $where) : ""));
            if($order_by_selected != ''){
              if ($fields_from_params["views"]["selected"] == 'title') {

                  $query .= " ORDER BY c.title $orderby ";
              } elseif (stripos($fields_from_params["views"]["selected"], 'categoryfield') !== FALSE) {

                  $query .= " ORDER BY categ.name $orderby ";
              } elseif ($fields_from_params["views"]["selected"] == 'hits') {

                  $query .= " ORDER BY c.hits $orderby";
              } elseif ($fields_from_params["views"]["selected"] == 'last_review' || $fields_from_params["views"]["selected"] == 'last_review_date') {
                  $query .= " ORDER BY c.last_review $orderby ";
              } elseif ($fields_from_params["views"]["selected"] == 'custom_order') {

                  $query .= ' ORDER BY ' . $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 c.eiid ORDER BY price.price_value $orderby";
              }  else {

                  $query .= " ORDER BY entcont.`{$fields_from_params["views"]["selected"]}` $orderby ";
              }
                // $query .= "\n ORDER BY $order_by_selected ";
            }
//            $query .= " LIMIT $pageNav->limitstart, $pageNav->limit ";
      }elseif($entities_type[$entity_id] == 'joomla_user'){
          $request_details = getRequestDetailsForAlphabeticalJoomlaUser($fields_from_params["views"]["selected"]);
          //var_dump($request_details); //exit;
          $comp_search_and_str = ' ';
          $comp_search_and = array_unique($comp_search_and);
          foreach($comp_search_and as $and){
              $comp_search_and_str .= ' (' . $and . ') AND ';
          }
//          if(!empty($comp_search_and)){
//                $comp_search_and_str = implode(' AND ', $comp_search_and) . 'AND ';
//            }
//            var_dump($order_by_selected);
//          var_dump($order_by_selected);
            if($order_by_selected == 'ceid') $order_by_selected = 'us.id';
            if($order_by_selected != '') $order_by_selected .=  ' ' . $fields_from_params["fields"]["sortType_all_instance_order_by"];
//            $order_by = ' ORDER BY ' . $request_details['field_name'] . ' ' . $fields_from_params["fields"]["sortType_all_instance_order_by"];
            $order_by = $order_by_selected;
            //if($order_by_selected != '') $order_by_selected = ' ORDER BY ' . $order_by_selected . ' ' . $fields_from_params["fields"]["sortType_all_instance_order_by"];
//var_dump($order_by_selected); exit;
            $query = "SELECT us.id as eiid FROM #__users as us " . implode(' ', $add_join);
            $query .= " WHERE us.block=0 " . $request_details['where'] . "  AND ";
            $query .= " EXISTS 
                        (
                        SELECT us2.id as eiid2 
                        FROM #__users as us2 " . str_ireplace('us.id', 'us2.id', implode(' ', $add_join));
            $query .= str_ireplace('us.', 'us2.', " WHERE us2.block=0 AND ".$comp_search_and_str."  (".implode(' OR ', $comp_search).")");
            $query .= "and us2.id  = us.id GROUP BY us2.id) ";
            $query .= "\n GROUP BY us.id $order_by ";
        }elseif($entities_type[$entity_id] == 'custom_sql'){
//          $request_details = getRequestDetailsForAlphabeticalJoomlaUser($fields_from_params["views"]["selected"]);
          //var_dump($request_details); //exit;
          $comp_search_and_str = ' ';
          $comp_search_and = array_unique($comp_search_and);


            $query = "SELECT DISTINCT t.$id_field->fid as eiid FROM ($entity->sql_select) as t $where_string ";

              if(isset($fields_from_params["views"]["selected"]) && $fields_from_params["views"]["selected"] != ''){
                $query .= " ORDER BY t.".str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]) . ' ' . $fields_from_params["fields"]["sortType_all_instance_order_by"];
              }
//            $query .= "\n LIMIT $pageNav->limitstart, $pageNav->limit ";
        }
        
        $query_no_limit = $query;
      $query .= " LIMIT $pageNav->limitstart, $pageNav->limit ";
      $db->setQuery($query);
      
      $items = $db->loadObjectList();
      
      $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[$layout->lid] = $no_limit_items;
//      }
      $session->set( 'no_limit_items_arr', $no_limit_items_arr );
      $session->set( 'last_overall_layout.', $layout->lid );
      
      foreach ($items as $key => $item) {
          if($entities_type[$entity_id] == 'os_cck_entity'){
            $instance = new os_cckEntityInstance($db->_db);
            $instance->load($item->eiid);
            $instancies[$key] = $instance;
            if(property_exists($item, 'fk_cid')) {
                $instancies[$key]->cat_id = $item->fk_cid;
            }else{
                $instancies[$key]->cat_id = 0;
            }
          }elseif($entities_type[$entity_id] == 'joomla_user'){
              //var_dump($item);
              $instance = ConvertEntityInstanceToUser($entity_id, $item->eiid);
              $instancies[$key] = $instance;
              $instancies[$key]->cat_id = '';
          }elseif($entities_type[$entity_id] == 'custom_sql'){
//              var_dump($entity); exit;
              $instance = ConvertEntityInstanceToCustomSql($entity, $item->eiid);
              $instancies[$key] = $instance;
              $instancies[$key]->cat_id = '';
          }
      }
      ////////end search request
      
      
      $noth_found = false;
      if (!isset($instancies[0])) {
        $noth_found = true;
          
          //return;
      }
      $layout_params = unserialize($layout->params);
      
      $layout_params['all_instance_layout_params'] = $fields_from_params;
      $bootstrap_version = $session->get( 'bootstrap','2');
      $layout->layout_html = $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');
        }
      }
      

      $type =  'all_instance';

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

    static function showItem($option, $eiid, $catid, $lid = 0, $mod_type = 0, $recursive_count = 10, $Itemid = 0){


      if($recursive_count < 1) return;


      global $app, $db, $user, $os_cck_configuration,$moduleId,$limitstart, $doc, $entityFieldLists, $entities_type, $cck_entity_configuration;
      $db = new os_cckDb();
      // var_dump($cck_entity_configuration); exit;
      $jinput = JFactory::getApplication()->input;
      //var_dump($jinput);
      if($Itemid == 0){
          global $Itemid;
      }
      
      
      $moduleId = (($moduleId == 0 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
      
      if(!$moduleId){
        $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($jinput->get('Itemid', 0, 'INT')) : $Itemid;
        // 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
        if (version_compare(JVERSION, '3.0', 'ge')) {
          $params = new JRegistry;
          $params->loadString($mod_row->params);
        } else {
          $params = new JRegistry($mod_row->params);
        }//end
        if($params->get('ItemId', '') != ''){
          $Itemid = $params->get('ItemId', '');
        }
      }
      $session = JFactory::getSession();
      $nextInstId = 0;
      $prevInstId = 0;
     
      $queryItemIds = $session->get("queryItemIds");
      $category_layout = new os_cckLayout($db->_db);
      $all_instance_layout = new os_cckLayout($db->_db);
      $layout = new os_cckLayout($db->_db);
      $entityInstance = new os_cckEntityInstance($db->_db);
      //var_dump($entityInstance);
      $search_layout = new os_cckLayout($db->_db);

      
      
      

      if(!$lid){
        

        //if we set menu all_cat(category_layout layout take from all_cat layout,
        //entity_layout and entity_type from category layout(set in the backend))
        //if we have a module then params takes from module
        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'));//(expression ? true_value : false_value)
          $fields_from_params = unserialize($all_category_layout->params);
          $entity_id = $all_category_layout->fk_eid;
          //if we set default category lyout
          if($fields_from_params['views']['category_layout'] == 1){
            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{
            $category_layout->load($fields_from_params['views']['category_layout']);
            $fields_from_params = unserialize($category_layout->params);
          }
          //if we set default items lyout
          if($fields_from_params['views']['item_layout'] == 1){
            if($layout->getDefaultLayout($entity_id, 'instance')){
              $layout->load(intval($layout->getDefaultLayout($entity_id, 'instance')));
            }else{

              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
              return;
            }
          }else{
              $layout->load($fields_from_params['views']['item_layout']);
          }
        }//end all_cat menu

        //if we display category menu
        if($params->get('category_layout') || $params->get('layout_type') == 'category'){
          $category_layout->load($params->get('layout')?$params->get('layout') : $params->get('category_layout'));
          $fields_from_params = unserialize($category_layout->params);
          $entity_id = $category_layout->fk_eid;
          if($fields_from_params['views']['item_layout'] == 1){
            if($layout->getDefaultLayout($entity_id, 'instance')){
              $layout->load(intval($layout->getDefaultLayout($entity_id, 'instance')));
            }else{

              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
              return;
            }
          }else{
            $layout->load($fields_from_params['views']['item_layout']);
          }
        }//end category menu

        //if we display category with map menu


        if($params->get('all_instance_layout')){
          $all_instance_layout->load($params->get('all_instance_layout'));
          $fields_from_params = unserialize($all_instance_layout->params);
          $entity_id = $all_instance_layout->fk_eid;
          if($fields_from_params['views']['item_layout'] == 1){
            if($layout->getDefaultLayout($entity_id, 'instance')){
              $layout->load(intval($layout->getDefaultLayout($entity_id, 'instance')));
            }else{

              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
              return;
            }
          }else{
            $layout->load($fields_from_params['views']['item_layout']);
          }
        }//end category with map menu
        
        //if we display one item menu
        if($params->get('instance_layout') || $params->get('layout_type') == 'instance'){
          $layout->load($params->get('layout')?$params->get('layout') : $params->get('instance_layout'));
          $fields_from_params = unserialize($layout->params);
          if(!$layout->fk_eid || !$layout->published){

            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY_LAYOUT"), 'warning');
            return;
          }
          
//var_dump($params);
          $entity_id = $layout->fk_eid;
          $entity = new os_cckEntity($db->_db);
          $entity->load($entity_id);
          
          if($entity->type == 'os_cck_entity'){
            $entityInstance->load($params->get('instance'));
          }elseif($entity->type == 'joomla_user'){
              $user_id = $params->get('user');
              $entityInstance = ConvertEntityInstanceToUser($entity->eid, $user_id);
          }elseif($entity->type == 'custom_sql'){
              $entityInstance = ConvertEntityInstanceToCustomSql($entity, $params->get('instance'));
          }
          
            if(!$entityInstance->eiid){
              if(isset($cck_entity_configuration[$entity_id]['redirect_missing_instance']) && $cck_entity_configuration[$entity_id]['redirect_missing_instance'] != ''){
                if(stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'http://') != false || stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'https://') != false){
                  $redirect_url = $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
                }else{
                  $redirect_url = JUri::root() . $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
                }
      
                $app->redirect($redirect_url);
              }
              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_INSTANCE"), 'warning');
              return;
            }
            
        }else{



          $fields_from_params = unserialize($layout->params);
          
          if(isset($layout_params['fields']['cck_instance_navigation_published']) 
        && $layout_params['fields']['cck_instance_navigation_published']){
            //query for pagination//itemindex -- index number of instance in cat-instances array
            $andCID = '';
            $no_limit_items_arr = $session->get('no_limit_items_arr', array());
            $last_overall_layout = $session->get('last_overall_layout', 0);
            if(isset($no_limit_items_arr[$last_overall_layout]) && is_array($no_limit_items_arr[$last_overall_layout]) && !empty($no_limit_items_arr[$last_overall_layout])){
                foreach($no_limit_items_arr[$last_overall_layout] as $key_item => $temp_item){
                    if($temp_item->eiid == $eiid){
                        if($key_item > 0){
                            $prevInstId = $no_limit_items_arr[$last_overall_layout][$key_item-1]->eiid;
                        }
                        if(count($no_limit_items_arr[$last_overall_layout])-1 > $key_item){
                            $nextInstId = $no_limit_items_arr[$last_overall_layout][$key_item+1]->eiid;
                        }
                    }
//                    var_dump($temp_item);
                }
            }else{
                if($entities_type[$layout->fk_eid] == 'os_cck_entity'){
                    if($params->get('layout_type', '') == 'category'){
                        $catid = $params->get('category', '');
                    }else{
                        $catid = 0;
                    }
                    if($catid > 0)
                      $andCID = "AND cc.fk_cid=$catid";
                    $query = "SELECT eiid FROM #__os_cck_entity_instance as i "
                            ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = i.fk_lid "
                            ."\n LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = i.eiid "
                            ."\n WHERE l.type ='add_instance' ".$andCID." AND i.published=1 "
                            ."\n AND i.approved=1   AND i.eiid > ".intval($eiid)
                            ."\n AND i.fk_eid= " . $layout->fk_eid
                            ."\n ORDER BY eiid LIMIT 1";
                    $db->setQuery($query);
                    $nextInstId = $db->loadResult();

                    $query = "SELECT eiid FROM #__os_cck_entity_instance as i "
                            ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = i.fk_lid "
                            ."\n LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = i.eiid "
                            ."\n WHERE l.type ='add_instance' ".$andCID." AND i.published=1 "
                            ."\n AND i.approved=1   AND i.eiid < ".intval($eiid)
                            ."\n AND i.fk_eid= " . $layout->fk_eid
                            ."\n ORDER BY eiid DESC LIMIT 1";
                    $db->setQuery($query);
                    $prevInstId = $db->loadResult();
                }elseif($entities_type[$layout->eid] == 'joomla_user'){

                    $query = "SELECT id as eiid FROM #__users "
                            . "WHERE block=0 AND id> ".intval($eiid)
                            ."\n ORDER BY id LIMIT 1";
                    $db->setQuery($query);
                    $nextInstId = $db->loadResult();
    //                var_dump($nextInstId);

                    $query = "SELECT id as eiid FROM #__users "
                            . "WHERE block=0 AND id < ".intval($eiid)
                            ."\n ORDER BY id LIMIT 1";
                    $db->setQuery($query);
                    $prevInstId = $db->loadResult();
                }elseif($entities_type[$layout->eid] == 'custom_sql'){

                }
            }

            if(isset($_REQUEST['next']) && $_REQUEST['next'] > 0 && $nextInstId){
              $entityInstance->load(intval($nextInstId));
            }else if(isset($_REQUEST['prev']) && $_REQUEST['prev'] > 0 && $prevInstId){
              $entityInstance->load(intval($prevInstId));
            }else{
              $entityInstance->load(intval($eiid));
            }
          }
        }//end item menu
        //
        
        
        if($entityInstance->access != ''){
            $groupAccess = explode(',', $entityInstance->access);
        }else{
            $groupAccess = array();
            $groupAccess[] = '1';
        }
        
        $user = JFactory::getUser();
        if (!checkAccess_cck($groupAccess, $user->groups, $entity_id, 'instances')){

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_INSTANCE"), 'warning');
          return;
        }
        
        //if we display search menu
        if($params->get('search_layout') || $params->get('layout_type') == 'search'){
          $search_layout->load($params->get('layout')?$params->get('layout') : $params->get('search_layout'));
          $entity_id = $search_layout->fk_eid;
          $fields_from_params = unserialize($search_layout->params);
          if($fields_from_params['views']['all_instance_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{

              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
              return;
            }
          }else{
            $category_layout->load($fields_from_params['views']['all_instance_layout']);
            $fields_from_params = unserialize($category_layout->params);
          }
          if($fields_from_params['views']['item_layout'] == 1){
            if($layout->getDefaultLayout($entity_id, 'instance')){
              $layout->load(intval($layout->getDefaultLayout($entity_id, 'instance')));
            }else{

              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
              return;
            }
          }else{
            $layout->load($fields_from_params['views']['item_layout']);
          }
        }//end search menu


      }else{

          
        $layout->load($lid);
        $entity_id = $layout->fk_eid;
        $entity = new os_cckEntity($db->_db);
        $entity->load($entity_id);
          
//          if($entity->type == 'os_cck_entity'){
//            $entityInstance->load($params->get('instance'));
//          }elseif($entity->type == 'joomla_user'){
//              $user_id = $params->get('user');
//              $entityInstance = ConvertEntityInstanceToUser($entity->eid, $user_id);
//          }
        if($layout->params){
          $fields_from_params = unserialize($layout->params);
        }else{
          $fields_from_params = array();
        }
        // if(isset($fields_from_params['views']['show_navigation'])){
          //query for pagination//itemindex -- index number of instance in cat-instances array
          $andCID = '';
          $no_limit_items_arr = $session->get('no_limit_items_arr', array());
            $last_overall_layout = $session->get('last_overall_layout', 0);
            if(isset($no_limit_items_arr[$last_overall_layout]) && is_array($no_limit_items_arr[$last_overall_layout]) && !empty($no_limit_items_arr[$last_overall_layout])){
                foreach($no_limit_items_arr[$last_overall_layout] as $key_item => $temp_item){
                    if($temp_item->eiid == $eiid){
                        if($key_item > 0){
                            $prevInstId = $no_limit_items_arr[$last_overall_layout][$key_item-1]->eiid;
                        }
                        if(count($no_limit_items_arr[$last_overall_layout])-1 > $key_item){
                            $nextInstId = $no_limit_items_arr[$last_overall_layout][$key_item+1]->eiid;
                        }
                    }

                }
            }else{

                if($entities_type[$layout->fk_eid] == 'os_cck_entity'){

                    if($params->get('layout_type', '') == 'category'){
                        $catid = $params->get('category', '');
                    }else{
                        $catid = 0;
                    }
                      if($catid > 0)
                        $andCID = "AND cc.fk_cid=$catid";
                      $query = "SELECT eiid FROM #__os_cck_entity_instance as i "
                              ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = i.fk_lid "
                              ."\n LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = i.eiid "
                              ."\n WHERE l.type ='add_instance' ".$andCID." AND i.published=1 "
                              ."\n AND i.approved=1   AND i.eiid > ".intval($eiid)
                              ."\n AND i.fk_eid= " . $layout->fk_eid
                              ."\n ORDER BY eiid LIMIT 1";
                      $db->setQuery($query);
                      $nextInstId = $db->loadResult();

                      $query = "SELECT eiid FROM #__os_cck_entity_instance as i "
                              ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = i.fk_lid "
                              ."\n LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = i.eiid "
                              ."\n WHERE l.type ='add_instance' ".$andCID." AND i.published=1 "
                              ."\n AND i.approved=1   AND i.eiid < ".intval($eiid)
                              ."\n AND i.fk_eid= " . $layout->fk_eid
                              ."\n ORDER BY eiid DESC LIMIT 1";
                      $db->setQuery($query);
                      $prevInstId = $db->loadResult();
                  }elseif($entities_type[$layout->fk_eid] == 'joomla_user'){

                      $query = "SELECT id as eiid FROM #__users "
                              . "WHERE block=0 AND id> ".intval($eiid)
                              ."\n ORDER BY id LIMIT 1";
                      $db->setQuery($query);
                      $nextInstId = $db->loadResult();

                      $query = "SELECT id as eiid FROM #__users "
                              . "WHERE block=0 AND id < ".intval($eiid)
                              ."\n ORDER BY id DESC LIMIT 1";
                      $db->setQuery($query);
                      $prevInstId = $db->loadResult();
                  }elseif($entities_type[$layout->fk_eid] == 'custom_sql'){

                      $fieldId = $entityFieldLists[$layout->fk_eid]['custom_sql_id']->fid;
                      $query = "SELECT t.$fieldId as eiid FROM ($entity->sql_select) as t "
                              . "WHERE t.id> ".intval($eiid)
                              ."\n ORDER BY id LIMIT 1";
                      $db->setQuery($query);
                      $nextInstId = $db->loadResult();


                      $query = "SELECT t.$fieldId as eiid FROM ($entity->sql_select) as t "
                              . "WHERE t.id< ".intval($eiid)
                              ."\n ORDER BY t.id DESC LIMIT 1";
                      $db->setQuery($query);
                      $prevInstId = $db->loadResult();

                  }
            }

          if($entity->type == 'os_cck_entity'){
              if(isset($_REQUEST['next']) && $_REQUEST['next'] > 0 && $nextInstId){
                $entityInstance->load(intval($nextInstId));
              }else if(isset($_REQUEST['prev']) && $_REQUEST['prev'] > 0 && $prevInstId){
                $entityInstance->load(intval($prevInstId));
              }else{
                $entityInstance->load(intval($eiid));
              }
          }elseif($entity->type == 'joomla_user'){
              //$user_id = $params->get('user');
              $entityInstance = ConvertEntityInstanceToUser($entity->eid, $eiid);
          }elseif($entity->type == 'custom_sql'){
              $entityInstance = ConvertEntityInstanceToCustomSql($entity, $eiid);
          }
        // }else{
        //   $entityInstance->load(intval($eiid));
        // }

        //features
        if($entityInstance->featured_clicks == 0){
          //return;
        }else{
          if($entityInstance->eiid){
            $featured_clicks = 0;
            if($entityInstance->featured_clicks != 0 && $entityInstance->featured_clicks != ''){
              $featured_clicks = 1;
            }
            $query = "UPDATE #__os_cck_entity_instance SET "
                      ."\n featured_clicks = featured_clicks-".$featured_clicks
                      ."\n WHERE eiid=".$entityInstance->eiid;
            $db->setQuery($query);
            $db->execute();
          }
        }
      }
      
//      var_dump($no_limit_items_arr);
      $layout->layout_html = $layout->getLayoutHtml('2');
      if($layout->layout_html !== null){
          $lay_html = urldecode($layout->layout_html);
      }else{
          $lay_html = '';
      }
      $limit = (isset($fields_from_params['views']['pagenator_limit']) && strpos($lay_html,"{|f-joom_pagination|}")) ? $fields_from_params['views']['pagenator_limit'] : 0;
      // var_dump($limit);
      if(isset($fields_from_params['views']['limit'])){
          $max_items = $fields_from_params['views']['limit'];
      }else{
          $max_items = 0;
      }
      $fields_from_params = getOrderByOptions('cck_review_order_by', $fields_from_params, $layout->fk_eid, $mod_type, $layout->lid);

    $GLOBALS['review_limit'] = $limit;
    $GLOBALS['review_max_items'] = $max_items;
//$doc->setDescription('');
        $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$entity_id/custom.css");
//        var_dump($cck_entity_configuration[$layout->fk_eid]);
        if(isset($cck_entity_configuration[$layout->fk_eid]['meta_title_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_title_source'] === '0'){
            $doc->setTitle('');
        }elseif(isset($cck_entity_configuration[$layout->fk_eid]['meta_title_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_title_source'] === '2'){
            $title = getInstanceTitle($entityInstance);
            $doc->setTitle($title);
        }elseif(isset($cck_entity_configuration[$layout->fk_eid]['meta_title_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_title_source'] === '3'){
            $title = getInstanceTitle($entityInstance);
            if($title != ''){
                $doc->setTitle($title);
            }
        }
//        var_dump($cck_entity_configuration[$layout->fk_eid]['meta_description_source']);
        if(isset($cck_entity_configuration[$layout->fk_eid]['meta_description_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_description_source'] === '0'){

            $doc->setDescription('');
        }elseif(isset($cck_entity_configuration[$layout->fk_eid]['meta_description_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_description_source'] === '2'){
            $doc->setDescription($entityInstance->meta_description);
        }elseif(isset($cck_entity_configuration[$layout->fk_eid]['meta_description_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_description_source'] === '3'){
            if($entityInstance->meta_description != ''){
                $doc->setDescription($entityInstance->meta_description);
            }
        }
        
        if(isset($cck_entity_configuration[$layout->fk_eid]['meta_keywords_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_keywords_source'] === '0'){
            $doc->setMetaData('keywords','');
        }elseif(isset($cck_entity_configuration[$layout->fk_eid]['meta_keywords_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_keywords_source'] === '2'){
            $doc->setMetaData('keywords',$entityInstance->meta_keywords);
        }elseif(isset($cck_entity_configuration[$layout->fk_eid]['meta_keywords_source']) && $cck_entity_configuration[$layout->fk_eid]['meta_keywords_source'] === '3'){
            if($entityInstance->meta_keywords != ''){
                $doc->setMetaData('keywords',$entityInstance->meta_keywords);
            }
        }
//        if($entityInstance->meta_title != ''){
//            $doc->setTitle($entityInstance->meta_title);
//        }
//        if($entityInstance->meta_description != ''){
//            $doc->setDescription($entityInstance->meta_description);
//        }
//        if($entityInstance->meta_keywords != ''){
//            $doc->setMetaData('keywords',$entityInstance->meta_keywords);
//        }
        
        if($entityInstance->meta_robots > 0){
            if($entityInstance->meta_robots == 1){
                $robots_text = 'index, follow';
            }elseif($entityInstance->meta_robots == 2){
                $robots_text = 'noindex, follow';
            }elseif($entityInstance->meta_robots == 3){
                $robots_text = 'index, nofollow';
            }elseif($entityInstance->meta_robots == 4){
                $robots_text = 'noindex, nofollow';
            }
//            var_dump($robots_text);
//            switch ($entityInstance->meta_robots){
//            case 1:
//                $robots_text = 'index, follow';
//            case 2:
//                $robots_text = 'noindex, follow';
//            case 3:
//                $robots_text = 'index, nofollow';
//            case 4:
//                $robots_text = 'noindex, nofollow';
//            }    

            $doc->setMetaData('robots',$robots_text);
            
        }
      


      if(!$layout->title || $layout->type != 'instance'){
        if(isset($cck_entity_configuration[$entity_id]['redirect_missing_instance']) && $cck_entity_configuration[$entity_id]['redirect_missing_instance'] != ''){
          if(stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'http://') != false || stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'https://') != false){
            $redirect_url = $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
          }else{
            $redirect_url = JUri::root() . $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
          }

          $app->redirect($redirect_url);
        }
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_INSTANCE"), 'warning');
        return;
      }
      if (!$entityInstance->eiid){
        if(isset($cck_entity_configuration[$entity_id]['redirect_missing_instance']) && $cck_entity_configuration[$entity_id]['redirect_missing_instance'] != ''){
          if(stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'http://') != false || stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'https://') != false){
            $redirect_url = $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
          }else{
            $redirect_url = JUri::root() . $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
          }

          $app->redirect($redirect_url);
        }
        // var_dump($redirect_url);
        // var_dump($cck_entity_configuration[$entity_id]);
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_INSTANCE"), 'warning');
        return;
      }
      if(!$entityInstance->published || !$entityInstance->approved){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INSTANCE_ERROR_APPROVE_PUBLISH"), 'warning');
        return;
      }
      $header = $category_layout->title;
      $params->def('header', $header);
      $params->def('pageclass_sfx', '');
      // $use_bredcrambs = $params->get('use_bredcrambs', '1');
      // var_dump($use_bredcrambs);
      
      if ($catid > 0) {
        $query = "SELECT * FROM #__os_cck_categories WHERE cid='{$catid}'";
        $db->setQuery($query);
        $category = $db->loadObjectList();
        os_cck_site_controller::cck_constructPathway($category[0], 'instance', $mod_type);
        $pathway = JRoute::_('index.php?option=' . $option . '&task=showCategory&catid=' . 
          $category[0]->cid . '&Itemid=' . $Itemid);
        $pathway_name = $category[0]->name;
        if($mod_type == 0){
          if($entityInstance->title != ''){
              $app->getPathway()->addItem($entityInstance->title, $pathway);
          }else{
              $query = "SELECT name FROM #__os_cck_entity WHERE eid = " . $entityInstance->fk_eid;
              $db->setQuery($query);
              $entity_name = $db->loadResult();
              $app->getPathway()->addItem('One ' . $entity_name, $pathway);
              //var_dump($entity_name);
          }
        }

      } else {


        $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=" . $entityInstance->eiid . ""
                . "\n LIMIT 0,1";
        $db->setQuery($query);
        $category = $db->loadObjectList();
//        var_dump($layout_params);
        if($mod_type == 0){
          if($entityInstance->meta_title != ''){
              $app->getPathway()->addItem($entityInstance->meta_title, $entityInstance->meta_title);
          }elseif($entityInstance->title != ''){
              $app->getPathway()->addItem($entityInstance->title, $entityInstance->title);
          }else{
              $layout_params = $fields_from_params;
              foreach($entityFieldLists[$entityInstance->fk_eid] as $i => $field){
                  if(isset($layout_params['fields'][$entityFieldLists[$entityInstance->fk_eid][$i]->db_field_name.'_title_field']) && $layout_params['fields'][$entityFieldLists[$entityInstance->fk_eid][$i]->db_field_name.'_title_field'] == 1){
          //                                $title_field = $entityFieldLists[$fk_eid][$i]->db_field_name;
                      $title_field = $entityFieldLists[$entityInstance->fk_eid][$i];
                  }
                }
                if(isset($title_field)){
                    $title = $entityInstance->getFieldValue($title_field);
                    $title = $title[0]->data;
  //                  var_dump($title);
                    $app->getPathway()->addItem($title, $title);
                }
          }
        }
        

      }
      if($category)
        $category = $category[0];

      //Record the hit
      $sql = "UPDATE #__os_cck_entity_instance SET hits = hits + 1 WHERE eiid = " . $entityInstance->eiid . "";
      $db->setQuery($sql);
      $db->execute();
      $params->def('pageclass_sfx', '');
      $params->def('item_description', 1);
      $params->def('back_button', $app->getCfg('back_button'));
      $currentcat = new stdclass();
      $currentcat->header = $params->get('header');
      $currentcat->header = $currentcat->header . ": " . $entityInstance->title;
      $bootstrap_version = $session->get( 'bootstrap','2');
      $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
      $layout_params = $fields_from_params;
      
      $layout_params['custom_fields'] = unserialize($layout->custom_fields);
      
      $layout_params['nextInstId'] = $nextInstId;
      $layout_params['prevInstId'] = $prevInstId;

      $layout_params['has_price'] = 0;
      //var_dump($entity);
      if(isset($entity) && $entity->eid){
          $layout->field_list = $entityFieldLists[$entity->eid];
      }else{
        $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
      }

      if($layout->layout_html !== null){
        $html = urldecode($layout->layout_html);
      }else{
          $html = '';
      }
      $layout_fields = $layout_params['fields'];

      foreach ($layout->field_list as $field) {
        if(strpos($html,"{|f-".$field->fid."|}")){
          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(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);
          foreach($mids as $key => $mid){
              if($mid == 'undefined'){
                  unset($mids[$key]);
              }
          }
          if(!empty($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');
          }
        }
      }
      //features
      if($entityInstance->featured_shows == 0){
        //return;
      }else{
        $featured_shows = 0;
        if($entityInstance->featured_shows != 0 && $entityInstance->featured_shows != ''){
          $featured_shows = 1;
        }
        $query = "UPDATE #__os_cck_entity_instance SET "
                  ."\n featured_shows = featured_shows-".$featured_shows
                  ."\n WHERE eiid=".$entityInstance->eiid;
        $db->setQuery($query);
        $db->execute();
      }

      //features
      $type = 'instance';

      //check access for category

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

        $db->setQuery("SELECT * FROM `#__os_cck_categories` e WHERE e.`cid` = {$category->cid}");
        $carCatParams =$db->loadObjectList();

        if(!$carCatParams){

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_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) {

            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_CATEGORY"), 'warning');
            return;
        }//end  
      }
      //check access for category

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

    static function showInstanceManager($instance_type){

      global $option,$os_cck_configuration, $Itemid, $moduleId, $db, $app, $templateDir, $user, $entityFieldLists, $os_cck_state;
      $db = new os_cckDb();
//      var_dump($instance_type);

      $input = $app->input;
      
      $option = 'com_os_cck';

        if($input->get('option', 'com_os_cck') == 'com_simplemembership'){

            $plugin = JPluginHelper::getPlugin('simplemembership', 'plg_simplemembership_get_cck_user_instances');
            $params = new JRegistry($plugin->params);
        }else{
            if(!$moduleId){
              // Params(cck component menu)
              if (version_compare(JVERSION, '3.0', 'ge')) {
                $menu = new JTableMenu($db->_db);
                $menu->load($Itemid);

                $params = new JRegistry;
                if($menu->params){
                  $params->loadString($menu->params);
                }

              }else{
                $app    = JFactory::getApplication();
                $menu   = $app->getMenu();
                $params = new JRegistry;
                $params = $menu->getParams( $Itemid );
              }//end
            }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
              if (version_compare(JVERSION, '3.0', 'ge')) {
                $params = new JRegistry;
                $params->loadString($mod_row->params);
              } else {
                $params = new JRegistry($mod_row->params);
              }//end
            }
        }

        $entity_list = $params->get('entity_list',array() ) ;
        $entity_list_str = implode(',',$entity_list);
        if(empty($entity_list_str)){

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY"), 'warning');
          return;
        }

        //Calling the general method of processing manager instances.
        $instance = new os_cckEntityInstance($db->_db);
        $vars = $instance->getInstanceManager($option, false, $instance_type,$entity_list);

      if($instance_type == 'add_instance'){
        $type = 'instance_manager';
        require getLayoutPathCCK::getLayoutPathCom($option, $type);
      }else if($instance_type == 'rent_request_instance'){
        $type = 'rent_requests_manager';
        require getLayoutPathCCK::getLayoutPathCom($option, $type);
      }else if($instance_type == 'buy_request_instance'){
        $type = 'buy_requests_manager';
        require getLayoutPathCCK::getLayoutPathCom($option, $type);
      }else if($instance_type == 'request_instance'){
        $type = 'requests_manager';
        require getLayoutPathCCK::getLayoutPathCom($option, $type);
      }
 
    }

    static function publishInstances($eiid, $publish, $option){

      global $db, $os_cck_configuration, $user, $Itemid, $app, $os_cck_state;

      $db = new os_cckDb();
      if(!cck_checkReferer()){
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
          return;
      }

      if(!isset($os_cck_state->data) ){
          echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
          return ;
      }

      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      //$catid = protectInjectionWithoutQuote('catid', array());
      if (!is_array($eiid) || count($eiid) < 1) {
        $action = $publish ? 'publish' : 'unpublish';
        echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
        exit;
      }

      $max_items_error = false;
      foreach ($eiid as $inst_id){
          $instance = new os_cckEntityInstance($db->_db);
          $instance->load($inst_id);
          //var_dump(!$publish);
          //var_dump(isСorrectMaxItemsLimit($instance->fk_eid)); exit;
          if(!$publish || isСorrectMaxItemsLimit($instance->fk_eid)){
              $instance->publishInstance($publish);
              $instance->checkin($inst_id);
          }else{
              $max_items_error = true;
          }
      }
      if(!$max_items_error){
        $app->enqueueMessage('ok', 'success');
        $app->redirect("index.php?option=$option&task=instance_manager&Itemid=".$Itemid);
      }else{
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_MAX_ITEMS"), 'warning');
          $app->redirect("index.php?option=$option&task=instance_manager&Itemid=".$Itemid);
      }
    }

    static function approveInstances($eiid, $publish, $option){
      global $db, $os_cck_configuration, $user, $Itemid, $app, $entityFieldLists, $os_cck_state;
      $db = new os_cckDb();
      if(!cck_checkReferer()){

            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      $catid = protectInjectionWithoutQuote('catid', array());
      if (!is_array($eiid) || count($eiid) < 1) {
        $action = $publish ? 'approve' : 'unapprove';
        echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
        exit;
      }
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    foreach ($eiid as $inst_id){
        $instance = new os_cckEntityInstance($db->_db);
          $instance->load($inst_id);
          $instance->approvInstance($publish);
    }
//      $eiids = implode(',', $eiid);
//      $db->setQuery("UPDATE #__os_cck_entity_instance SET approved='$publish'"
//                      . "\n WHERE eiid IN ($eiids) AND (checked_out=0 OR (checked_out='$user->id'))");
//      if (!$db->execute()) {
//        echo "<script> alert('" . addslashes($db->getErrorMsg()) . "'); window.history.go(-1); </script>\n";
//        exit ();
//      }
//      if (count($eiid) == 1) {
//        $instance = new os_cckEntityInstance($db->_db);
//        $instance->checkin($eiid[0]);
//      }
      $app->enqueueMessage('ok', 'success');
      $app->redirect("index.php?option=$option&task=instance_manager&Itemid=".$Itemid);
    }

    static function remove_buy_request_instance($eiids, $option){
      global $db, $os_cck_configuration, $Itemid, $app, $entityFieldLists, $os_cck_state;
      $db = new os_cckDb();
      if(!cck_checkReferer()){

            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      if (!is_array($eiids) || count($eiids) < 1) {
        echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
        exit;
      }
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      if (count($eiids)) {
        foreach ($eiids as $eiid) {
          $instance = new os_cckEntityInstance($db->_db);
          $instance->load($eiid);
          $instance->delete();
        }
      }
      $app->enqueueMessage('ok', 'success');
      $app->redirect("index.php?option=$option&task=show_buy_request_instances&Itemid=".$Itemid);
    }

    static function editRentRequestInstance($option, $eiid, $recursive = 1){
      global $db, $os_cck_configuration, $user, $app, $Itemid, $entityFieldLists, $os_cck_state;
      $db = new os_cckDb();
      $Itemid = (($Itemid == 0 || empty($Itemid)) && isset($_REQUEST['Itemid'])) ? intval($_REQUEST['Itemid']) : $Itemid;
      $select_type = protectInjectionWithoutQuote('lay_type','');
      $entityInstance = new os_cckEntityInstance($db->_db);
      $entityInstance->load(intval($eiid));
      if(!$entityInstance->eiid){
        return;
      }
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $extra_fields_list = $entityFieldLists[$entityInstance->fk_eid];
      $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child = $entityInstance->eiid";
      $db->setQuery($query);
      $parent_instance = $db->loadResult();
      
      $layout = new os_cckLayout($db->_db);
      if(empty($parent_instance)){
        if($layout->getDefaultLayout($entityInstance->fk_eid, 'instance')){
          $layout->load(intval($layout->getDefaultLayout($entityInstance->fk_eid, 'instance')));
        }else{

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
          return;   
        }
      }else{
        $layout->load(intval($entityInstance->fk_lid));
      }
      
     $layout_params = unserialize($layout->params);
     if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $str_list = array();
      $str_list['layout_params'] = $layout_params;
      $str_list['layout'] = $layout;
      $str_list['parent_instance'] = $parent_instance;
      
      $str_list['extra_fields_list'] = $extra_fields_list;
      //print_r($entityInstance);exit;
      //AdminViewRent_request :: editRentRequestInstance($option, $entityInstance, $str_list);
      $type = 'edit_rent_request';
      
      require getLayoutPathCCK::getLayoutPathCom($option, $type);
    }

    static function editBuyRequestInstance($option, $eiid){
      global $db, $os_cck_configuration, $user, $app, $Itemid, $entityFieldLists, $os_cck_state;
      $db = new os_cckDb();
      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      $select_type = protectInjectionWithoutQuote('lay_type','');
      $entityInstance = new os_cckEntityInstance($db->_db);
      $entityInstance->load(intval($eiid));
      if(!$entityInstance->eiid){
        return;
      }
      $extra_fields_list = $entityFieldLists[$entityInstance->fk_eid];
      $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child = $entityInstance->eiid";
      $db->setQuery($query);
      $parent_instance = $db->loadResult();
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $layout = new os_cckLayout($db->_db);
      if(empty($parent_instance)){
        if($layout->getDefaultLayout($entityInstance->fk_eid, 'instance')){
          $layout->load(intval($layout->getDefaultLayout($entityInstance->fk_eid, 'instance')));
        }else{

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
          return;   
        }
      }else{
        $layout->load(intval($entityInstance->fk_lid));
      }
      
      $layout_params = unserialize($layout->params);

      $str_list = array();
      $str_list['layout_params'] = $layout_params;
      $str_list['layout'] = $layout;
      $str_list['parent_instance'] = $parent_instance;
      $str_list['extra_fields_list'] = $extra_fields_list;
      //print_r($entityInstance);exit;
      //AdminViewRent_request :: editRentRequestInstance($option, $entityInstance, $str_list);
      $type = 'edit_buy_request';
      require getLayoutPathCCK::getLayoutPathCom($option, $type);
    }

    static function editInstance($option, $eiid=0, $lid=0){
      global $db, $os_cck_configuration, $user, $app, $Itemid, $moduleId, $entityFieldLists, $os_cck_state, $doc;

      $db = new os_cckDb();

      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      $session = JFactory::getSession();
      $select_type = protectInjectionWithoutQuote('lay_type','');
      $task = protectInjectionWithoutQuote('task','');
      // var_dump($task);
      $entityInstance = new os_cckEntityInstance($db->_db);
      $entityInstance->load(intval($eiid));

      if(!$moduleId){
        // Params(cck component menu)
        if (version_compare(JVERSION, '3.0', 'ge')) {
          $menu = new JTableMenu($db->_db);
          $menu->load($Itemid);
          $menu_params = new JRegistry;
          if($menu->params){
            $menu_params->loadString($menu->params);
          }          

        }else{
          $app    = JFactory::getApplication();
          $menu   = $app->getMenu();
          $menu_params = new JRegistry;
          $menu_params = $menu->getParams( $Itemid );
        }//end
      }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
        if (version_compare(JVERSION, '3.0', 'ge')) {
          $menu_params = new JRegistry;
          $menu_params->loadString($mod_row->params);
        } else {
          $menu_params = new JRegistry($mod_row->params);
        }//end
      }

      // var_dump($_REQUEST);
      $layout = new os_cckLayout($db->_db);
      $is_new = false;
      if (($eiid === 0 || empty($eiid) || (isset($eiid[0]) && $eiid[0] == 0)) && $lid > 0) {
        $is_new = true;
        $layout->load($lid);
        $entity = new os_cckEntity($db->_db);
        $entity->load($layout->fk_eid);
        $entityInstance->fk_eid = $layout->fk_eid;
      } else if( ($eiid === 0 || empty($eiid) || (isset($eiid[0]) && $eiid[0] == 0)) && $lid == 0 )  {
        //task add_instance

        $is_new = true;
        $entity_list = $menu_params->get('entity_list',array());
        if( count($entity_list) == 1  && $task == "add_instance"  ){
          //task add_instance and 1 entity add permited
           
          $entity = new os_cckEntity($db->_db);
          $entity->load($entityInstance->fk_eid);
          $lid = $entityInstance->fk_lid;
          $layout->load($lid);
        }else if( count($entity_list) > 1  && $task == "add_instance"  ){
          //task add_instance and many entity add permited
          //we at next code defind Entey List and Layout List - for select for add instance

        } else {
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY"), 'warning');
          return;
        }
      } else {
        $entity = new os_cckEntity($db->_db);
        $entity->load($entityInstance->fk_eid);
        $select_type = $entityInstance->fk_lid;
      }

      $input = $app->input;
      
      if(!$lid){
        $lid = $input->getInt('lay_type', false);
      }

      if($lid){
        $select_type = $lid;
      }
      if(!$lid && $entityInstance->fk_lid){
        $layout->load($entityInstance->fk_lid);
      }elseif($lid){
        $layout->load($lid);
      }
      // var_dump($layout); //exit;
      
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      

    // var_dump($params);
    $groupAccess = $menu_params->get('instance_manager_access','1');
    //$show_type = $menu_params->get('show_type','1');//1-own//2-all -- here incorrect not "show type" - here show instances from "owner" or "all"
    $show_type = 1;

    $user = JFactory::getUser();
    $layout_type = $menu_params->get('layout_type', '');
    if($layout_type == ''){
      if (!checkAccess_cck($groupAccess, $user->groups, $entityInstance->fk_eid, 'instances', $eiid)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_INSTANCE_MANAGER"), 'warning');
        return;
      }
      
      if(!checkInstanceManagerItem($menu_params)){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY"), 'warning');
        return;
      }

    }else{
      // var_dump($_REQUEST);
      $old_lid = protectInjectionWithoutQuote('old_lid', 0, 'INT');
      if($old_lid > 0){
        $query = "SELECT params FROM #__os_cck_layout WHERE lid=$old_lid";
        // var_dump($old_lid); exit;
        $db->setQuery($query);
        $old_lay_params = $db->loadResult();
        $old_lay_params = unserialize($old_lay_params);
        // var_dump($old_lay_params); exit;
        $button = protectInjectionWithoutQuote('button', 0, 'INT');

        $groupAccess = $old_lay_params['fields']['access_cck_action_button_'.$button];
        if (!checkAccess_cck($groupAccess, $user->groups, $entityInstance->fk_eid, 'instances', $eiid)){

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_INSTANCE_MANAGER"), 'warning');
          return;
        } 
      }
    }

    //get accessible layouts
    $entity_list = $menu_params->get('entity_list',array());
    $entity_str = ",".implode(',', $entity_list). ",";
    if( !empty($entity_list) && !empty($entityInstance->fk_eid)  ){
      //task edit_instance and entity defined
       
      if( $task == 'edit_instance' && !strpos($entity_str,"{$entityInstance->fk_eid}" ) ) {
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY"), 'warning');
        return;
      } else if( $task == 'add_instance' ){
        //all good  
      }
    }



    $where_and = '';
    if($entityInstance->fk_eid != ''){
        $where_and = "AND c.fk_eid = '" . $entityInstance->fk_eid . "' ";
    }elseif(isset($entity_list) && count($entity_list) > 0 ){
      //task add_instance : show all what permited
      $entity_str = implode(',', $entity_list);
      $where_and = " AND c.fk_eid in (". $entity_str . ") ";
    }
    $query = "SELECT c.title,c.lid,c.custom_fields,c.type,c.params,c.fk_eid,ent.name FROM #__os_cck_layout as c"
            ."\n LEFT JOIN #__os_cck_entity as ent ON c.fk_eid = ent.eid WHERE c.type='add_instance' "
            ."\n AND c.published = '1' " . $where_and ;
    $db->setQuery($query);
    $layouts = $db->loadObjectList();
    if(!$layouts){
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ADD_LAYOUT"), 'warning');
      return;
    }
// var_dump($select_type); exit ;


    // $default_layout = $layout->getDefaultLayout($eid,'add_instance');
    
    // if(isset($entityInstance->fk_eid)){
    //     $default_layout = $instance_layout->getDefaultLayout($entityInstance->fk_eid,'add_instance');
    // }else{
    //     $app->enqueueMessage(cck_lang_text("Sanity test error 1121"), 'warning');
    //     return;
    // }


    $lid_array = [];
    foreach($layouts as $key => $value){
      $lid_array[] = $value->lid;
    }

    // if(!in_array($select_type, $lid_array)){
    //   $select_type = $default_layout;
    // }

    foreach($layouts as $key => $value){
      $params = unserialize($value->params);
      $params['instance_type'] = $value->type;
      $params['custom_fields'] = unserialize($value->custom_fields);
      if($select_type){
        if($select_type == $value->lid){
          $lid = $value->lid;
          $layout_params = $params;  
          $ceid = $value->fk_eid;
        }
      }else{
        if(!$key){//select first option
          $lid = $value->lid;
          $layout_params = $params;
          $ceid = $value->fk_eid;
        }
      }
      $type[]= JHTML::_('select.option',"$value->lid",$value->title.'('.$value->name.')');
    }
    
    if(isset($type) && is_array($type) && count($type) > 1){
      $layout_type = JHTML::_('select.genericlist',$type, 'lay_type', 
        'class="inputbox" size="1" onchange="swich_task(\''.$task.'\');lay_type_select();"',
         'value', 'text', $select_type);
    }else{
      $layout_type = '';
    }


      // print_r($entityInstance->fk_eid);
      // exit;
      if($entityInstance->fk_eid){
        $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_{$entityInstance->fk_eid}/custom.css");
      }elseif( $layout->fk_eid ){
        $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_{$layout->fk_eid}/custom.css");
      }
      
      
      if($is_new && $select_type && JLanguageMultilang::isEnabled()){
          $lang = JFactory::getLanguage();
          $lang_tag = $lang->getTag();
          
          $query = "SELECT language, associate_layout FROM #__os_cck_layout WHERE lid=".$select_type;
          $db->setQuery($query);
          $layouts_langs = $db->loadObjectList();
          
          if($layouts_langs[0]->language != '' && $layouts_langs[0]->language != '*' && $layouts_langs[0]->language != $lang_tag){
              $assoc_layouts = unserialize($layouts_langs[0]->associate_layout);
              if(isset($assoc_layouts[$lang_tag])){
                  $select_type = $assoc_layouts[$lang_tag];
              }
              
          }
      }
      
      $categories = array();
      $db->setQuery("SELECT cid AS value, name AS text FROM #__os_cck_categories" .
                          " ORDER BY ordering");
      $cat = $db->loadObjectList();
      if (count($cat) > 0) $categories = array_merge($categories, $cat);
      $query = "SELECT fk_cid FROM #__os_cck_categories_connect WHERE fk_eiid='" . $entityInstance->eiid . "'";
      $db->setQuery($query);
      $cid = $db->loadResult();
      $clist = os_cck_HTML::categoryList($cid);
      if ($entityInstance->checked_out && $entityInstance->checked_out <> $user->id) {
          $app->enqueueMessage(cck_lang_text('COM_OS_CCK_IS_EDITED'), 'warning');
        
        return;
      }

      if (!$is_new) {
        if($user->id){
            $entityInstance->checkout($user->id);
            $entityInstance->fk_userid = $user->id;
        }else{
            $entityInstance->fk_userid = 0;
        }
      } else {
        // initialise new record
        $entityInstance->published = 0;
        $entityInstance->approved = 0;
      }

      if ($is_new) $query = 'SELECT eid,name FROM #__os_cck_entity WHERE published="1" ORDER BY name ';
      else $query = 'SELECT eid,name FROM #__os_cck_entity ORDER BY name ';
      $db->setQuery($query);
      $entities_list = $db->loadObjectList();
      if (count($entities_list) < 1) {

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY"), 'warning');
        return;
      }
      if ($is_new && $ceid != 0) $entityInstance->fk_eid = $ceid;
      $extra_fields_list = $entityFieldLists[$entityInstance->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->load($lid);
      $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
      $layout->parent_eiid = $eiid;
      $bootstrap_version = $session->get( 'bootstrap','2');
      $layout->layout_html = $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 && $attachedModuleId != 'undefined'){
            $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($task); exit;
      if($task == 'add_instance'){
        $type = 'add_instance';
      }else if($task == 'editInstance' && $$eiid == 0 ){
        $type = 'add_instance';
      }else{
          if($layout->type == 'review_instance'){
              $type = 'review_instance';
          }else{
              $type = 'editInstance';
          }
      }
      require getLayoutPathCCK::getLayoutPathCom('com_os_cck',$type);
    }

    static function decline_rent_requests($option, $eiids){
      global $db, $os_cck_configuration, $Itemid, $app, $os_cck_state;
      $db = new os_cckDb();
      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      foreach ($eiids as $eiid) {
        $rent_request = new os_cckEntityInstance($db->_db);
        $rent_request->load($eiid);
        $tmp = $rent_request->decline();
        if ($tmp != null) {
          echo "<script> alert('" . addslashes($tmp) . "'); window.history.go(-1); </script>\n";
          exit ();
        }
      }
      $app->enqueueMessage('ok', 'success');
      $app->redirect("index.php?option=$option&task=show_rent_request_instances&Itemid=".$Itemid);
    }

    static function accept_rent_requests($option, $eiids){

      
      global $db, $os_cck_configuration, $Itemid, $app, $os_cck_state, $input;
      $db = new os_cckDb();
      if(!cck_checkReferer()){

            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
      $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;

      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      foreach ($eiids as $eiid) {

        $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child=$eiid";

        $db->setQuery($query);
        $parent_id = $db->loadResult();

        $rent_request = new os_cckEntityInstance($db->_db);
        $rent_request->load($parent_id);
        $rent_request->child_id = $eiid;

        $entity = new os_cckEntity($db->_db);
        $entity->load($rent_request->fk_eid);
        $rent_request->entity_name = $entity->name;

        $tmp = $rent_request->accept();

        if ($tmp != null) {
          echo "<script> alert('" . addslashes($tmp) . "'); window.history.go(-1); </script>\n";
          exit ();
        }
      }
      $app->enqueueMessage('ok', 'success');

      if($input->get('view') != 'stripe') {
          $app->redirect("index.php?option=$option&task=show_rent_request_instances&Itemid=" . $Itemid);
      }
    }
    
    static function accept_buy_requests($option, $eiids){
        global $db,$app, $os_cck_state, $input;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }

        foreach ($eiids as $bid) {
            $instance = new os_cckEntityInstance($db->_db);
            $instance->load($bid);
            $instance->publishInstance(0);

//          $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child=$bid";
//          $db->setQuery($query);
//          $parent_id = $db->loadResult();
//
//          $query = "UPDATE `#__os_cck_entity_instance` SET `published` = '0' WHERE `eiid` = $bid";
//          $db->setQuery($query);
//          $db->execute();

        }
        
        $app->enqueueMessage('ok');
        if($input->get('task') != 'stripe') {
            $app->redirect("index.php?option=$option&task=show_buy_request_instances&Itemid=" . $Itemid);
        }
        
    }

    static function  show_all_instance($option, $lid, $mod_type = 0, $Itemid = 0){
      global $app, $db, $user ,$doc, $entities_type, $layouts_type;
      global $os_cck_configuration, $limit, $total, $limitstart,$moduleId, $cck_entity_configuration, $entityFieldLists;

      $db = new os_cckDb();
      $input = $app->input;

      $moduleId =(($moduleId == 0
                   || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
      if(!$moduleId){
        if($Itemid == 0){
           $Itemid = intval($input->get('Itemid'));
        }
        // 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 '%back_button%'"
                        . "\n AND params LIKE '%all_instance%'"
                        . "\n AND published = 1";
        $db->setQuery($query);
        if($Itemid == 0){
            $Itemid = $db->loadResult();
            if($params->get('ItemId'))$Itemid=$params->get('ItemId');
        }
      }
      $layout = new os_cckLayout($db->_db);
      $layout->load($lid);
      
      $lang_where = '';
//      $lang = JFactory::getLanguage();
      
      if(JLanguageMultilang::isEnabled()){

          $layout = setLayoutLangCCK($layout);
          $lang_where = getCCKLangWhere();
         
      }
      
      if(empty($layout->title) || ($layout->type != 'all_instance' && $layout->type != 'all_instance_pdf')){
        if(!$moduleId){
          throw new Exception(cck_lang_text("COM_OS_CCK_ERROR_MENU_NO_LAYOUT"), 500);
        }else{
          throw new Exception(cck_lang_text("COM_OS_CCK_ERROR_MODULE_NO_LAYOUT"), 500);
        }
        
        return;
      }
      
      if($params->get('all_instance_layout') || $params->get('layout') || $layout->title){
        $fields_from_params = unserialize($layout->params);
        $entity_id = $layout->fk_eid;
      }//end all instance menu
      
      if(!isset($fields_from_params['views']['show_request_layout']) || empty($fields_from_params['views']['show_request_layout'])){
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ENTER_INSTANCE_LAYOUT_FOR_ALL_INSTANCIES"), 'warning');

          return;
      }

      $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$entity_id/custom.css");


      $layout->layout_html = $layout->getLayoutHtml('2');
      $lay_html = urldecode($layout->layout_html);
      
      $entity_name = $entity_id;
      $limit = (isset($fields_from_params['views']['pagenator_limit']) && strpos($lay_html,"{|f-joom_pagination|}")) ? $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;
      }
      
      //creating order by list
       if(stripos($lay_html, 'all_instance_order_by')){
           
          $fields_from_params = getOrderByOptions('all_instance_order_by', $fields_from_params, $entity_id, $mod_type, $layout->lid);
          $header = $layout->title;
          $params->def('header', $header);
          $params->def('pageclass_sfx', '');
       }

    
       //alfabetical pagination
       //$bootstrap_version = $session->get( 'bootstrap','2');
          $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($entities_type[$entity_id] == 'custom_sql'){
                      $prefix = 't';
                  }else{
                      $prefix = 'instance';
                  }
                  $now_indexed = str_replace('custom_sql_', '', $_REQUEST['now_indexed']);
                if($sp == 1 && $_REQUEST['now_indexed'] == $fields_from_params["views"]["selected"]){
                  if($entities_type[$entity_id] != 'custom_sql'){
                    $where = " AND LOWER($prefix." . $now_indexed . ") LIKE '$search%' ";
                  }else{
                      $where = " LOWER($prefix." . $now_indexed . ") LIKE '$search%' ";
                  }
                }else{
                  $where = '';
                }
                
              }
          }
          
          $need_lid = protectInjectionWithoutQuote('lid');
          if($need_lid == $lid){
            $event_date = (protectInjectionWithoutQuote('event_date'))?protectInjectionWithoutQuote('event_date'):false;
            $event_date_field = (protectInjectionWithoutQuote('event_date_field'))?protectInjectionWithoutQuote('event_date_field'):false;
          }else{
            $event_date = false;
            $event_date_field = false;
          }


          if($event_date_field && $event_date){
            $event_where = " AND " . $event_date_field . " LIKE '%" . $event_date . "%'";
          }else{
            $event_where = '';
          }
          
          $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(stripos($lay_html, 'joom_alphabetical')){
            
          if(isset($fields_from_params["views"]["selected"]) && (strstr($fields_from_params["views"]["selected"], 'text_textfield') !== false || (($entities_type[$entity_id] == 'joomla_user' || $entities_type[$entity_id] == 'custom_sql') && checkUserFieldType($entity_id, $fields_from_params["views"]["selected"])))){

            if($entities_type[$entity_id] == 'os_cck_entity'){
              $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_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_$layout->fk_eid` 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 AND ei.fk_eid='" . $entity_id . "' $event_where  $access_where $custom_sql_where $lang_where GROUP BY ei.eiid ORDER BY symb";
          
              $db->setQuery($query);
              $tmp_arr = $db->loadObjectList();
            }elseif($entities_type[$entity_id] == 'joomla_user'){
                $request_details = getRequestDetailsForAlphabeticalJoomlaUser($fields_from_params["views"]["selected"]);
                $query = "SELECT  DISTINCT UPPER(SUBSTRING(".$request_details['field_name'].", 1,1)) AS symb FROM #__users as us "
                . "LEFT JOIN #__user_usergroup_map as ugm ON ugm.user_id = us.id "
                . "LEFT JOIN #__usergroups as ug ON ug.id = ugm.group_id "
                . " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id "
                . " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
                //$query .= $request_details['join'];
                $query .= ' WHERE us.block=0 ';
                $query .= $request_details['where'] . $custom_sql_where . ' GROUP BY us.id ORDER BY symb';
                $db->setQuery($query);
                $tmp_arr = $db->loadObjectList();
            }elseif ($entities_type[$entity_id] == 'custom_sql'){
                $entity = new os_cckEntity($db->_db);
                $entity->load($entity_id);
//                var_dump($custom_sql_where);
                if(trim($custom_sql_where) != ''){
                    $where_string = " WHERE $custom_sql_where ";
                }else{
                    $where_string = "";
                }
                $query = "SELECT DISTINCT UPPER(SUBSTRING(t.".str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]).", 1,1)) AS symb FROM ($entity->sql_select) as t $where_string ORDER BY symb";
                $db->setQuery($query);
//                var_dump($query); exit;
                $tmp_arr = $db->loadObjectList();
            }
            
              if(count($tmp_arr)>1){

              $symb_list_str = '<ul>';
              foreach($tmp_arr as $symbol){
                  if(empty($symbol->symb)){
                    continue;
                  }

                  if($event_where!=''){
                    $symb_list_str.= '<li><a href="index.php?option=' . $option . 
                    '&view=all_instance&letindex=' . $symbol->symb . '&sp=1&Itemid=' . $Itemid . '&now_indexed=' . $fields_from_params["views"]["selected"] . '&event_date='.$event_date.'&event_date_field='.$event_date_field.'&lid='.$lid.'">' . 
                    $symbol->symb . '</a></li> ';
                  }else{
                    $symb_list_str.= '<li><a href="index.php?option=' . $option . 
                    '&view=all_instance&letindex=' . $symbol->symb . '&sp=1&Itemid=' . $Itemid . 
                      '&now_indexed=' . $fields_from_params["views"]["selected"] . '">' . 
                    $symbol->symb . '</a></li> ';
                  }

              }

              //check string not empty
              $temp_var =  strip_tags($symb_list_str) ;
              if(!empty( $temp_var ) ){

                  if($event_where!=''){
                    $symb_list_str.= '<li><a href="index.php?option=' . $option . 
                    '&view=all_instance&letindex=all&sp=1&Itemid=' . $Itemid . '&now_indexed=' . $fields_from_params["views"]["selected"] . '&event_date='.$event_date.'&event_date_field='.$event_date_field.'&lid='.$lid.'">all</a></li> ';
                  }else{
                    $symb_list_str.= '<li><a href="index.php?option=' . $option . 
                    '&view=all_instance&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;
          }
      }
     $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 ) ";
      } 
//      var_dump($entity_id);
//      var_dump($entity);
//      var_dump($where);
//      var_dump($event_where);
//      var_dump($access_where);
//      var_dump($custom_sql_where);   


      if($entities_type[$entity_id] == 'os_cck_entity'){

        $query = " SELECT COUNT(DISTINCT ei.eiid) FROM  #__os_cck_entity_instance AS ei "
              . "\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_$layout->fk_eid` 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 AND ei.fk_eid='" . $entity_id . "' $where $event_where $access_where $custom_sql_where $lang_where";
      }elseif($entities_type[$entity_id] == 'joomla_user'){
          if(isset($request_details)){
          	  $query = "SELECT COUNT(DISTINCT us.id) FROM #__users as us "
                  . "LEFT JOIN #__user_usergroup_map as ugm ON ugm.user_id = us.id "
                  . "LEFT JOIN #__usergroups as ug ON ug.id = ugm.group_id "
                  . " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id "
                  . " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                  . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
              //$query .= $request_details['join'];
              $query .= ' WHERE block=0 ';
              $query .= $request_details['where'] . $request_details['where2'] . $custom_sql_where;
              
              //var_dump($query); //exit;
          }else{
            $query = "SELECT COUNT(DISTINCT us.id) FROM #__users as us " 
                    . "LEFT JOIN #__user_usergroup_map as ugm ON ugm.user_id = us.id "
                    . "LEFT JOIN #__usergroups as ug ON ug.id = ugm.group_id "
                    . " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id "
                    . " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                    . "LEFT JOIN #__fields as fi ON val.field_id = fi.id WHERE us.block=0 ". $custom_sql_where;
            //var_dump($query);
          }
      }elseif($entities_type[$entity_id] == 'custom_sql'){
          $entity = new os_cckEntity($db->_db);
          $entity->load($entity_id);
          $id_field = $entityFieldLists[$entity_id]['custom_sql_id'];
//          var_dump($id_field); exit;
          if(trim($custom_sql_where) != ''){
              $where_string = " WHERE $custom_sql_where " . $where;
          }elseif($where != ''){
              $where_string = " WHERE " . $where;
          }else{
              $where_string = "";
          }
//            var_dump($custom_sql_where); exit;
          
          $query = "SELECT COUNT(t.$id_field->fid) FROM ($entity->sql_select) as t $where_string";
          
      }
      
      $db->setQuery($query);
      // print_r($query); //exit;
      $total = $db->loadResult();
//      var_dump($max_items); exit;
      if($max_items != '0' && $max_items < $total ) {
        if($limit > $max_items )$limit = $max_items;
        $total = $max_items;
      }


//var_dump(!in_array($fields_from_params["views"]["selected"],$fields_from_params['views']['order_by_fields']));

//        var_dump($fields_from_params["views"]["selected"]);
//       var_dump($fields_from_params['views']['show_request_layout']);

//     $pageNav = new os_cckPagination($total, $limitstart, $limit);
//        var_dump($limit); exit;
     $pageNav = new os_libPagination($total, $limitstart, intval($limit));

     if($entities_type[$entity_id] == 'os_cck_entity'){
     $query = " SELECT DISTINCT ei.eiid,ccc.fk_cid 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 cat ON cat.cid=ccc.fk_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_$layout->fk_eid` 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 AND ei.fk_eid='" . $entity_id . "' $where $event_where $access_where $custom_sql_where $lang_where  ";
      //var_dump($query);
      
        if(isset($fields_from_params["fields"]["indexed_all_instance_order_by"])) { // if selected sortable field
          
          $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';
          if($orderby != 'RAND()') {
            
              if (isset($fields_from_params["views"]["selected"]) && !empty($fields_from_params["views"]["selected"])) {
                  $index = 0;
                  // var_dump($fields_from_params["fields"]["indexed_all_instance_order_by"]);
                  foreach ($fields_from_params['views']['show_request_layout'] as $key => $val) {

                      $request_layout = new os_cckLayout($db->_db);
                      $request_layout->load($key);
                      if($request_layout->params){
                        $request_layout_fields_params = unserialize($request_layout->params);
                      }
                      $views_selected = $fields_from_params["views"]["selected"] . '_average';

                      if ($request_layout->type == 'instance' && $index == 0) {
                        if($orderby != 'RAND()') {
                            if ($fields_from_params["views"]["selected"] == 'title') {

                                $query .= " GROUP BY ei.eiid ORDER BY ei.title $orderby ";
                            } elseif (stripos($fields_from_params["views"]["selected"], 'categoryfield') !== FALSE) {

                                $query .= " GROUP BY ei.eiid ORDER BY cat.name $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' || $fields_from_params["views"]["selected"] == 'last_review_date') {
                                $query .= " GROUP BY ei.eiid ORDER BY ei.last_review $orderby ";
                            } elseif ($fields_from_params["views"]["selected"] == 'custom_order') {

                                $query .= ' GROUP BY ei.eiid ORDER BY ' . $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 cat ON cat.cid=ccc.fk_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_$layout->fk_eid` 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_$layout->fk_eid` 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 ei.fk_eid='" . $entity_id . "' $where $event_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 .= " ORDER BY $orderby ";
                        }
                      }

                  }
              } elseif ($fields_from_params["fields"]["indexed_all_instance_order_by"] == 'eid') {
                  $query .= " GROUP BY ei.eiid ORDER BY ei.eiid $orderby ";
              } elseif ($fields_from_params["fields"]["indexed_all_instance_order_by"] == 'title') {
                  $query .= " GROUP BY ei.eiid ORDER BY ei.title $orderby ";
              } elseif ($fields_from_params["fields"]["indexed_all_instance_order_by"] == 'hits') {
                  $query .= " GROUP BY ei.eiid ORDER BY ei.hits $orderby ";
              } elseif ($fields_from_params["fields"]["indexed_all_instance_order_by"] == 'last_review' || $fields_from_params["fields"]["indexed_all_instance_order_by"] == 'last_review_date') {
                  $query .= " GROUP BY ei.eiid ORDER BY ei.last_review $orderby ";
              }elseif ($fields_from_params["fields"]["indexed_all_instance_order_by"] == 'custom_order') {
                  $query .= ' GROUP BY ei.eiid ORDER BY ' . $fields_from_params['views']['custom_order_by'][0] . " $orderby ";
              } elseif (isset($fields_from_params["fields"]["indexed_all_instance_order_by"]) && stripos($fields_from_params["fields"]["indexed_all_instance_order_by"], 'categoryfield') !== FALSE) {
                  $query .= " GROUP BY ei.eiid ORDER BY cat.name $orderby ";
              } elseif (stripos($fields_from_params["fields"]["indexed_all_instance_order_by"], 'pricefield_number_') !== false) {

                  $query .= " AND price.fk_fid = " . str_replace('pricefield_number_', '', $fields_from_params["fields"]["indexed_all_instance_order_by"]) . " GROUP BY ei.eiid ORDER BY price.price_value $orderby";
              } else { // for other fields

                      $query .= " GROUP BY ei.eiid ORDER BY instance.`{$fields_from_params["fields"]["indexed_all_instance_order_by"]}` $orderby ";



              }
          }else{
              $query .= " ORDER BY $orderby ";
          }
          
        }
     }elseif($entities_type[$entity_id] == 'joomla_user'){
          $query = "SELECT DISTINCT us.id as eiid FROM #__users as us "
          . "LEFT JOIN #__user_usergroup_map as ugm ON ugm.user_id = us.id "
          . "LEFT JOIN #__usergroups as ug ON ug.id = ugm.group_id "
          . " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id "
          . " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
          . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
          if(isset($fields_from_params["fields"]["indexed_all_instance_order_by"])) { // if selected sortable field
              //var_dump($fields_from_params["fields"]["indexed_all_instance_order_by"]);
              $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';
              if (isset($fields_from_params["views"]["selected"]) && !empty( $fields_from_params["views"]["selected"])) {
                  $request_details = getJoinForOrderByJoomlaUser($fields_from_params["views"]["selected"], $orderby);
                  //$query .= $request_details['join'];
                  $query .= ' WHERE block=0 ';
                  if($orderby != 'RAND()') {
                      $query .= $request_details['where'] . ' ' . $custom_sql_where . ' ' . $request_details['order_by'] . ' ' . $orderby;
                  }else{
                      $query .= $request_details['where'] . ' ' . $custom_sql_where . ' ' . $request_details['order_by'] . ' ' . $orderby;
                  }
                  //var_dump($query); exit;
                  
              }else{
              	$query .= ' WHERE block=0 ' . $custom_sql_where;
              }
          }else{
          		$query .= ' WHERE block=0 ' . $custom_sql_where;
          }
      }elseif($entities_type[$entity_id] == 'custom_sql'){
         $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';

         if(trim($custom_sql_where) != ''){
             $where_string = " WHERE $custom_sql_where ";
         }elseif($where != ''){
             $where_string = " WHERE " . $where;
         }else{
             $where_string = "";
         }

         $query = "SELECT DISTINCT t.$id_field->fid as eiid FROM ($entity->sql_select) as t $where_string ";

         if((isset($fields_from_params["views"]["selected"]) && $fields_from_params["views"]["selected"] && $fields_from_params["views"]["selected"] != '' && $fields_from_params["views"]["selected"] != 'custom_order')
             || (isset($fields_from_params["views"]["selected"]) && $fields_from_params["fields"]["indexed_all_instance_order_by"] && $fields_from_params["fields"]["indexed_all_instance_order_by"] != '' && $fields_from_params["views"]["selected"] != 'custom_order')){

             if($fields_from_params["views"]["selected"]){
                 if($orderby != 'RAND()') {
                     $query .= " ORDER BY t." . str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]) . ' ' . $orderby;
                 }else{
                     $query .= " ORDER BY " . $orderby;
                 }
             }

         }

     }
        
      $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 ";
      
      $db->setQuery($query);
      
      $items = $db->loadObjectList();
      
      $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[$layout->lid] = $no_limit_items;
//      }
//        var_dump($no_limit_items_arr);
      $session->set( 'no_limit_items_arr', $no_limit_items_arr );
//      $session->set( 'last_overall_layout.', $lid );
      
      
       
      $instancies = array($session->get('no_limit_items_arr', array()));
        
      //this may happened when we do import but for User layout - users not exist
      if(empty($items) ) $instancies = array() ;

      foreach ($items as $key => $item) {
        if(isset($item->fk_cid) && !empty($item->fk_cid)){ //is not isset category (skip access checking)
        //check access for category
          if(!isset($GLOBALS['categories'][$item->fk_cid] )){
              $db->setQuery("SELECT * FROM `#__os_cck_categories` e WHERE e.`cid` = " . (int)$item->fk_cid);
              $carCatParams = $db->loadObjectList();
              $GLOBALS['categories'][$item->fk_cid] = $carCatParams;
          }else{
              $carCatParams = $GLOBALS['categories'][$item->fk_cid];
          }
          

          if(!$carCatParams){
              continue;
          }
          
          $carCatParams = $carCatParams[0];
          //user access to category
          $user = JFactory::getUser();
          if (($carCatParams->params == implode(',',array_diff(explode(',',$carCatParams->params),$user->groups)))
              && $carCatParams->params != 1) {
              continue;
          }//end  
        }else{
            $item->fk_cid = '';
        }

        //check access for category
        if($entities_type[$entity_id] == 'os_cck_entity'){
            $instance = new os_cckEntityInstance($db->_db);
            $instance->load($item->eiid);
        }elseif ($entities_type[$entity_id] == 'joomla_user') {
            $instance = ConvertEntityInstanceToUser($entity_id, $item->eiid);
        }elseif ($entities_type[$entity_id] == 'custom_sql'){
            $instance = ConvertEntityInstanceToCustomSql($entity, $item->eiid);
        }

        $instancies[$key] = $instance;
        $instancies[$key]->cat_id = $item->fk_cid;
      }

      //////////////////////////////////////////////////////////////////
      $params->def('show_rating', 1);
      $params->def('hits', 1);
      $params->def('back_button', $app->getCfg('back_button'));
      if(!$instancies){
          echo '<div style="text-align:center"><h2>'.cck_lang_text("COM_OS_CCK_NO_INSTANCE").'</h2></div>';
      }
      
      $layout_params['custom_fields'] = unserialize($layout->custom_fields);
      $layout_params['all_instance_layout_params'] = $fields_from_params;
      $bootstrap_version = $session->get( 'bootstrap','2');
      $layout->layout_html = $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($layout->type == 'all_instance'){
        $type =  'all_instance';
        // $layout = $
        require getLayoutPathCCK::getLayoutPathCom($option, $type);
      }elseif($layout->type == 'all_instance_pdf'){
        os_cck_site_controller::displayCckPdf('', $instancies, $layout, $layout_params);
      }
    }
    
    static function showUserInstances($option, $lid, $mod_type = 0, $number_of_plugin='', $user = 0, $Itemid = 0){ 

    global $app, $db, $acl, $doc, $session, $_globals;
    global $os_cck_configuration, $limit, $total, $limitstart,$moduleId ,$session, $cck_entity_configuration, $entityFieldLists;
    $db = new os_cckDb();
    $input = $app->input;
    
    $option = $input->get('option', '');
    $task = $input->get('task', '');
    $moduleId =(($moduleId == 0
                 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    

    $currentcat = NULL;
    if($option == 'com_simplemembership'){
            $GLOBALS['number_of_plugin'] = $number_of_plugin;
          $plugin = JPluginHelper::getPlugin('simplemembership', 'plg_simplemembership_get_cck_user_instances' . $number_of_plugin);
          $params = new JRegistry($plugin->params);
          
      }else{
        if(!$moduleId){
          if($Itemid == 0){
                $Itemid = intval($input->get('Itemid'));
            }
          // 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');

          $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);
    $user_instances_layout = new os_cckLayout($db->_db);

    
    if(!$lid || $lid == -1){        
        //var_dump($_REQUEST);
      //from category menu
      
        if($params->get('layout') || $params->get('layout_type') == 'user_instances_layout' || $params->get('user_layout')){

            $user_instances_layout->load($params->get('layout')?$params->get('layout') : $params->get('user_instances_layout'));
            
            if(!$user_instances_layout->published){
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');

                return;
            }
            $fields_from_params = unserialize($user_instances_layout->params);
            $entity_id = $user_instances_layout->fk_eid;
            if (!$entity_id){
              if(!$params->get('layout'))//component or module
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_CATEGORY_LAYOUT"), 'warning');

              else
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_MODULE_CATEGORY_LAYOUT"), 'warning');

              return;
            }
            if($user == 0){
                if($option == 'com_simplemembership' && isset($_REQUEST['userId'])){
                    //var_dump(userId);
                   $user = $_REQUEST['userId'];
                }elseif($option == 'com_simplemembership' && ($task == 'my_account' || $option == 'com_simplemembership')){
                    $user = JFactory::getUser()->id;
                }else{
                    $user = $params->get('layout')?$params->get('item') : $params->get('user');
                }
            }
               
        }//end category menu
    

        $user = (!$user) ? $params->get('user') : $user; 
        $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($user == 0){
//            var_dump($input->get('userId', ''));
            if($input->get('userId', '') != ''){
                $user= $input->get('userId', '');
            }elseif ($input->get('task', '') == 'my_account' && $input->get('option', 'com_os_cck') == 'com_simplemembership') {
                $user = JFactory::getUser()->id;   
            }else{
                $user = $params->get('user');
            }
        }
        
        $user_instances_layout->load($lid);
        $fields_from_params = unserialize($user_instances_layout->params);
        $entity_id = $user_instances_layout->fk_eid;
        
    }
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$entity_id/custom.css");
    //var_dump($user);
    $lang_where = '';
//      $lang = JFactory::getLanguage();
      
      if(JLanguageMultilang::isEnabled()){

          $user_instances_layout = setLayoutLangCCK($user_instances_layout);
          $lang_where = getCCKLangWhere();
         
      }
    if($user_instances_layout->type != 'user_instances' && $user_instances_layout->type != 'user_instances_pdf'){

        $app->enqueueMessage("Layout type load error User instances layout ID: ".$user_instances_layout->lid, 'warning');
      
      return;
    }
    $user_instances_layout->layout_html = $user_instances_layout->getLayoutHtml('2');
      $lay_html = urldecode($user_instances_layout->layout_html);
    $limit = (isset($fields_from_params['views']['pagenator_limit']) && strpos($lay_html,"{|f-joom_pagination|}")) ? $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($user_instances_layout->fk_eid){
        $entity_name = $user_instances_layout->fk_eid;
    }else{
        return;
    }
    $userId = $user;

    //creating order by list
    $fields_from_params = getOrderByOptions('user_order_by', $fields_from_params, $entity_id, $mod_type, $user_instances_layout->lid);

    if($params->get('layout')){
        $header = $user_instances_layout->title;
    }elseif($option == 'com_simplemembership'){
        $header = $params->get('tab_name');
    }else{
        $header = set_header_name_cck($menu, $Itemid);
    }
    //$header = $params->get('layout') ? "$user_instances_layout->title" : set_header_name_cck($menu, $Itemid);
    $params->def('header', $header);
    $params->def('pageclass_sfx', '');
    

    //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 = '';
          }
        }
    }
    
      $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(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_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 AND ei.fk_userid='{$user}' "
          . "\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=user_instances&letindex=' . $symbol->symb . '&sp=1&Itemid=' . $Itemid . 
            '&now_indexed=' . $fields_from_params["views"]["selected"] . '&userId=' . $user . '">' . 
          $symbol->symb . '</a></li> ';
            
          }

          //check string not empty
          if(!empty(strip_tags($symb_list_str))){
            $symb_list_str.= '<li><a href="index.php?option=' . $option . 
            '&view=user_instances&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;
    }

    //alfabetical pagination

    

    $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_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 AND ei.fk_userid='{$user}' "
            . "\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;
    }
//     if( isset($fields_from_params['views']['selected']) && 
//         ( !isset( $fields_from_params['views']['order_by_fields'] ) || !is_array( $fields_from_params['views']['order_by_fields'] ) ||
//          ( is_array( $fields_from_params['views']['order_by_fields'] ) && !in_array($fields_from_params["views"]["selected"],$fields_from_params['views']['order_by_fields']) 
//          ) 
//         )
//        )
//     {
//
//        $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_user_order_by"])?$fields_from_params["fields"]["indexed_user_order_by"]:'';
//     }
    
    $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_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 AND ei.fk_userid='{$user}' "
            . "\n AND ei.fk_eid='" . $entity_id . "' $where $access_where $custom_sql_where $lang_where  ";
            
            
            
        if(isset($fields_from_params["fields"]["indexed_user_order_by"])){ // if selected sortable field
            $orderby = (!empty($fields_from_params["views"]["sortType_user_order_by"])) ? $fields_from_params["views"]["sortType_user_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' || $fields_from_params["views"]["selected"] == 'last_review_date') {

                                    $query .= " GROUP BY ei.eiid ORDER BY ei.last_review $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) {
                                    $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_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 ei.fk_userid='{$user}' "
                                        . "\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++;
                            }

                        }
                    }
                } elseif ($fields_from_params["fields"]["indexed_user_order_by"] == 'eid') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.eiid $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_user_order_by"] == 'title') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.title $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_user_order_by"] == 'hits') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.hits $orderby ";
                }elseif ($fields_from_params["fields"]["indexed_user_order_by"] == 'last_review' || $fields_from_params["fields"]["indexed_user_order_by"] == 'last_review_date') {
                    $query .= " GROUP BY ei.eiid ORDER BY ei.last_review $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_user_order_by"] == 'custom_order') {
                    $query .= ' GROUP BY ei.eiid ' . $fields_from_params['views']['custom_order_by'][0] . " $orderby ";
                } elseif (stripos($fields_from_params["fields"]["indexed_user_order_by"], 'pricefield_number_') !== false) {

                    $query .= " AND price.fk_fid = " . str_replace('pricefield_number_', '', $fields_from_params["fields"]["indexed_user_order_by"]) . " GROUP BY ei.eiid ORDER BY price.price_value $orderby";
                } else { // for other fields
                    $query .= " GROUP BY ei.eiid ORDER BY instance.`{$fields_from_params["fields"]["indexed_user_order_by"]}` $orderby ";
                }
            }else{
                $query .= " ORDER BY $orderby ";
            }
        }
    $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 = $db->loadObjectList();

    $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[$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();
    // var_dump($items);
    $instancies = array();
//    var_dump($items); exit;
    foreach ($items as $item) {
        $instance = new os_cckEntityInstance($db->_db);
        
        $instance->load($item->eiid);
        $instancies[] = $instance;
    }
    

    //////////////////////////////////////////////////////////////////
    $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 WHERE section='com_os_cck' ORDER BY ordering ";
    $db->setQuery($query);
    $cat_all1 = $db->loadObjectList();
    

    //cck_constructPathway($category, 'category');
    $params->def('show_rating', 1);
    $params->def('hits', 1);
    $params->def('back_button', $app->getCfg('back_button'));

    
    $layout_params = unserialize($user_instances_layout->params);
    $layout_params['custom_fields'] = unserialize($user_instances_layout->custom_fields);
    $layout_params['cat_layout_params'] = $fields_from_params;
    $bootstrap_version = $session->get( 'bootstrap','2');
    $user_instances_layout->layout_html = $user_instances_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');
      }
    }

    $layout = $user_instances_layout;
    
    $type = 'user_instances';
    if($option == 'com_simplemembership'){
        $option = 'com_os_cck';
        
    }
    
    if($layout->type == 'user_instances'){
    require getLayoutPathCCK::getLayoutPathCom($option, $type);
    }elseif($layout->type == 'user_instances_pdf'){
        os_cck_site_controller::displayCckPdf('', $instancies, $layout, $layout_params);
      }
    
  }



    static function show_calendar($option, $lid,$showLayModId = '', $Itemid=0){

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

    $input = $app->input;
    
    $moduleId =(($moduleId == 0
                 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    if(!$moduleId){
        if($Itemid == 0){
            $Itemid = intval($input->get('Itemid'));
        }
      // 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 (), 0);

      }
      //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 params LIKE '%calendar%'"
                      . "\n AND published = 1";
      $db->setQuery($query);
      if($Itemid == 0){
          $Itemid = $db->loadResult();
           if($params->get('ItemId'))$Itemid=$params->get('ItemId');
      }
    }
    $layout = new os_cckLayout($db->_db);
    $layout->load($lid);
    
    $lang_where = '';
      if(JLanguageMultilang::isEnabled()){
          $layout = setLayoutLangCCK($layout);
          $lang_where = getCCKLangWhere();
          
      }
      
    if(empty($layout->title) || $layout->type != 'calendar'){
      if(!$moduleId){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_MENU_NO_LAYOUT"), 'warning');
      }else{
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_MODULE_NO_LAYOUT"), 'warning');
      }
      return;
    }

    if($params->get('calendar_layout') || $params->get('layout') || $layout->title){
      $fields_from_params = unserialize($layout->params);
      $entity_id = $layout->fk_eid;
    }
    //end all instance menu

    $session = JFactory::getSession();

    $layout_params = unserialize($layout->params);
    $layout_params['custom_fields'] = unserialize($layout->custom_fields);
    $layout_params['calendar_layout_params'] = $fields_from_params;
    $bootstrap_version = $session->get( 'bootstrap','2');
    $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$layout->fk_eid/custom.css");
 
    //calendar start

    //modules
    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');
      }
    } 
    //modules

    $current_month = isset($fields_from_params['views']['month_calendar'])?$fields_from_params['views']['month_calendar']:date('Y-m');
    $event_title = isset($layout_params['calendar_layout_params']['fields']['calendar_table_event_title']) ? $layout_params['calendar_layout_params']['fields']['calendar_table_event_title'] : 0;
    $instance_lid = $fields_from_params['views']['instance_layout'];
    $all_instance_lid = $fields_from_params['views']['all_instance_layout'];
    $show_past_events = $fields_from_params['views']['show_past_events'];
    $events_over_years = isset($fields_from_params['views']['events_over_years']) ? $fields_from_params['views']['events_over_years'] : 0;
    $event_date_field = isset($fields_from_params['views']['event_date'])?$fields_from_params['views']['event_date']:false;
    $sortType = isset($fields_from_params['fields']['sortType_all_instance_order_by'])?$fields_from_params['fields']['sortType_all_instance_order_by']:'ASC';
    $event_sort_by = $fields_from_params['views']['event_sort_by'];
    $schedule_instance_lid = $layout_params['calendar_layout_params']['fields']['calendar_table_schedule_instance_lid'];

//    var_dump($event_date_field);
    //check isset needs layouts and fields

    //shedule instance
    if($schedule_instance_lid == '-1'){
          $schedule_instance_lid = $layout->getDefaultLayout($entity_id, 'instance');
      if(empty($schedule_instance_lid)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_CALENDAR_INST_NO_LAYOUT"), 'warning');
        return;
      }
    }
    //instance
    if($instance_lid == '-1'){
          $instance_lid = $layout->getDefaultLayout($entity_id, 'instance');
      if(empty($instance_lid)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_CALENDAR_INST_NO_LAYOUT"), 'warning');
        return;
      }
    }
    //all instance
    if($all_instance_lid == '-1'){
          $all_instance_lid = $layout->getDefaultLayout($entity_id, 'all_instance');
      if(empty($all_instance_lid)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_CALENDAR_ALL_INST_NO_LAYOUT"), 'warning');
        return;
      }
    }

    //data field
    if($event_date_field == '-1'){
        $event_date_field = $layout->getDefaultField($entity_id, 'datetime_popup');
      if(empty($event_date_field)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_CALENDAR_DATE_NO_FIELD"), 'warning');
        return;
      }
    }
    //title field
    if($event_title == '-1'){
        $event_title = $layout->getDefaultField($entity_id, 'text_textfield');
      if(empty($event_title)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_CALENDAR_TEXT_NO_FIELD"), 'warning');
        return;
      }
    }
    
    $custom_sql_where = '';
      if(isset($fields_from_params['fields']['calendar_table_sql_show']) && !empty($fields_from_params['fields']['calendar_table_sql_show'])){
          $sql_show = $fields_from_params['fields']['calendar_table_sql_show'];
          if(isset($fields_from_params['fields']["calendar_table_sql_where_type"]) && $fields_from_params['fields']["calendar_table_sql_where_type"] == 'PHP'){
              eval($sql_show);
              $custom_sql_where .= ' ' . $sql_where_string . ' ';
          }else{
              $custom_sql_where .= ' ' . $sql_show . ' ';
          }


      }
      // var_dump($custom_sql_where);
    //   $fields_from_params['fields']["calendar_table_sql_where_type"]
    // $field_sql_show = (isset($fields_from_params[$fName.'_sql_show'])) ? $fields_from_params[$fName.'_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($events_over_years){
        $query = " SELECT count(instance.".$event_date_field."), DATE_FORMAT(instance.".$event_date_field.", '%m-%d') 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_layout AS lay ON lay.lid=ei.fk_lid "
            . "\n LEFT JOIN `#__os_cck_content_entity_$layout->fk_eid` 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 AND instance.".$event_date_field."!='0000-00-00 00:00:00' "
            . "\n AND ei.fk_eid='" . $entity_id . "' " . $access_where . $lang_where . $custom_sql_where . " GROUP BY DATE_FORMAT(instance.".$event_date_field.", '%m-%d') ";
    }else{
        $query = " SELECT count(instance.".$event_date_field."), DATE(instance.".$event_date_field.") 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_layout AS lay ON lay.lid=ei.fk_lid "
            . "\n LEFT JOIN `#__os_cck_content_entity_$layout->fk_eid` 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 AND instance.".$event_date_field."!='0000-00-00 00:00:00' "
            . "\n AND ei.fk_eid='" . $entity_id . "' " . $access_where . $lang_where . $custom_sql_where . " GROUP BY DATE(instance.".$event_date_field.") ";
    }
    $db->setQuery($query);
    $calenDate = $db->loadRowList();
//    var_dump($event_date_field);
    
    $calendarParams = array();
    $calendarParams['all_instance_lid'] = $all_instance_lid;
    $calendarParams['event_date_field'] = $event_date_field;
    $calendarParams['calenDate'] = $calenDate;
    $calendarParams['show_past_events'] = $show_past_events;
    $calendarParams['events_over_years'] = $events_over_years;
    $calendarParams['instance_lid'] = $instance_lid;
    $calendarParams['event_title'] = $event_title;
    $calendarParams['calendar_view'] =  $layout_params['calendar_layout_params']['fields']['calendar_view_calendar_table'];
    $calendarParams['date_format'] = $layout_params['calendar_layout_params']['fields']['calendar_table_output_format'];
    $calendarParams['show_time'] = $layout_params['calendar_layout_params']['fields']['calendar_table_show_time'];
    $calendarParams['header_format'] = $layout_params['calendar_layout_params']['fields']['calendar_table_output_header_format'];
    $calendarParams['show_header'] = $layout_params['calendar_layout_params']['fields']['calendar_table_show_header_date_time'];
    $calendarParams['schedule_instance_lid'] = $schedule_instance_lid;



    $eiids = array();
    $item_infos = array();

    if($event_sort_by == -1){
      $event_sort_by = 'TIME(time)';
    }else{
      $event_sort_by = 'instance.'.$event_sort_by;
    }
    
    foreach ($calenDate as $key => $value) {

      $event_where = " AND " . $event_date_field . " LIKE '%" . $value[1] . "%' ";

        $query = " SELECT  ei.eiid, instance.".$event_title." as title, instance.".$event_date_field." as time 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_layout AS lay ON lay.lid=ei.fk_lid "
            . "\n LEFT JOIN `#__os_cck_content_entity_$layout->fk_eid` 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 AND ei.fk_eid='" . $entity_id . "' $event_where $access_where $lang_where $custom_sql_where GROUP BY ei.eiid ORDER BY $event_sort_by $sortType ";
        $db->setQuery($query);

        $item_infos[$value[1]] = $db->loadAssocList();

    }
    
    //to time formnat
    foreach ($item_infos as $key => $value) {
      foreach ($value as $key1 => $value1) {
        $item_infos[$key][$key1]['time'] = date($calendarParams['date_format'],strtotime($value1['time']));
      }
    }
    
    $calendarParams['item_infos'] = $item_infos;


    //get instances for schedule layout
    $query = " SELECT  ei.eiid,ccc.fk_cid 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_layout AS lay ON lay.lid=ei.fk_lid "
              . "\n LEFT JOIN `#__os_cck_content_entity_$layout->fk_eid` as instance ON instance.`fk_eiid` = ei.eiid "
              . "\n WHERE ei.published='1' "
              . "\n AND ei.approved='1' "
              . "\n AND lay.type='add_instance' $custom_sql_where ";
    $db->setQuery($query);
    $items = $db->loadObjectList();

    $instancies = [];

    foreach ($items as $key => $item) {
      
          if(isset($item->fk_cid) && !empty($item->fk_cid)){ //is not isset category (skip access checking)
          //check access for category
            $db->setQuery("SELECT * FROM `#__os_cck_categories` e WHERE e.`cid` = " . (int)$item->fk_cid);
            $carCatParams = $db->loadObjectList();
            if(!$carCatParams){
                continue;
            }

            $carCatParams = $carCatParams[0];
            //user access to category
            $user = JFactory::getUser();
            if (($carCatParams->params == implode(',',array_diff(explode(',',$carCatParams->params),$user->groups)))
                && $carCatParams->params != 1) {
                continue;
            }//end  
          }
          //check access for category

          $instance = new os_cckEntityInstance($db->_db);
          $instance->load($item->eiid);
          $instancies[$key] = $instance;
          $instancies[$key]->cat_id = $item->fk_cid;
      }


      $calendarParams['instancies'] = $instancies;
      $calendarParams['option'] = $option;
      $calendarParams['layout_fk_eid'] = $layout->fk_eid;
      $calendarParams['layout_params'] = $layout_params;
      $calendarParams['Itemid'] = $Itemid;

    // Category::show_attached_layout($option, $instance_lid, $layout->fk_eid, $layout_params, '', '', 0, $instancies, '');  
    // exit;

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



  static function show_request_layout($option, $lid,$eiid,$show_type = 1,$button_name = '', $has_price = 0,$title = '', $button_style = '', $parent_layout_params = false){
      
    global $os_cck_configuration, $db, $moduleId, $task, $doc, $entityFieldLists, $app, $layouts;
    $db = new os_cckDb();
    
    $input = JFactory::getApplication()->input;
    $price_fields = $input->get('price_fields', '', 'STRING');
//    if($price_fields == ''){
//        $price_fields = $session->get('price_fields', '');
//    }
    
    $entityInstance = new os_cckEntityInstance($db->_db);
    $session = JFactory::getSession();
    $bootstrap_version = $session->get('bootstrap','2');
    if($price_fields == ''){
        $price_fields = $session->get('price_fields', '');
        $session->set('price_fields', '');
    }
    $fields_values_arr = $session->get('fields_val', '');
    if(isset($layouts[$lid])){
        $layout = $layouts[$lid];
    }else{
        $layout = new os_cckLayout($db->_db);
        $layout->load($lid);
        if(!$layout->lid) return;
        // var_dump($layout->lid);
        $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
        $GLOBALS['layouts'][$lid] = $layout;
    }
    if(!$layout->lid){

      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ADD_INSTANCE"), '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);
    $layout_fields = $layout_params['fields'];
    $layout_params['has_price'] = $has_price;
//    var_dump($layout_params['custom_fields']);
    $layout_params['title'] = $title;
    
    $layout->parent_eiid = $eiid;
    // var_dump($layout->type);
    if($show_type)
      $layout_params['show_type'] = $show_type;
    $layout_params['button_name'] = $button_name;
    $Itemid = $input->get('Itemid', 0);
    if($layout->type == 'show_review_instance'){

      
      $entityInstance->load($eiid);

      $reviews = $entityInstance->getReviews($parent_layout_params);
      // $pageNav = $reviews['pagenav'];
      $reviews = $reviews['reviews'];


      if ($reviews != null && count($reviews) > 0) {
        foreach ($reviews as $review) {
          $entityInstance = new os_cckEntityInstance($db->_db);
          $entityInstance->load($review->eiid);
          $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
          //load attached module ids
          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');
            }
          }
          
          
          require getLayoutPathCCK::getLayoutPathCom($option,$layout->type);
        }
        // echo '<div id="pagination" class="review-pagination">';
        //   if (!empty($pageNav) && ($pageNav->total > $pageNav->limit)) {
        //     echo $pageNav->getPagesLinks();
        //   }
        // echo '</div>';
      }else{
        if($layout_params['views']['no_review_message']){
          echo '<span class="first-review">'.cck_lang_text("COM_OS_CCK_SELECT_NO_REVIEW").'</span>';
        }
      }
    }elseif($layout->type == 'calendar'){
      self::show_calendar('com_os_cck', $layout->lid);
    }else{
      // var_dump($layout->type);
      $entityInstance->fk_eid = $layout->fk_eid;
      if(isset($entityFieldLists[$entityInstance->fk_eid])){
        $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
      }else{
          $layout->field_list = array();
      }
      if($layout_params['has_price'] == 0){
        $parentInstance = new os_cckEntityInstance($db->_db);
        $parentInstance->load($eiid);
        if(isset($entityFieldLists[$parentInstance->fk_eid])){
            $field_list = $entityFieldLists[$parentInstance->fk_eid];
        }else{
            $field_list = array();
        }
        foreach ($field_list as $field) {
          $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(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);
      $input->set('view', 'cck_layout');
    }
  }
  
  static function showParentChildLayout($option, $lid, $mod_type = 0, $number_of_plugin = '', $eiid = 0, $Itemid = 0){ 

    global $app, $db, $acl, $user, $doc, $session, $_globals, $input, $entityFieldLists, $entities_type;
    global $os_cck_configuration, $limit, $total, $limitstart,$moduleId ,$session, $cck_entity_configuration;
    $db = new os_cckDb();
    
      
    $input = $app->input;
    
    $option = $input->get('option', '');
    $moduleId =(($moduleId == 0
                 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    

    $currentcat = NULL;
    
    if($option == 'com_simplemembership'){
          $GLOBALS['number_of_plugin'] = $number_of_plugin;
          if($number_of_plugin == '1'){
              $plugin = JPluginHelper::getPlugin('simplemembership', 'plg_simplemembership_get_cck_user_instances');
          }else{
              $plugin = JPluginHelper::getPlugin('simplemembership', 'plg_simplemembership_get_cck_user_instances' . $number_of_plugin);
          }
          
          $params = new JRegistry($plugin->params);
      }else{
        if(!$moduleId){
            if($Itemid == 0){
                $Itemid = intval($input->get('Itemid'));
            }
          // 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');

          $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);
    $parent_child_instances_layout = new os_cckLayout($db->_db);
    
    
    if(!$lid || $lid == -1){        
        
      //from category menu
      
        if($params->get('layout')){

            $parent_child_instances_layout->load($params->get('layout')?$params->get('layout') : $params->get('parent_child_layout'));
            
            if(!$parent_child_instances_layout->published){

                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
                return;
            }
            $fields_from_params = unserialize($parent_child_instances_layout->params);
            $entity_id = $parent_child_instances_layout->fk_eid;
            
            if (!$entity_id){
              if(!$params->get('layout'))//component or module

                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_CATEGORY_LAYOUT"), 'warning');
              else

                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_MODULE_CATEGORY_LAYOUT"), 'warning');
              return;
            }
            if($option == 'com_simplemembership' && isset($_REQUEST['userId'])){
                
               $user = $_REQUEST['userId'];
            }else{
                $user = $params->get('layout')?$params->get('item') : $params->get('user');
            }
            $entity = new os_cckEntity($db->_db);
            $entity->load($entity_id);
            if($entity->type == 'os_cck_entity'){
                if($eiid == 0){
                    $eiid = ($params->get('instance')) ? $params->get('instance') : 0;
                }
                $entityInstance = new os_cckEntityInstance($db->_db);
                $entityInstance->load($eiid);
                
                $parent_child_instances_layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
                $parent_instance_id = $params->get('instance');
            }elseif($entity->type == 'joomla_user'){
                if($eiid == 0){
                    $eiid = ($params->get('user')) ? $params->get('user') : 0;
                }
                // var_dump($params->get('user'));
                $entityInstance = new os_cckEntityInstance($db->_db);
                $entityInstance = ConvertEntityInstanceToUser($entity->eid, $eiid);
                $parent_child_instances_layout->field_list = $entityFieldLists[$entity->eid];
                $parent_instance_id = $params->get('user');
            }elseif($entity->type == 'custom_sql'){
                if($eiid == 0){
                    $eiid = ($params->get('instance')) ? $params->get('instance') : 0;
                }
                $entityInstance = new os_cckEntityInstance($db->_db);
                $entityInstance = ConvertEntityInstanceToCustomSql($entity, $eiid);
                $parent_child_instances_layout->field_list = $entityFieldLists[$entity->eid];
                $parent_instance_id = $params->get('instance');
            }

            $fields_from_params = unserialize($parent_child_instances_layout->params);
            if(isset($fields_from_params['views']['show_request_layout'])){
              $child_layouts = $fields_from_params['views']['show_request_layout'];
            }else{
              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ENTER_INSTANCE_LAYOUT_FOR_PARENT_CHILD"), 'warning');
              
              return;
            }
            
            foreach($child_layouts as $key => $child_layout){
                $child_layout_id = $key;
            }
            
            $child_layout = new os_cckLayout($db->_db);
            $child_layout->load($child_layout_id);
            $child_entity_id = $child_layout->fk_eid;
            
        }//end category menu
    

        $user = (!$user) ? $params->get('user') : $user; 
        $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($input->get('userId', 0) > 0){
            $user= $input->get('userId', 0);
        }elseif ($input->get('task', '') == 'my_account' && $option == 'com_simplemembership') {
            $user = JFactory::getUser()->id;   
        }else{
            $user = $params->get('user');
        }
                
        if($eiid == 0){
            $eiid = $input->get('eiid', 0, 'INT');
        }
        if(is_array($eiid)){
            $eiid = $eiid[0];
        }
        if($eiid == 0 && $mod_type == 1){
            $eiid = $params->get('instance');
        }
        
        $parent_child_instances_layout->load($lid);
        $entity_id = $parent_child_instances_layout->fk_eid;
        $entity = new os_cckEntity($db->_db);
        $entity->load($entity_id);
        
        if($entity->type == 'os_cck_entity'){
            $entityInstance = new os_cckEntityInstance($db->_db);
            $entityInstance->load($eiid);
            $parent_child_instances_layout->field_list = isset($entityFieldLists[$entityInstance->fk_eid]) ? $entityFieldLists[$entityInstance->fk_eid] : array();
        }elseif($entity->type == 'joomla_user'){
            if(!$eiid){
                $eiid = $user;
            }
            $entityInstance = new os_cckEntityInstance($db->_db);
            $entityInstance = ConvertEntityInstanceToUser($entity->eid, $eiid);
            $parent_child_instances_layout->field_list = $entityFieldLists[$entity->eid];
            $parent_instance_id = $params->get('user');
        }elseif($entity->type == 'custom_sql'){
            $entityInstance = new os_cckEntityInstance($db->_db);
            $entityInstance = ConvertEntityInstanceToCustomSql($entity, $eiid);
            $parent_child_instances_layout->field_list = $entityFieldLists[$entity->eid];
            $parent_instance_id = $params->get('instance');
        }
        $fields_from_params = unserialize($parent_child_instances_layout->params);
        
        $child_layouts = (isset($fields_from_params['views']['show_request_layout'])) ? $fields_from_params['views']['show_request_layout'] : array();
        // var_dump($parent_child_instances_layout); exit;
        foreach($child_layouts as $key => $child_layout){
            $child_layout_id = $key;
        }

        
        $child_layout = new os_cckLayout($db->_db);
        if(isset($child_layout_id)){
          $child_layout->load($child_layout_id);
        }
        $child_entity_id = $child_layout->fk_eid;
        
        $parent_instance_id = $eiid;

        $entity_id = $parent_child_instances_layout->fk_eid;
        
        
    }

    
          $parent_entity = new os_cckEntity($db->_db);
          $parent_entity->load($entity_id);
          $parent_entityInstance = new os_cckEntityInstance($db->_db);
          // var_dump($parent_entity);
          if($parent_entity->type == 'os_cck_entity'){
            $parent_entityInstance->load($parent_instance_id);
          }elseif($parent_entity->type == 'joomla_user'){

            if($option == 'com_simplemembership'){
              $user_id = $user;
            }else{
              $user_id = $params->get('user');
            }
              
              $parent_entityInstance = ConvertEntityInstanceToUser($parent_entity->eid, $user_id);
          }elseif($parent_entity->type == 'custom_sql'){
              $parent_entityInstance = ConvertEntityInstanceToCustomSql($parent_entity, $parent_instance_id);
          }

            if(!$parent_entityInstance->eiid){
              if(isset($cck_entity_configuration[$entity_id]['redirect_missing_instance']) && $cck_entity_configuration[$entity_id]['redirect_missing_instance'] != ''){
                if(stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'http://') != false || stripos($cck_entity_configuration[$entity_id]['redirect_missing_instance'], 'https://') != false){
                  $redirect_url = $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
                }else{
                  $redirect_url = JUri::root() . $cck_entity_configuration[$entity_id]['redirect_missing_instance'];
                }
      
                $app->redirect($redirect_url);
              }
              $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_INSTANCE"), 'warning');
              return;
            }
    
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/files/entity_files_$entity_id/custom.css");
    $lang_where = '';
      if(JLanguageMultilang::isEnabled()){
          $parent_child_instances_layout = setLayoutLangCCK($parent_child_instances_layout);
          $lang_where = getCCKLangWhere();
          
      }
    
    if($parent_child_instances_layout->type != 'parent_child' && $parent_child_instances_layout->type != 'parent_child_pdf'){

      $app->enqueueMessage("Layout type load error User instances layout ID: ".$parent_child_instances_layout->lid, 'warning');
      return;
    }
    $parent_child_instances_layout->layout_html = $parent_child_instances_layout->getLayoutHtml('2');
      $lay_html = urldecode($parent_child_instances_layout->layout_html);
    $limit = (isset($fields_from_params['views']['pagenator_limit']) && strpos($lay_html,"{|f-joom_pagination|}")) ? $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($parent_child_instances_layout->fk_eid){
        $entity_name = $parent_child_instances_layout->fk_eid;
    }else{
        return;
    }
    $nextInstId = 0;
    $prevInstId = 0;
    if(isset($fields_from_params['fields']['cck_instance_navigation_published']) 
        && $fields_from_params['fields']['cck_instance_navigation_published']){
        //query for pagination//itemindex -- index number of instance in cat-instances array
        $andCID = '';

        if($entities_type[$parent_child_instances_layout->fk_eid] == 'os_cck_entity'){
            if($params->get('layout_type', '') == 'category'){
                $catid = $params->get('category', '');
            }else{
                $catid = 0;
            }
            if($catid > 0)
              $andCID = "AND cc.fk_cid=$catid";
            $query = "SELECT eiid FROM #__os_cck_entity_instance as i "
                    ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = i.fk_lid "
                    ."\n LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = i.eiid "
                    ."\n WHERE l.type ='add_instance' ".$andCID." AND i.published=1 "
                    ."\n AND i.approved=1   AND i.eiid > ".intval($eiid)
                    ."\n AND i.fk_eid= " . $parent_child_instances_layout->fk_eid
                    ."\n ORDER BY eiid LIMIT 1";
            $db->setQuery($query);
            $nextInstId = $db->loadResult();

            $query = "SELECT eiid FROM #__os_cck_entity_instance as i "
                    ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = i.fk_lid "
                    ."\n LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = i.eiid "
                    ."\n WHERE l.type ='add_instance' ".$andCID." AND i.published=1 "
                    ."\n AND i.approved=1   AND i.eiid < ".intval($eiid)
                    ."\n AND i.fk_eid= " . $parent_child_instances_layout->fk_eid
                    ."\n ORDER BY eiid DESC LIMIT 1";
            $db->setQuery($query);
            $prevInstId = $db->loadResult();
        }elseif($entities_type[$parent_child_instances_layout->fk_eid] == 'joomla_user'){

            $query = "SELECT id as eiid FROM #__users "
                    . "WHERE block=0 AND id> ".intval($eiid)
                    ."\n ORDER BY id LIMIT 1";
            $db->setQuery($query);
            $nextInstId = $db->loadResult();


            $query = "SELECT id as eiid FROM #__users "
                    . "WHERE block=0 AND id < ".intval($eiid)
                    ."\n ORDER BY id LIMIT 1";
            $db->setQuery($query);
            $prevInstId = $db->loadResult();
        }elseif($entities_type[$layout->fk_eid] == 'custom_sql'){

        }


        if(isset($_REQUEST['next']) && $_REQUEST['next'] > 0 && $nextInstId){
          $entityInstance->load(intval($nextInstId));
        }else if(isset($_REQUEST['prev']) && $_REQUEST['prev'] > 0 && $prevInstId){
          $entityInstance->load(intval($prevInstId));
        }else{
          $entityInstance->load(intval($eiid));
        }
    }


    //creating order by list
    $fields_from_params = getOrderByOptions('parent_child_order_by', $fields_from_params, $child_entity_id, $mod_type, $parent_child_instances_layout->lid);
//    $fields_from_params["views"]["sortField"][] = isset($fields_from_params["fields"]["indexed_parent_child_order_by"])?$fields_from_params["fields"]["indexed_parent_child_order_by"]:'';
    $entity = new os_cckEntity($db->_db);
    
    $entity->load($child_entity_id);
    
    if(isset($entityFieldLists[$entity->eid])){
      $fields_list = $entityFieldLists[$entity->eid];
    }else{
      $fields_list = array();
    }

    if($params->get('layout')){
        $header = $parent_child_instances_layout->title;
    }elseif($option == 'com_simplemembership'){
        $header = $params->get('tab_name');
    }else{
        $header = set_header_name_cck($menu, $Itemid);
    }
    //$header = $params->get('layout') ? "$user_instances_layout->title" : set_header_name_cck($menu, $Itemid);
    $params->def('header', $header);
    $params->def('pageclass_sfx', '');
    
    
    //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($entities_type[$entity_id] == 'custom_sql'){
                  $prefix = 't';
              }else{
                  $prefix = 'instance';
              }
              $now_indexed = str_replace('custom_sql_', '', $_REQUEST['now_indexed']);
            if($sp == 1 && $_REQUEST['now_indexed'] == $fields_from_params["views"]["selected"]){
              if($entities_type[$entity_id] != 'custom_sql'){
                $where = " AND LOWER($prefix." . $now_indexed . ") LIKE '$search%' ";
              }else{
                  $where = " LOWER($prefix." . $now_indexed . ") LIKE '$search%' ";
              }
            }else{
              $where = '';
            }

          }
      }
    
        $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 . ' ';
                  }

              }
          } 
      }
//      var_dump($fields_from_params['views']);
      $parent_or_child = 'all';
      foreach($fields_from_params['views']['show_request_layout'] as $lay_key => $lay_val){
          $temp_request_layout = new os_cckLayout($db->_db);
          $temp_request_layout->load($lay_key);
          if($temp_request_layout->type == 'instance' && isset($fields_from_params['views']['parents_or_childs_'.$lay_key])){
              $parent_or_child = $fields_from_params['views']['parents_or_childs_'.$lay_key];
          }
//          var_dump($temp_request_layout);
      }
      
      if($parent_or_child == 'childs'){
          $parent_or_child_where = " AND c_p_ch.fid_parent='$parent_instance_id' ";
      }elseif($parent_or_child == 'parents'){
          $parent_or_child_where = " AND c_p_ch.fid_child='$parent_instance_id' ";
          
      }else{
          $parent_or_child_where = " AND (c_p_ch.fid_child='$parent_instance_id' OR c_p_ch.fid_parent='$parent_instance_id')";
      }
//      var_dump($parent_or_child);
//    $parent_or_child = $fields_from_params['views'];
    
    //user access
    if($child_entity_id > 0 && isset($cck_entity_configuration[$child_entity_id]) && $cck_entity_configuration[$child_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"]["selected"]) && (strstr($fields_from_params["views"]["selected"], 'text_textfield') !== false || (($entities_type[$child_entity_id] == 'joomla_user' || $entities_type[$child_entity_id] == 'custom_sql') && checkUserFieldType($child_entity_id, $fields_from_params["views"]["selected"])))){
        if($entities_type[$child_entity_id] == 'os_cck_entity'){
            $query = "SELECT DISTINCT UPPER(SUBSTRING(instance.".$fields_from_params["views"]["selected"].", 1,1)) AS symb FROM #__os_cck_entity_instance AS ei "
                . "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = ei.eiid OR c_p_ch.fid_parent = ei.eiid) "
                . "LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
                . "LEFT JOIN `#__os_cck_content_entity_$child_entity_id` as instance ON instance.`fk_eiid` = ei.eiid "
                . "WHERE ei.published='1' "
                . "AND ei.approved='1' "
                . "AND ei.fk_eid='$child_entity_id' "
                . "$parent_or_child_where $access_where $custom_sql_where $lang_where GROUP BY ei.eiid ORDER BY symb";  
        }elseif($entities_type[$child_entity_id] == 'joomla_user'){
//             $query = "SELECT COUNT(DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent) FROM #__users as us "
//                . "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = us.id OR c_p_ch.fid_parent = us.id) "
//                . "WHERE us.block=0 "
//                . "AND (c_p_ch.fid_child='$parent_instance_id' OR c_p_ch.fid_parent='$parent_instance_id')";
            
                $request_details = getRequestDetailsForAlphabeticalJoomlaUser($fields_from_params["views"]["selected"]);
                $query = "SELECT  DISTINCT UPPER(SUBSTRING(".$request_details['field_name'].", 1,1)) AS symb FROM #__users as us ";
                $query .= "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = us.id OR c_p_ch.fid_parent = us.id) ";
                $query .= $request_details['join'];
                $query .= ' WHERE us.block=0 ';
                $query .= "$parent_or_child_where";
                $query .= $request_details['where'] . $custom_sql_where . ' GROUP BY us.id ORDER BY symb';
        }elseif($entity->type == 'custom_sql' && $entities_type[$parent_child_instances_layout->fk_eid] == 'custom_sql'){
            $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';
              if(trim($custom_sql_where) != ''){
                  $where_string = " WHERE $custom_sql_where ";
              }elseif($where != ''){
                  $where_string = " WHERE " . $where;
              }else{
                  $where_string = "";
              }
              $parent_entity = new os_cckEntity($db->_db);
              $parent_entity->load($parent_child_instances_layout->fk_eid);
              $parent_related_fields = $fields_from_params['views']['parent_related_fields'];
              $child_related_fields = $fields_from_params['views']['child_related_fields'];
              $child_fields = $entityFieldLists[$parent_child_instances_layout->fk_eid];
              $id_field = $child_fields['custom_sql_id'];

              $query = "SELECT DISTINCT UPPER(SUBSTRING(c.".str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]).", 1,1)) AS symb FROM ($parent_entity->sql_select) as t "
                      . "LEFT JOIN ($entity->sql_select) as c ON t.$parent_related_fields= c.$child_related_fields "
                      . "WHERE t.$id_field->fid=$parent_instance_id";
        }elseif ($entities_type[$entity_id] == 'custom_sql'){

            if(trim($custom_sql_where) != ''){
                $where_string = " WHERE $custom_sql_where ";
            }else{
                $where_string = "";
            }
            $query = "SELECT DISTINCT UPPER(SUBSTRING(t.".str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]).", 1,1)) AS symb FROM ($entity->sql_select) as t LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = t.id OR c_p_ch.fid_parent = us.id) $where_string 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=parent_child&letindex=' . $symbol->symb . '&sp=1&Itemid=' . $Itemid . 
            '&now_indexed=' . $fields_from_params["views"]["selected"] . '&userId=' . $user . '">' . 
          $symbol->symb . '</a></li> ';
            
          }

          //check string not empty
          if(!empty(strip_tags($symb_list_str))){
            $symb_list_str.= '<li><a href="index.php?option=' . $option . 
            '&view=parent_child&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;
    }

    //alfabetical pagination

    // var_dump($entity->type); exit;

//    $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_layout AS lay ON lay.lid=ei.fk_lid "
//            . "\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 AND ei.fk_userid='{$user}' "
//            . "\n AND ei.fk_eid='" . $entity_id . "' $where ";
//        var_dump($entities_type[$child_entity_id]);
    // var_dump($entity->type ); exit;
    if($entity->type == 'os_cck_entity'){        
        $query = "SELECT COUNT(DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent) FROM #__os_cck_entity_instance AS ei "
            . "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = ei.eiid OR c_p_ch.fid_parent = ei.eiid) "
            . "LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
            . "LEFT JOIN `#__os_cck_content_entity_$child_entity_id` as instance ON instance.`fk_eiid` = ei.eiid "
            . "WHERE ei.published='1' "
            . "AND ei.approved='1' "
            . "AND ei.fk_eid='$child_entity_id' "
            . "$parent_or_child_where $access_where $custom_sql_where $lang_where ";
    }elseif($entity->type == 'joomla_user'){
        $query = "SELECT COUNT(DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent) FROM #__users as us "
                    . "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = us.id OR c_p_ch.fid_parent = us.id) ";
        if(isset($request_details)){
              //$query = "SELECT COUNT(us.id) FROM #__users as us";
              $query .= $request_details['join'];
              $query .= " WHERE block=0 $parent_or_child_where ";
              $query .= $request_details['where'] . $request_details['where2'] . $custom_sql_where;
              
              
          }else{
            $query .= "WHERE us.block=0 "
                    . "$parent_or_child_where $custom_sql_where";
          }
    }elseif($entity->type == 'custom_sql' && $entities_type[$parent_child_instances_layout->fk_eid] == 'custom_sql'){
        $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';
          if(trim($custom_sql_where) != ''){
              $where_string = " WHERE $custom_sql_where ";
          }elseif($where != ''){
              $where_string = " WHERE " . $where;
          }else{
              $where_string = "";
          }
          $parent_entity = new os_cckEntity($db->_db);
          $parent_entity->load($parent_child_instances_layout->fk_eid);
          $parent_related_fields = $fields_from_params['views']['parent_related_fields'];
          $child_related_fields = $fields_from_params['views']['child_related_fields'];
          $child_fields = $entityFieldLists[$parent_child_instances_layout->fk_eid];
          $id_field = $child_fields['custom_sql_id'];

          $query = "SELECT COUNT(*) FROM ($parent_entity->sql_select) as t "
                  . "LEFT JOIN ($entity->sql_select) as c ON t.$parent_related_fields= c.$child_related_fields "
                  . "WHERE t.$id_field->fid=$parent_instance_id";
    }elseif ($entity->type == 'custom_sql'){

            $orderby = (!empty($fields_from_params["fields"]["sortType_all_instance_order_by"])) ? $fields_from_params["fields"]["sortType_all_instance_order_by"] : 'ASC';
          if(trim($custom_sql_where) != ''){
              $where_string = " WHERE $custom_sql_where ";
          }elseif($where != ''){
              $where_string = " WHERE " . $where;
          }else{
              $where_string = "";
          }

          
            
            $query = "SELECT COUNT(DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent) FROM ($entity->sql_select) as t LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = t.id OR c_p_ch.fid_parent = t.id) $where_string ";
            
        }
    if(isset($query)){
      $db->setQuery($query);
      $total = $db->loadResult();
    }else{
      $total = 0;
    }
//    var_dump($total); exit;
    if($max_items != '0' && $max_items < $total ) {
      if($limit > $max_items )$limit = $max_items;
      $total = $max_items;
    }
    
    //  if( isset($fields_from_params['views']['selected']) && 
    //      ( !isset( $fields_from_params['views']['order_by_fields'] ) || !is_array( $fields_from_params['views']['order_by_fields'] ) ||
    //       ( is_array( $fields_from_params['views']['order_by_fields'] ) && !in_array($fields_from_params["views"]["selected"],$fields_from_params['views']['order_by_fields']) 
    //       ) 
    //      )
    //     )
    //  {

    //     $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_parent_child_order_by"])?$fields_from_params["fields"]["indexed_parent_child_order_by"]:'';
    //  }
    
    $pageNav = new os_libPagination($total, $limitstart, $limit);
    //  var_dump($fields_from_params["fields"]["indexed_parent_child_order_by"]);
    if($entity->type == 'os_cck_entity'){ 
    $query = "SELECT DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent 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 cat ON cat.cid=ccc.fk_cid "
            . "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = ei.eiid OR c_p_ch.fid_parent = ei.eiid) "
            . "LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid "
            . "LEFT JOIN `#__os_cck_content_entity_$child_entity_id` as instance ON instance.`fk_eiid` = ei.eiid "
            . "WHERE ei.published='1' "
            . "AND ei.approved='1' "
            . "AND ei.fk_eid='$child_entity_id' "
            . "$parent_or_child_where $access_where $custom_sql_where $lang_where";
            
            
            
        if(isset($fields_from_params["fields"]["indexed_parent_child_order_by"])){ // if selected sortable field
            $orderby = (!empty($fields_from_params["views"]["sortType_parent_child_order_by"])) ? $fields_from_params["views"]["sortType_parent_child_order_by"] : 'ASC';
            if($orderby != 'RAND()') {
                if (isset($fields_from_params["views"]["selected"]) && !empty($fields_from_params["views"]["selected"])) {
                    $index = 0;
                    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 .= "ORDER BY ei.title $orderby ";
                            } elseif ($fields_from_params["views"]["selected"] == 'hits') {

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

                                $query .= " ORDER BY ei.last_review $orderby";
                            } elseif ($fields_from_params["views"]["selected"] == 'custom_order') {
                                $query .= ' ORDER BY ' . $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"]) . " ORDER BY price.price_value $orderby";
                            } elseif (stripos($fields_from_params["views"]["selected"], 'rating_field') !== FALSE) {
                                $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 cat ON cat.cid=ccc.fk_cid "
                                    . "\n LEFT JOIN #__os_cck_layout AS lay ON lay.lid=ei.fk_lid "
                                    . "\n LEFT JOIN `#__os_cck_content_entity_$child_entity_id` as instance ON instance.`fk_eiid` = ei.eiid "
                                    . "\n LEFT JOIN #__os_cck_content_instances_price AS price ON price.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_$child_entity_id` 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 ei.fk_userid='{$user}' "
                                    . "\n AND ei.fk_eid='" . $child_entity_id . "' $where $access_where $custom_sql_where $lang_where "
                                    . "\n GROUP BY ei.eiid "
                                    . "\n ORDER BY rating $orderby";

                            } else {

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

                    }
                } elseif ($fields_from_params["fields"]["indexed_parent_child_order_by"] == 'eid') {
                    $query .= "ORDER BY ei.eiid $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_parent_child_order_by"] == 'title') {
                    $query .= "ORDER BY ei.title $orderby ";
                } elseif (stripos($fields_from_params["fields"]["indexed_parent_child_order_by"], 'categoryfield') !== FALSE) {
                    $query .= "ORDER BY cat.name $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_parent_child_order_by"] == 'hits') {
                    $query .= "ORDER BY ei.hits $orderby ";
                }elseif ($fields_from_params["fields"]["indexed_parent_child_order_by"] == 'last_review' || $fields_from_params["fields"]["indexed_parent_child_order_by"] == 'last_review_date') {
                    $query .= "ORDER BY ei.last_review $orderby ";
                } elseif ($fields_from_params["fields"]["indexed_parent_child_order_by"] == 'custom_order') {
                    $query .= ' ORDER BY ' . $fields_from_params['views']['custom_order_by'][0] . " $orderby ";
                } elseif (stripos($fields_from_params["fields"]["indexed_parent_child_order_by"], 'pricefield_number_') !== false) {

                    $query .= " AND price.fk_fid = " . str_replace('pricefield_number_', '', $fields_from_params["fields"]["indexed_parent_child_order_by"]) . " ORDER BY price.price_value $orderby";
                } else { // for other fields
                    $query .= "ORDER BY instance.`{$fields_from_params["fields"]["indexed_parent_child_order_by"]}` $orderby ";
                }
            }else{
                $query .= " ORDER BY $orderby ";
            }
        }
    }elseif($entity->type == 'joomla_user'){
        $query = "SELECT DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent FROM #__users as us "
                . "LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = us.id OR c_p_ch.fid_parent = us.id) ";
          if(isset($fields_from_params["fields"]["indexed_parent_child_order_by"])) { // if selected sortable field
              //var_dump($fields_from_params["fields"]["indexed_all_instance_order_by"]);
              $orderby = (!empty($fields_from_params["views"]["sortType_parent_child_order_by"])) ? $fields_from_params["views"]["sortType_parent_child_order_by"] : 'ASC';
              //$orderby = (!empty($fields_from_params["fields"]["sortType_parent_child_order_by"])) ? $fields_from_params["fields"]["sortType_parent_child_order_by"] : 'ASC';
              if (isset($fields_from_params["views"]["selected"]) && !empty( $fields_from_params["views"]["selected"])) {
                  $request_details = getJoinForOrderByJoomlaUser($fields_from_params["views"]["selected"], $orderby);
                  $query .= $request_details['join'];
                  $query .= " WHERE block=0 $parent_or_child_where ";
                  $query .= $request_details['where'] . ' ' . $custom_sql_where . ' ' . $request_details['order_by'] . ' ' . $orderby;
              }
          }else{
              $query .= "WHERE us.block=0 $parent_or_child_where " . $custom_sql_where;
          }
          
        

    }elseif($entity->type == 'custom_sql' && $entities_type[$parent_child_instances_layout->fk_eid] == 'custom_sql'){
        $orderby = (!empty($fields_from_params["fields"]["sortType_parent_child_order_by"])) ? $fields_from_params["fields"]["sortType_parent_child_order_by"] : 'ASC';
//        var_dump($orderby);
          if(trim($custom_sql_where) != ''){
              $where_string = " WHERE $custom_sql_where ";
          }elseif($where != ''){
              $where_string = " WHERE " . $where;
          }else{
              $where_string = "";
          }
          $parent_entity = new os_cckEntity($db->_db);
          $parent_entity->load($parent_child_instances_layout->fk_eid);
          $parent_related_fields = $fields_from_params['views']['parent_related_fields'];
          $child_related_fields = $fields_from_params['views']['child_related_fields'];
          $child_fields = $entityFieldLists[$entity->eid];
          $child_id_field = $child_fields['custom_sql_id'];
          $parent_fields = $entityFieldLists[$parent_child_instances_layout->fk_eid];
          $parent_id_field = $parent_fields['custom_sql_id'];

          $query = "SELECT DISTINCT c.$child_id_field->fid as fid_child FROM ($parent_entity->sql_select) as t "
                  . "LEFT JOIN ($entity->sql_select) as c ON t.$parent_related_fields= c.$child_related_fields "
                  . "WHERE t.$parent_id_field->fid=$parent_instance_id $custom_sql_where";
          if(isset($fields_from_params["views"]["selected"]) && $fields_from_params["views"]["selected"] != '' && $fields_from_params["views"]["selected"] != 'custom_order'){
            $query .= " ORDER BY c.".str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]) . ' ' . $orderby;
          }

    }elseif ($entity->type == 'custom_sql'){

        $orderby = (!empty($fields_from_params["fields"]["sortType_parent_child_order_by"])) ? $fields_from_params["fields"]["sortType_parent_child_order_by"] : 'ASC';
          if(trim($custom_sql_where) != ''){
              $where_string = " WHERE $custom_sql_where ";
          }elseif($where != ''){
              $where_string = " WHERE " . $where;
          }else{
              $where_string = "";
          }

          
        $query = "SELECT DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent FROM ($entity->sql_select) as t LEFT JOIN #__os_cck_child_parent_connect as c_p_ch ON (c_p_ch.fid_child = t.id OR c_p_ch.fid_parent = t.id) $where_string ";
        if(isset($fields_from_params["views"]["selected"]) && $fields_from_params["views"]["selected"] != '' && $fields_from_params["views"]["selected"] != 'custom_order'){
            if($orderby != 'RAND()') {
                $query .= " ORDER BY t." . str_replace('custom_sql_', '', $fields_from_params["views"]["selected"]) . ' ' . $orderby;
            }else{
                $query .= " ORDER BY " . $orderby;
            }
          }
        $db->setQuery($query);
//                var_dump($query); exit;
        $tmp_arr = $db->loadObjectList();
    }
    if($query){
      $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 = $db->loadObjectList();
      
      $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[$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 = $db->loadObjectList();
    }else{
      $items = array();
    }

    $instancies = array();
    $temp_instancies_id = array();

    foreach ($items as $item) {
        // var_dump($item->fid_child);
        if($item->fid_child == $parent_instance_id && property_exists($item, 'fid_parent')){
          // var_dump(property_exists($item, 'fid_parent'));
            if(property_exists($item, 'fid_parent') && !in_array($item->fid_parent, $temp_instancies_id) && $item->fid_parent){

                if($entity->type == 'os_cck_entity'){
                    $instance = new os_cckEntityInstance($db->_db);
                    $instance->load($item->fid_parent);
                }elseif ($entity->type == 'joomla_user') {
                    $instance = ConvertEntityInstanceToUser($entity->eid, $item->fid_parent);
                }elseif($entity->type == 'custom_sql' && $entities_type[$parent_child_instances_layout->fk_eid] == 'custom_sql'){
                    $instance = ConvertEntityInstanceToCustomSql($entity, $item->fid_parent, false, $fields_from_params['views']['parent_related_fields'], $fields_from_params['views']['child_related_fields'], $parent_child_instances_layout->fk_eid);
                    $instance->parent_eiid = $parent_instance_id;
                }elseif ($entity->type == 'custom_sql') {
                    $instance = ConvertEntityInstanceToCustomSql($entity, $item->fid_parent);
                }
                $temp_instancies_id[] = $item->fid_parent;
                $instancies[] = $instance;
            }
        }else{
          
            if(!in_array($item->fid_child, $temp_instancies_id) && $item->fid_child){
                if($entity->type == 'os_cck_entity'){
                    $instance = new os_cckEntityInstance($db->_db);
                    $instance->load($item->fid_child);
                }elseif ($entity->type == 'joomla_user') {
                    $instance = ConvertEntityInstanceToUser($entity->eid, $item->fid_child);
                }elseif($entity->type == 'custom_sql' && $entities_type[$parent_child_instances_layout->fk_eid] == 'custom_sql'){
                    $instance = ConvertEntityInstanceToCustomSql($entity, $item->fid_child, false, $fields_from_params['views']['parent_related_fields'], $fields_from_params['views']['child_related_fields'], $parent_child_instances_layout->fk_eid);
                    $instance->parent_eiid = $parent_instance_id;
                }elseif ($entity->type == 'custom_sql') {
                    $instance = ConvertEntityInstanceToCustomSql($entity, $item->fid_child);
                }
                $temp_instancies_id[] = $item->fid_child;
                $instancies[] = $instance;
            }
        }
        
    }

    $params->def('show_rating', 1);
    $params->def('hits', 1);
    $params->def('back_button', $app->getCfg('back_button'));

    //var_dump($fields_from_params['views']);
    $layout_params = unserialize($parent_child_instances_layout->params);
    $layout_params['custom_fields'] = unserialize($parent_child_instances_layout->custom_fields);
    $layout_params['cat_layout_params'] = $fields_from_params;
    $bootstrap_version = $session->get( 'bootstrap','2');
    $parent_child_instances_layout->layout_html = $parent_child_instances_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');
      }
    }
    $layout_params['nextInstId'] = $nextInstId;
    $layout_params['prevInstId'] = $prevInstId;

    $layout = $parent_child_instances_layout;
    
    if($layout->type == 'parent_child'){
        $type = 'parent_child';
        $option = 'com_os_cck';
        if($option == 'com_simplemembership'){
            

        }

        require getLayoutPathCCK::getLayoutPathCom($option, $type);

    }elseif($layout->type == 'parent_child_pdf'){
        os_cck_site_controller::displayCckPdf('', $instancies, $layout, $layout_params, $eiid);
    }
    
  }
  
  static function showCartLayout($option, $lid, $mod_type = 0, $cart_type = 'default', $Itemid = 0){
    global $app, $db, $acl, $user, $doc, $session;
    global $os_cck_configuration, $limit, $total, $limitstart,$moduleId ,$session;
    
    $db = new os_cckDb();
    // $cache = JFactory::getCache('com_os_cck', '');
//    var_dump($cache);
    // $cache->setCaching(false);
//    var_dump($cache);
//    $cache = new JCache;
//    var_dump($cache);
    
    $app = JFactory::getApplication();
    $input = $app->input;
    
    $moduleId =(($moduleId == 0
                 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
    
    
    
    $task = $input->get('view', '', 'STRING');
    
    $currentcat = NULL;
    $cart = $session->get('cart', array());
    //var_dump($session->get('cart', array())); exit;

    if(!$moduleId){
        if($Itemid == 0){
            $Itemid = $input->get('Itemid');
        }
      // 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);
    $cart_layout = new os_cckLayout($db->_db);

    
    if(!$lid || $lid == -1){
        
      if($params->get('cart_layout') || $params->get('layout_type') == 'cart'){
          
        $cart_layout->load($params->get('layout')?$params->get('layout') : $params->get('cart_layout'));
        if(!$cart_layout->published){

            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_CATEGORY_LAYOUT"), 'warning');
            return;
        }
        $fields_from_params = unserialize($cart_layout->params);

      }//end category menu
      
    }else{

      $cart_layout->load($lid);
      if($cart_layout->params){
        $fields_from_params = unserialize($cart_layout->params);
      }else{
          $fields_from_params = array();
      }
      $entity_id = $cart_layout->fk_eid;
    }
    

    if($cart_layout->type != 'cart'){

      $app->enqueueMessage("Layout type load error Cart layout ID: ".$cart_layout->lid, 'warning');
      return;
    }
    
    if($cart_layout->fk_eid){
        $entity_name = $cart_layout->fk_eid;
    }else{
        return;
    }

    
    
    $instancies = array();
    foreach ($cart as $item) {
        
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($item['eiid']);
        $instancies[] = $instance;
    }
    
    $categories = array();

    //os_cck_site_controller::cck_constructPathway($category, 'cart', $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/';
    
//    if ($category->image != null && $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, $cart_layout->fk_eid);


    $tabclass = array('sectiontableentry1', 'sectiontableentry2');
    if(!$instancies && $cart_type == 'default'){
        echo '<div style="text-align:center"><h2>'.cck_lang_text("COM_OS_CCK_CART_IS_EMPTY").'</h2></div>';
    }
    $layout_params = unserialize($cart_layout->params);
    
    $layout_params['custom_fields'] = unserialize($cart_layout->custom_fields);
    $layout_params['cat_layout_params'] = $fields_from_params;
    $bootstrap_version = $session->get( 'bootstrap','2');
    $cart_layout->layout_html = $cart_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');
      }
    }
    
    $count = 0;
    foreach ($cart as $key => $item){
          $price_fields = json_decode($item['price_fields']);
          if(isset($price_fields[0]->quantity)){
              $count += $price_fields[0]->quantity;
          }elseif(isset($price_fields[0])){
              $count += 1;
              // var_dump($price_fields); exit;
              $price_fields[0]->quantity = 1;
              $cart[$key]['price_fields'] = json_encode($price_fields);
          }

      }

    

    $layout = $cart_layout;

    if($cart_type == 'default'){
        $type = 'cart';
    }else{
        $type = 'small_cart';
    }

    require getLayoutPathCCK::getLayoutPathCom($option, $type);
    
    // $cache->setCaching(true);
  }

  static function deleteInstances($eiid, $option){
    global $db, $os_cck_configuration, $user, $Itemid, $app, $entityFieldLists, $os_cck_state, $moduleId;
    $db = new os_cckDb();
    if(!cck_checkReferer()){

          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
          return;
      }
    $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
    if(!$moduleId){
      // Params(cck component menu)
      if (version_compare(JVERSION, '3.0', 'ge')) {
        $menu = new JTableMenu($db->_db);
        $menu->load($Itemid);
        $menu_params = new JRegistry;
        if($menu->params){
          $menu_params->loadString($menu->params);
        }  
      }else{
        $app    = JFactory::getApplication();
        $menu   = $app->getMenu();
        $menu_params = new JRegistry;
        $menu_params = $menu->getParams( $Itemid );
      }//end
    }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
      if (version_compare(JVERSION, '3.0', 'ge')) {
        $menu_params = new JRegistry;
        $menu_params->loadString($mod_row->params);
      } else {
        $menu_params = new JRegistry($mod_row->params);
      }//end
    }
  if (!is_array($eiid) || count($eiid) < 1) {
    echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
    exit;
  }
  $layout_type = $menu_params->get('layout_type', '');
  if($layout_type == ''){
    $groupAccess = $menu_params->get('im_delete_access','1');
    if (!checkAccess_cck($groupAccess, $user->groups, 0, 'instances', $eiid)){

      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_INSTANCE_MANAGER"), 'warning');
      return;
    }
    
    if(!checkInstanceManagerItem($menu_params)){
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY"), 'warning');
      return;
    }
  }else{
    $old_lid = protectInjectionWithoutQuote('access', 0, 'INT');
    if($old_lid > 0){
      $query = "SELECT params FROM #__os_cck_layout WHERE lid=$old_lid";
      $db->setQuery($query);
      $old_lay_params = $db->loadResult();
      $old_lay_params = unserialize($old_lay_params);
      // var_dump($old_lay_params); exit;
      $button = protectInjectionWithoutQuote('button', 0, 'INT');

      $groupAccess = $old_lay_params['fields']['access_cck_action_button_'.$button];
      if (!checkAccess_cck($groupAccess, $user->groups, 0, 'instances', $eiid)){

        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_INSTANCE_MANAGER"), 'warning');
        return;
      } 
    }
  }
  // exit;
  // if(!checkInstanceManagerItem($menu_params)){
  //   $app->enqueueMessage(cck_lang_text("COM_OS_CCK_SELECT_ENTITY"), 'warning');
  //   return;
  // }
  
  // // var_dump($groupAccess);
  // if (!checkAccess_cck($groupAccess, $user->groups, 0, 'instances', $eiid)){

  //   $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ACCESS_INSTANCE_MANAGER"), 'warning');
  //   return;
  // }
  if (count($eiid)) {
    foreach ($eiid as $id) {
      $instance = new os_cckEntityInstance($db->_db);
      $instance->load($id);
      $instance->delete();
    }
  }
  if($layout_type == ''){
    $app->enqueueMessage('ok', 'success');
    $app->redirect("index.php?option=$option&task=instance_manager&Itemid=".$Itemid);
  }else{
    $app->enqueueMessage('ok', 'success');
    $app->redirect($_SERVER['HTTP_REFERER']);
  }
  }
  

}
