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

if(!function_exists('showAllCat')){
  function showAllCat($option, $id, $categories, $params, $Itemid, $deep,$layout,$layout_params, $menu, $category_layout) {
    global $mosConfig_live_site,$moduleId,$db;
    $db = new os_cckDb();
    $deep++; 
    if($layout_params['key'] == $layout->lid){
        $attach_layout = $layout;
    }elseif($layout_params['key'] == $category_layout->lid){
        $attach_layout = $category_layout;
    }else{
       $attach_layout = new os_cckLayout($db->_db);
       $attach_layout->load($layout_params['key']);
       // var_dump($attach_layout);
    }
    for ($i = 0; $i < count($categories); $i++) { //
        
      if (($id == $categories[$i]->parent_id) && ($categories[$i]->display == 1)) {
          
        $layout_html = urldecode($layout->layout_html);
        $layout_html = cut_params($layout_html);
        $layout_html = remove_admin_classes($layout_html);
        $field = new stdClass();
        

        $field->db_field_name = "l".$layout_params['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);
        
        //get tag
        $shell_tag = isset($layout_params['fields']['field_tag_'.$field->db_field_name])?$layout_params['fields']['field_tag_'.$field->db_field_name]:'div';
        
//        var_dump($attach_layout);
        //end
        //if below fn works , that this is add_instance view
        echo '<'.$shell_tag.' class="cat_instance_body'.$custom_class.'" ' . $offset_animation . ' ' .$field_styling.'>';
        
        Category::show_attached_layout($option, $attach_layout, '', $layout_params,
                                       $layout_params['show_type'],'',$categories[$i]->cid, $categories, $button_style, 10, $Itemid, $params, $menu);
        echo '</'.$shell_tag.'>';

      }//end if
    }//end for
  }//end fn
}



if(isset($layout_params['views']['show_layout_title']) && $layout_params['views']['show_layout_title'])
  {
        echo "<h3>";
          echo $layout_params['views']['layout_title'];
        echo "</h3>";
  }
$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);

if(isset($layout_params["views"]["instance_grid"]) && $layout_params["views"]["instance_grid"] == 1){ ?>

            <script>
              
               jQuerOs(document).ready(function(){

                jQuerOs(".cat_instance_body").parent().addClass('flex-block');

               });

            </script>

            <?php  }

            $unique_class = 'all_category_unique_class_'.$layout->lid;

            $cck_wrapper_instance = (isset($layout_params["views"]["instance_grid"]) && $layout_params["views"]["instance_grid"] == 1)?"cck-wrapper-allcat":"";

            $resolutions = ($cck_wrapper_instance != "" && isset($layout_params["views"]["auto_custom"]) && $layout_params["views"]["auto_custom"] == "custom")?"instance-col-lg-".$layout_params["views"]["resolition_one"]." "."instance-col-md-".$layout_params["views"]["resolition_two"]." "."instance-col-sm-".$layout_params["views"]["resolition_three"]." "."instance-col-xs-".$layout_params["views"]["resolition_four"]." ":'';
