<?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
*/

class os_cckLayout extends JTable
{

    var $lid = null;
    var $title = null;
    var $type = null;
    var $fk_eid = null;
    var $params = null;
    var $checked_out = null;
    var $checked_out_time = null;
    var $published = null;
    var $approved = null;
    var $created = null;
    var $changed = null;
    var $pdf_structure = '';
    var $language = null;
    var $associate_layout = null;

    function __construct(&$db)
    {
        parent::__construct('#__os_cck_layout', 'lid', $db);
    }

    function quoteName($name)
    {
        if (version_compare(JVERSION, "3.0.0", "lt")) {
            $return = $this->_db->NameQuote($name);
        } else {
            $return = $this->_db->quoteName($name);
        }
        return $return;
    }

    function getLayoutParams($fk_eid, $type)
    {
        $query = "SELECT lid FROM #__os_cck_layout WHERE fk_eid = '" . $fk_eid . "' AND type = '" . $type ."'";
        $this->_db->setQuery($query);
        $result = $this->_db->loadResult();
        return $result;
    }

    function getDefaultLayout($fk_eid, $type, $lang = '*')
    {   
        $lang_where = '';
        if($lang != '*'){
            $lang_where = " AND language='$lang' ";
        }
        $query = "SELECT lid FROM #__os_cck_layout WHERE fk_eid = '" . $fk_eid . "' AND type = '" . $type . "' AND published='1'  AND approved='1' " . $lang_where;
        $this->_db->setQuery($query);
        $result = $this->_db->loadResult();
        
        return $result;
    }

    function getDefaultField($fk_eid, $type)
    {   
        $query = "SELECT db_field_name FROM #__os_cck_entity_field WHERE fk_eid = '" . $fk_eid . "' AND field_type = '" . $type . "' AND  published='1'";
        $this->_db->setQuery($query);
        $result = $this->_db->loadResult();
        return $result;
    }

    function getDefaultLayoutCheck($lid, $type, $fk_eid)
    {   
        $query = "SELECT lid FROM #__os_cck_layout WHERE  fk_eid = '" . $fk_eid . "' AND  lid != '" . $lid . "' AND type = '" . $type . "' AND approved = '1' AND published='1'";
        $this->_db->setQuery($query);
        $result = $this->_db->loadResult();
        return $result;
    }
    
    function getEntityName($fk_eid)
    {   
        $query = "SELECT e.`name` FROM `#__os_cck_entity` e WHERE e.`eid` = $fk_eid";
        $this->_db->setQuery($query);
        $result = $this->_db->loadResult();
        return $result;
    }

    function getLayoutHtml($bootstrap_version){ 
      global $app;
      
//        $query = "SELECT layout_html FROM #__os_cck_layout as c "
//            ."\n LEFT JOIN #__os_cck_layout_html as ch ON c.lid = ch.fk_lid"
//            ."\n WHERE c.lid=$this->lid"
//            ."\n AND c.published = '1' AND bootstrap = '".$bootstrap_version."'";
        $query = "SELECT layout_html FROM #__os_cck_layout as c "
            ."\n LEFT JOIN #__os_cck_layout_html as ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid=$this->lid"
            ."\n AND c.published = '1' AND bootstrap = '3'";


        $this->_db->setQuery($query);
        try {
            $result = $this->_db->loadResult();
        }catch (Exception $e){
            echo $aaa;
            echo $query; exit;
        }

        if(!isset($result) || empty($result)){
          $query = "SELECT type,title FROM #__os_cck_layout as c"
            ."\n WHERE c.lid=$this->lid";

          $this->_db->setQuery($query);
          $result = $this->_db->loadAssoc();
          
          if($result['type'] == 'calendar') return;

          
          $app->enqueueMessage($result['title']. ' ' .cck_lang_text("COM_OS_CCK_ERROR_EMPTY_LAYOUT"), 'notice');
          return;
        }else{
            
          return $result;
        }
    }
    
    function getLayoutListLang($lang){
        $query = "SELECT lid, title FROM #__os_cck_layout WHERE language='$lang' AND fk_eid='$this->fk_eid' AND type='$this->type'";
        $this->_db->setQuery($query);
        $result = $this->_db->loadObjectList();
        return $result;
    }
    
    function getLayoutViews($entityInstance, $fields_list, $layout_html, $layout_params, $hover_animated, $option, $child_entities, $moduleId, $Itemid, $recursive_count, $recursive=0, $category=null){
        global $entities_type, $doc, $os_cck_configuration, $db, $entityFieldLists, $app, $layouts_type, $user_profile_form;

      $db = new os_cckDb();
      $hover_item = 0;
      $layout = $this;
      $jinput = $app->input;
      $eiid = $entityInstance->eiid;
      
      ?>
      <script type="text/javascript">
        
        function order_field_submitbutton(moduleId){
          if (moduleId) {
            var form = document.getElementById('orderForm_cckmod_'+moduleId);
          }else{
            var form = document.orderForm;
          }
          form.submit();
        }

        function allreordering(moduleId){ 
          if (moduleId) { 
              if(document.getElementById('order_direction_cckmod_'+moduleId).value == 'ASC'){
                document.getElementById('order_direction_cckmod_'+moduleId).value = 'DESC';
              }else{
                document.getElementById('order_direction_cckmod_'+moduleId).value = 'ASC';
              }
              var form = document.getElementById('orderForm_cckmod_'+moduleId);
          }else{ 
              if(document.orderForm.order_direction.value == 'ASC'){
                document.orderForm.order_direction.value = 'DESC';
              }else{
                document.orderForm.order_direction.value = 'ASC';
              }
              var form = document.orderForm;
          }

          form.submit();
        }
  </script>
  <?php
      // var_dump($eiid);
      if($entities_type[$entityInstance->fk_eid] == 'joomla_user'){
          $user = JFactory::getUser($entityInstance->eiid);
//          $dispatcher = JDispatcher::getInstance();
          JPluginHelper::importPlugin('user');
          JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
          $user_profile_form = JForm::getInstance('com_users.user', 'profile');
          $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array('com_users.user', $user));
          $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $user));
          $user_profile_form->bind($user);
          //$user_profile = JUserHelper::getProfile($user->id);
      }
      if(!class_exists('Instance')){
          require_once JPATH_SITE . '/components/com_os_cck/php/instance.php';
      }