//            var_dump($resolutions);
            if($cck_wrapper_instance != "" &&  $resolutions == ""){

              $count_inst_columns = (isset($layout_params["views"]["count_inst_columns"]))?$layout_params["views"]["count_inst_columns"]:"";
              $min_width = (isset($layout_params["views"]["lay_min_width"]))?$layout_params["views"]["lay_min_width"]:"";
              $space_between = (isset($layout_params["views"]["space_between"]))?$layout_params["views"]["space_between"]:"";

              ?>
                <script type="text/javascript">

                jQuerOs( document ).ready(function() {

                    var cckGridLayout1 = function (container, params) {

                        if (!(this instanceof cckGridLayout1)) return new cckGridLayout1(container, params);

                        var defaults = {
                            minImgEnable : 1,
                            spaceBetween: 0,
                            minImgSize: 200,
                            numColumns: 4,
                        };

                        for (var param in defaults) {
                            if (!params[param]){
                            params[param] = defaults[param];
                            }
                        }
                        // gallery settings
                        var cckGrid = this;
                        // Params
                        cckGrid.params = params || defaults;

                            cckGrid.getImgBlockWidth = function (numColumns){
                                if(typeof(numColumns) == 'undefined')numColumns = cckGrid.params.numColumns;
                                spaceBetween = cckGrid.params.spaceBetween;
                                mainBlockW = jQuerOs(container).width();
                                imgBlockW = ((((mainBlockW-(spaceBetween*numColumns))/numColumns)-1)*100)/mainBlockW;

                                
                                if(cckGrid.params.minImgEnable){

                                    if(((imgBlockW*mainBlockW)/100) < cckGrid.params.minImgSize){
                                    numColumns--;
                                    cckGrid.getImgBlockWidth(numColumns);
                                    }
                                }

                                return imgBlockW;
                            }

                        //initialize function
                            cckGrid.init = function (){
                            imgBlockW = cckGrid.getImgBlockWidth();

                        // jQuerOs(container+" .item").css("width",imgBlockW+"%");

                            
                            jQuerOs(container+" .cat_instance_body").css({
                            'width': imgBlockW+"%",
                            'margin':  cckGrid.params.spaceBetween / 2 
                            });

                            cckGrid.resizeGallery = function (){
                                imgBlockW = cckGrid.getImgBlockWidth();
                                jQuerOs(container+" .cat_instance_body").css("width",imgBlockW+"%");
                            }

                            jQuerOs(window).resize(function(event) {
                            cckGrid.resizeGallery();
                            });
                        }

                        cckGrid.init();
                    }


                window.cckGridLayout1 = cckGridLayout1;
                
                 });


                jQuerOs(document).ready(function() {

                    var gallery = new cckGridLayout1(".<?php echo $unique_class; ?>",{
                        minImgEnable : 1,
                        spaceBetween: <?php echo $space_between; ?>,
                        minImgSize: <?php echo $min_width; ?>,
                        numColumns: <?php echo $count_inst_columns; ?>,
                    });



                  });

                </script>
              <?php

            }
?>
<div class="cck-body">

  <?php if( checkOsCckVersionProFree() == "free" ){ ?>
  <noscript>
      Javascript is required to use OrdaSoft Joomla CCK 
      <a href="https://ordasoft.com/joomla-cck"
  >OrdaSoft Joomla CCK allows you to quickly and easily create a Joomla website exactly the way you want it to look.</a>,
      <a href="https://ordasoft.com/joomla-cck" >Joomla CCK</a>
  </noscript>
  <?php } ?>
    
  <div class="<?php echo $cck_wrapper_instance.' '.$unique_class.' '.$resolutions.' '.$form_custom_class; ?> all_cat_main" <?php echo $form_styling; ?> >
    <?php
    $layout_html = urldecode($layout->layout_html);
    $layout_html = cut_params($layout_html);
    
    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){
            $layout_params['show_type'] = isset($layout_params['views']['show_type_request_layout'][$key][0])?$layout_params['views']['show_type_request_layout'][$key][0]:1;
            
            if(strpos($layout_html,"{|l-".$key."|}")){
              $layout_params['key'] = $key;
              //if below fn works , that this is add_instance view

              if(isset($layout_params['views']['show_request_layout'][$layout_params['key']][0])
                  && $layout_params['views']['show_request_layout'][$layout_params['key']][0] != '1'
                  && $layout_params['views']['show_request_layout'][$layout_params['key']][0] != ''){
                $user = JFactory::getUser();
                if(!checkAccess_cck($layout_params['views']['show_request_layout'][$layout_params['key']], $user->groups, $layout->fk_eid, 'fields')){
                  $layout_html = str_replace("{|l-".$key."|}", '', $layout_html);
                  continue;
                }
              }
              
              if(isset($layout_params['views']['show_request_layout_name'][$layout_params['key']]) &&
                  isset($layout_params['views']['show_request_layout_name'][$layout_params['key']][0]) &&
                  $layout_params['views']['show_request_layout_name'][$layout_params['key']][0] == 'on'){
                $layout_html = str_replace($layout_params['key'].'-label-hidden', '', $layout_html);
              }

                
              
              if($layouts_type[$key] == 'category'){
                  ob_start();
                  showAllCat($option, 0, $categories, $params, $Itemid, 0,$layout,$layout_params, $menu, $category_layout);
                  $layout_html = str_replace("{|l-".$key."|}", ob_get_contents(), $layout_html);
                  ob_end_clean();
              }else{
                    ob_start();
                    $field = new stdClass();

                    // $field->db_field_name = $layout_params['key'];
                    // $field_styling = get_field_styles($field, $layout);
                    // $custom_class = get_field_custom_class($field, $layout);

                    $field->db_field_name = "l".$layout_params['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);

                    //get tag
                    $shell_tag = isset($layout_params['fields']['field_tag_'.$field->db_field_name])?$layout_params['fields']['field_tag_'.$field->db_field_name]:'div';
                    //end
                    //if below fn works , that this is add_instance view
                    echo '<'.$shell_tag.' class="cat_instance_body'.$custom_class.'" ' . $offset_animation . ' ' .$field_styling.'>';

                    Category::show_attached_layout($option, $layout_params['key'], '', $layout_params,
                                                   $layout_params['show_type'],'','', $categories, $button_style, 10, $Itemid);
                    echo '</'.$shell_tag.'>';
                    $layout_html = str_replace("{|l-".$key."|}", ob_get_contents(), $layout_html);
                    ob_end_clean();
              }
            }
            }else{
                    $layout_html = str_replace("{|l-".$key."|}", '', $layout_html);
                }
      }
    }
    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."|}")){
//           //check access
//           if(isset($custom_field['custom_code_field_'.$cust_key.'_access'])
//               && $custom_field['custom_code_field_'.$cust_key.'_access'] != '1'){
//             $user = JFactory::getUser();
//             if(!checkAccess_cck($custom_field['custom_code_field_'.$cust_key.'_access'], $user->groups, $layout->fk_eid, 'fields')){
//               $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);

//             }
//           }
//           // 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'){
//             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{
//             $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);
//           }
//         }
//       }
//     }
    
    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);
      }
    //end render
    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);
            //get tag
            $shell_tag = isset($layout_params['fields']['field_tag_'.$field->db_field_name])?$layout_params['fields']['field_tag_'.$field->db_field_name]:'div';
            //end
            $module = JModuleHelper::getModule($attachedModule->type,$attachedModule->title);
            $options  = array('style' => 'xhtml');
            $html = '<'.$shell_tag.' class="'.$custom_class.'" ' . $offset_animation . ' ' .$field_styling.'>'.JModuleHelper::renderModule($module,$options).'</'.$shell_tag.'>';
            
            $layout_html = str_replace("{|m-".$attachedModule->id."|}", $html, $layout_html);
          }
        }
      }
    }
    $layout_html = str_replace('data-label-styling', 'style',  $layout_html);
    echo $layout_html;
    ?>
  </div>
  <script>
    jQuerOs("div[class *='cck-row-'], div[id *='cck_col-']").each(function(index, el) {
      jQuerOs(el).attr("style",jQuerOs(el).data("block-styling"))
    });
    jQuerOs("div[class *='cck-row-']").addClass('row');
    //jQuerOs("span.cck-help-string").remove();
    jQuerOs(function () {
      jQuerOs('[data-toggle="tooltip"]').tooltip()
    })
  </script>
  <?php if( checkOsCckVersionProFree() == "free" ){ ?>
    <div><p style="text-align: center;font-size: 10px;"><a href="https://ordasoft.com/joomla-cck" 
      target="_blank" title="Joomla CCK" >Joomla CCK</a>, by OrdaSoft!</p></div>
  <?php } ?>  
</div>