//      Instance
      $field_from_params = $layout_params['fields'];
      $show_add_to_cart_button = false;
      
      foreach($fields_list as $i => $field){
          //var_dump($i); var_dump($fields_list[$i]);
        $html = '';
        $field = $fields_list[$i]; 
        
        $field_styling = get_field_styles($field, $layout);
        $params_field = isset($field_from_params['Params_'.$field->db_field_name]) ? $field_from_params['Params_'.$field->db_field_name] : '';
        $params_field = json_decode($params_field);
        
        if(isset($params_field->hoverAnimated) && $params_field->hoverAnimated){
//            var_dump($hover_animated); exit;
            $hover_animated[$hover_item][] = ($params_field->hoverAnimated);
            $hover_animated[$hover_item][] = ($field->db_field_name);
            $hover_item++;
        }
        
        $hover_border_collor = (isset($params_field->hover_border_collor)) ? $params_field->hover_border_collor : '';
        $hover_background_color = (isset($params_field->hover_background_collor)) ? $params_field->hover_background_collor : '';
        $hover_text_color = (isset($params_field->hover_text_collor)) ? $params_field->hover_text_collor : '';
        
        if($hover_border_collor != '' || $hover_background_color != ''
                                      || $hover_text_color != ''){
            ?>
      <style type="text/css"> .<?php echo $field->db_field_name; ?>:hover{
            color: <?php echo $hover_text_color ?> !important;
            border-color: <?php echo $hover_border_collor ?> !important;
            background-color: <?php echo $hover_background_color ?> !important;

        }
        </style>
        <?php } 

        
        $layout_params['field_styling'] = $field_styling;
        $custom_class = get_field_custom_class($field, $layout);
        $offset_animation = get_field_offset_animation($field, $layout);
        $shell_tag = isset($layout_params['fields']['field_tag_'.$field->db_field_name])?$layout_params['fields']['field_tag_'.$field->db_field_name]:'div';
        
        require getSiteUniqueFiledViewPath('com_os_cck', 'custom_code');
        //start render custom code
//         if(count($layout_params['custom_fields'])){
//           foreach ($layout_params['custom_fields'] as $cust_key => $custom_field) {
//             if(strpos($layout_html,"{|f-custom_code_field_".$cust_key."|}")){
//               // var_dump($custom_field);
//               if(isset($custom_field['access_custom_code_field_'.$cust_key])
//                   && $custom_field['access_custom_code_field_'.$cust_key] != '1'){
//                 $user = JFactory::getUser();
//                 if(!checkAccess_cck($custom_field['access_custom_code_field_'.$cust_key], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
//                   $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", '', $layout_html);
//                   continue;
//                 }
//               }
// //              $dispatcher = JDispatcher::getInstance();


//               JPluginHelper::importPlugin('content');
//               $plug_row = new stdClass();
//               $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
//               preg_match_all('#\{loadmoduleid [0-9]*\}#', $plug_row->text, $matches);
//               foreach($matches as $res){
//                 foreach($res as $str){
                  
//                   $moduleId = str_replace('{loadmoduleid ', '', $str);
//                   $moduleId = str_replace('}', '', $moduleId);

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

//                   if (! $mod_row->load ( $moduleId )) {

//                     throw new Exception($mod_row->getError (), 500);
//                   }

//                   $module = JModuleHelper::getModule($mod_row->module,$mod_row->title);
//                   $options  = array('style' => 'xhtml');
//                   $mod_html = JModuleHelper::renderModule($module,$options);

//                   $plug_row->text = str_replace($str, $mod_html, $plug_row->text);

//                 }
//               }
//               // var_dump($matches);
//               // JFactory::getApplication()->triggerEvent('onContentPrepare', array('com_os_cck', &$plug_row, &$plug_params, 0));
//               $plug_row->text = str_replace("{|this_entity_filesfolder|}", JURI::root() . 'components/com_os_cck/files/entity_files_'.$layout->fk_eid.'', $plug_row->text);
//               $plug_row->text = str_replace("{|cck_images_folder|}", JURI::root() . 'images/os-cck/', $plug_row->text);
//               $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = $plug_row->text;
              
//               //if below fn works , that this is add_instance view
//               $code_type = $custom_field['custom_code_field_'.$cust_key.'_custom_code_type'];
//               if($code_type == 'SCRIPT'){
//                 $custom_code = '<script type="text/javascript">';
//                 $custom_code .= $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
//                 $custom_code .= '</script>';
//                 $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_code, $layout_html);
//               }elseif($code_type == 'PHP'){
//                   //replace mask like {|decimal_textfield_31|}
//                   //var_dump($child_entities);
//                 $func_result = replaceMaskCustomCodePHP($entityInstance,$plug_row->text, $layout_params, $layout_html, $layout, $child_entities);
//                 // var_dump($func_result);
//                 //get custom field content
//                 //var_dump($func_result); exit;
//                 //$custom_field['custom_code_field_'.$cust_key.'_custom_code'] = isset($func_result['custom_code_str']) ? $func_result['custom_code_str'] : '';
//                 $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = $func_result['custom_code_str'];
//                 //get variables for custom code
//                 //if(isset($func_result['variables_arr'])){
// //                var_dump($func_result);
//                     extract($func_result['variables_arr']);
                    
//                 //}
//                 // var_dump($custom_field['custom_code_field_'.$cust_key.'_custom_code']); exit;
//                 ob_start();
//                 $custom_code = eval($custom_field['custom_code_field_'.$cust_key.'_custom_code']);
//                 $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", ob_get_contents(), $layout_html);
//                 ob_end_clean();
//               }elseif($code_type == 'CSS'){
//                 $custom_css = '<style>'.$custom_field['custom_code_field_'.$cust_key.'_custom_code'].'</style>';
//                 $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_css, $layout_html);
//               }else{
//                 $func_result = addChildSelectToCustomCode($entityInstance,$plug_row->text, $layout_params, $layout_html, $layout);
//                 $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = $func_result['custom_code_str'];
//                 $custom_code = $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
//                 $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_code, $layout_html);
//               }
//             }
//           }
//         }
        //end render custom 

//        echo '3333333333333333333'; exit;
        if(strpos($layout_html,"{|f-".$field->fid."|}")){
            
          if($field->field_type == 'captcha_field'){
                $layout_html = str_replace("{|f-".$field->fid."|}", '', $layout_html);
                continue;
            } 
           $php_if = isset($layout_params['fields'][$field->db_field_name.'_php_show']) ? $layout_params['fields'][$field->db_field_name.'_php_show'] : '';
           $php_result = true;
           if($php_if != ''){
                $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
                
           }
           
          if($php_result){
            if($field->field_type == 'categoryfield'){
              // echo '111111111111';
              $field->sorting = (isset($layout_params['fields']['categories_sort_'.$field->db_field_name])) ? $layout_params['fields']['categories_sort_'.$field->db_field_name] : 'ordering';
            } 
          if($entities_type[$entityInstance->fk_eid] == 'os_cck_entity' || $entities_type[$entityInstance->fk_eid] == 'custom_sql'){
              $value = $entityInstance->getFieldValue($field, $entities_type[$entityInstance->fk_eid]);
          }elseif($entities_type[$entityInstance->fk_eid] == 'joomla_user'){
            $value = $entityInstance->getFieldValue($field, 'joomla_user', $user_profile_form, $user);
          }

          
          if($field->field_type == 'rating_field' && isset($layout_params['fields'][$field->db_field_name.'_average'])
              && $layout_params['fields'][$field->db_field_name.'_average'] == 'on'){
              $value = get_average_rating($field, $layout, $entityInstance);
              
              if(isset($layout_params['fields']['display_'.$field->db_field_name]) && $layout_params['fields']['display_'.$field->db_field_name] == 'stars'){
                  $value[0]->data = round($value[0]->data) / 2;
              }elseif(isset($layout_params['fields']['display_'.$field->db_field_name]) && $layout_params['fields']['display_'.$field->db_field_name] == 'nuber'){
                  $value[0]->data = round($value[0]->data, 1);
              }else{
                  $value[0]->data = round($value[0]->data) / 2;
              }
            
            
          }
          
          if(isset($layout_params['fields'][$field->db_field_name]['options']['strlen']) &&
            $layout_params['fields'][$field->db_field_name]['options']['strlen'])
          {
            $field->len = $layout_params['fields'][$field->db_field_name]['options']['strlen'];
          }
//          var_dump($value);
//          var_dump($entityInstance);
          if(isset($value[0]) && isset($field->len) && $value[0]->data && strlen($value[0]->data) > $field->len)
          {
              $value[0]->data = substr($value[0]->data,0,$field->len);
          }
             
          if(isset($layout_params['fields'][$field->db_field_name.'_published'])){
            $field->published = true;
          }else{
            $field->published = false;
          }
          
          if($field->field_type == 'datetime_popup' && isset($value[0]) && $value[0]->data == '0000-00-00 00:00:00'){
              $datetimevalue = false;
          }else{
              $datetimevalue = true;
          }
//          var_dump($field->fid);
          
          if(empty($value) || !$field->published || !$datetimevalue || ($field->field_type=='imagefield' && $value[0]->data == '' && $layout_params['fields'][$field->db_field_name . '_def_img'] == '')){
            $layout_html = str_replace("{|f-".$field->fid."|}", '', $layout_html);
            continue;
          }
          
          if(isset($layout_params['fields']['access_'.$field->db_field_name])
              && $layout_params['fields']['access_'.$field->db_field_name] != '1'){
            $user = JFactory::getUser();
            
            if(!checkAccess_cck($layout_params['fields']['access_'.$field->db_field_name], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
                
              $layout_html = str_replace("{|f-".$field->fid."|}", $html, $layout_html);
              continue;
            }
          }
          
          if(isset($layout_params['fields'][$field->db_field_name]['options'])){
            $field->options = $layout_params['fields'][$field->db_field_name]['options'];
          }
//if($field->field_type == 'decimal_textfield'){
//            var_dump($value);
//        }
          $title = getInstanceTitle($entityInstance);
          
          if(!$title){
              $title = $entityInstance->eiid;
            
          }
          $layout_params['title'] = $title;
//          if(isset($layout_params['fields'][$field->db_field_name.'_title_field']) 
//              && $layout_params['fields'][$field->db_field_name.'_title_field']){
//            if(isset($value[0]->data) && !empty($value[0]->data))$title = $value[0]->data;
//            else 
//            $title = $entityInstance->eiid;
//            $layout_params['title'] = $title;
//          } 
          
          $image_css = ($field->field_type=='imagefield' && isset($field->options['width'])
                        && isset($field->options['height']) && $value[0]->data != '')?
                        'width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;':
                        '';
          if($field->field_type=='imagefield'){
              
              $width_heigth = (isset($field->options['width']) && $value[0]->data != '') ? ' width="' . $field->options['width'] . 'px" ' : '';
              $width_heigth .= (isset($field->options['height']) && $value[0]->data != '') ? ' height="' . $field->options['height'] . 'px" ' : '';
          } else{
              $width_heigth = (isset($field->options['width'])) ? ' width="' . $field->options['width'] . 'px" ' : '';
              $width_heigth .= (isset($field->options['height'])) ? ' height="' . $field->options['height'] . 'px" ' : '';
          }
          
          //$field_styling = substr_replace($field_styling, ' display:block;'.$image_css.'"', strlen($field_styling)-1, strlen($field_styling));
          if($field->field_type == 'text_single_checkbox_onoff' && $value[0]->data == 0){
              
          }else{
            $field_styling = substr_replace($field_styling, ' display:block;"', strlen($field_styling)-1, strlen($field_styling));
          }
          $a_styling = $field_styling;

          //for calendar schedule view
          if(isset($category_params['calendar_layout_params']['fields']['calendar_view_calendar_table'])
            && $category_params['calendar_layout_params']['fields']['calendar_view_calendar_table'] == 'schedule'){

            $layout_params['views']['link_field'] = 
                      (isset($category_params['calendar_layout_params']['fields']['calendar_table_link_field'])) ? 
                      $category_params['calendar_layout_params']['fields']['calendar_table_link_field'] : 
                      array();
          }
          if($field->field_type == 'text_select_list') $shell_tag = 'span';
          $hidden_class = '';
          
          
          if(stripos($field->field_type, 'pricefield_number') === 0 && property_exists($value[0], 'price_value') && $value[0]->price_value == '0.00'){
              $layout_html = str_replace("{|f-".$field->fid."|}", '', $layout_html);
              continue;
          }

      
          if(!isset($value[0]->data) || $value[0]->data == '' || $value[0]->data == '[]' || $value[0]->data == '[""]' || $value[0]->data == '""'){
              if(($field->field_type == 'categoryfield' && $value[0]->catid != '') 
                      || $field->field_type == 'locationfield' 
                      || ($field->field_type == 'videofield' && isset($value[0][0]) && $value[0][0]->id != '')
                      || stripos($field->field_type, 'pricefield') === 0
                      || ($field->field_type == 'text_textfield' && isset($layout_params['fields'][$field->db_field_name.'_default_text']) && $layout_params['fields'][$field->db_field_name.'_default_text'] != '')
                      || ($field->field_type == 'galleryfield' && isset($layout_params['fields'][$field->db_field_name.'_def_img']) && $layout_params['fields'][$field->db_field_name.'_def_img'] != '')){
                  
              }else{
                  $hidden_class = ' hidden_field ';
              }
          }
          
//          var_dump($field->db_field_name);
//          var_dump($layout_params['fields'][$field->db_field_name . '_instance_layout']);
              if((isset($layout_params['fields'][$field->db_field_name . '_instance_layout'])
                    && $layout_params['fields'][$field->db_field_name . '_instance_layout'] != '-1') || $hidden_class != ''){
                  $html_field_stiling = '';
              }else{
                  $html_field_stiling = $field_styling;
              }
          $html .='<'.$shell_tag.$width_heigth.' '.$html_field_stiling.' class="col_box '.$custom_class. $hidden_class .' ' .$field->db_field_name . '"' . $offset_animation . '>';
//                if(isset($layout_params['views']['link_field'])
//                    && (array_search ( $field->fid , $layout_params['views']['link_field']) > 0
//                    || array_search ( $field->fid , $layout_params['views']['link_field']) === 0)){
//                    var_dump($layout_params['views']['instance_layout']);
          
                if(isset($layout_params['fields'][$field->db_field_name . '_instance_layout'])
                    && $layout_params['fields'][$field->db_field_name . '_instance_layout'] != '-1'){
                    
                  $modId = ($moduleId) ? '&moduleId=' . $moduleId : ''; 
                  $redirect_type = (isset($layout_params['fields']['redirect_type_'.$field->db_field_name])) ? $layout_params['fields']['redirect_type_'.$field->db_field_name] : 'redirect';
                  $target = ($redirect_type == 'redirect_blank') ? 'target="_blank"' : '';
                  if($entities_type[$entityInstance->fk_eid] == 'joomla_user' && $layout_params['fields'][$field->db_field_name . '_instance_layout'] == 'sms'){
                      $link =  "index.php?option=com_simplemembership&Itemid=$Itemid&task=showUsersProfile&userId=".$entityInstance->eiid;
                  }else{
                      
                      $layout_for_link_type = $layouts_type[$layout_params['fields'][$field->db_field_name . '_instance_layout']];

                      $cat_id = (isset($category->cid))?'&amp;catid='.$category->cid : '&amp;catid=0';
                      $link = 'index.php?option=com_os_cck&amp;view='.$layout_for_link_type.'&amp;eiid[]='
                      . $entityInstance->eiid .'&amp;lid='.$layout_params['fields'][$field->db_field_name . '_instance_layout']
                      . $cat_id . '&amp;Itemid=' . $Itemid . $modId;
                  }
                  
                  
                    if($redirect_type == 'popUp'){

                        ob_start();
                        $html .= "<a href='#' $field_styling data-toggle='os_cck_modal' data-target='#show_request_layout_" . $layout_params['fields'][$field->db_field_name . '_instance_layout'] . "_".$entityInstance->eiid."'>";
                        require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                        $html .= ob_get_contents();
                        $html.="</a>";
                        ob_end_clean();
                        $html .= '<div class="fade os_cck_modal" id="show_request_layout_' . $layout_params['fields'][$field->db_field_name . '_instance_layout'] . '_' . $entityInstance->eiid . '" tabindex="-1" role="dialog" aria-hidden="true">
                          <div class="os_cck_modal-dialog os_cck_modal-dialog-centered" role="document">
                            <div class="os_cck_modal-content">
                              <div class="os_cck_modal-header">
                                <button type="button" class="close" data-dismiss="os_cck_modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>
                              <div class="os_cck_modal-body">';
                        $instancies = array();
                        $instancies[$entityInstance->eiid] = $entityInstance;
                        ob_start();
                        Category::show_attached_layout($option, $layout_params['fields'][$field->db_field_name . '_instance_layout'], $entityInstance->eiid, $layout_params, 0, '', 0, $instancies, '', $recursive_count);
                        $html .= ob_get_contents();
                        $html .= '</div>
                                          
                                        </div>
                                      </div>
                                    </div>';
                        ob_end_clean();
                        
                    }else{
                        ob_start();
//                        var_dump($link);
                        $html .= "<a href='".JRoute::_($link)."' ".$target." $field_styling>";
//                        if($field->fid != 1484 && $field->fid != 1485 && $field->fid != 1486){
//            var_dump($field); exit;
//          }
                        require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                        
                        $html .= ob_get_contents();
                        $html.="</a>";
                        ob_end_clean();

                        if($redirect_type == 'hover'){
                            $html .= '<ul class="os_cck_hover_child">';
                            $instancies = array();
                            $instancies[$entityInstance->eiid] = $entityInstance;
                            ob_start();
                            
                            try {
                                Category::show_attached_layout($option, $layout_params['fields'][$field->db_field_name . '_instance_layout'], $entityInstance->eiid, $layout_params, 0, '', 0, $instancies, '', $recursive_count);
                            } catch (Exception $ex) {
                                var_dump($field);
                                echo $ex->getMessage();
                            }
                            
                            $html .= ob_get_contents();
                            $html .= '</ul>';
                            ob_end_clean();
                        }
                    }
                  
                }else{
                    
                  $layout_params['instance_currency'] = $entityInstance->instance_currency;
                  ob_start();
                  
                  try {
                        require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                    } catch (Exception $ex) {
                        echo "Exception in layout show: ";
                        var_dump($field);
                        echo $ex->getMessage();
                    }
                    
                    $html .= ob_get_contents();
                  ob_end_clean();
                }


            $html .='</'.$shell_tag.'>';
//          $html .='<span>';
          }
        }
          
        $layout_html = str_replace('data-label-styling', 'style',  $layout_html);
        $layout_html = str_replace("{|f-".$field->fid."|}", $html, $layout_html);
//          if($field->fid != 1484 && $field->fid != 1485 && $field->fid != 1486){
//            var_dump($field); exit;
//          }
        
      }
      
      
      $hover_animated = json_encode($hover_animated);
      
      if(isset($layout_params['calculated_price_fields']) && count($layout_params['calculated_price_fields'])){
          foreach($layout_params['calculated_price_fields'] as $key=>$val){
            $field = new stdClass();
            $field->db_field_name = 'cck_calculated_price_' . $key;
              $field_styling = get_field_styles($field, $layout);

              $custom_class = get_field_custom_class($field, $layout);
              $offset_animation = get_field_offset_animation($field, $layout);
              $div_styling = get_align_styles($field, $layout);
              $calculated_price_html ='<div '.$field_styling.' class="col_box '.$custom_class. ' ' .$field->db_field_name . '"' . $offset_animation . '>';
//            $calculated_price_html = '';
            ob_start();
            require getSiteUniqueFiledViewPath('com_os_cck', 'calculated_price');
            $calculated_price_html .= ob_get_contents();
            $calculated_price_html .= "</div>";
            
            ob_end_clean();
            $layout_html = str_replace("{|f-cck_calculated_price_$key|}", $calculated_price_html, $layout_html);
          }
      }

      if(isset($layout_params['action_button_fields']) && count($layout_params['action_button_fields'])){
        foreach($layout_params['action_button_fields'] as $key=>$val){
//            var_dump($key);
          $field = new stdClass();
          $field->db_field_name = 'cck_action_button_' . $key;
          // var_dump($layout_params['fields']['access_'.$field->db_field_name]);
          if(isset($layout_params['fields']['access_'.$field->db_field_name])
              && $layout_params['fields']['access_'.$field->db_field_name] != '1'){
            $user = JFactory::getUser();
            // var_dump($user);
            if(!checkAccess_cck($layout_params['fields']['access_'.$field->db_field_name], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
              $layout_html = str_replace("{|f-cck_action_button_$key|}", '', $layout_html);
              // continue;
            }
          }

          ob_start();
          require getSiteUniqueFiledViewPath('com_os_cck', 'action_button');
          $action_button_html = ob_get_contents();
          ob_end_clean();

          $layout_html = str_replace("{|f-cck_action_button_$key|}", $action_button_html, $layout_html);
        }
      }

      // var_dump($layout_params['views']['show_request_layout']);
      // var_dump($layout_params['views']['show_request_layout']);
      if(isset($layout_params['views']['show_request_layout'])){
          
          foreach ($layout_params['views']['show_request_layout'] as $key => $value) {
               $php_if = isset($layout_params['views']['request_layout_php_show'][$key][0]) ? $layout_params['views']['request_layout_php_show'][$key][0] : '';
              
               $php_result = true;
               if($php_if != ''){
                    $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
               }
               if($php_result){
                  if(isset($layout_params['views']['show_type_request_layout'][$key][0])){
                    $show_type = $layout_params['views']['show_type_request_layout'][$key][0];
                  }else{
                    $show_type = 1;
                  }
                  $field = new stdClass();
                  $field->db_field_name = "l".$key;
                  $field_styling = get_field_styles($field, $layout);
                  $custom_class = get_field_custom_class($field, $layout);
                  $offset_animation = get_field_offset_animation($field, $layout);
                  $div_styling = get_align_styles($field, $layout);
                  $button_style = array('field_styling'=>$field_styling,'custom_class'=>$custom_class,'offset_animation'=>$offset_animation,'div_styling'=>$div_styling);
                  
                  $button_name = isset($layout_params['views']['show_request_layout_button_name'][$key])?$layout_params['views']['show_request_layout_button_name'][$key][0]:'';
                  if(strpos($layout_html,"{|l-".$key."|}")){
                    $field = new stdClass();
                    $field->db_field_name = $key;
                    if(isset($layout_params['views']['show_request_layout_name'][$key]) &&
                        isset($layout_params['views']['show_request_layout_name'][$key][0]) &&
                        $layout_params['views']['show_request_layout_name'][$key][0] == 'on'){
                      $layout_html = str_replace($key.'-label-hidden', '', $layout_html);
                    }

                    //var_dump($div_styling);
                    $custom_class = get_field_custom_class($field, $layout);
                    //if below fn works , that this is add_instance view
                    $layout_params['title'] = isset($layout_params['title'])?$layout_params['title']:'';
                    
                    ob_start();
                    //echo '<div class="'.$custom_class.'" ' . $offset_animation . ' ' .$div_styling.'>';
                    echo '<div class="'.$custom_class.'" ' . $offset_animation . '>';
                    Instance::show_request_layout($option, $key, $entityInstance->eiid, $show_type,$button_name , isset($layout_params['has_price']) ? $layout_params['has_price'] : '',$layout_params['title'], $button_style, $layout_params);
                    echo '</div>';  
                    $user = JFactory::getUser();
                    if( $value != '1' && !checkAccess_cck($value, $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
                        $layout_html = str_replace("{|l-".$key."|}", '', $layout_html);
                    } else {
                        $layout_html = str_replace("{|l-".$key."|}", ob_get_contents(), $layout_html);
                    }

                    ob_end_clean();
                  }
                }else{
                    $layout_html = str_replace("{|l-".$key."|}", '', $layout_html);
                }
           }
      }
      
      

      
      if(isset($layout_params['attachedModule'])){
        
        foreach ($layout_params['attachedModule'] as $attachedModule) {
          if($attachedModule){
            
            if(strpos($layout_html,"{|m-".$attachedModule->id."|}")){
                $field = new stdClass();
              $field->db_field_name = 'm_'.$attachedModule->id;
              $field_styling = get_field_styles($field, $layout);
              $custom_class = get_field_custom_class($field, $layout);
              $offset_animation = get_field_offset_animation($field, $layout);
              // var_dump($attachedModule);
              $module = JModuleHelper::getModule($attachedModule->type,$attachedModule->title);
              $options  = array('style' => 'xhtml');
              $html = '<div class="'.$custom_class.'" ' . $offset_animation . ' ' .$field_styling.'>'.JModuleHelper::renderModule($module,$options).'</div>';
              $layout_html = str_replace("{|m-".$attachedModule->id."|}", $html, $layout_html);
            }
          }
        }
      }
    
    //  var_dump($child_entities); 
      if(isset($child_entities) && is_array($child_entities) && !empty($child_entities)){
          set_time_limit(0);
          // ini_set('memory_limit', '-1');
//          var_dump($child_entities);
//          var_dump($entityInstance);
          $child_instancies = getChildInstancies($child_entities, $entityInstance); 
        //  var_dump($child_instancies);
//          foreach($layout_params['fields'] as $l => $param_field){
//              if(stripos($l, 'field_tag_') !== false){
//                  var_dump($l);
//                  var_dump($param_field);
//              }
//          }
//              var_dump($layout_params['fields']['field_tag_'.$field->db_field_name]);
            
          foreach($child_instancies['child_istancies'] as $childEntityId => $childInstancies){

          //  var_dump($childEntityId);  
          //  echo '<br>';
          //  var_dump($childInstancies);
          //  echo '<br>';
              
              if(isset($GLOBALS['enteties'][$childEntityId])){
                  $childEntity = $GLOBALS['enteties'][$childEntityId];
              }else{
                  $childEntity = new os_cckEntity($db->_db);
                  $childEntity->load($childEntityId);
                  $GLOBALS['enteties'][$childEntityId] = $childEntity;
              }
              
              foreach($childInstancies as $child_instance_id => $child_instance){
                  
                  $profile_and_custom_field_init = check_profile_and_custom_field_init($child_instancies['child_instancies_fields'][$childEntityId][$child_instance_id]);
                  if($childEntity->type == 'joomla_user'){
                    if(isset($GLOBALS['users'][$child_instance_id])){
                        $user = $GLOBALS['users'][$child_instance_id];
                    }else{
                        $user = JFactory::getUser($child_instance_id);
                        $GLOBALS['users'][$child_instance_id] = $user;
                    }
                  }
                  if(!$profile_and_custom_field_init){
                      $user_profile_form = '';
                  }else{
                    // var_dump($user); exit;
//                      $dispatcher = JDispatcher::getInstance();
                      JPluginHelper::importPlugin('user');
                      JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
                      $user_profile_form = JForm::getInstance('com_users.user', 'profile');
                      if($user->id){
                        $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array('com_users.user', $user));
                        $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $user));
                        $user_profile_form->bind($user);
                      }
                  }
//                  var_dump($child_instancies['child_instancies_fields'][$childEntityId]); exit;
                  foreach($child_instancies['child_instancies_fields'][$childEntityId][$child_instance_id] as $temp_child_entity){
                      
                      if(strpos($layout_html,"{|".$temp_child_entity->data_field_name."|}")){
                          if(!is_object($child_instance) || !property_exists($child_instance, 'eiid') || !$child_instance->eiid) {
                            $layout_html = str_replace("{|".$temp_child_entity->data_field_name."|}", '', $layout_html);
                            continue;
                          }
                          if($childEntity->type == 'os_cck_entity'){

                            $field = clone $entityFieldLists[$temp_child_entity->childEntityId][$temp_child_entity->childEntityFields];
//                            var_dump($field); exit;
                          }elseif($childEntity->type == 'joomla_user'){
                              
                              $field = new os_cckEntityField($db->_db);
                              //var_dump($childEntity);
                              $child_field_list = '';
                              $child_field_list = $entityFieldLists[$childEntity->eid];
                              //var_dump($child_field_list);
                              foreach ($child_field_list as $temp_field){
                                  if($temp_field->db_field_name == 'user_' . $temp_child_entity->childEntityFields){
                                      
                                      $field = clone $temp_field;
                                      //break;
                                  }
                              }
                          }elseif($childEntity->type == 'custom_sql'){
                              $field = new os_cckEntityField($db->_db);
                              $value = '';
                              $child_field_list = '';
                              $child_field_list = $entityFieldLists[$childEntity->eid];
//                              var_dump($temp_child_entity);
                              foreach ($child_field_list as $temp_field){
//                                  var_dump($temp_field);
//                                  var_dump($temp_child_entity); exit;
                                  if($temp_field->db_field_name == 'custom_sql_' . $temp_child_entity->childEntityFields){
                                      
                                      $field = clone $temp_field;
                                      //break;
                                  }
                              }
                              
                              
                          }
                          
                          if(!$field->db_field_name){
                              $layout_html = str_replace("{|".$temp_child_entity->data_field_name."|}", '', $layout_html);
                              continue;
                          }
                          $php_if = isset($layout_params['fields'][$temp_child_entity->data_field_name.'_php_show']) ? $layout_params['fields'][$temp_child_entity->data_field_name.'_php_show'] : '';
                          // var_dump($php_if);
                           $php_result = true;
                           if($php_if != ''){
                                $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
                                
                           }
                           if(!$php_result){
                              $layout_html = str_replace("{|".$temp_child_entity->data_field_name."|}", '', $layout_html);
                              continue;
                          }
//                          var_dump($field);
                          $field_styling = get_field_styles($temp_child_entity->data_field_name, $layout);
                          $offset_animation = get_field_offset_animation($temp_child_entity->data_field_name, $layout);
                          $custom_class = get_field_custom_class($temp_child_entity->data_field_name, $layout);
                          $shell_tag = isset($layout_params['fields']['field_tag_'.$temp_child_entity->data_field_name])?$layout_params['fields']['field_tag_'.$temp_child_entity->data_field_name]:'div';
//                          var_dump($layout_params['fields']['field_tag_'.$field->db_field_name]);
//                          field_tag_owner_standart_name

                          if($entities_type[$child_instance->fk_eid] == 'os_cck_entity'){
                              try {
                                  $value = $child_instance->getFieldValue($field);
                              } catch (Exception $ex) {
                                  var_dump($field);
                              }
                              
                          }elseif($entities_type[$child_instance->fk_eid] == 'joomla_user'){
                            //$user = JFactory::getUser($child_instance->eiid);
                            $value = $child_instance->getFieldValue($field, $entities_type[$child_instance->fk_eid], $user_profile_form, $user);
                            
                          }elseif($entities_type[$child_instance->fk_eid] == 'custom_sql' && $entities_type[$entityInstance->fk_eid] == 'custom_sql'){
//                              var_dump($temp_child_entity); exit;
                              $value = $child_instance->getFieldValue($field, $entities_type[$child_instance->fk_eid], '', '', true, $entityInstance, $temp_child_entity->related_fields);
//                              var_dump($child_instance);
//                              var_dump($value);
                          }elseif($entities_type[$child_instance->fk_eid] == 'custom_sql'){
                              $value = $child_instance->getFieldValue($field, $entities_type[$child_instance->fk_eid]);
                          }
                          
                          $field->db_field_name = $temp_child_entity->data_field_name;
                          
                          $html = '';
                          if($field->field_type == 'rating_field' && isset($layout_params['fields'][$field->db_field_name.'_average'])
                              && $layout_params['fields'][$field->db_field_name.'_average'] == 'on'){
                              $value = get_average_rating($field, $layout, $entityInstance);

                              if(isset($layout_params['fields']['display_'.$field->db_field_name]) && $layout_params['fields']['display_'.$field->db_field_name] == 'stars'){
                                  $value[0]->data = round($value[0]->data) / 2;
                              }elseif(isset($layout_params['fields']['display_'.$field->db_field_name]) && $layout_params['fields']['display_'.$field->db_field_name] == 'nuber'){
                                  $value[0]->data = round($value[0]->data, 1);
                              }else{
                                  $value[0]->data = round($value[0]->data) / 2;
                              }


                          }

                          if(isset($layout_params['fields'][$field->db_field_name]['options']['strlen']) &&
                            $layout_params['fields'][$field->db_field_name]['options']['strlen'])
                          {
                            $field->len = $layout_params['fields'][$field->db_field_name]['options']['strlen'];
                          }
                        //  var_dump($value);
                          if($value != '' && isset($value[0]) && property_exists($value[0], 'data') && $value[0]->data != null && isset($field->len) && strlen($value[0]->data) > $field->len)
                          {
                              $value[0]->data = substr($value[0]->data,0,$field->len);
                          }

                          if(isset($layout_params['fields'][$field->db_field_name.'_published'])){
                              $field->published = true;
                          }else{
                              $field->published = false;
                          }


                          if($field->field_type == 'datetime_popup' && $value[0]->data == '0000-00-00 00:00:00'){
                              $datetimevalue = false;
                          }else{
                              $datetimevalue = true;
                          }
                          //var_dump($value);
                          if(empty($value) || $value == '' || !$field->published || !$datetimevalue){
                            $layout_html = str_replace("{|".$field->db_field_name."|}", '<span class="delete_empty_child_entity"></span>', $layout_html);
                            continue;
                          }
                          if(is_array($value) && !empty($value) && isset($value[0]) && property_exists($value[0], 'data') && $value[0]->data){
                              $layout_html = str_replace("hide-child-entity-alias-".$field->db_field_name, '', $layout_html);
                          }

                          if(isset($layout_params['fields']['access_'.$field->db_field_name])
                              && $layout_params['fields']['access_'.$field->db_field_name] != '1'){
                            $user = JFactory::getUser();
                            if(!checkAccess_cck($layout_params['fields']['access_'.$field->db_field_name], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
                              $layout_html = str_replace("{|".$field->db_field_name."|}", $html, $layout_html);
                              continue;
                            }
                          }

                          if(isset($layout_params['fields'][$field->db_field_name]['options'])){
                            $field->options = $layout_params['fields'][$field->db_field_name]['options'];
                          }
                          $title = getInstanceTitle($entityInstance);
                          if(!$title){
                              $title = $entityInstance->eiid;

                          }
                          $layout_params['title'] = $title;
//                          if(isset($layout_params['fields'][$field->db_field_name.'_title_field']) 
//                              && $layout_params['fields'][$field->db_field_name.'_title_field']){
//                            if(isset($value[0]->data) && !empty($value[0]->data))$title = $value[0]->data;
//                            else $title = $entityInstance->eiid;
//                            $layout_params['title'] = $title;
//                          }

                          $image_css = ($field->field_type=='imagefield' && isset($field->options['width'])
                                        && isset($field->options['height']) && $value[0]->data != '')?
                                        'width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;':
                                        '';
                          if($field->field_type=='imagefield'){
                              $width_heigth = (isset($field->options['width']) && $value[0]->data != '') ? ' width="' . $field->options['width'] . 'px" ' : '';
                              $width_heigth .= (isset($field->options['height']) && $value[0]->data != '') ? ' height="' . $field->options['height'] . 'px" ' : '';
                          } else{
                              $width_heigth = (isset($field->options['width'])) ? ' width="' . $field->options['width'] . 'px" ' : '';
                              $width_heigth .= (isset($field->options['height'])) ? ' height="' . $field->options['height'] . 'px" ' : '';
                          }
                          //$field_styling = substr_replace($field_styling, ' display:block;'.$image_css.'"', strlen($field_styling)-1, strlen($field_styling));
                          if($field->field_type == 'text_single_checkbox_onoff' && $value[0]->data == 0){

                          }else{
                            $field_styling = substr_replace($field_styling, ' display:block;"', strlen($field_styling)-1, strlen($field_styling));
                          }
                          $a_styling = $field_styling;

                          //for calendar schedule view
                          if(isset($category_params['calendar_layout_params']['fields']['calendar_view_calendar_table'])
                            && $category_params['calendar_layout_params']['fields']['calendar_view_calendar_table'] == 'schedule'){

                            $layout_params['views']['link_field'] = 
                                      (isset($category_params['calendar_layout_params']['fields']['calendar_table_link_field'])) ? 
                                      $category_params['calendar_layout_params']['fields']['calendar_table_link_field'] : 
                                      array();
                          }
                          if($field->field_type == 'text_select_list') $shell_tag = 'span';

                          $html .='<'.$shell_tag.$width_heigth.' '.$field_styling.' class="col_box '.$custom_class. ' ' .$field->db_field_name . '"' . $offset_animation . '>';
        //                        if(isset($layout_params['views']['link_field'])
        //                            && (array_search ( $field->fid , $layout_params['views']['link_field']) > 0
        //                            || array_search ( $field->fid , $layout_params['views']['link_field']) === 0)){
                                if(isset($layout_params['fields'][$field->db_field_name . '_instance_layout'])
                                    && $layout_params['fields'][$field->db_field_name . '_instance_layout'] != '-1'){
                                  $modId = ($moduleId) ? '&moduleId=' . $moduleId : '';

                                  $layout_for_link = new os_cckLayout($db->_db);
                                  $layout_for_link->load($layout_params['fields'][$field->db_field_name . '_instance_layout']);
                                  //var_dump($childEntity);
                                  //$cat_id = (isset($category->cid))?'&amp;catid='.$category->cid : '&amp;catid=0';
                                  if($entities_type[$childEntity->eid] == 'joomla_user' && $layout_params['fields'][$field->db_field_name . '_instance_layout'] == 'sms'){
                                      $link = JURI::root()."index.php?option=com_simplemembership&Itemid=$Itemid&task=showUsersProfile&userId=".$child_instance_id;
                                  }else{

                                      $cat_id = (isset($category->cid))?'&amp;catid='.$category->cid : '&amp;catid=0';
                                      $link = JURI::root().'index.php?option=com_os_cck&amp;view='.$layout_for_link->type.'&amp;eiid[]='
                                    . $child_instance_id .'&amp;lid='.$layout_params['fields'][$field->db_field_name . '_instance_layout']
                                    . $cat_id . '&amp;Itemid=' . $Itemid . $modId;
                                  }
//                                  $link = 'index.php?option=com_os_cck&amp;view='.$layout_for_link->type.'&amp;eiid[]='
//                                  . $child_instance_id .'&amp;lid='.$layout_params['fields'][$field->db_field_name . '_instance_layout']
//                                  . $cat_id . '&amp;Itemid=' . $Itemid . $modId;

                                  ob_start();
                                    $html .= "<a href='".JRoute::_($link)."'>";
                                    require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                                    $html .= ob_get_contents();
                                    $html.="</a>";
                                  ob_end_clean();
                                }else{
                                  $layout_params['instance_currency'] = $entityInstance->instance_currency;
                                  ob_start();
                                  
                                    require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                                    $html .= ob_get_contents();
                                  ob_end_clean();
                                }


                          $html .='</'.$shell_tag.'>';
                          
                          $layout_html = str_replace("{|".$temp_child_entity->data_field_name."|}", $html, $layout_html);
                      }

                  }
              }
          }
      }
      
      //send button
      if(strpos($layout_html, "{|f-cck_add_to_cart_button|}") !== FALSE){
          $field = new os_cckEntityField($db->_db);
        $field->db_field_name = 'cck_add_to_cart_button';
        $php_if = isset($layout_params['fields'][$field->db_field_name.'_php_show']) ? $layout_params['fields'][$field->db_field_name.'_php_show'] : '';
       $php_result = true;
       if($php_if != ''){
            $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
       }
       if(!$php_result){
           $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
       }
       $show_without_product = isset($layout_params['fields']['show_without_product_'.$field->db_field_name]) ? $layout_params['fields']['show_without_product_'.$field->db_field_name] : '';
       if($show_without_product == '' && !$show_add_to_cart_button){
            $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
       }
      //  var_dump($show_add_to_cart_button);
        $onclick_event = (isset($layout_params['fields'][$field->db_field_name.'_onclick_event'])) ? $layout_params['fields'][$field->db_field_name.'_onclick_event'] : 0;
        if($onclick_event == 0){
            $onclick_event_value = (isset($layout_params['fields'][$field->db_field_name.'_add_effect'])) ? $layout_params['fields'][$field->db_field_name.'_add_effect'] : '';
        }else{
            $cart_layout = (isset($layout_params['fields'][$field->db_field_name.'_cart_layout'])) ? $layout_params['fields'][$field->db_field_name.'_cart_layout'] : '';
            $link = 'index.php?option=com_os_cck&amp;view=cart&amp;lid='.$cart_layout;
            $onclick_event_value = JRoute::_($link);
        }
        
        $field_styling = get_field_styles($field, $layout);
        $custom_class = get_field_custom_class($field, $layout);
        $offset_animation = get_field_offset_animation($field, $layout);
        $div_styling = get_align_styles($field, $layout);
        ob_start();
        echo '<div '.$div_styling.'>';
          $buttonText = isset($layout_params["views"]["layout_button_text"])
                        && !empty($layout_params["views"]["layout_button_text"])?$layout_params["views"]["layout_button_text"]:cck_lang_text('COM_OS_CCK_BUTTON_FORM_SEND_REQUEST');
          ?>
          <input <?php echo $field_styling; ?> type="button" name="request_button" value="<?php echo $buttonText; ?>"
                       class="button btn-info <?php echo $custom_class; ?>" <?php echo $offset_animation; ?> onclick="javascript:CckAddToCart('<?php echo $entityInstance->eiid; ?>', '<?php echo $onclick_event; ?>', '<?php echo $onclick_event_value; ?>', this, '<?php echo JURI::root(); ?>');">
        <?php
        echo '</div>';
        $layout_html = str_replace("{|f-cck_add_to_cart_button|}", ob_get_contents(), $layout_html);
        ob_end_clean();
      }
        //send button
      
      if(isset($layout_params['fields']['cck_booking_cal_published']) 
              && $layout_params['fields']['cck_booking_cal_published'] 
              && strpos($layout_html, "{|f-cck_booking_cal|}") !== false){
          $field = new os_cckEntityField($db->_db);
          $field->db_field_name = 'cck_booking_cal';
          $php_if = isset($layout_params['fields'][$field->db_field_name.'_php_show']) ? $layout_params['fields'][$field->db_field_name.'_php_show'] : '';
           $php_result = true;
           if($php_if != ''){
                $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
           }
           if(!$php_result){
               $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
           }
           $user = JFactory::getUser();
            if(isset($layout_params['fields']['access_'.$field->db_field_name])
                && $layout_params['fields']['access_'.$field->db_field_name] != '1' 
                && !checkAccess_cck($layout_params['fields']['access_'.$field->db_field_name], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
                $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
            }
            
            //get contents
            $field_styling = get_field_styles($field, $layout);
            $custom_class = get_field_custom_class($field, $layout);
            $offset_animation = get_field_offset_animation($field, $layout);
            $shell_tag = isset($layout_params['fields']['label_tag_'.$field->db_field_name])?$layout_params['fields']['label_tag_'.$field->db_field_name]:'span';
            
            $month = $jinput->get('month_selected', date('n'), 'INT');;
            $year = $jinput->get('year_selected', date('Y'), 'INT');;
            //var_dump($jinput); exit;
            $show_month = $layout_params['fields']['months_'.$field->db_field_name];
            $show_details = $layout_params['fields'][$field->db_field_name.'_show_day_details'];
            //var_dump($layout_params['fields'][$field->db_field_name.'_show_month_year']);
            ob_start();
            echo '<'.$shell_tag .' '. $field_styling.' class="cck_booking_calendar ' . $custom_class . '" lid="'.$layout->lid.'">';
            $calendar = new booking_calendar();
            if($layout_params['fields'][$field->db_field_name.'_show_month_year']){
                $month_year_html = $calendar->getMonthYearSelect($layout_params['fields'][$field->db_field_name.'_initial_year'], $layout_params['fields'][$field->db_field_name.'_final_year']);
                echo $month_year_html;
            }
            $calendar_html = $calendar::getCalendar($month,$year,$entityInstance->eiid,$show_details);
            if(in_array('last', $show_month)) echo $calendar_html->tab1;
            if(in_array('current', $show_month)) echo $calendar_html->tab2;
            if(in_array('next1', $show_month)) echo $calendar_html->tab3;
            if(in_array('next2', $show_month)) echo $calendar_html->tab4;
            
            if($layout_params['fields'][$field->db_field_name.'_show_nav_butt']){
                $nav_buttons_html = $calendar->getNavButtons();
                echo $nav_buttons_html;
            }
            echo '</'.$shell_tag.'>';
            $layout_html = str_replace("{|f-".$field->db_field_name."|}", ob_get_contents(), $layout_html);
            ob_end_clean();
      }
      
      if(isset($layout_params['fields']['cck_cal_import_published']) 
              && $layout_params['fields']['cck_cal_import_published'] 
              && strpos($layout_html, "{|f-cck_cal_import|}") !== false){
        $field = new os_cckEntityField($db->_db);
        $field->db_field_name = 'cck_cal_import';
        $php_if = isset($layout_params['fields'][$field->db_field_name.'_php_show']) ? $layout_params['fields'][$field->db_field_name.'_php_show'] : '';
        $php_result = true;
        if($php_if != ''){
            $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
        }
           
        if($php_result){
          includeJavaScriptCCK('components/com_os_cck/assets/bootstrap/js/bootstrapOS.js');

          $user = JFactory::getUser();
          if(isset($layout_params['fields']['access_'.$field->db_field_name])
              && $layout_params['fields']['access_'.$field->db_field_name] != '1' 
              && !checkAccess_cck($layout_params['fields']['access_'.$field->db_field_name], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
            $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
          }

          //get contents

          //get calendar list
          $calendars_list = $layout_params['fields']['cck_cal_import_calendars_list'];

          //get field names
          $event_title = $layout_params['fields']['cck_cal_import_event_title'];
          $event_date_start = $layout_params['fields']['cck_cal_import_event_date_start'];
          $event_date_end = $layout_params['fields']['cck_cal_import_event_date_end'];
          $event_description = $layout_params['fields']['cck_cal_import_event_description'];
          $event_location = $layout_params['fields']['cck_cal_import_event_location'];
          $event_items_location = $layout_params['fields']['cck_cal_import_event_items_location'];

          //get field values
          $event_title = $entityInstance->getFieldValueCalImport($event_title);
          $event_date_start = $entityInstance->getFieldValueCalImport($event_date_start);
          $event_date_end = $entityInstance->getFieldValueCalImport($event_date_end);
          $event_description = $entityInstance->getFieldValueCalImport($event_description);
          $event_location_db = $entityInstance->getFieldValueCalImport($event_location, true);

          $event_location_string = '';
          if($event_location != '-1' && count($event_items_location) > 0){
            foreach ($event_items_location as $key => $value) {
              if(is_object($event_location_db) && property_exists($event_location_db, $value)){
                  $event_location_string .= $event_location_db->$value;
              }
              if(count($event_items_location)-1 != $key) $event_location_string .= ", ";
            }
          }

          if(is_object($event_title) && property_exists($event_title, 'data')
            && is_object($event_date_start) && property_exists($event_date_start, 'data')
            && is_object($event_date_end) && property_exists($event_date_end, 'data')
            && is_object($event_description) && property_exists($event_description, 'data')){
                $calendarConstruct = new CalendarUrlConstruct($event_title->data, 
                                                              $event_date_start->data,
                                                              $event_date_end->data,
                                                              $event_description->data,
                                                              $event_location_string); 

                $googleUrl = $calendarConstruct->get("Url","Google");
                $yahooUrl = $calendarConstruct->get("Url","Yahoo");
                $icsUrl = $calendarConstruct->get("Url","ICS");

                //get contents
                $field_styling = get_field_styles($field, $layout);
                $custom_class = get_field_custom_class($field, $layout);
                $offset_animation = get_field_offset_animation($field, $layout);
                $shell_tag = isset($layout_params['fields']['label_tag_'.$field->db_field_name])?$layout_params['fields']['label_tag_'.$field->db_field_name]:'span';

                ob_start();
                  echo '<'.$shell_tag .' '. $field_styling.'  >';

                ?>

                  <div class="btn-group <?php echo $custom_class;?>" <?php echo $offset_animation; ?> style="z-index: 999;">
                    <div class="btn dropdown_cck-toggle" align="center" data-toggle="dropdown_cck">
                    <?php echo JHtml::_('image', 'components/com_os_cck/assets/images/cal_icons/addthis_16.png','', array());?> 
                    <?php echo cck_lang_text('COM_OS_CCK_LAYOUT_CALENDAR_IMPORT');?> <span class="caret"></span></div>
                    <ul class="dropdown_cck-menu" >
                    <?php if(in_array('google', $calendars_list)): ?>
                      <li><a href="<?php echo $googleUrl;?>">
                      <?php echo JHtml::_('image', 'components/com_os_cck/assets/images/cal_icons/google_cal-16.png','', array());?> 
                      Google Calendar</a></li>
                    <?php endif;?>
                    <?php if(in_array('ical', $calendars_list)): ?>
                      <li><a href="<?php echo JRoute::_($icsUrl);?>">
                      <?php echo JHtml::_('image', 'components/com_os_cck/assets/images/cal_icons/apple_ical-16.png','', array());?> 
                      ICal Calendar</a></li>
                    <?php endif;?>
                    <?php if(in_array('outlook', $calendars_list)): ?>
                      <li><a href="<?php echo JRoute::_($icsUrl);?>">
                      <?php echo JHtml::_('image', 'components/com_os_cck/assets/images/cal_icons/outlook_cal-16.png','', array());?> 
                      Outlook Calendar</a></li>
                    <?php endif;?>
                    <?php if(in_array('yahoo', $calendars_list)): ?>
                      <li><a href="<?php echo $yahooUrl;?>">
                      <?php echo JHtml::_('image', 'components/com_os_cck/assets/images/cal_icons/yahoo_cal-16.png','', array());?> 
                      Yahoo Calendar</a></li>
                    <?php endif;?>
                    </ul>
                  </div>
              <script type="text/javascript">
                  jQuerOs(document).ready(function(){
                    jQuerOs('[data-field-name=cck_cal_import]').parents('.drop-item').css('z-index', '71999');
                    
                  })

              </script>

              <?php

              echo '</'.$shell_tag.'>';
              $layout_html = str_replace("{|f-".$field->db_field_name."|}", ob_get_contents(), $layout_html);
              ob_end_clean();
          }else{
              $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
          }
        }else{
              $layout_html = str_replace("{|f-".$field->db_field_name."|}", '', $layout_html);
        }
      }
      
      if(isset($layout_params['fields']['cck_pdf_button_published']) 
              && $layout_params['fields']['cck_pdf_button_published'] 
              && strpos($layout_html, "{|f-cck_pdf_button|}") !== false){
            $field = new stdClass();
            $field->db_field_name = 'cck_pdf_button';
             $field_styling = get_field_styles($field, $layout);
            
            $custom_class = get_field_custom_class($field, $layout);
            $offset_animation = get_field_offset_animation($field, $layout);
            $pdf_html = '';
            $pdf_html .='<span '.$field_styling.' class="col_box '.$custom_class. ' ' .$field->db_field_name . '"' . $offset_animation . '>';
            ob_start();
            require getSiteUniqueFiledViewPath('com_os_cck', 'pdf_button');
            $pdf_html .= ob_get_contents();
            ob_end_clean();
            $pdf_html .= '</span>';
            $layout_html = str_replace("{|f-cck_pdf_button|}", $pdf_html, $layout_html);
      }else{
          $layout_html = str_replace("{|f-cck_pdf_button|}", '', $layout_html);
      }
      
      if(isset($layout_params['fields']['cck_number_of_views_published']) 
              && $layout_params['fields']['cck_number_of_views_published'] 
              && strpos($layout_html, "{|f-cck_number_of_views|}") !== false){
          
            $field = new stdClass();
            $field->db_field_name = 'cck_number_of_views';
            $field_styling = get_field_styles($field, $layout);
            
            $custom_class = get_field_custom_class($field, $layout);
            $offset_animation = get_field_offset_animation($field, $layout);
            $shell_tag = isset($layout_params['fields']['label_tag_'.$field->db_field_name])?$layout_params['fields']['label_tag_'.$field->db_field_name]:'span';
            $number_of_views_html = '';
            $number_of_views_html .='<'.$shell_tag.' '.$field_styling.' class="col_box '.$custom_class. ' ' .$field->db_field_name . '"' . $offset_animation . '>';
            ob_start();
            require getSiteUniqueFiledViewPath('com_os_cck', 'number_of_views');
            $number_of_views_html .= ob_get_contents();
            $number_of_views_html .= '</'.$shell_tag.'>';
            ob_end_clean();
            
            $layout_html = str_replace("{|f-cck_number_of_views|}", $number_of_views_html, $layout_html);
      }else{
          $layout_html = str_replace("{|f-cck_number_of_views|}", '', $layout_html);
      }

      if(strpos($layout_html, "{|f-cck_review_pagination|}") !== false){
          // var_dump($GLOBALS['review_pagenav']);
            $field = new stdClass();
            $field->db_field_name = 'cck_review_pagination';
            $field_styling = get_field_styles($field, $layout);

            $pageNav = $GLOBALS['review_pagenav'];
            
            $custom_class = get_field_custom_class($field, $layout);
            $offset_animation = get_field_offset_animation($field, $layout);
            $shell_tag = isset($layout_params['fields']['label_tag_'.$field->db_field_name])?$layout_params['fields']['label_tag_'.$field->db_field_name]:'span';
            $review_pagination_html = '';
            $review_pagination_html .='<'.$shell_tag.' '.$field_styling.' class="col_box '.$custom_class. ' ' .$field->db_field_name . '"' . $offset_animation . '>';
            ob_start();
            echo '<div id="pagination" class="review-pagination">';
            if (!empty($pageNav) && ($pageNav->total > $pageNav->limit)) {
              echo $pageNav->getPagesLinks();
            }
            echo '</div>';
            $review_pagination_html .= ob_get_contents();
            $review_pagination_html .= '</'.$shell_tag.'>';
            ob_end_clean();
            
            $layout_html = str_replace("{|f-cck_review_pagination|}", $review_pagination_html, $layout_html);
      }else{
          $layout_html = str_replace("{|f-cck_review_pagination|}", '', $layout_html);
      }

      if(strpos($layout_html,"{|f-cck_review_order_by|}")){
        //check access
        
        $field = new stdClass();
        $field->db_field_name = 'review_order_by';
        $field_styling = get_field_styles($field, $layout);
        $field_styling = substr_replace($field_styling, ' display:block;"', strlen($field_styling)-1, strlen($field_styling));
        $hover_styling = get_hover_css_style($field, $layout_params);
        echo $hover_styling;
        $custom_class = get_field_custom_class($field, $layout);
        $offset_animation = get_field_offset_animation($field, $layout);
        $shell_tag = 'span';
        
        ob_start();

// var_dump($)
        $reviews = array();
        $reviews[] = 1;
      if(isset($layout_params['fields']['cck_review_order_by_published']) 
          && $layout_params['fields']['cck_review_order_by_published'] == 'on'){
            
            // var_dump($layout_params['views']['sortField']);
            if(count($reviews) > 0 && isset($layout_params['views']['sortField'])
                            && !empty($layout_params['views']['sortField'])
                            && count($layout_params['views']['sortField']) > 1){
                              
            $sort_arr['sortField'] = $layout_params['views']['sortField'];
            $sort_arr['order_direction'] = isset($layout_params['fields']['sortType_cck_review_order_by'])?$layout_params['fields']['sortType_cck_review_order_by']:'ASC';

            
            $selected = (isset($layout_params['views']['selected'])) ? $layout_params['views']['selected'] : '' ;
            session_set_order_data($sort_arr['order_direction'], $selected, $layout->lid);
//            $session = JFactory::getSession();
//            $session->set('order_direction', $sort_arr['order_direction']);
//            $session->set('selected', $selected); 
            
            ?>

            <div id="CckOrderBy<?php echo ($moduleId) ? '_cckmod_'.$moduleId : '' ;?>" class="orderTable <?php echo $custom_class;?> <?php echo $field->db_field_name; ?>" <?php echo $offset_animation; ?> >
                <form class="<?php echo $field->db_field_name; ?>" <?php echo $field_styling;?> id="orderForm<?php echo ($moduleId) ? '_cckmod_'.$moduleId : '' ;?>" method="POST" action="<?php echo JRoute::_($_SERVER["REQUEST_URI"]); ?>" name="orderForm<?php echo ($moduleId) ? '_cckmod_'.$moduleId : '' ;?>">
                    <input type="hidden" id="order_direction<?php echo ($moduleId) ? '_cckmod_'.$moduleId : '' ;?>" name="order_direction" value="<?php echo $sort_arr['order_direction']; ?>" >
                    <a title="Click to sort by this column." onclick="javascript:allreordering(<?php echo ($moduleId) ? $moduleId : 0 ;?>);return false;" href="#">
                        <img alt="" src="<?php echo JURI::root() ?>/components/com_os_cck/images/sort_<?php echo strtolower($sort_arr['order_direction']); ?>.png" />
                    </a>
                    <?php
                    echo cck_lang_text("COM_OS_CCK_LABEL_ORDER_BY"); ?>
                    <select size="1" class="inputbox" onchange="order_field_submitbutton(<?php echo ($moduleId) ? $moduleId : 0 ;?>);" id="order_field" name="order_field">
                    <?php

                    foreach($sort_arr['sortField'] as $key){
                        
                      if(!isset($key['value'])){?>
                        <option  value="ceid" selected="selected">Index</option>
                    <?php
                      }else{ ?>
                        <option  value="<?php echo $key['value'] ?>" <?php if ($selected == $key['value'])echo 'selected="selected"'; ?> >  <?php echo $key['text']; ?> </option>
                        <?php
                      }
                    } ?>
                    </select>
                </form>
            </div>
            <?php
        }//else{
//          JFactory::getApplication()->enqueueMessage(cck_lang_text('COM_OS_CCK_LAYOUT_ORDER_BY_FIELDS_TOOLTIP'), 'notice');
//        }
      }
        $layout_html = str_replace("{|f-cck_review_order_by|}", ob_get_contents(), $layout_html);
        ob_end_clean();

      }

      if(isset($layout_params['fields']['cck_instance_id_published']) 
              && $layout_params['fields']['cck_instance_id_published'] 
              && strpos($layout_html, "{|f-cck_instance_id|}") !== false){
          
            $field = new stdClass();
            $field->db_field_name = 'cck_instance_id';
            $field_styling = get_field_styles($field, $layout);
            
            $custom_class = get_field_custom_class($field, $layout);
            $offset_animation = get_field_offset_animation($field, $layout);
            $shell_tag = isset($layout_params['fields']['label_tag_'.$field->db_field_name])?$layout_params['fields']['label_tag_'.$field->db_field_name]:'span';
            $number_of_views_html = '';
            $number_of_views_html .='<'.$shell_tag.' '.$field_styling.' class="col_box '.$custom_class. ' ' .$field->db_field_name . '"' . $offset_animation . '>';
            ob_start();
            require getSiteUniqueFiledViewPath('com_os_cck', 'instance_id');
            $number_of_views_html .= ob_get_contents();
            $number_of_views_html .= '</'.$shell_tag.'>';
            ob_end_clean();
            
            $layout_html = str_replace("{|f-cck_instance_id|}", $number_of_views_html, $layout_html);
      }else{
          $layout_html = str_replace("{|f-cck_instance_id|}", '', $layout_html);
      }


        if (version_compare(JVERSION, "4.0.0", "ge")) {
          if ($app->isClient('site')){
            $check = true;
          }else{
            $check = false;
          }
        }else{
          if ($app->isSite()){
            $check = true;
          }else{
            $check = false;
          }
        }
       if($check && isset($layout_params['fields']['cck_instance_navigation_published']) 
        && $layout_params['fields']['cck_instance_navigation_published']){
           //echo '11111111111111111111111';
           $field = new stdClass();
           $field->db_field_name = 'cck_instance_navigation';
           $db_field_name = 'cck_instance_navigation';
           $php_if = isset($layout_params['fields'][$db_field_name.'_php_show']) ? $layout_params['fields'][$db_field_name.'_php_show'] : '';
           $php_result = true;
           if($php_if != ''){
                $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
           }
           
          if($php_result){
        //access
        
            $user = JFactory::getUser();
            
            if(isset($layout_params['fields']['access_cck_instance_navigation'])
                  && $layout_params['fields']['access_cck_instance_navigation'] != '1' 
                  && !checkAccess_cck($layout_params['fields']['access_cck_instance_navigation'], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
                
              $layout_html = str_replace("{|f-cck_instance_navigation|}", '', $layout_html);
            }
            
            $modId = ($moduleId) ? '&moduleId=' . $moduleId : '';
            if( strpos( "&moduleId", $Itemid) != false ) $modId = "";
            $catId = isset($category->cid)?'&amp;catid='.$category->cid:'';
            $link = 'index.php?option=com_os_cck&amp;view=instance&amp;lid='.$layout->lid. $catId. '&amp;Itemid=' . $Itemid . $modId;
//            var_dump($link);
            $prevInstId = (isset($layout_params['prevInstId'])) ? $layout_params['prevInstId'] : 0;
            $nextInstId = (isset($layout_params['nextInstId'])) ? $layout_params['nextInstId'] : 0;
            $prev = '&amp;eiid[0]='.$prevInstId;
            $next = '&amp;eiid[0]='.$nextInstId;
            $custom_class = get_field_custom_class($field, $layout);
            $shell_tag = isset($layout_params['fields']['label_tag_'.$field->db_field_name])?$layout_params['fields']['label_tag_'.$field->db_field_name]:'span';
            $field_styling = get_field_styles($field, $layout);

            ob_start();
            ?>
            <div id="os_navigation" class="<?php echo $custom_class; ?>">
              <?php
              if($layout_params['prevInstId']){
                ?>
                <<?php echo $shell_tag; ?> class="os_navigation_prev">
                  <a <?php echo $field_styling?> href="<?php echo $link.$prev;?>">
                      Prev
                  </a>
                </<?php echo $shell_tag; ?>>
                <?php
              }
              if($layout_params['nextInstId']){
                ?>
                <<?php echo $shell_tag; ?> class="os_navigation_next">
                  <a <?php echo $field_styling?> href="<?php echo $link.$next?>">
                      Next
                  </a>
                </<?php echo $shell_tag; ?>>
                <?php
              } ?>
            </div>
            <?php
            $html = ob_get_contents();
            
            ob_end_clean();

              $layout_html = str_replace("{|f-cck_instance_navigation|}", $html, $layout_html);
          }else{
              $layout_html = str_replace("{|f-cck_instance_navigation|}", $html, $layout_html);
          }
          
        }else{
            $layout_html = str_replace("{|f-cck_instance_navigation|}", '', $layout_html);
        }
        
        return $layout_html;
    }
    
    public function store($updateNulls = false){
        if(!parent::store()){
            var_dump($this->getError()); exit;
            echo $this->getError();
            return false;
        }else{
            return true;
        }
    }

    public function getEditInstanceLayoutViews($layout, $layout_params, $entityInstance, $option, $robots_option, $unique_form_id = 'adminForm', $Itemid = '', $lang_list = '', $instanse_lang_list = array(), $assoc_list = ''){
      global  $cck_entity_configuration, $os_cck_configuration, $doc, $entityFieldLists;

      require_once(JPATH_ADMINISTRATOR . '/components/com_os_cck/elements/getUserModal.php');
      // var_dump($html_lang_list);
      $access = ($entityInstance->access != '') ? explode(',', $entityInstance->access) : '1';
      $gtree = get_group_children_tree_cck();
//      var_dump($layout);
      $task = protectInjectionWithoutQuote('task', '');
      $field = new stdClass();
        $field->db_field_name = 'form-'.$layout->lid;
        $form_styling = get_field_styles($field, $layout);
        $form_custom_class = get_field_custom_class($field, $layout);
        $form_offset_animation = get_field_offset_animation($field, $layout);
        $form_hover_animation = get_field_hover_animation($field, $layout);
// var_dump($task);
      $is_site = cck_is_site();
      if($is_site){
        $form_action = 'index.php?option='.protectInjectionWithoutQuote('option').'&amp;task=save_instance&amp;Itemid='.$Itemid;
      }else{
        $form_action = 'index.php?option=com_os_cck&task=show_instance';
      }
      // ob_start();
      ?>
      <form action="<?php echo $form_action; ?>" class="<?php echo $form_custom_class; ?>" <?php echo $form_offset_animation; ?> <?php echo $form_hover_animation; ?> <?php echo $form_styling; ?> method="post" name="<?php echo $unique_form_id; ?>" id="<?php echo $unique_form_id; ?>" enctype="multipart/form-data">
      <?php
        $options = Array('active'    => 'panel_1_id');
        
        echo JHtml::_('bootstrap.startTabSet', 'instance-tab', $options);
        //echo JHtml::_('tabs.start', 'instance-tab', $options);
        //echo JHtml::_('tabs.panel', cck_lang_text('COM_OS_CCK_ADMIN_INSTANCE_MAIN'), 'panel_1_id');
        echo JHtml::_('bootstrap.addTab', 'instance-tab', 'panel_1_id', cck_lang_text('COM_OS_CCK_ADMIN_INSTANCE_MAIN'));

        ?>
        <div class="edit_instance cck-body">
      <?php
        if( ( isset($layout_params['layout_type']) && $layout_params['layout_type'] != '' ) && 
          ($task == 'add_instance' || $task == 'new_instance'|| $task == 'edit_instance') ) {
          // var_dump($layout_params['layout_type']);
      ?>
          <div class="row content-row">
            <span>
            <strong><?php echo cck_lang_text('COM_OS_CCK_LABLE_SELECT_TYPE') ?>:</strong></span>
            <span align="left">
              <?php echo $layout_params['layout_type']; ?>
            </span>
          </div>
      <?php
        }else{
            ?>
            <input type="hidden" name="lay_type" value="<?php echo $layout->lid; ?>">
            <?php
        }
        
      $layout_html = urldecode($layout->layout_html);
      $layout_html = str_replace('data-label-styling', 'style',  $layout_html);
      $layout_params['custom_fields'] = unserialize($layout->custom_fields);
      $field_from_params = $layout_params["fields"];
//      var_dump($layout_params);
      $fields_list = $entityFieldLists[$layout->fk_eid];
      $layout_type = $layout->type;
      $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : '';
      //var_dump($layout);
      //add child selects to layout
      $addChildSelectToLayout = addChildSelectToLayout($fields_list, $entityInstance, $layout_params, $layout_html, $layout);
      $layout_html = $addChildSelectToLayout['layout_html'];
      $layout_params = $addChildSelectToLayout['layout_params'];
      $parent = $addChildSelectToLayout['select_parent'];
      $layout->params = serialize($layout_params);
      //add child selects to layout
    // var_dump($entityInstance);

      require getSiteUniqueFiledViewPath('com_os_cck', 'custom_code');
      

      foreach ($fields_list as $i => $f){
    //  for ($i = 0; $i < count($fields_list); $i++){

        $html = '';
        $value = '';
        $field = $fields_list[$i];
        
        

        $field_styling = get_field_styles($field, $layout);
        $custom_class = get_field_custom_class($field, $layout);
        $layout_params['field_styling'] = $field_styling;
        $layout_params['custom_class'] = $custom_class;

        

        //delete inappropriate short cods
//        var_dump($layout_params['mail_fields']);
        if(strpos($layout_html,"{|f-cck_mail|}")){
          $layout_html = str_replace("{|f-cck_mail|}",'', $layout_html);
        }
        if(isset($layout_params['mail_fields'])){
            foreach($layout_params['mail_fields'] as $mail_fields){
                $layout_html = str_replace("{|f-$mail_fields|}",'', $layout_html);
            }
        }
        if(!$is_site && strpos($layout_html,"{|f-cck_send_button|}")){
          $layout_html = str_replace("{|f-cck_send_button|}",'', $layout_html);
        }
        if(!$is_site && isset($layout_params['action_button_fields']) && count($layout_params['action_button_fields'])){
          foreach($layout_params['action_button_fields'] as $act_butt_key => $act_butt_val){
            if(strpos($layout_html,"{|f-cck_action_button_$act_butt_key|}")){
              $layout_html = str_replace("{|f-cck_action_button_$act_butt_key|}",'', $layout_html);
            }
          }
          // var_dump($layout_params['action_button_fields']);
        }
        
        if(!$is_site && $field->field_type == "captcha_field"){
          $layout_html = str_replace("{|f-".$field->fid."|}",'', $layout_html);
          continue;
        }
        //delete inappropriate short cods


        if(strpos($layout_html,"{|f-".$field->fid."|}")){
          $php_if = isset($layout_params['fields'][$field->db_field_name.'_php_show']) ? $layout_params['fields'][$field->db_field_name.'_php_show'] : '';
          $php_result = true;

          if($php_if != ''){
                $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
          }

          if($php_result){
          //get field value
              $value = $entityInstance->getFieldValue($field);

              //get field value for checkbox
              if($field->field_type == 'text_single_checkbox_onoff'){
                  $checkbox_value = $entityInstance->getFieldValue($field);
                  
                  $checkbox_value = isset($checkbox_value[0]->data) ? $checkbox_value[0]->data : '';

              }

              //get field value if this rating field
              if($field->field_type == 'rating_field' 
                && isset($layout_params['fields'][$field->db_field_name.'_average'])
                && $layout_params['fields'][$field->db_field_name.'_average'] == 'on'){

                $value = get_average_rating($field, $layout, $entityInstance);
              }
              //get field value if this rating field

              //publish\unpublish check
              if((!isset($field_from_params[$field->db_field_name.'_published']) 
                  || $field_from_params[$field->db_field_name.'_published'] != 'on')){
                $layout_html = str_replace("{|f-".$field->fid."|}", '', $layout_html);
                continue;
              }
              //publish\unpublish check

              //check access
                if(isset($field_from_params['access_'.$field->db_field_name])
                    && $field_from_params['access_'.$field->db_field_name] != '1'){
                  $user = JFactory::getUser();
                  if(!checkAccess_cck($field_from_params['access_'.$field->db_field_name], $user->groups, $entityInstance->fk_eid, 'fields')){
                    $layout_html = str_replace("{|f-".$field->fid."|}", $html, $layout_html);
                    continue;
                  }
                }
              //check access

              //regular expression
              if(isset($field_from_params[$field->db_field_name.'_check_expression'])){
                  $checkExpr = ($field_from_params[$field->db_field_name.'_check_expression'] != 'custom') ? $field_from_params[$field->db_field_name.'_check_expression'] : $field_from_params[$field->db_field_name.'_check_expression_custom'];
                ?>
                <script>
                  checkExpr[checkExpr.length] = ["<?php echo $field->db_field_name;?>",
                                                encodeURI(<?php echo $checkExpr?>),
                                                "<?php echo $field_from_params[$field->db_field_name.'_error_text'];?>"];
                </script>
                <?php
              }
              //regular expression

              //add prefix_
              if(!empty($field_from_params[$field->db_field_name.'_prefix'])){
                $html .= '<span class="'.$field->db_field_name.'_prefix'.'">'.$field_from_params[$field->db_field_name.'_prefix'].'</span>';
              }
              //add prefix_

              if($field->field_type == 'categoryfield'){
                $cats = $value;
                $value = array();
                if(is_array($cats)){
                  foreach ($cats as $id){
                    if(isset($id->catid)){
                      $value[] = $id->catid;
                    }
                  }
                }  
              }else if($field->field_type == 'locationfield'){
                $value = isset($value[0]) ? $value = $value[0] : '';
              }elseif($field->field_type == 'pricefield_number'){
                  $value = (isset($value[0])) ? $value[0] : '';
              }elseif($field->field_type == 'pricefield_select_list' || $field->field_type == 'pricefield_radio_buttons'){
                  
              }else{
                $value = (isset($value[0]->data)) ? $value[0]->data : '';
              }
              //check from search or not
    //var_dump($value);
              $fromSearch = 0;
              $field_from_params['ceid'] = $layout->fk_eid;
              $field_from_params['lay_type'] = $layout_type;
              $field_from_params['field_styling']= $field_styling;
              $field_from_params['custom_class']= $custom_class;
              $field_from_params['form_id'] = $unique_form_id;
              $offset_animation = get_field_offset_animation($field, $layout);
              //attach field
              ob_start();
                require getSiteAddFiledViewPath('com_os_cck', $field->field_type);
              $html .= ob_get_contents();
              ob_end_clean();
              //attach field

              //add _suffix  
              if(!empty($field_from_params[$field->db_field_name.'_suffix'])){
                $html.= '<span class="'.$field->db_field_name.'_suffix'.'">'.$field_from_params[$field->db_field_name.'_suffix'].'</span>';
              }

              //add _suffix
          }
          //add field to layout / replace shortcode
          $layout_html = str_replace("{|f-".$field->fid."|}", $html, $layout_html);
        }
        
      }
      // var_dump($child_entities);
      if(is_array($child_entities) && count($child_entities) > 0){
          
          foreach($child_entities as $child_entity){
              
              $child_enteties_html = '';
              if(strpos($layout_html,"{|".$child_entity->data_field_name."|}")){
                  $php_if = isset($layout_params['fields'][$child_entity->data_field_name.'_php_show']) ? $layout_params['fields'][$child_entity->data_field_name.'_php_show'] : '';
                  $php_result = true;

                  if($php_if != ''){
                        $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
                  }
                  if(!$php_result){
                      $layout_html = str_replace("{|".$child_entity->data_field_name."|}", '', $layout_html);
                        continue;
                  }

                  //publish\unpublish check


                  if((!isset($field_from_params[$child_entity->data_field_name.'_published']) 
                      || $field_from_params[$child_entity->data_field_name.'_published'] != 'on')){
                    $layout_html = str_replace("{|".$child_entity->data_field_name."|}", '', $layout_html);
                    continue;
                  }

                  //publish\unpublish check

                  //check access
                    if(isset($field_from_params['access_'.$child_entity->data_field_name])
                        && $field_from_params['access_'.$child_entity->data_field_name] != '1'){
                      $user = JFactory::getUser();
                      if(!checkAccess_cck($field_from_params['access_'.$child_entity->data_field_name], $user->groups, $child_entity->childEntityId, 'fields')){
                        $layout_html = str_replace("{|".$child_entity->data_field_name."|}", $child_enteties_html, $layout_html);
                        continue;
                      }
                    }
                  //check access
                    
                    if(!empty($field_from_params[$child_entity->data_field_name.'_prefix'])){
                        $child_enteties_html .= '<span class="'.$child_entity->data_field_name.'_prefix'.'">'.$field_from_params[$child_entity->data_field_name . '_prefix'].'</span>';
                      }
                  ob_start();
                    require getSiteAddFiledViewPath('com_os_cck', 'child_select');
                  $child_enteties_html .= ob_get_contents();
                  ob_end_clean();

                  //add _suffix  
                  if(!empty($field_from_params[$child_entity->data_field_name.'_suffix'])){
                    $child_enteties_html.= '<span class="'.$child_entity->data_field_name.'_suffix'.'">'.$field_from_params[$child_entity->data_field_name.'_suffix'].'</span>';
                  }
                  
                  $layout_html = str_replace("{|".$child_entity->data_field_name."|}", $child_enteties_html, $layout_html);
                  //var_dump($child_entity);
              }
              
          }
      }

      if($is_site){
        if(isset($layout_params['attachedModule'])){
          foreach ($layout_params['attachedModule'] as $attachedModule) {
            if($attachedModule && $attachedModule != 'undefined'){
              if(strpos($layout_html,"{|m-".$attachedModule->id."|}")){
                $field->field_name = 'm_'.$attachedModule->id;
                $field_styling = get_field_styles($field, $instance_layout);
                $custom_class = isset($layout_params['fields'][$field->field_name.'_custom_class'])?$layout_params['fields'][$field->field_name.'_custom_class']:'';
                $offset_animation = get_field_offset_animation($field, $layout);
                $module = JModuleHelper::getModule($attachedModule->type,$attachedModule->title);
                $options  = array('style' => 'xhtml');
                $html = '<div class="'.$custom_class.'" '. $offset_animation . ' ' .$field_styling.'>'.JModuleHelper::renderModule($module,$options).'</div>';
                $layout_html = str_replace("{|m-".$attachedModule->id."|}", $html, $layout_html);
              }
            }
          }
        }
        
  
        if(isset($layout_params['action_button_fields']) && count($layout_params['action_button_fields'])){
          foreach($layout_params['action_button_fields'] as $key=>$val){
              $field = new stdClass();
              $field->db_field_name = 'cck_action_button_' . $key;
              if(isset($layout_params['fields']['access_'.$field->db_field_name])
                  && $layout_params['fields']['access_'.$field->db_field_name] != '1'){
                $user = JFactory::getUser();
                // var_dump($user);
                if(!checkAccess_cck($layout_params['fields']['access_'.$field->db_field_name], $user->groups, $layout->fk_eid, 'fields', $entityInstance->eiid)){
                  $layout_html = str_replace("{|f-cck_action_button_$key|}", '', $layout_html);
                  // continue;
                }
              }

              ob_start();
              require getSiteUniqueFiledViewPath('com_os_cck', 'action_button');
              $action_button_html = ob_get_contents();
              ob_end_clean();

              $layout_html = str_replace("{|f-cck_action_button_$key|}", $action_button_html, $layout_html);
            }
        }
        
      }
    
        //render layout    
        echo $layout_html;
        
        
        
        
        //var_dump($new_class);
      ?>


        <input type="hidden" name="id" value="<?php echo $entityInstance->eiid; ?>"/>
        <input type="hidden" name="option" value="<?php echo $option; ?>"/>
        <input type="hidden" name="boxchecked" value="0"/>
        <?php if($entityInstance->eiid && trim($entityInstance->eiid) != ''):?>
          <input id="inst_id" type="hidden" name="eiid[]" value="<?php echo $entityInstance->eiid;?>"/>
        <?php endif;?>
        <input id="inst_task" type="hidden" name="task" value="apply_instance"/>
      </div>

      <script type="text/javascript">
          window.addEventListener('load', function() {
            jQuerOs("*[class*='hide-field-name-'] , .delete-field, .delete-row, .delete-layout").remove();
            jQuerOs("div[class *='cck-row-'], div[id *='cck_col-']").each(function(index, el) {
              jQuerOs(el).attr("style",jQuerOs(el).data("block-styling"));
            });
          })
      </script>

      <?php
      echo JHtml::_('bootstrap.endTab');
      $user = JFactory::getUser();
      $lay_access = array('6', '7', '8');
      if(checkAccess_cck($lay_access, $user->groups, $entityInstance->fk_eid, 'fields')){
      echo JHtml::_('bootstrap.addTab', 'instance-tab', 'panel_2_id', cck_lang_text('COM_OS_CCK_ADMIN_INSTANCE_SETTINGS'));
      //echo JHtml::_('tabs.panel', cck_lang_text('COM_OS_CCK_ADMIN_INSTANCE_SETTINGS'), 'panel_2_id');
      ?>

      <div class="instance-settings-block">
        <div class="settings-block">
          <div class="settings-header">
            <label><?php echo cck_lang_text('COM_OS_CCK_LABEL_ADVERTISMENT')?>:</label>
          </div>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_FEATURED_CLICKS')?>:</span>
            <span class="col-2">
              <input type="number" name="featured_clicks" value="<?php echo ($entityInstance->featured_clicks <= -1)?'':$entityInstance->featured_clicks?>" min="0" step="1" max="2147483647">
            </span>
          </div>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_FEATURED_SHOWS')?>:</span>
            <span class="col-2">
              <input type="number" name="featured_shows" value="<?php echo ($entityInstance->featured_shows <= -1)?'':$entityInstance->featured_shows?>" min="0" step="1" max="2147483647">
            </span>
          </div>
          <?php if(!$is_site){ ?>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_FEATURED_OWNER_ID')?>:</span>
            <span class="col-2">
                <?php 
                $get_user_modal = new os_cckFieldUser();
                $owner_id = (!$entityInstance->fk_userid) ? JFactory::getUser()->id : $entityInstance->fk_userid;
                if(!checkingUser($owner_id)) $owner_id = JFactory::getUser()->id;
                echo $get_user_modal->getHtmlInput($owner_id); ?>
            </span>
          </div>
          <?php } ?>  
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_TITLE')?>:</span>
            <span class="col-2">
              <input type="text" name="meta_title" value="<?php echo $entityInstance->meta_title; ?>" maxlength="255">
              <span class="label label-default" class="count_message" id="count_message_meta_title"></span>
            </span>
          </div>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_DESCRIPTION')?>:</span>
            <span class="col-2">
                <textarea class="form-control" name="meta_description"><?php echo $entityInstance->meta_description; ?></textarea>
                <span class="label label-default" class="count_message" id="count_message_meta_description"></span>
            </span>
          </div>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_KEYWORDS')?>:</span>
            <span class="col-2">
              <textarea class="form-control" name="meta_keywords"><?php echo $entityInstance->meta_keywords; ?></textarea>
              <span class="label label-default" class="count_message" id="count_message_meta_keywords"></span>
            </span>
          </div>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_ROBOTS')?>:</span>
            <span class="col-2">
              <?php echo JHTML::_('select.genericlist', $robots_option, 'meta_robots', '','value', 'text',$entityInstance->meta_robots)?>
            </span>
          </div>
          <?php if(JLanguageMultilang::isEnabled()){ ?>
          <div class="settings-content">
            <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_LANGUAGE')?>:</span>
            <span class="col-2">
                <?php echo $lang_list; ?>
            </span>
          </div>
            <?php

            foreach ($instanse_lang_list as $key => $list){ ?>
                <div class="settings-content <?php echo $key; ?> assoc_instancce">
                    <span class="col-1"><?php echo cck_lang_text('COM_OS_CCK_LABEL_ASSOCIATED_INSTANCE') . ' ' . $key; ?>:</span>
                    <span class="col-2">
                        <?php  echo JHTML::_('select.genericlist',$list, 'instanse_assoc_'.$key, 'size="1" class="inputbox"', 'value', 'text', (isset($assoc_list[$key])) ? $assoc_list[$key] : '');?>
                    </span>
                </div>
            <?php } 
          }else{ ?>
              <input type="hidden" name="language" value="*">
          <?php }?>
            
            <?php if($cck_entity_configuration[$entityInstance->fk_eid]['check_access_instances'] == '1') { 
                $attr = array (
                'list.attr' => ' multiple="true" ',
                'id' => 'fi_access_'.$fName,
                'list.select' => $access,
                'group.items' => null,
                'option.key.toHtml' => false,
                'option.text.toHtml' => false
            );
                ?>
              <div class="settings-content">
                <span class="col-1"><?php echo cck_lang_text("COM_OS_CCK_LABEL_FIELD_ACCESS")?></span>
                <span class="col-2">
                  <?php //echo JHTML::_('select.genericlist', $gtree, 'access[]', 'multiple="true"','value', 'text',$access)
                echo JHTML::_('select.groupedlist',$gtree,'access[]', $attr);?>
                </span>
              </div>
            <?php } ?>
            
            

        </div>  
      </div>

      <?php
        echo JHtml::_('bootstrap.endTab');
      }
        echo JHtml::_('bootstrap.endTabSet');
        //echo JHtml::_('tabs.end');
      ?>
    </form>
                      <script>

                        var text_max = 255;
                        // console.log('11111111111111', typeof(jQuerOs('[name=meta_description]').val()) != undefined)
                        if(jQuerOs('[name=meta_description]').val() != undefined){
                          jQuerOs('#count_message_meta_description').html(jQuerOs('[name=meta_description]').val().length+' / ' + text_max );
                        }

                        jQuerOs('[name=meta_description]').on('input', function() {
                          var text_length = jQuerOs('[name=meta_description]').val().length;
                          if(text_length > text_max){
                              var text = jQuerOs('[name=meta_description]').val().slice(0, text_max)
//                              console.log('1111111111111', text)
                              jQuerOs('[name=meta_description]').val(text)
                              text_length = text_max
                          }
                          var text_remaining = text_max - text_length;
                          jQuerOs('#count_message_meta_description').html(text_length + ' / ' + text_max);
                        });
                        if(jQuerOs('[name=meta_title]').val() != undefined){
                          jQuerOs('#count_message_meta_title').html(jQuerOs('[name=meta_title]').val().length+' / ' + text_max );
                        }
                        jQuerOs('[name=meta_title]').on('input', function() {
                          var text_length = jQuerOs('[name=meta_title]').val().length;
                          if(text_length > text_max){
                              var text = jQuerOs('[name=meta_title]').val().slice(0, text_max)
//                              console.log('1111111111111', text)
                              jQuerOs('[name=meta_title]').val(text)
                              text_length = text_max
                          }
                          var text_remaining = text_max - text_length;
                          jQuerOs('#count_message_meta_title').html(text_length + ' / ' + text_max);
                        });
                        
                        if(jQuerOs('[name=meta_keywords]').val() != undefined){
                          jQuerOs('#count_message_meta_keywords').html(jQuerOs('[name=meta_keywords]').val().length+' / ' + text_max );
                        }
                        
                        jQuerOs('[name=meta_keywords]').on('input', function() {
                          var text_length = jQuerOs('[name=meta_keywords]').val().length;
                          if(text_length > text_max){
                              var text = jQuerOs('[name=meta_keywords]').val().slice(0, text_max)
//                              console.log('1111111111111', text)
                              jQuerOs('[name=meta_keywords]').val(text)
                              text_length = text_max
                          }
                          var text_remaining = text_max - text_length;
                          jQuerOs('#count_message_meta_keywords').html(text_length + ' / ' + text_max);
                        });
                      </script>
      <?php
    }


}

?>
