<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/

//for Joomla 5-6
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
// use Joomla\CMS\Access\Access;
// use Joomla\CMS\Version;
use Joomla\Registry\Registry;
use Joomla\CMS\Table\Table;
use Joomla\Filesystem\Path;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\File;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Editor\Editor;
use Joomla\CMS\Helper\UserGroupsHelper;
use Joomla\CMS\User\User ;
use Joomla\CMS\User\UserHelper ;
use Joomla\CMS\Filter\OutputFilter;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\Form\Field\UserField ;
// use Joomla\CMS\Component\Router\RouterView;
use Joomla\CMS\Table\Menu;
use Joomla\CMS\Application\ApplicationHelper ;
use Joomla\CMS\Component\ComponentHelper ;
// use Joomla\CMS\Helper\ModuleHelper ;
use Joomla\CMS\Plugin\PluginHelper ;
use Joomla\CMS\Plugin\CMSPlugin ;
// use Joomla\CMS\User\User ;
use Joomla\CMS\HTML\Helpers\Behavior ;
use Joomla\CMS\Language\LanguageHelper ;
use Joomla\CMS\Language\Multilanguage ;
use Joomla\CMS\Object\CMSObject ;
use Joomla\CMS\MVC\Controller\BaseController ;
use Joomla\CMS\MVC\View\HtmlView ;
use Joomla\Archive\Archive;
use Joomla\CMS\Installer\Installer;

if (version_compare(JVERSION, "5.0.0", "ge")) {

    if (!class_exists('JFactory')) class_alias('Joomla\CMS\Factory', 'JFactory');
    if (!class_exists('JURI')) class_alias('Joomla\CMS\Uri\Uri', 'JURI');
    // if (!class_exists('JAccess')) class_alias('Joomla\CMS\Access\Access', 'JAccess');
    // if (!class_exists('JVersion')) class_alias('Joomla\CMS\Version', 'JVersion');
    if (!class_exists('JRegistry')) class_alias('Joomla\Registry\Registry', 'JRegistry');
    if (!class_exists('JTable')) class_alias('Joomla\CMS\Table\Table', 'JTable');
    if (!class_exists('JPath')) class_alias('Joomla\Filesystem\Path', 'JPath');
    if (!class_exists('JFolder')) class_alias('Joomla\Filesystem\Folder', 'JFolder');
    if (!class_exists('JFile')) class_alias('Joomla\Filesystem\File', 'JFile');
    if (!class_exists('JToolbarHelper')) class_alias('Joomla\CMS\Toolbar\ToolbarHelper', 'JToolbarHelper');
    if (!class_exists('JHtml')) class_alias('Joomla\CMS\HTML\HTMLHelper', 'JHtml');
    if (!class_exists('JText')) class_alias('Joomla\CMS\Language\Text', 'JText');
    if (!class_exists('JEditor')) class_alias('Joomla\CMS\Editor\Editor', 'JEditor');
    if (!class_exists('JHelperUsergroups')) class_alias('Joomla\CMS\Helper\UserGroupsHelper', 'JHelperUsergroups');
    if (!class_exists('JUser')) class_alias('Joomla\CMS\User\User', 'JUser');
    if (!class_exists('JUserHelper')) class_alias('Joomla\CMS\User\UserHelper', 'JUserHelper');
    if (!class_exists('JFilterOutput')) class_alias('Joomla\CMS\Filter\OutputFilter', 'JFilterOutput');
    if (!class_exists('JRoute')) class_alias('Joomla\CMS\Router\Route', 'JRoute');
    if (!class_exists('JForm')) class_alias('Joomla\CMS\Form\Form', 'JForm');
    if (!class_exists('JFormField')) class_alias('Joomla\CMS\Form\FormField', 'JFormField');
    if (!class_exists('JFormFieldUser')) class_alias('Joomla\CMS\Form\Field\UserField', 'JFormFieldUser');
    // if (!class_exists('JComponentRouterView')) class_alias('Joomla\CMS\Component\Router\RouterView', 'JComponentRouterView');
    if (!class_exists('JTableMenu')) class_alias('Joomla\CMS\Table\Menu', 'JTableMenu');
    if (!class_exists('JApplicationHelper')) class_alias('Joomla\CMS\Application\ApplicationHelper', 'JApplicationHelper');
    if (!class_exists('JComponentHelper')) class_alias('Joomla\CMS\Component\ComponentHelper', 'JComponentHelper');
    // if (!class_exists('JModuleHelper')) class_alias('Joomla\CMS\Helper\ModuleHelper', 'JModuleHelper');
    if (!class_exists('JPluginHelper')) class_alias('Joomla\CMS\Plugin\PluginHelper', 'JPluginHelper');
    if (!class_exists('JPlugin')) class_alias('Joomla\CMS\Plugin\CMSPlugin', 'JPlugin');
    // if (!class_exists('JUser')) class_alias('Joomla\CMS\User\User', 'JUser');
    if (!class_exists('JHtmlBehavior')) class_alias('Joomla\CMS\HTML\Helpers\Behavior', 'JHtmlBehavior');
    if (!class_exists('JLanguageHelper')) class_alias('Joomla\CMS\Language\LanguageHelper', 'JLanguageHelper');
    if (!class_exists('JLanguageMultilang')) class_alias('Joomla\CMS\Language\Multilanguage', 'JLanguageMultilang');
    if (!class_exists('JObject')) class_alias('Joomla\CMS\Object\CMSObject', 'JObject');
    if (!class_exists('JControllerLegacy')) class_alias('Joomla\CMS\MVC\Controller\BaseController', 'JControllerLegacy');
    if (!class_exists('JViewLegacy')) class_alias('Joomla\CMS\MVC\View\HtmlView', 'JViewLegacy');
    if (!class_exists('JArchive')) class_alias('Joomla\Archive\Archive', 'JArchive');
    if (!class_exists('JInstaller')) class_alias('Joomla\CMS\Installer\Installer', 'JInstaller');
} 

if (!function_exists('print_vars')) {
  function print_vars($obj,$space_plus = "")
  {
    $space_plus .= " "; //need for tree create 
    if(is_object($obj) ){
      echo " $space_plus Object: <br>\n";
      $arr = get_object_vars($obj);
      foreach($arr as $key => $val)
        if (isset($val) && ( is_object($val) || is_array($val) ) ) {
          echo " $space_plus $key -> <br>\n";
          print_vars($val,$space_plus);
        }
        else echo "\t $space_plus $key -> $val<br>\n";
    } elseif(is_array($obj) ){
      echo " $space_plus Array (".count($obj)."): <br>\n";
      foreach($obj as $key => $val)
        if (isset($val) && ( is_object($val) || is_array($val) ) ){
          echo " $space_plus [$key] = <br>\n";
          print_vars($val,$space_plus);
        }
        else echo "\t $space_plus [$key] = $val<br>\n";
    } else print_r( $obj );
  }
}

if (!function_exists('print_methods')) {
  function print_methods($obj)
  {
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method) echo "\tfunction $method()\n <br />";
  }
}

if (!function_exists('getInstanceCount')) {
  // mask like {|decimal_textfield_31|}
  function getInstanceCountInCategory($cid = '', $eid = ''){
      global $db;
      $db = new os_cckDb();
      if($eid == ''){
          $where = '';
      }else{
          $where = ' AND ent.fk_eid =' . $eid;
      }
      $section = "com_os_cck";
      $query = "SELECT  COUNT(c_con.id) AS inst_count "
        . "\n FROM #__os_cck_categories AS c"
        . "\n LEFT JOIN #__os_cck_categories_connect AS c_con FORCE INDEX (fk_cid) ON c_con.fk_cid=c.cid"
        . "\n LEFT JOIN #__users AS u ON u.id = c.checked_out"
        . "\n LEFT JOIN #__os_cck_entity_instance AS ent ON ent.eiid = c_con.fk_eiid"
        . "\n WHERE c.section='$section'  AND c.cid ='".$cid."'  AND ent.published = '1'"
        . "\n AND c.published = 1" . $where
        . "\n GROUP BY c.cid"
        . "\n ORDER BY section, parent_id, ordering";

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

      return $count;
  }
}



if (!function_exists('addChildSelectToLayout')) {
  function addChildSelectToLayout($fields_list, $entityInstance, $layout_params, $layout_html, $layout, $fid = ''){

    // this function need only for SHOW layouts !!!!!
    //other need check anf remove 5.04.2026
    if( $layout->type == 'search' || $layout->type == 'add_instance' 
        || $layout->type == 'buy_request_instance' || $layout->type == 'request_instance' 
        || $layout->type == 'rent_request_instance' || $layout->type == 'review_instance' 
        || $layout->type == 'all_categories' || $layout->type == 'category' 
        || $layout->type == 'all_instance' || $layout->type == 'user_instances' 
      ){
        return ['layout_html' => $layout_html,
            'layout_params' => $layout_params,
            'select_parent' => "",
            'castom_childs' => "",
            'castom_childs_list' => ""];
    }

    //skip child selects
    $params = new JRegistry;
    $childs_list = [];
    foreach ($fields_list as $field) {
      if($field->field_type !== 'text_select_list') continue ;
      if($field->params){
          try {
              $params->loadString($field->params);
          } catch (Exception $ex) {

          }
      }

      $childs_list = array_merge($childs_list, explode('|',$params->get('child_select', '')));
    }
    
    $childs_list = array_unique($childs_list);

    $castom_childs = '';
    //find child fids
    $childList = array();
    $assoc_field_list = array();
    foreach ($fields_list as $key => $field){

      if($field->field_type == 'text_select_list'){
        //get assoc fields_list
        $assoc_field_list[$field->fid] = $field;
  
        //gathering only parents fields
        if(in_array($field->fid, $childs_list)) continue;

        //and for parents field search  dependence fields
        $childList[$field->fid] = recurseSelectTree($field->fid, $entityInstance);
      }
    }

    $parent = '';
    $layout_params['fields']['parent'] = '';
    //add child placeholder in layout
    $castom_childs_list = array();
    //determine where the function is called from the layout or from the custom code
    if($fid == ''){

        foreach ($childList as $parent => $childs) {

          if((is_array($parent) && count($parent) > 0) || $parent > 0){

            $childs_string = "";
            if(!is_array($childs)) continue;

            foreach ($childs as $child) {
                $tmp_val = $entityInstance->getSelectFieldValue($child) ;
                if(isset($tmp_val) && !empty($tmp_val) ) $field_val = json_decode($tmp_val);
                // if($field_val[0] != '0' || $layout->type == 'add_instance'){ ?????? - this function need only for SHOW layouts
                if( isset($field_val) && is_array($field_val) && $field_val[0] != '' ){ //0 - is also value, so compare with empty

                  $layout_params['fields']['Params_text_select_list_'.$child] = (isset($layout_params['fields']['Params_text_select_list_'.$parent])) ? $layout_params['fields']['Params_text_select_list_'.$parent] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_published'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_published'])) ? $layout_params['fields']['text_select_list_'.$parent.'_published'] : '';
                  $layout_params['fields']['showName_text_select_list_'.$child] = (isset($layout_params['fields']['showName_text_select_list_'.$parent])) ? $layout_params['fields']['showName_text_select_list_'.$parent] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_alias'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_alias'])) ? $layout_params['fields']['text_select_list_'.$parent.'_alias'] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_tooltip'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_tooltip'])) ? $layout_params['fields']['text_select_list_'.$parent.'_tooltip'] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_prefix'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_prefix'])) ? $layout_params['fields']['text_select_list_'.$parent.'_prefix'] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_suffix'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_suffix'])) ? $layout_params['fields']['text_select_list_'.$parent.'_suffix'] : '';
                  $layout_params['fields']['access_text_select_list_'.$child] = (isset($layout_params['fields']['access_text_select_list_'.$parent])) ? $layout_params['fields']['access_text_select_list_'.$parent] : '';
                  $layout_params['fields']['label_tag_text_select_list_'.$child] = (isset($layout_params['fields']['label_tag_text_select_list_'.$parent])) ? $layout_params['fields']['label_tag_text_select_list_'.$parent] : 'span';
                  $layout_params['fields']['field_tag_text_select_list_'.$child] = (isset($layout_params['fields']['field_tag_text_select_list_'.$parent])) ? $layout_params['fields']['field_tag_text_select_list_'.$parent] : 'span';
                  $wrap_value = (isset($layout_params['fields']['Params_text_select_list_'.$parent])) ? $layout_params['fields']['Params_text_select_list_'.$parent] : '';
                  $label_styles = get_field_label_styles($wrap_value);
                  //var_dump($layout_params['fields']['label_tag_text_select_list_49']);
                  //remove aliases in child select lists
                  //VlaDOS 08.01.2019
//                  if(isset($layout_params['fields']['showName_text_select_list_'.$parent])){
//                      $start_wrap = '<div class="drop-item" data-parent="'.$parent.'" data-content=""><span class="f-inform-button"></span><!-- clear back/front title --><' . $layout_params['fields']['label_tag_text_select_list_'.$child] . ' class="field-name"' . $label_styles . 'data-field-name="'.$assoc_field_list[$child]->db_field_name.'" data-field-type="text_select_list" style="font-weight:normal;">'.$assoc_field_list[$child]->field_name.'</' . $layout_params['fields']['label_tag_text_select_list_'.$child] . '><span class="col_box admin_aria_hidden">';
//                      $end_wrap = '</span><input class="f-params" name="fi_Params_'.$assoc_field_list[$child]->db_field_name.'" type="hidden" value="'. $wrap_value .'"></div>';
//                  } else {
                      $start_wrap = '<span class="col_box admin_aria_hidden">';
                      $end_wrap = '</span><input class="f-params" name="fi_Params_'.$assoc_field_list[$child]->db_field_name.'" type="hidden" value="'. $wrap_value .'">';
//                  }


                  $childs_string .= $start_wrap."{|f-".$child."|}".$end_wrap;
                  $castom_childs_list[] = $child;
                }
            }

            $layout_params['fields']['parent'] = $parent;
            $layout_html = str_ireplace('<i class="f-parent" fid="'.$parent.'" style="display: none;">{|f-parent-'.$parent.'|}</i>', $childs_string, $layout_html);
            $castom_childs = $childs_string;
          }
          $layout_params['fields']['parent'] = $parent;

        }
    }else{
        $parent = $fid;

        $childs = isset($childList[$fid]) ? $childList[$fid] : '';
        if((is_array($parent) && count($parent) > 0) || $parent > 0){
            $childs_string = "";
            if(is_array($childs)) {

            foreach ($childs as $child) {
                $tmp_val = $entityInstance->getSelectFieldValue($child) ;
                if(isset($tmp_val) && !empty($tmp_val) ) $field_val = json_decode($tmp_val);
                if( isset($field_val) && is_array($field_val) && $field_val[0] != '' ){ //0 - is also value, so compare with empty

                  $layout_params['fields']['Params_text_select_list_'.$child] = (isset($layout_params['fields']['Params_text_select_list_'.$parent])) ? $layout_params['fields']['Params_text_select_list_'.$parent] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_published'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_published'])) ? $layout_params['fields']['text_select_list_'.$parent.'_published'] : '';
                  $layout_params['fields']['showName_text_select_list_'.$child] = (isset($layout_params['fields']['showName_text_select_list_'.$parent])) ? $layout_params['fields']['showName_text_select_list_'.$parent] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_alias'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_alias'])) ? $layout_params['fields']['text_select_list_'.$parent.'_alias'] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_tooltip'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_tooltip'])) ? $layout_params['fields']['text_select_list_'.$parent.'_tooltip'] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_prefix'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_prefix'])) ? $layout_params['fields']['text_select_list_'.$parent.'_prefix'] : '';
                  $layout_params['fields']['text_select_list_'.$child.'_suffix'] = (isset($layout_params['fields']['text_select_list_'.$parent.'_suffix'])) ? $layout_params['fields']['text_select_list_'.$parent.'_suffix'] : '';
                  $layout_params['fields']['access_text_select_list_'.$child] = (isset($layout_params['fields']['access_text_select_list_'.$parent])) ? $layout_params['fields']['access_text_select_list_'.$parent] : '';
                  $layout_params['fields']['label_tag_text_select_list_'.$child] = (isset($layout_params['fields']['label_tag_text_select_list_'.$parent])) ? $layout_params['fields']['label_tag_text_select_list_'.$parent] : 'span';
                  $layout_params['fields']['field_tag_text_select_list_'.$child] = (isset($layout_params['fields']['field_tag_text_select_list_'.$parent])) ? $layout_params['fields']['field_tag_text_select_list_'.$parent] : 'span';
                  $wrap_value = (isset($layout_params['fields']['Params_text_select_list_'.$parent])) ? $layout_params['fields']['Params_text_select_list_'.$parent] : '';
                  $label_styles = get_field_label_styles($wrap_value);
                  //var_dump($layout_params['fields']['label_tag_text_select_list_49']);

                      $start_wrap = '<span class="col_box admin_aria_hidden">';
                      $end_wrap = '</span><input class="f-params" name="fi_Params_'.$assoc_field_list[$child]->db_field_name.'" type="hidden" value="'. $wrap_value .'">';

                  $childs_string .= $start_wrap."{|f-".$child."|}".$end_wrap;
                  $castom_childs_list[] = $child;
                }
            }
        }
            $layout_params['fields']['parent'] = $parent;
            $layout_html = str_ireplace('<i class="f-parent" fid="'.$parent.'" style="display: none;">{|f-parent-'.$parent.'|}</i>', $childs_string, $layout_html);
            $castom_childs = $childs_string;


          }
          $layout_params['fields']['parent'] = $parent;
    }
    if($layout_params['fields']['parent'] == ''){
        $layout_params['fields']['parent'] = $parent;
    }

    return ['layout_html' => $layout_html,
            'layout_params' => $layout_params,
            'select_parent' => $layout_params['fields']['parent'],
            'castom_childs' => $castom_childs,
            'castom_childs_list' => $castom_childs_list];
  }
}


if (!function_exists('noticeLinkToDocLayout')) {
  // mask like {|decimal_textfield_31|}
  function noticeLinkToDocLayout($db_lay_name = '', $lay_title = '', $doc_link = '#'){ ?>
      <div class="alert-layout">
        <div class="alert alert-warning alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span></button>
          <strong>Notice!</strong> For more information on how to use the '<?php echo $lay_title ?>', refer to the
          <b><a target="blank" href="<?php echo $doc_link; ?>">documentation.</a></b><span class="btn btn-primary btn-xs not-show-alert" data-dismiss="alert" >Do not show more?</span>
        </div>
      </div>

      <script type="text/javascript">
        var cookie = getCookie('<?php echo $db_lay_name ?>');

        if(cookie != undefined && cookie == 'on'){
          jQuerOs('.alert-layout').hide();
        }

        function getCookie(name) {
          var matches = document.cookie.match(new RegExp(
            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
          ));
          return matches ? decodeURIComponent(matches[1]) : undefined;
        }

        //jQuerOs(document).ready(function(){
        window.addEventListener('load', function() {
          jQuerOs('.not-show-alert').click(function(){
            document.cookie = "<?php echo $db_lay_name; ?>=on;  path='/'; expires=''; ";
          })
        })
      </script>
  <?php
  }
}


if (!function_exists('replaceMaskCustomCodePHP')) {
  // mask like {|decimal_textfield_31|}
  function replaceMaskCustomCodePHP($instance,$custom_code_str,$layout_params, $layout_html, $layout, $child_entities = array()){
      global $entityFieldLists, $db, $entities_type, $app;
      $db = new os_cckDb();
// echo '1111111111111111';
      if(!$instance || $custom_code_str == ''){
          $result = ['custom_code_str' => isset($custom_code_str) ? $custom_code_str : '',
          'variables_arr'=>isset($fields) ? $fields : [],
          'childs_html' => isset($childs) ? $childs : ''];
          return $result;
      }else{

      $fields = [];
        $childs = '';
        //var_dump($instance);
      if(isset($entityFieldLists[$instance->fk_eid])){

          foreach ($entityFieldLists[$instance->fk_eid] as  $field) {
            $var_name = "cust_field_".$field->fid;
            //get childs for select lists
            if($field->field_type == 'text_select_list' && stripos($custom_code_str, (string)$field->fid)){

               $childs = addChildSelectToLayout($entityFieldLists[$instance->fk_eid], $instance, $layout_params, $layout_html, $layout, $field->fid);

               if(isset($childs['castom_childs'])){
                //$childs = $childs['castom_childs'];
                if(stripos($custom_code_str, "{|f-" . $field->fid . "|}")){
                    //insert childs in custom code html
                    $child_str = explode("{|f-" . $field->fid . "|}", $custom_code_str);

                    $child_str[] = '{|f-' . $field->fid . '|}";';
                    $child_str[] = " echo '". $childs['castom_childs'] . "';";
                    $temp = $child_str[1];
                    $temp = substr($temp, 4);

                    unset($child_str[1]);
                    $child_str[] = $temp;

                    $child_str = implode($child_str);

                }elseif(stripos($custom_code_str, '{|'.$field->db_field_name.'|}')){

                    $custom_code_str = str_replace('{|'.$field->db_field_name.'|}', '$'.$var_name, $custom_code_str);
                    $custom_code_str_temp = '';
                    if(is_array($childs['castom_childs_list'])){
                        foreach ($childs['castom_childs_list'] as $child_list){

                            $child_var = '$cust_field_' . $child_list;

                            $custom_code_str_temp .= str_replace('$'.$var_name, $child_var, $custom_code_str);

                        }
                    }
                    $custom_code_str .= $custom_code_str_temp;
                }

               }
            }elseif(stripos($custom_code_str, '{|'.$field->db_field_name.'|}')){

                    $custom_code_str = str_replace('{|'.$field->db_field_name.'|}', '$'.$var_name, $custom_code_str);
                    $custom_code_str_temp = '';

                    $custom_code_str .= $custom_code_str_temp;
            }

    //        $fields[$var_name] = $$var_name = $instance->getFieldValue($field);
            if($entities_type[$instance->fk_eid] == 'os_cck_entity'){
                $fields[$var_name] = $$var_name = $instance->getFieldValue($field);
            }elseif($entities_type[$instance->fk_eid] == 'joomla_user'){
              //$user = JFactory::getUser($child_instance->eiid);
              $fields[$var_name] = $$var_name = $instance->getFieldValue($field, $entities_type[$instance->fk_eid], $user_profile_form, $user);

            }elseif($entities_type[$instance->fk_eid] == 'custom_sql'){
              $fields[$var_name] = $$var_name = $instance->getFieldValue($field, $entities_type[$instance->fk_eid]);
            }
            //var_dump($fields);

          }
      }
      // var_dump(stripos($custom_code_str, '{|cck_instance_id|}'));
      if(stripos($custom_code_str, '{|cck_instance_id|}') !== false){
        // echo '1111111111111111';
        $var_name = "cust_field_cck_instance_id";
        $custom_code_str = str_replace('{|cck_instance_id|}', '$'.$var_name, $custom_code_str);
        $custom_code_str_temp = '';
// var_dump($custom_code_str);
        $custom_code_str .= $custom_code_str_temp;
        $fields[$var_name] = $$var_name = $instance->eiid;
      }
      if(stripos($custom_code_str, '{|cck_number_of_views|}') !== false){
        // echo '1111111111111111';
        $var_name = "cust_field_cck_number_of_views";
        $custom_code_str = str_replace('{|cck_number_of_views|}', '$'.$var_name, $custom_code_str);
        $custom_code_str_temp = '';
// var_dump($custom_code_str);
        $custom_code_str .= $custom_code_str_temp;
        $fields[$var_name] = $$var_name = $instance->hits;
      }
      if(!empty($child_entities)){
          $child_instancies = getChildInstancies($child_entities, $instance);

          foreach($child_instancies['child_istancies'] as $childEntityId => $childInstancies){

              $childEntity = new os_cckEntity($db->_db);
              $childEntity->load($childEntityId);

              foreach($childInstancies as $child_instance_id => $child_instance){
                  //var_dump($child_instancies);
                  $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'){

                    $user = JFactory::getUser($child_instance_id);
                  }
                  if(!$profile_and_custom_field_init){
                      $user_profile_form = '';
                  }else{

                      JPluginHelper::importPlugin('user');
                      JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
                      $user_profile_form = JForm::getInstance('com_users.user', 'profile');
                      $results2 = $app->triggerEvent('onContentPrepareData', array('com_users.user', $user));
                      $results = $app->triggerEvent('onContentPrepareForm', array($user_profile_form, $user));
                      $user_profile_form->bind($user);
                  }

                  foreach($child_instancies['child_instancies_fields'][$childEntityId][$child_instance_id] as $temp_child_entity){

                      if(strpos($custom_code_str,"{|".$temp_child_entity->data_field_name."|}") || strpos($custom_code_str,"{|f-".$temp_child_entity->data_field_name."|}")){

                          if($childEntity->type == 'os_cck_entity'){

                            $field = new os_cckEntityField($db->_db);
                            $field->load($temp_child_entity->childEntityFields);
                          }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;
                                  }
                              }
                          }

                          if($child_instance->eiid){
                            if($entities_type[$child_instance->fk_eid] == 'os_cck_entity'){
                                $value = $child_instance->getFieldValue($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'){
                              $value = $child_instance->getFieldValue($field, $entities_type[$child_instance->fk_eid]);
                            }
                          }else{
                            $value_class = new stdClass();
                            $value_class->data = null;
                            $value = array();
                            $value[] = $value_class;
                          }

                          $field->db_field_name = $temp_child_entity->data_field_name;

                          $var_name = "cust_field_p_ch_".$field->fid;
//                          var_dump($var_name);
                          if(strpos($custom_code_str,"{|".$temp_child_entity->data_field_name."|}")){
                            $custom_code_str = str_replace('{|'.$field->db_field_name.'|}', '$'.$var_name, $custom_code_str);
                          }else{
                              $custom_code_str = str_replace('{|f-'.$field->db_field_name.'|}', '$'.$var_name, $custom_code_str);
                          }

                          $fields[$var_name] = $$var_name = $value;
                      }
//                      if(strpos($custom_code_str,"{|f-".$temp_child_entity->data_field_name."|}")){
//                          $child_str = explode("{|f-" . $temp_child_entity->data_field_name . "|}", $custom_code_str);
//
//                            $child_str[] = '{|f-' . $temp_child_entity->data_field_name. '|}";';
//                            $child_str[] = " echo '". $childs['castom_childs'] . "';";
//                            var_dump($child_str);
//                            $temp = $child_str[1];
//                            $temp = substr($temp, 4);
//
//                            unset($child_str[1]);
//                            $child_str[] = $temp;
//
//                            $child_str = implode($child_str);
//                      }
                  }
              }
          }
      }
      if(isset($child_str)){
          $custom_code_str = $child_str;
      }
      //var_dump($custom_code_str);
      $result = ['custom_code_str' => $custom_code_str,
          'variables_arr'=>$fields,
          'childs_html' => $childs];
      }
      //var_dump($result); exit;
      return $result;
  }
}

if (!function_exists('addChildSelectToCustomCode')) {
    function addChildSelectToCustomCode ($instance,$custom_code_str,$layout_params, $layout_html, $layout){
        global $entityFieldLists;

        $field_list = $entityFieldLists[$layout->fk_eid];
        $fields = [];
        $childs = '';
//      foreach ($instance->getFields() as  $field) {
      foreach ($field_list as  $field) {
          $fid = (property_exists($field, 'fid')) ? $field->fid : '';
        $var_name = "cust_field_".$fid;
        //get childs for select lists
        if(property_exists($field, 'field_type') && $field->field_type == 'text_select_list' && stripos($custom_code_str, (string)$fid)){
           $childs = addChildSelectToLayout($field_list, $instance, $layout_params, $layout_html, $layout, $field->fid);
           if(isset($childs['castom_childs'])){
            $childs = $childs['castom_childs'];

            if(stripos($custom_code_str, "{|f-" . $fid . "|}") >= 0){
                //insert childs in custom code html
                $child_str = explode("{|f-" . $fid . "|}", $custom_code_str);

                $child_str[] = '{|f-' . $fid . '|}';
                $child_str[] = $childs;
                $temp = $child_str[1];
                //$temp = substr($temp, 4);

                unset($child_str[1]);
                $child_str[] = $temp;

                $child_str = implode($child_str);

            }
           }
           $fields[$var_name] = $$var_name = $instance->getFieldValue($field);
        }




      }
      if(isset($child_str)){
          $custom_code_str = $child_str;
      }
      //var_dump($custom_code_str);
      $result = ['custom_code_str' => $custom_code_str, 'variables_arr'=>$fields];

      return $result;
    }

}


if (!function_exists('recurseSelectTree')) {
  function recurseSelectTree($fid, $instance, $array = array()){
      global $entityFieldLists;
      //check parent select and add child to list

//      $fieldObject = $instance->getField($fid);
      $fieldObject = $entityFieldLists[$instance->fk_eid][$fid];
      $temp_value = $instance->getSelectFieldValue($fid);
      if($temp_value) {
          $fValue = json_decode($temp_value);
      }else{
          $fValue = '';
      }

      if(is_object($fValue)) {
          return $array;
      }
      $fValue = (isset($fValue) && $fValue && $fValue[0] != '') ? $fValue : '';
      //if select value - not selected, return before gathering "array"
      if($fValue == '') return $array;
      //if select value array with count more 1(we not work with multi select), return before gathering "array"
      if( is_array($fValue) && count($fValue) != 1 ) return $array;

      $fParams = new JRegistry;
      try {
          $fParams = $fParams->loadString($fieldObject->params);
      } catch (Exception $ex) {
          var_dump($fieldObject->params); exit;
      }
      
      $field_have_child = false;
      // PregExp : digitals before | (not 0) ;or digitals after  | (not 0 )
      // preg_match("/([1-9]\d*\|)|(\|[1-9])/", $fParams->get('child_select',''),$matches ) ; if( count($matches) > 0)...
      if( preg_match("/([1-9]\d*\|)|(\|[1-9])/", $fParams->get('child_select','') ) ){
          $field_have_child = true;
      }
      //if not have child , return before gathering "array"
      if( !$field_have_child ) return $array;

      $fChild = explode('|',$fParams->get('child_select',''));


      // $fValues = explode('\sprt',$fParams->get('allowed_value',''));

      // $fChild = array_combine($fValues, $fChild);

      // foreach ($fValues as $value) {
      //   $value_array = explode('|',$value);
      //   if($fValue[0] == $value_array[0]) $fValue = $value;
      // }
      // if(is_array($fValue)){
      //     $fValue = '0';
      // }

      if(isset($fChild[$fValue[0] ]) && $fChild[$fValue[0] ] != 0 ){

        $array[] = $fChild[$fValue[0] ];
        return recurseSelectTree($fChild[$fValue[0] ], $instance, $array);
      }else{

        return $array;
      }

  }
}

if (!function_exists('cck_getMonth')) {
  function cck_getMonth($month){
      switch ($month) {
        case 1:
            $smonth = cck_lang_text('COM_OS_CCK_JANUARY');
            break;
        case 2:
            $smonth = cck_lang_text('COM_OS_CCK_FEBRUARY');
            break;
        case 3:
            $smonth = cck_lang_text('COM_OS_CCK_MARCH');
            break;
        case 4:
            $smonth = cck_lang_text('COM_OS_CCK_APRIL');
            break;
        case 5:
            $smonth = cck_lang_text('COM_OS_CCK_MAY');
            break;
        case 6:
            $smonth = cck_lang_text('COM_OS_CCK_JUNE');
            break;
        case 7:
            $smonth = cck_lang_text('COM_OS_CCK_JULY');
            break;
        case 8:
            $smonth = cck_lang_text('COM_OS_CCK_AUGUST');
            break;
        case 9:
            $smonth = cck_lang_text('COM_OS_CCK_SEPTEMBER');
            break;
        case 10:
            $smonth = cck_lang_text('COM_OS_CCK_OCTOBER');
            break;
        case 11:
            $smonth = cck_lang_text('COM_OS_CCK_NOVEMBER');
            break;
        case 12:
            $smonth = cck_lang_text('COM_OS_CCK_DECEMBER');
            break;
    }

    return $smonth;

  }
}

if (!function_exists('getEventCCK')) {
  function getEventCCK($calenDate,$date){

    foreach ($calenDate as $value) {
      if(stripos($date, $value[1]) !== false) return array('date'=>$date,'count'=>$value[0]);
//      if($value[1] == $date) return array('date'=>$date,'count'=>$value[0]);
    }
    return false;
  }
}

if (!function_exists('cck_getMonthSchedule')) {
  function cck_getMonthSchedule($month, $year, $calendarParams){
    global $database;

      $database = JFactory::getDbo();
      $skip = date("w", mktime(0, 0, 0, $month, 1, $year)) - 1;
      if ($skip < 0){
        $skip = 6;
      }
      $daysInMonth = date("t", mktime(0, 0, 0, $month, 1, $year));
      $calendar = '';
      $day = 1;
      $smonth = cck_getMonth($month);

      $calendar = "<div class='schedule_main'>";
      $calendar .= "<div class='schedule_month_year'>$smonth $year</div>";

      //isset events in months
      $compare_date = date('Y-m',strtotime($year."-".$month));
      $isset_date_array = array();
      foreach ($calendarParams['item_infos'] as $key => $value){
        if($calendarParams['events_over_years']){
            $key = date('Y-'). $key;
        }
        if(!in_array($key,$isset_date_array)){
          $isset_date_array[] = date('Y-m',strtotime($key));
        }
      }

      if(!in_array($compare_date, $isset_date_array)){
        $calendar .= "<div class='schedule_not_event'>". cck_lang_text('COM_OS_CCK_NO_EVENT') ."</div>";
        $calendar .= "</div>";

        return $calendar;
      }
      //isset events in months

      for ($i = 0; $i < 6; $i++) {
        // $calendar .= '<tr>';
        for ($j = 0; $j < 7; $j++) {
          if (($skip > 0) or ($day > $daysInMonth)){
            // $calendar .= '<td> &nbsp; </td>';
            $skip--;
          }else{

            $date = strtotime($day.'-'.$month.'-'.$year);
            $date = date('Y-m-d',$date);
            $dateEvent = getEventCCK($calendarParams['calenDate'],$date);

            if(strtotime($date) < strtotime('-1 day') && !$calendarParams['show_past_events']){
              $dateEvent = false;
            }

            if(is_array($dateEvent)){
                if($calendarParams['events_over_years']){
                    $dateEvent['date'] = substr($dateEvent['date'], 5);
                }
                $events_string = '';
                if(isset($calendarParams['item_infos'][$dateEvent['date']])
                  && is_array($calendarParams['item_infos'][$dateEvent['date']])){
                  $item_infos = $calendarParams['item_infos'][$dateEvent['date']];
                }

                $eiids = array();
                foreach ($item_infos as $date => $item_info) {
                  $eiids[$date] = $item_info['eiid'];
                }

                $instances = array();
                foreach ($calendarParams['instancies'] as $key => $instance) {
                  if(in_array($instance->eiid, $eiids)) $instances[] = $instance;
                }

                $items = array();
                foreach ($instances as $key => $instance) {

                  $items[] = $instance;

                  ob_start();

                    echo "<div class='shedule_event'>";

                    Category::show_attached_layout($calendarParams['option'], $calendarParams['schedule_instance_lid'] ,$calendarParams['layout_fk_eid'], $calendarParams['layout_params'], '', '', 0, $items, '');

                    echo "</div>";
                  $events_string  .= ob_get_contents();
                  ob_end_clean();

                  $items = array();
                }

                if(isset($calendarParams['calendar_view']) && $calendarParams['calendar_view'] == 'small'){
                  $events_string = '';
                }

                $calendar .= "<div class='schedule_item row row-fluid ".$calendarParams['custom_class']."'>";

                //show/hide header date
                if($calendarParams['show_header'] == 1){
                  $calendar .= "<div ".$calendarParams['field_styling_table_header']." class='schedule_date col-lg-2 span2'>";
                    $calendar .=
                    "<a href='".JRoute::_("index.php?option=com_os_cck&view=all_instance&lid=".$calendarParams['all_instance_lid']."&event_date=".$dateEvent['date']."&event_date_field=".$calendarParams['event_date_field'].
                      "&Itemid=".$calendarParams['Itemid'])."'>".
                      date($calendarParams['header_format'], strtotime($year."-".$month."-".$day))
                    .'</a>';
                  $calendar .= "</div>";
                }

                  $calendar .= "<div class='schedule_event_list col-lg-10 span10'>";
                    $calendar .= $events_string;
                  $calendar .= "</div>";

                $calendar .= "</div>";
            }
            $day++;
          }
        }
        // $calendar .= '</tr>';
      }

      $calendar .= "</div>";

      return $calendar;
  }
}

if (!function_exists('cck_getMonthCal')) {
  function cck_getMonthCal($month, $year, $calendarParams){
    global $database;

      $database = JFactory::getDbo();
      $skip = date("w", mktime(0, 0, 0, $month, 1, $year)) - 1;
      if ($skip < 0){
        $skip = 6;
      }
      $daysInMonth = date("t", mktime(0, 0, 0, $month, 1, $year));
    /*******************************get only rent days*****************************/

      $calendar = '';
      $day = 1;
      $smonth = cck_getMonth($month);
      $calendar = '<div class="table-responsive"><table '.$calendarParams['field_styling'] .' class="cck_tableC table '.$calendarParams['custom_class'].'">
      <tr class="year">
        <th '.$calendarParams['field_styling_table_header'].' colspan = "7">' . $smonth . ' ' . $year . '</th>
      </tr>
      <tr class="days">
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_MON') . '</th>
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_TUE') . '</th>
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_WED') . '</th>
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_THU') . '</th>
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_FRI') . '</th>
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_SAT') . '</th>
        <th '.$calendarParams['field_styling_table_header'].'>' . cck_lang_text('COM_OS_CCK_SUN') . '</th>
      </tr>'
      ;
      for ($i = 0; $i < 6; $i++) {
        if($day > $daysInMonth) continue;
        $calendar .= '<tr>';
        for ($j = 0; $j < 7; $j++) {
          if (($skip > 0) or ($day > $daysInMonth)){
            $calendar .= '<td> &nbsp; </td>';
            $skip--;
          }else{

            $date = strtotime($day.'-'.$month.'-'.$year);
            $date = date('Y-m-d',$date);
            $dateEvent = getEventCCK($calendarParams['calenDate'],$date);
//            var_dump($dateEvent);
            if(strtotime($date) < strtotime('-1 day') && !$calendarParams['show_past_events']){
              $dateEvent = false;
            }

            if(is_array($dateEvent)){

                $events_string = '';

                if($calendarParams['events_over_years']){
                    $dateEvent['date'] = substr($dateEvent['date'], 5);
                }
                if(isset($calendarParams['item_infos'][$dateEvent['date']])
                  && is_array($calendarParams['item_infos'][$dateEvent['date']])){
                  $item_infos = $calendarParams['item_infos'][$dateEvent['date']];
                }

                foreach ($item_infos as $key => $item_info) {

                  if($calendarParams['show_time'] != 1){
                    $item_info['time'] = '';
                  }


                  $query = "SELECT cat.name FROM #__os_cck_categories_connect as cc "
                          . "LEFT JOIN #__os_cck_categories as cat ON cat.cid = cc.fk_cid "
                          . "WHERE cc.fk_eiid = " . $item_info['eiid'];
                  $database->setQuery($query);

                  $cat_name = $database->loadResult();
                  // var_dump($cat_name);
                  if($cat_name){
                    $cat_name = str_replace(' ', '_', $cat_name);
                  }else{
                    $cat_name = '';
                  }

                  $redirect_type = (isset($calendarParams['layout_params']['views']['redirect_type'])) ? $calendarParams['layout_params']['views']['redirect_type'] : 'redirect';
                  $target = ($redirect_type == 'redirect_blank') ? 'target="_blank"' : '';

                  if($redirect_type == 'popUp'){

                        $events_string .=  "<div class='event_string calendar_event_" . $cat_name . "'><a href='#' data-toggle='os_cck_modal' data-target='#show_request_layout_".$item_info['time']."_".$item_info['eiid']."' $target><span class=\"cck_calendar_time\">".$item_info['time'].'</span> '.$item_info['title']."</a></div>";

                        $events_string .= '<div class="os_cck_modal fade" id="show_request_layout_' . $item_info['time'] . '_' . $item_info['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();
                        $inst = new os_cckEntityInstance($database);
                        $inst->load($item_info['eiid']);
                        $instancies[$item_info['eiid']] = $inst;

//                        $instancies[$entityInstance->eiid] = $entityInstance;
                        ob_start();

                        Category::show_attached_layout('com_os_cck', $calendarParams['instance_lid'], $item_info['eiid'], $calendarParams['layout_params'], 0, '', 0, $instancies);
                        $events_string .= ob_get_contents();
                        $events_string .= '</div>
                                          
                                        </div>
                                      </div>
                                    </div>';
                        ob_end_clean();

                    }else{

                        $events_string .=  "<div class='event_string calendar_event_" . $cat_name . "'><a href='".JRoute::_("index.php?option=com_os_cck&view=instance&lid=".$calendarParams['instance_lid']."&eiid[0]=".$item_info['eiid'].
                            "&Itemid=".$calendarParams['Itemid'])."' $target><span class=\"cck_calendar_time\">".$item_info['time'].'</span> '.' '.$item_info['title']."</a>";


                        if($redirect_type == 'hover'){
                            $events_string .= '<ul class="os_cck_hover_child">';
                            $instancies = array();
                            $inst = new os_cckEntityInstance($database);
                            $inst->load($item_info['eiid']);
                            $instancies[$item_info['eiid']] = $inst;
                            ob_start();
                            Category::show_attached_layout('com_os_cck', $calendarParams['instance_lid'], $item_info['eiid'], $calendarParams['layout_params'], 0, '', 0, $instancies);
                            $events_string .= ob_get_contents();
                            $events_string .= '</ul>';
                            ob_end_clean();
                        }
                        $events_string .= '</div>';
                    }

//                   $events_string .=  "<div class='event_string calendar_event_" . $cat_name . "'><a href='".JRoute::_("index.php?option=com_os_cck&view=instance&lid=".$calendarParams['instance_lid']."&eiid[0]=".$item_info['eiid'].
//                    "&Itemid=".$calendarParams['Itemid'])."'>".$item_info['time'].' '.$item_info['title']."</a></div>";
                }

                if(isset($calendarParams['calendar_view']) && $calendarParams['calendar_view'] == 'small'){
                  $events_string = '';
                }


                $calendar .= "
                <td class='dateTrue marker_event_date'>
                  <div class='whole_cell'>

                    <div class='event_date'>
                      <a href='".JRoute::_("index.php?option=com_os_cck&view=all_instance&lid=".$calendarParams['all_instance_lid'].
                        "&event_date=".$dateEvent['date'].
                        "&event_date_field=".$calendarParams['event_date_field'].
                        "&Itemid=".$calendarParams['Itemid'])."'>
                        <span class='showDay'>$day</span>
                        <!-- <span class='showCount'>{$dateEvent['count']}</span> --!>
                      </a>
                    </div>
                    <!-- collection event in div tags --!>
                    $events_string
                  
                  </div>
                </td>";
            }else{
              $calendar .= "<td class='dateTrue' ><div class='whole_cell'>$day</div></td>";
            }

            $day++;
          }
        }
        $calendar .= '</tr>';
      }
      $calendar .= '</table></div>';

      return $calendar;
  }
}

if (!function_exists('getCalendar')) {
  function getCalendar($month, $year, $calendarParams){
    $month = (int) $month;
    $year = (int) $year;

    if ($month == 1){
        $month1 = 12;
        $year1 = $year - 1;
    }else{
        $month1 = $month - 1;
        $year1 = $year;
    }

    if ($month == 12){
      $month2 = 1;
      $month3 = 2;
      $month4 = 3;
      $month5 = 4;
      $month6 = 5;
      $month7 = 6;
      $month8 = 7;
      $month9 = 8;
      $month10 = 9;
      $month11 =10;
      $month12 = 11;
      $month13 = 12;
      $year2 = $year3 = $year4 = $year5
      = $year5 = $year6 = $year7 = $year8
      = $year9 = $year10 = $year11 = $year12 = $year13  = $year + 1;
    }else{
      $month2 = $month + 1;
      $month3 = $month + 2;
      $month4 = $month + 3;
      $month5 = $month + 4;
      $month6 = $month + 5;
      $month7 = $month + 6;
      $month8 = $month + 7;
      $month9 = $month + 8;
      $month10 = $month + 9;
      $month11 = $month + 10;
      $month12 = $month + 11;
      $month13 = $month + 12;
      $year2 =$year3 = $year4 =$year5
      = $year6 =$year7 = $year8 =$year9
      = $year10 =$year11 = $year12 =$year13 = $year;
    }

    if($month3 > 12){
      $month3 = $month3 - 12;
      $year3 = $year + 1;
    }

    if($month4 > 12){
      $month4 = $month4 - 12;
      $year4 = $year + 1;
    }

    if($month5 > 12){
      $month5 = $month5 - 12;
      $year5 = $year + 1;
    }

    if($month6 > 12){
      $month6 = $month6 - 12;
      $year6 = $year + 1;
    }

    if($month7 > 12){
      $month7 = $month7 - 12;
      $year7 = $year + 1;
    }

    if($month8 > 12){
      $month8 = $month8 - 12;
      $year8 = $year + 1;
    }

    if($month9 > 12){
      $month9 = $month9 - 12;
      $year9 = $year + 1;
    }

    if($month10 > 12){
      $month10 = $month10 - 12;
      $year10 = $year + 1;
    }

    if($month11 > 12){
      $month11 = $month11 - 12;
      $year11 = $year + 1;
    }

    if($month12 > 12){
      $month12 = $month12 - 12;
      $year12 = $year + 1;
    }

    if($month13 > 12){
      $month13 = $month13 - 12;
      $year13 = $year + 1;
    }

    $function_name = ($calendarParams['calendar_view'] == 'schedule')?'cck_getMonthSchedule':'cck_getMonthCal';

    $calendar = new stdClass();


    $calendar->tab1 = $function_name($month1, $year1, $calendarParams);
    $calendar->tab2 = $function_name($month, $year, $calendarParams);
    $calendar->tab3 = $function_name($month2, $year2, $calendarParams);
    $calendar->tab4 = $function_name($month3, $year3, $calendarParams);
    $calendar->tab5 = $function_name($month4, $year4, $calendarParams);
    $calendar->tab6 = $function_name($month5, $year5, $calendarParams);
    $calendar->tab7 = $function_name($month6, $year6, $calendarParams);
    $calendar->tab8 = $function_name($month7, $year7, $calendarParams);
    $calendar->tab9 = $function_name($month8, $year8, $calendarParams);
    $calendar->tab10 = $function_name($month9, $year9, $calendarParams);
    $calendar->tab11 = $function_name($month10, $year10, $calendarParams);
    $calendar->tab12 = $function_name($month11, $year11, $calendarParams);
    $calendar->tab13 = $function_name($month12, $year12, $calendarParams);
    $calendar->tab14 = $function_name($month13, $year13, $calendarParams);

    return $calendar;
  }
}

if(!function_exists('createSettingsOptions')){
    function createSettingsOptions($fields, $default = false){
      $options = array();
      if($default) $options[] = JHTML::_('select.option','-1','none');

      foreach($fields as $value) {
          $options[] = JHTML::_('select.option',$value['value'],$value['text']);
      }
      return $options;
    }
}



if(!function_exists('protectInjection')){
    function protectInjection($element, $def = '', $filter = "STRING",$bypass_get=false){
        global $db;
        $db = new os_cckDb();
        if(!$bypass_get){
                if($filter == "password")
                    $value = JFactory::getApplication()->input->get($element, $def, "raw");
                else $value = JFactory::getApplication()->input->get($element, $def, $filter);
                // $value = $element;
             }else{
                $value = $element;
             }

        if(empty($value)) return $def;



        if(is_array($value)){
            foreach($value as $key=>$item_value){
                $value[$key] = $db->quote($item_value);
            }
            return $value ;

        }

        return $db->quote($value);
    }
}


if(!function_exists('protectInjectionWithoutQuote')){
    function protectInjectionWithoutQuote($element, $def = '', $filter = "STRING", $bypass_get=false){
        global $db;
        require_once(JPATH_SITE . "/components/com_os_cck/classes/cckDb.class.php");
        $db = new os_cckDb();
        if(!$bypass_get){
                if($filter == "password")
                    $value = JFactory::getApplication()->input->get($element, $def, "raw");
                else $value = JFactory::getApplication()->input->get($element, $def, $filter);
                // $value = $element;
             }else{
                $value = $element;
             }

        if(empty($value)) return $def;
        $special_symb = array("/*","*/","select", "insert", "update", "drop", "delete", "alter", "truncate");

        if(is_array($value)){
            foreach($value as $key => $val){

                if(!is_array($val)){
                    $isset_spec_symb = false;
                    foreach($special_symb as $symb){
                        $indx = stripos($val, $symb);
                        if($indx  !== false){
                            if($indx == 0 && preg_match('#'.$symb.'[0-9a-zA-Z@]+#i', $val)==0 ){
                                $isset_spec_symb = true;
                                continue;
                            } else if($indx > 0 && preg_match('#[0-9a-zA-Z@]+'.$symb.'#i', $val)==0 ){
                                $isset_spec_symb = true;
                                continue;
                            }
                        }
                    }

                    if($isset_spec_symb){
                        $val = protectInjection($val, $def , $filter ,true);
                    }else{
                        $val = protectInjectionWithoutQuote($val, $def , $filter ,true);
                    }
                }else{
                    $val = protectInjectionWithoutQuote($val, $def , $filter ,true);
                }
                $value[$key] = $val;
            }
        }else {
            $isset_spec_symb = false;
            foreach($special_symb as $symb){
                $indx = stripos($value, $symb);
                if($indx !== false){
                    if($indx == 0 && preg_match('#'.$symb.'[0-9a-zA-Z@]+#i', $value)==0 ){
                        $isset_spec_symb = true;
                        continue;
                    } else if($indx > 0 && preg_match('#[0-9a-zA-Z@]+'.$symb.'#i', $value)==0 ){
                        $isset_spec_symb = true;
                        continue;
                    }
                }
            }

            if($isset_spec_symb){
                $value = protectInjection($value, $def , $filter ,true);
            }elseif( $filter == "password" ){
                $value = $value;
            }else{
                $value = $db->escape($value);
            }

        }

        return $value;
    }
}

if(!function_exists('prepere_field_for_show')){
function prepere_field_for_show($field, $value,$row=0)
{
    global $moduleId ;
    $field->options['strlen'] = 100;
    $field->options['width'] = 100;
    $field->options['height'] = 100;
    if ($field->published != "1") return "";
    $ftype = $field->field_type;
    $global_settings = isset($field->global_settings) ? unserialize($field->global_settings) : '';
    $db_columns = isset($field->db_columns) ? unserialize($field->db_columns) : '';
    $sufix = '';
    if ($ftype == 'text_textfield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = (strlen($value) > $field->options['strlen']) ? substr($value, 0, $field->options['strlen']) . "..." : $value;
        return $return;
    }elseif ($ftype == 'categoryfield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = $value;
        return $return;
    }elseif ($ftype == 'decimal_textfield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = $value;
        return $return;
    }elseif ($ftype == 'rating_field') {
        return '<img src="'.JURI::root().'/components/com_os_cck/images/rating-'.($value->data*2).'.png"
                alt="'.$value->data.'" border="0"/>&nbsp;';
    } else if ($ftype == 'datetime_popup') {

        $value = (isset($value->data) && $value->data != '0000-00-00 00:00:00') ? $value->data : '';
        $format=(isset($global_settings['output_format']) && $global_settings['output_format']!="") ? ($global_settings['output_format']) : 'Y-m-d';
        $value = date(str_replace('%','',$format), strtotime($value));
        return $value;
    } else if ($ftype == 'filefield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = '<a href="' . JURI::root() . $value . '" > download </a>';
        return $return;
    } else if ($ftype == 'imagefield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        $width_heigth = (isset($field->options['width'])) ? ' width="' . $field->options['width'] . 'px" ' : '';
        $width_heigth .= (isset($field->options['height'])) ? ' height="' . $field->options['height'] . 'px" ' : '';
        if ($value != '') {
            $image = show_image_cck($value, $field->options['width'], $field->options['height']);
            $return = '<img src="' . JURI::root() . $image . '"  /><br />';
        }
        return $return;
    } else if ($ftype == 'locationfield') {
        $layout_params = array();
        $layout_params['map_field_name'] = $field->field_name;
        $width = (isset($field->options['width'])) ? $field->options['width'] : '';
        $heigth = (isset($field->options['height'])) ? $field->options['height'] : '';
        $field->settings = unserialize($field->global_settings);
        if($row){
            $fieldName=str_replace(' ','_',($row->title.'_'.$field->field_name));
        }else{
            $fieldName=str_replace(' ','_',$field->field_name);
        }
        ob_start();
        showLocationMap($layout_params,false, $fieldName
            , $value->{$field->field_name . "_vlat"}
            , $value->{$field->field_name . "_vlong"}
            , $value->{$field->field_name . "_zoom"}
            , $value->{$field->field_name . "_adress"}
            , $field->settings['maptype']
            , $width
            , $heigth

        );

        $return = ob_get_contents();
        ob_end_clean();

        return $return;
    }
//    else if ($ftype == 'galleryfield') {
//
//        $width_heigth = (isset($field->options['width'])) ? 'width:' . $field->options['width'] . 'px;' : '';
//        $width_heigth .= (isset($field->options['height'])) ? ' height:' . $field->options['height'] . 'px;' : '';
//        $return = '';
//
//        if(!empty($value) && $images = json_decode(base64_decode($value->data))){
//            $return .= "<div class='gallery_".$field->field_name."' id='gallery_".$field->field_name."'>";
//            $images = json_decode(base64_decode($value->data));
//
//            foreach ($images as $image) {
//                if (!isset($_REQUEST['view']) || $_REQUEST['view'] != 'category')
//                    $return .= '<a href="' . JURI::root() . 'images/com_os_cck' . $field->fid . '/original/' . $image->file . '" data-lightbox="roadtrip_'.$field->field_name.$moduleId.'" title="' . $image->alt . '">';
//                $return .= '<img style="' . $width_heigth . '" src="' . JURI::root() . 'images/com_os_cck' . $field->fid . '/thumbnail/' . $image->file . '"  />';
//                if (!isset($_REQUEST['view']) || $_REQUEST['view'] != 'category') $return .= '</a>';
//                if (isset($_REQUEST['view']) && $_REQUEST['view'] == 'category') break;
//            }
//            return $return . "</div>";
//        }
//    }
    else if ($ftype == 'text_radio_buttons') {
        $value = (isset($value->data)) ? $value->data : '';
      $return = '';
      $arr = array();
      $allowed_values = urlencode($global_settings['allowed_values']);
      if (strpos($allowed_values, '%0D%0A') !== false) $allowed_values = explode('%0D%0A', $allowed_values);
      else if (strpos($allowed_values, '%0D') !== false) $allowed_values = explode('%0D', $allowed_values);
      else if (strpos($allowed_values, '%0A') !== false) $allowed_values = explode('%0A', $allowed_values);
      else return "Bad set 'allow value' for this field!";
      foreach ($allowed_values as $item) {
          $key_value = explode('%7C', $item);
          if ($key_value[0] == $value) $return = (isset($key_value[1]))?urldecode($key_value[1]):urldecode($key_value[0]);
      }
      return $return;
    } else if ($ftype == 'text_select_list') {
        $value = (isset($value->data)) ? $value->data : '';
          $return = '';
          $arr = array();
          $allowed_values = $global_settings['allowed_values'];
          $allowed_values = urlencode($allowed_values);
          if (strpos($allowed_values, '%0D%0A') !== false) $allowed_values = explode('%0D%0A', $allowed_values);
          else if (strpos($allowed_values, '%0D') !== false) $allowed_values = explode('%0D', $allowed_values);
          else if (strpos($allowed_values, '%0A') !== false) $allowed_values = explode('%0A', $allowed_values);
          else return "Bad set 'allow value' for this field!";
          foreach ($allowed_values as $key => $allow_value) {
            $allow_value = str_replace("+", ' ', $allow_value);
            $allowed_values[$key] = trim(urldecode($allow_value));
          }
          foreach ($allowed_values as $item) {
              //echo ":1111111111:".$item.":1111111111:".$value.":1111111111:";
              $key_value = explode('|', $item);
              if(!isset($key_value[0]) && isset($key_value[1])){
                $key_value[0] = str_replace(' ', '', $key_value[1]);
              }
              //print_r($key_value);
              if($key_value[0] !== 0){
                if ($key_value[0] == $value and count($key_value) > 1) $return = $key_value[1];
                else if ($key_value[0] == $value) $return = $key_value[0];
              }
          }
          return $return;
    } else if ($ftype == 'text_single_checkbox_onoff') {
        $value = (isset($value->data)) ? $value->data : '';
      $return = '';
      $arr = array();
      $allowed_values = str_replace(' ', '', $global_settings['allowed_values']);
      $allowed_values = urlencode($allowed_values);
      if (strpos($allowed_values, '%0D%0A') !== false) $allowed_values = explode('%0D%0A', $allowed_values);
      else if (strpos($allowed_values, '%0D') !== false) $allowed_values = explode('%0D', $allowed_values);
      else if (strpos($allowed_values, '%0A') !== false) $allowed_values = explode('%0A', $allowed_values);

      foreach ($allowed_values as $key => $item) {
        $key_value = explode('%7C', $item);
        if (isset($key_value[0]) && isset($key_value[1]) && $key_value[0] == $value) $return = urldecode($key_value[1]);
        else if (isset($key_value[0]) && !isset($key_value[1]) && $key_value[0] == $value) $return = urldecode($key_value[0]);
        else if (!isset($key_value[0]) && isset($key_value[1]) && $key_value[1] == $value) $return = urldecode($key_value[1]);
        else if (count($allowed_values) == 2 && empty($value) && $key == 0){
          if (isset($key_value[0]) && isset($key_value[1]))
            $return = urldecode($key_value[1]);
          else
            $return = urldecode($key_value[0]);
        }
      }
      return $return;

    } else if ($ftype == 'text_textarea') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
//       if($value!=''){
//         $return = '<textarea class="text_area" type="text"  rows="'.$field->options['rows'].'" cols="'.$field->options['cols'].'" readonly="true" > '.$value.'</textarea>' ;
//       }
        if ($value != '') $return = (strlen($value) > $field->options['strlen']) ? substr($value, 0, $field->options['strlen']) . "..." : $value;

        return $return;

    } else if ($ftype == 'text_url') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '' && $value != 'http://') {
            $return = '<a href="' . $value . '">' . $value . '</a>';
        }
        return $return;
    } else {
        return 'Canity test. Error - Bad type sellected!';
    }
}
}

if(!function_exists('cck_sort_head')){
  function cck_sort_head($title, $fieldname, $sort_arr,$task=''){
    global $Itemid;

    $ItemidStr = (isset($_REQUEST['Itemid']) && 
      ($Itemid == 0 || empty($Itemid)) )?"&amp;Itemid=".intval($_REQUEST['Itemid']) : "&amp;Itemid=".$Itemid;
    $img_str = "";
    if($task)
      $task = "&amp;task=$task";
    $direction=$sort_arr['sorting_direction'];
    if ($sort_arr['sorting_direction'] == 'ASC') {
      $img_path = JURI::root().'components/com_os_cck/images/arrow_up.png';
      $img_str = "<img src=\"$img_path\" width=\"12\" height=\"12\" border=\"0\" alt='Sorted up' />";
    } else {
      $img_path = JURI::root().'components/com_os_cck/images/arrow_down.png';
      $img_str = "<img src=\"$img_path\" width=\"12\" height=\"12\" border=\"0\" alt='Sorted up' />";
    }
    //JURI::base() - return mit "administrator" when in admin part run
    //JURI::root() - return without "administrator" when in admin part run
    $str = "<a href='".JURI::base().
      "index.php?option=com_os_cck$task&amp;sort=$fieldname&amp;sorting_direction=$direction".$ItemidStr."'>".
      $title . $img_str . "</a>";
    return $str;
  }
}

if (!function_exists('get_field_styles')) {
  function get_field_styles($field, $layout){
//      var_dump($field);
//      var_dump($layout);

    $layout_params = unserialize($layout->params);
//    if($field->db_field_name == 12){
//        var_dump($layout_params)   ;
//      }
    //var_dump($layout_params);
    $params = new JRegistry;
    if(is_array($field)){
        $field = (object)$field;
    }
//    if(is_object($field) && property_exists($field, 'field_name')){
//        var_dump($field->field_name);
//    }

    if(is_object($field) && property_exists($field, 'field_name') && $field->field_name !== null && stripos($field->field_name, 'm_') === 0){
      return '';
    }
    if(is_string($field) && $field != ''){
        if(isset($layout_params['fields']['Params_' . $field])){
            $params = $params->loadString($layout_params['fields']['Params_' . $field]);
        }else{
            return '';
        }
    }elseif($field == 'cck_search_field'){
        $params = $params->loadString($layout_params['fields']['Params_cck_search_field']);
    }elseif(is_string($field) && stripos($field, 'e-') !== FALSE){
        $params = $params->loadString($layout_params['fields']['Params_'.$field]);
        //var_dump($params);
    }
    elseif($field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }elseif(is_int ($field->db_field_name)){
      if(isset($layout_params['fields']['Params_l'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_l'.$field->db_field_name]);
      }
    }else{

      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }
    //var_dump($params);
    //styling
    //margin
    if($params->get("margin")){
      $marginPx = 'px';
    }else{
      $marginPx = '%';
    }


    if($params->get('marginTop','') == '0'){
      $margin_top = '0';
    }else{
      $margin_top = ($params->get('marginTop',''))? $params->get('marginTop').$marginPx : '';
    }

    if($params->get('marginRight','') == '0'){
      $margin_right = '0';
    }else{
      $margin_right = ($params->get('marginRight',''))? $params->get('marginRight').$marginPx : '';
    }

    if($params->get('marginBottom','') == '0'){
      $margin_bottom = '0';
    }else{
      $margin_bottom = ($params->get('marginBottom',''))? $params->get('marginBottom').$marginPx : '';
    }

    if($params->get('marginLeft','') == '0'){
      $margin_left = '0';
    }else{
      $margin_left = ($params->get('marginLeft',''))? $params->get('marginLeft').$marginPx : '';
    }


    // $margin_top = ($params->get('marginTop',''))? $params->get('marginTop').$marginPx : '';
    // $margin_right = ($params->get('marginRight',''))? $params->get('marginRight').$marginPx : '';
    // $margin_bottom = ($params->get('marginBottom',''))? $params->get('marginBottom').$marginPx : '';
    // $margin_left = ($params->get('marginLeft',''))? $params->get('marginLeft').$marginPx : '';

    //padding
    if($params->get("padding")){
      $paddingPx = 'px';
    }else{
      $paddingPx = '%';
    }

    if($params->get('paddingTop','') == '0'){
      $padding_top = '0';
    }else{
      $padding_top = ($params->get('paddingTop',''))? $params->get('paddingTop').$paddingPx : '';
    }

    if($params->get('paddingRight','') == '0'){
      $padding_right = '0';
    }else{
      $padding_right = ($params->get('paddingRight',''))? $params->get('paddingRight').$paddingPx : '';
    }

    if($params->get('paddingBottom','') == '0'){
      $padding_bottom = '0';
    }else{
      $padding_bottom = ($params->get('paddingBottom',''))? $params->get('paddingBottom').$paddingPx : '';
    }

    if($params->get('paddingLeft','') == '0'){
      $padding_left = '0';
    }else{
      $padding_left = ($params->get('paddingLeft',''))? $params->get('paddingLeft').$paddingPx : '';
    }



    // $padding_top = ($params->get('paddingTop',''))? $params->get('paddingTop').$paddingPx : '';
    // $padding_right = ($params->get('paddingRight',''))? $params->get('paddingRight').$paddingPx : '';
    // $padding_bottom = ($params->get('paddingBottom',''))? $params->get('paddingBottom').$paddingPx : '';
    // $padding_left = ($params->get('paddingLeft',''))? $params->get('paddingLeft').$paddingPx : '';

    //background-color
    $background_color = ($params->get('backgroundColor',''))? $params->get('backgroundColor') : '';
    //border
    $border = ($params->get('borderSize',''))? $params->get('borderSize').'px' : '';
    //border-color
    $border_color = ($params->get('borderColor',''))? $params->get('borderColor') : '';
    //custom class
    $custom_class = ($params->get('customClass',''))? $params->get('customClass') : '';
    //end styling
    //font_size
    $font_size = ($params->get('fontSize',''))? $params->get('fontSize') : '';
    //font_weight
    $font_weight = $params->get('fontWeight', 1);

    //font_color
    $font_color = ($params->get('fontColor',''))? $params->get('fontColor') : '';
    $align = ($params->get('text_align',''))? $params->get('text_align') : '';
    $width = ($params->get('width',''))? $params->get('width') : '';
    $formWidth = ($params->get('formWidth', '')) ? $params->get('formWidth', '') : '';

    //var_dump($align);
    $field_style = 'style="';
    //margin

    if(($margin_top || $margin_top == 0) && $margin_top != '')
      $field_style .= 'margin-top:'.$margin_top.';';
    if(($margin_right || $margin_right == 0) && $margin_right != '')
      $field_style .= 'margin-right:'.$margin_right.';';
    if(($margin_bottom || $margin_bottom == 0) && $margin_bottom != '')
      $field_style .= 'margin-bottom:'.$margin_bottom.';';
    if(($margin_left || $margin_left == 0) && $margin_left != '')
      $field_style .= 'margin-left:'.$margin_left.';';
    //padding
    if(($padding_top || $padding_top == 0) && $padding_top != '')
      $field_style .= 'padding-top:'.$padding_top.';';
    if(($padding_right || $padding_right == 0) && $padding_right != '')
      $field_style .= 'padding-right:'.$padding_right.';';
    if(($padding_bottom || $padding_bottom == 0) && $padding_bottom != '')
      $field_style .= 'padding-bottom:'.$padding_bottom.';';
    if(($padding_left || $padding_left == 0) && $padding_left != '')
      $field_style .= 'padding-left:'.$padding_left.';';
    //background-color
    if($background_color)
      $field_style .= 'background-color:'.$background_color.';';
    //border
    if($border)
      $field_style .= 'border:'.$border.' solid;';
    //border-color
    if($border_color)
      $field_style .= 'border-color:'.$border_color.';';
    //border-color
    if($font_size){
      $field_style .= 'font-size:'.$font_size.'px;';
      $field_style .= 'line-height:'.$font_size.'px;';
    }
    //border-color

    if($font_weight)
      $field_style .= 'font-weight:normal;';
    else
      $field_style .= 'font-weight:bold;';
    //border-color
    if($font_color)
      $field_style .= 'color:'.$font_color.';';
    //text-align

    if($align && $field != 'cck_search_field')
      $field_style .= 'text-align:'.$align.';';

    if($width){

        if(isset($field->field_type) && ($field->field_type == 'text_single_checkbox_onoff' || $field->field_type == 'text_radio_buttons') && $layout->type == 'add_instance'){


        }else{
            $field_style .= 'width:'.$width.';';
        }
    }
    if($formWidth){
        $field_style .= 'width:'.$formWidth.'px;';
    }
    $field_style .= '"';



    return $field_style;
  }
}

if (!function_exists('get_field_styles_width_only')) {
  function get_field_styles_width_only($field, $layout){
    $layout_params = unserialize($layout->params);
    $params = new JRegistry;
    if(is_array($field)){
        $field = (object)$field;
    }
    if($field == 'cck_send_button'){
        $params = $params->loadString($layout_params['fields']['Params_cck_send_button']);
    }elseif($field == 'cck_search_field'){
        $params = $params->loadString($layout_params['fields']['Params_cck_search_field']);
    }
    elseif($field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }else{

      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }

    $width = ($params->get('width',''))? $params->get('width') : '';

    $field_style = 'style="display:block;';

    if($width){
        $field_style .= 'width:'.$width.';';
        $field_style .= '"';
        return $field_style;
    }else{
        return '';
    }




  }
}

if (!function_exists('get_field_label_styles')) {
  function get_field_label_styles($params){

    if($params != '{}' && $params != ''){
        $params = json_decode($params);



        //styling
        //margin
        if($params->labelMargin){
          $marginPx = 'px';
        }else{
          $marginPx = '%';
        }


        if($params->labelMarginTop == '0'){
          $margin_top = '0';
        }else{
          $margin_top = ($params->labelMarginTop)? $params->labelMarginTop . $marginPx : '';
        }

        if($params->labelMarginRight == '0'){
          $margin_right = '0';
        }else{
          $margin_right = ($params->labelMarginRight)? $params->labelMarginRight.$marginPx : '';
        }

        if($params->labelMarginBottom == '0'){
          $margin_bottom = '0';
        }else{
          $margin_bottom = ($params->labelMarginBottom)? $params->labelMarginBottom.$marginPx : '';
        }

        if($params->labelMarginLeft == '0'){
          $margin_left = '0';
        }else{
          $margin_left = ($params->labelMarginLeft)? $params->labelMarginLeft.$marginPx : '';
        }


        // $margin_top = ($params->get('marginTop',''))? $params->get('marginTop').$marginPx : '';
        // $margin_right = ($params->get('marginRight',''))? $params->get('marginRight').$marginPx : '';
        // $margin_bottom = ($params->get('marginBottom',''))? $params->get('marginBottom').$marginPx : '';
        // $margin_left = ($params->get('marginLeft',''))? $params->get('marginLeft').$marginPx : '';

        //padding
        if($params->labelPadding){
          $paddingPx = 'px';
        }else{
          $paddingPx = '%';
        }

        if($params->labelPaddingTop == '0'){
          $padding_top = '0';
        }else{
          $padding_top = ($params->labelPaddingTop)? $params->labelPaddingTop.$paddingPx : '';
        }

        if($params->labelPaddingRight == '0'){
          $padding_right = '0';
        }else{
          $padding_right = ($params->labelPaddingRight)? $params->labelPaddingRight.$paddingPx : '';
        }

        if($params->labelPaddingBottom == '0'){
          $padding_bottom = '0';
        }else{
          $padding_bottom = ($params->labelPaddingBottom)? $params->labelPaddingBottom.$paddingPx : '';
        }

        if($params->labelPaddingLeft == '0'){
          $padding_left = '0';
        }else{
          $padding_left = ($params->labelPaddingLeft)? $params->labelPaddingLeft.$paddingPx : '';
        }



        // $padding_top = ($params->get('paddingTop',''))? $params->get('paddingTop').$paddingPx : '';
        // $padding_right = ($params->get('paddingRight',''))? $params->get('paddingRight').$paddingPx : '';
        // $padding_bottom = ($params->get('paddingBottom',''))? $params->get('paddingBottom').$paddingPx : '';
        // $padding_left = ($params->get('paddingLeft',''))? $params->get('paddingLeft').$paddingPx : '';

        //background-color
        $background_color = (isset($params->labelBackgroundColor))? $params->labelBackgroundColor : '';
        //border
        $border = (isset($params->labelBorderSize))? $params->labelBorderSize.'px' : '';
        //border-color
        $border_color = (isset($params->labelBorderColor))? $params->labelBorderColor : '';
        //custom class
        $custom_class = (isset($params->labelCustomClass))? $params->labelCustomClass : '';
        //end styling
        //font_size
        $font_size = (isset($params->labelFontSize))? $params->labelFontSize : '';
        //font_weight
        $font_weight = $params->labelFontWeight;

        //font_color
        $font_color = (isset($params->labelFontColor))? $params->labelFontColor : '';
        $align = (isset($params->label_text_align))? $params->label_text_align : '';
        //var_dump($align);
        $field_style = 'style="';
        //margin

        if($margin_top || $margin_top == 0)
          $field_style .= 'margin-top:'.$margin_top.';';
        if($margin_right || $margin_right == 0)
          $field_style .= 'margin-right:'.$margin_right.';';
        if($margin_bottom || $margin_bottom == 0)
          $field_style .= 'margin-bottom:'.$margin_bottom.';';
        if($margin_left || $margin_left == 0)
          $field_style .= 'margin-left:'.$margin_left.';';
        //padding
        if($padding_top || $padding_top == 0)
          $field_style .= 'padding-top:'.$padding_top.';';
        if($padding_right || $padding_right == 0)
          $field_style .= 'padding-right:'.$padding_right.';';
        if($padding_bottom || $padding_bottom == 0)
          $field_style .= 'padding-bottom:'.$padding_bottom.';';
        if($padding_left || $padding_left == 0)
          $field_style .= 'padding-left:'.$padding_left.';';
        //background-color
        if($background_color)
          $field_style .= 'background-color:'.$background_color.';';
        //border
        if($border)
          $field_style .= 'border:'.$border.' solid;';
        //border-color
        if($border_color)
          $field_style .= 'border-color:'.$border_color.';';
        //border-color
        if($font_size){
          $field_style .= 'font-size:'.$font_size.'px;';
          $field_style .= 'line-height:'.$font_size.'px;';
        }
        //border-color

        if($font_weight)
          $field_style .= 'font-weight:normal;';
        else
          $field_style .= 'font-weight:bold;';
        //border-color
        if($font_color)
          $field_style .= 'color:'.$font_color.';';
        //text-align
        if($align)
          $field_style .= 'text-align:'.$align.';';
        $field_style .= '"';



        return $field_style;
    }
  }
}

if (!function_exists('get_field_styles_table_header')) {
  function get_field_styles_table_header($field, $layout){
    $layout_params = unserialize($layout->params);
    $params = new JRegistry;
    if($field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }else{

      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }

    //styling
    //background-color
    $background_color = ($params->get('backgroundTableHeaderColor',''))? $params->get('backgroundTableHeaderColor') : '';
    //font_color
    $font_color = ($params->get('fontTableHeaderColor',''))? $params->get('fontTableHeaderColor') : '';
    $field_style = 'style="';

    //background-color
    if($background_color)
      $field_style .= 'background-color:'.$background_color.';';

    if($font_color)
      $field_style .= 'color:'.$font_color.';';
    $field_style .= '"';

    return $field_style;
  }
}


if (!function_exists('get_field_styles_without_Style')) {
  function get_field_styles_without_Style($field, $layout){
    $layout_params = unserialize($layout->params);
    $params = new JRegistry;
    if($field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }else{
      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }

    //styling
    //margin
    if($params->get("margin")){
      $marginPx = 'px';
    }else{
      $marginPx = '%';
    }

    if($params->get('marginTop','') == '0'){
      $margin_top = '0';
    }else{
      $margin_top = ($params->get('marginTop',''))? $params->get('marginTop').$marginPx : '';
    }

    if($params->get('marginRight','') == '0'){
      $margin_right = '0';
    }else{
      $margin_right = ($params->get('marginRight',''))? $params->get('marginRight').$marginPx : '';
    }

    if($params->get('marginBottom','') == '0'){
      $margin_bottom = '0';
    }else{
      $margin_bottom = ($params->get('marginBottom',''))? $params->get('marginBottom').$marginPx : '';
    }

    if($params->get('marginLeft','') == '0'){
      $margin_left = '0';
    }else{
      $margin_left = ($params->get('marginLeft',''))? $params->get('marginLeft').$marginPx : '';
    }
    // $margin_top = ($params->get('marginTop',''))? $params->get('marginTop').$marginPx : '';
    // $margin_right = ($params->get('marginRight',''))? $params->get('marginRight').$marginPx : '';
    // $margin_bottom = ($params->get('marginBottom',''))? $params->get('marginBottom').$marginPx : '';
    // $margin_left = ($params->get('marginLeft',''))? $params->get('marginLeft').$marginPx : '';
    //padding
    if($params->get("padding")){
      $paddingPx = 'px';
    }else{
      $paddingPx = '%';
    }

    if($params->get('paddingTop','') == '0'){
      $padding_top = '0';
    }else{
      $padding_top = ($params->get('paddingTop',''))? $params->get('paddingTop').$paddingPx : '';
    }

    if($params->get('paddingRight','') == '0'){
      $padding_right = '0';
    }else{
      $padding_right = ($params->get('paddingRight',''))? $params->get('paddingRight').$paddingPx : '';
    }

    if($params->get('paddingBottom','') == '0'){
      $padding_bottom = '0';
    }else{
      $padding_bottom = ($params->get('paddingBottom',''))? $params->get('paddingBottom').$paddingPx : '';
    }

    if($params->get('paddingLeft','') == '0'){
      $padding_left = '0';
    }else{
      $padding_left = ($params->get('paddingLeft',''))? $params->get('paddingLeft').$paddingPx : '';
    }
    // $padding_top = ($params->get('paddingTop',''))? $params->get('paddingTop').$paddingPx : '';
    // $padding_right = ($params->get('paddingRight',''))? $params->get('paddingRight').$paddingPx : '';
    // $padding_bottom = ($params->get('paddingBottom',''))? $params->get('paddingBottom').$paddingPx : '';
    // $padding_left = ($params->get('paddingLeft',''))? $params->get('paddingLeft').$paddingPx : '';
    //background-color
    $background_color = ($params->get('backgroundColor',''))? $params->get('backgroundColor') : '';
    //border
    $border = ($params->get('borderSize',''))? $params->get('borderSize').'px' : '';
    //border-color
    $border_color = ($params->get('borderColor',''))? $params->get('borderColor') : '';
    //custom class
    $custom_class = ($params->get('customClass',''))? $params->get('customClass') : '';
    //end styling
    //font_size
    $font_size = ($params->get('fontSize',''))? $params->get('fontSize') : '';
    //font_weight
    $font_weight = $params->get('fontWeight', 1);

    //font_color
    $font_color = ($params->get('fontColor',''))? $params->get('fontColor') : '';

    $align = ($params->get('text_align',''))? $params->get('text_align') : '';

    $field_style = '';
    //margin

    if($margin_top || $margin_top == 0)
      $field_style .= 'margin-top:'.$margin_top.';';
    if($margin_right || $margin_right == 0)
      $field_style .= 'margin-right:'.$margin_right.';';
    if($margin_bottom || $margin_bottom == 0)
      $field_style .= 'margin-bottom:'.$margin_bottom.';';
    if($margin_left || $margin_left == 0)
      $field_style .= 'margin-left:'.$margin_left.';';
    //padding
    if($padding_top || $padding_top == 0)
      $field_style .= 'padding-top:'.$padding_top.';';
    if($padding_right || $padding_right == 0)
      $field_style .= 'padding-right:'.$padding_right.';';
    if($padding_bottom || $padding_bottom == 0)
      $field_style .= 'padding-bottom:'.$padding_bottom.';';
    if($padding_left || $padding_left == 0)
      $field_style .= 'padding-left:'.$padding_left.';';
    //background-color
    if($background_color)
      $field_style .= 'background-color:'.$background_color.';';
    //border
    if($border)
      $field_style .= 'border:'.$border.' solid;';
    //border-color
    if($border_color)
      $field_style .= 'border-color:'.$border_color.';';
    //border-color
    if($font_size){
      $field_style .= 'font-size:'.$font_size.'px;';
      $field_style .= 'line-height:'.$font_size.'px;';
    }
    //border-color

    if($font_weight)
      $field_style .= 'font-weight:normal;';
    else
      $field_style .= 'font-weight:bold;';
    //border-color
    if($font_color)
      $field_style .= 'color:'.$font_color.';';

    if($align && $field != 'cck_search_field')
      $field_style .= 'text-align:'.$align.';';
    // $field_style .= '"';

    return $field_style;
  }
}


if (!function_exists('get_field_custom_class')) {
  function get_field_custom_class($field, $layout){
    $layout_params = unserialize($layout->params);
    $params = new JRegistry;
//    var_dump($field);
    if(is_object($field) && $field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }elseif(is_string($field) && (stripos($field, 'e-') !== FALSE || isset($layout_params['fields']['Params_'.$field]))){
      if(isset($layout_params['fields']['Params_'.$field])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field]);
      }
    }else{
      // if($field->db_field_name == 'l42'){
      //   var_dump($layout_params['fields']);
      // }
      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }
    
//    var_dump($params);
    $animated = ($params->get('animated',''))?$params->get('animated') : '';
    $animated_class = '';
    if($animated != ''){
        $animated_class = ' wow animated ' . $animated;
    }
    $custom_class = ($params->get('customClass',''))? $params->get('customClass') : '';

    $custom_class .= $animated_class . ' ';
    //var_dump($custom_class);
    return $custom_class;
  }
}

if (!function_exists('get_field_offset_animation')) {
  function get_field_offset_animation($field, $layout){

    $layout_params = unserialize($layout->params);
    $params = new JRegistry;
    if(is_object($field) && property_exists($field, 'field_name') && $field->field_name !== null && stripos($field->field_name, 'm_') === 0){
      return '';
    }
    if(is_object($field) && $field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }elseif(is_string($field) && (stripos($field, 'e-') !== FALSE || isset($layout_params['fields']['Params_'.$field]))){
      if(isset($layout_params['fields']['Params_'.$field])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field]);
      }
    }else{
      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }

    $offset_animation = ($params->get('offsetAnimated',''))?$params->get('offsetAnimated') : '';
    $offset_animation = ' data-wow-offset="' . $offset_animation . '" ';

    return $offset_animation;
  }
}

if (!function_exists('get_field_hover_animation')) {
  function get_field_hover_animation($field, $layout){
    $layout_params = unserialize($layout->params);
    $params = new JRegistry;
    if($field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }else{
      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }
    $hover_animation = '';
    $hover_animation = ($params->get('hoverAnimated',''))?$params->get('hoverAnimated') : '';
    if($hover_animation != ''){
        $hover_animation = 'hover_animated="' . $hover_animation . '"';
    }

    return $hover_animation;
  }
}


if (!function_exists('showFieldType')) {
      function showFieldType($field_type){

          $field_types['datetime_popup'] = 'Date';
          $field_types['filefield'] = 'File Field';
          $field_types['videofield'] = 'Video Field';
          $field_types['audiofield'] = 'Audio Field';
          $field_types['categoryfield'] = 'Category';
          $field_types['imagefield'] = 'Image Field';
          $field_types['text_radio_buttons'] = 'Radio buttons';
          $field_types['text_select_list'] = 'Select list';
          $field_types['text_single_checkbox_onoff'] = 'Checkbox';
          $field_types['text_textarea'] = 'Text Area';
          $field_types['text_textfield'] = 'Text';
          $field_types['text_url'] = 'Url';
          $field_types['galleryfield'] = 'Gallery Field';
          $field_types['locationfield'] = 'Location map';
          $field_types['decimal_textfield'] = 'Number Field';
          $field_types['captcha_field'] = 'Captcha Field';
          $field_types['rating_field'] = 'Rating Field';
          $field_types['pricefield_number'] = 'Price Field (Number)';
          $field_types['pricefield_select_list'] = 'Price Field (Select List)';
          $field_types['pricefield_radio_buttons'] = 'Price Field (Radio buttons)';

          return $field_types[$field_type];
      }
  }


if(!function_exists('available_times_cck')){
  function available_times_cck($eiid, $input_date_format = "Y-m-d", $rent_to = false, $step_time = 0){
   global $db, $os_cck_configuration;
   $db = new os_cckDb();
    $query = "SELECT rent_from, rent_until
              FROM #__os_cck_rent WHERE fk_eiid='".$eiid."'
              AND rent_return is null";
    $db->setQuery($query);
    $curRentDates = $db->loadObjectList();
    //var_dump($curRentDates);
    $minutes_for_day = array();

    foreach($curRentDates as $curRentDate){
      $not_av_from_begin = new DateTime($curRentDate->rent_from);
      $not_av_until_end = new DateTime($curRentDate->rent_until);
//      var_dump($not_av_from_begin);
//      var_dump($not_av_until_end);
      //if until date ,add one step
      if($rent_to && $step_time != 0){

          if($not_av_from_begin->format("H:i:s") != '00:00:00'){
            $not_av_from_begin->modify('+'.$step_time.' minutes');
          }
          $not_av_until_end->modify('+'.$step_time.' minutes');
      }

        //range time in one day
        if($not_av_from_begin->format($input_date_format) == $not_av_until_end->format($input_date_format)){
          if(!isset($minutes_for_day[$not_av_from_begin->format($input_date_format)])){
            $minutes_for_day[$not_av_from_begin->format($input_date_format)] = array();
            $minutes_for_day[$not_av_from_begin->format($input_date_format)][] = array($not_av_from_begin->format("H:i:s"),
                                                                           $not_av_until_end->format("H:i:s"));
          }else{
            $minutes_for_day[$not_av_from_begin->format($input_date_format)][] = array($not_av_from_begin->format("H:i:s"),
                                                                           $not_av_until_end->format("H:i:s"));
          }
        }

        //time to end or from start day
        if(strtotime($not_av_from_begin->format($input_date_format)) < strtotime($not_av_until_end->format($input_date_format))){
          if(!isset($minutes_for_day[$not_av_from_begin->format($input_date_format)])){
            $minutes_for_day[$not_av_from_begin->format($input_date_format)] = array();
            $minutes_for_day[$not_av_from_begin->format($input_date_format)][] = array($not_av_from_begin->format("H:i:s"),
                                                                           '23:59:59');
          }else{
            $minutes_for_day[$not_av_from_begin->format($input_date_format)][] = array($not_av_from_begin->format("H:i:s"),
                                                                           '23:59:59');
          }

          if(!isset($minutes_for_day[$not_av_until_end->format($input_date_format)])){
            $minutes_for_day[$not_av_until_end->format($input_date_format)] = array();
            $minutes_for_day[$not_av_until_end->format($input_date_format)][] = array('00:00:00',
                                                                           $not_av_until_end->format("H:i:s"));
          }else{
            $minutes_for_day[$not_av_until_end->format($input_date_format)][] = array('00:00:00',
                                                                           $not_av_until_end->format("H:i:s"));
          }
        }

      }

      // print_r($minutes_for_day);
      // exit;

      return $minutes_for_day;
  }
}

//return not avaliable dates
if(!function_exists('available_dates_cck')){
  function available_dates_cck($eiid, $step_time = 0, $available_times_in_day = array()){
   global $db, $os_cck_configuration, $session;
   $db = new os_cckDb();
//rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time   
//   if($os_cck_configuration->get('rent_type') == 2){
//     //if rent with time
//       if($time_start == '00:00:00'){
//           $time_start = $session->get('rent_time_start', '00:00:00');
//       } else if($time_start != '00:00:00'){
//           $session->set('rent_time_start', $time_start);
//       }
//
//       if($time_finish == '00:00:00'){
//           $time_finish = $session->get('rent_time_finish', '00:00:00');
//       } else if($time_finish != '00:00:00'){
//           $session->set('rent_time_finish', $time_finish);
//       }
//   }

    $date_NA=[];
    $query = "SELECT rent_from, rent_until
              FROM #__os_cck_rent WHERE fk_eiid='".$eiid."'
              AND rent_return is null";
    $db->setQuery($query);
    $curRentDates = $db->loadObjectList();

    $minutes_sum = array();



    foreach($curRentDates as $curRentDate){
      $not_av_from = $curRentDate->rent_from;
      $not_av_until = $curRentDate->rent_until;
      $not_av_from_begin = new DateTime($not_av_from);
      $not_av_until_end = new DateTime($not_av_until);

      //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
      if($os_cck_configuration->get('rent_type') != 2){
        //if rent not with time
        $not_av_until_end = $not_av_until_end->modify( '+1 day' );
      }

      if ($step_time === false){

          $interval = new DateInterval('P1D');
          $daterange = new DatePeriod($not_av_from_begin, $interval, $not_av_until_end);

          foreach($daterange as $datess){
            $date_NA[] = $datess->format("Y-m-d");
            $date_NA[] = $datess->format("d-m-Y");
          }
      }
      //if($os_cck_configuration->get('rent_type') == 2){

          //range time in one day, how many minutes
          if($not_av_from_begin->format("Y-m-d") == $not_av_until_end->format("Y-m-d")){

            $time_interval = date_diff($not_av_from_begin,$not_av_until_end);
            $minutes = ($time_interval->h*60)+$time_interval->i;

            if(!isset($minutes_sum[$not_av_from_begin->format("Y-m-d")])){
              $minutes_sum[$not_av_from_begin->format("Y-m-d")] = $minutes;
            }else{
              $minutes_sum[$not_av_from_begin->format("Y-m-d")] += $minutes;
            }
          }

          //time to end or from start day
          if(strtotime($not_av_from_begin->format("Y-m-d")) < strtotime($not_av_until_end->format("Y-m-d"))){

            $end_rest_min =  new DateTime(date("Y-m-d 23:59:59",strtotime($not_av_from)));
            $start_rest_min =  new DateTime(date("Y-m-d 00:00:00",strtotime($not_av_until)));

            $time_interval_end = date_diff($not_av_from_begin,$end_rest_min);
            $minutes_end = ($time_interval_end->h*60)+$time_interval_end->i;

            $time_interval_start = date_diff($start_rest_min,$not_av_until_end);
            $minutes_start = ($time_interval_start->h*60)+$time_interval_start->i;

            $time_inteval_day = date_diff($end_rest_min,$start_rest_min);

            if(!isset($minutes_sum[$not_av_from_begin->format("Y-m-d")])){
              $minutes_sum[$not_av_from_begin->format("Y-m-d")] = $minutes_end;
            }else{
              $minutes_sum[$not_av_from_begin->format("Y-m-d")] += $minutes_end;
            }

            if(!isset($minutes_sum[$not_av_until_end->format("Y-m-d")])){
              $minutes_sum[$not_av_until_end->format("Y-m-d")] = $minutes_start;
            }else{
              $minutes_sum[$not_av_until_end->format("Y-m-d")] += $minutes_start;
            }

            if($time_inteval_day->days > 0){
                $not_av_time_day = new DateTime($not_av_from_begin->format("Y-m-d"));
                for($i=0; $i<$time_inteval_day->days; $i++){
                    $not_av_time_day = $not_av_time_day->modify( '+ 1 day' );
                    $minutes_sum[$not_av_time_day->format("Y-m-d")] = 1440;
                }
            }
            $interval = date_diff($not_av_from_begin,$not_av_until_end);

            if ($interval->days > 0){
                //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
                if($os_cck_configuration->get('rent_type') == 2
                        && (($minutes_end + $step_time) > 1439 || $minutes_end > $minutes_start)){
                    $n = $interval->days - 1;
                }else{
                    $n = $interval->days;
                }

                $i = 0;
                for($i; $i < $n; $i++){
                    //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
                    if($os_cck_configuration->get('rent_type') == 2 || $os_cck_configuration->get('rent_type') == 0){
                        $days = $i + 1;
                    }else{
                        $days = $i;
                    }

                    if($days < $n){

                        $not_av_diff = new DateTime($not_av_from_begin->format("Y-m-d"));
                        $not_av_from_begin = $not_av_from_begin->modify( '+ 1 day' );

                        $date_NA[] = $not_av_diff->format("Y-m-d");
                    }

                }

            }
          }

    }

      //if isset rent , //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
    if($os_cck_configuration->get('rent_type') == 2){
      //if rent with time
      if(count($minutes_sum) > 0){
//          var_dump($minutes_sum);
        foreach ($minutes_sum as $date => $mins) {
            $day_week = date('w', strtotime($date));
            if(isset($available_times_in_day[$day_week]) && is_array($available_times_in_day[$day_week])){
//            var_dump($available_times_in_day[$day_week]);
                foreach($available_times_in_day[$day_week] as $time){
//                    $time_start_array = explode(':', $time);
//                            var_dump($time);
//                    var_dump((strtotime(data_transform_cck($time[1],'H:i')) - strtotime(data_transform_cck($time[0],'H:i')))/60);
                    $mins = $mins + (strtotime(data_transform_cck($time[1],'H:i')) - strtotime(data_transform_cck($time[0],'H:i')))/60;
                }
//            if($time_start != '00:00:00'){
//                //var_dump($time_start);
//                $time_start_array = explode(':', $time_start);
//                $mins = $mins + ($time_start_array[0]*60 + $time_start_array[1]);
//            }
//            if($time_finish != '00:00:00'){
//                //var_dump($time_start);
//                $time_finish_array = explode(':', $time_finish);
//                $mins = $mins + ((23 - $time_finish_array[0])*60 + (60 - $time_finish_array[1]));
//            }
          }
//          var_dump($mins);
          //if whole day is busy - disable it
          if($mins >= (1440 - $step_time)){
            $date_NA[] = $date;
          }
        }
      }
    }


      return $date_NA;
  }
}




if(!function_exists('sendMailCck')){
  function sendMailCck($mail_body, $subject = '', $sender = '', $recipient = '', $encoding = 1 ){
      global $app; 

// echo ":88888888888888888:"; 
// var_dump( func_get_args() );
// exit ;
    $mailer = JFactory::getMailer();
    $config = JFactory::getConfig();

    //from
    if(empty($sender)){
      $sender = array(
          $config->get( 'mailfrom' ),
          $config->get( 'fromname' )
      );
    }
    $mailer->setSender($sender);

    //to
    if(empty($recipient)){
      // $recipient = array( $config->get( 'mailfrom' ));
      $app->enqueueMessage(cck_lang_text("Recipient list empty! Error sending email!!!"), 'warning');
      return;
    }else{
      $recipient = explode(',',$recipient);
    }

    $mailer->addRecipient($recipient);

//    var_dump($mailer); exit;
    //body
    $mailer->isHTML(true);
    //html = 1 /text = 0  encoding
    if($encoding)
      $mailer->Encoding = 'base64';
    if($subject)
      $mailer->setSubject($subject);
    else
      $mailer->setSubject($config->get( 'fromname' ));

    $mailer->setBody($mail_body);

    //send mail
    try {
        $send = $mailer->Send();
    } catch (Exception $ex) {
        $send = false;
    }
    

    if ( $send !== true ) {
      $app->enqueueMessage(cck_lang_text("Error sending email!!!"), 'warning');
    }
  }
}

if(!function_exists('recursive_array_replace')){
  function recursive_array_replace($find, $replace, $array) {
      if (!is_array($array)) {
          return str_replace($find, $replace, $array);
      }
      $newArray = array();
      foreach ($array as $key => $value) {
          $newArray[$key] = recursive_array_replace($find, $replace, $value);
      }
      return $newArray;
  }
}


if(!function_exists('createImage')){
  function createImage($imgSrc, $imgDest, $width, $height, $crop = true, $quality = 100) {
    if (JFile::exists($imgDest)) {
      $info = getimagesize($imgDest, $imageinfo);
      if (($info[0] == $width) && ($info[1] == $height)) {
        return;
      }
    }
    if (JFile::exists($imgSrc)) {
      $info = getimagesize($imgSrc, $imageinfo);
      $sWidth = $info[0];
      $sHeight = $info[1];
      resize_img($imgSrc, $imgDest, $width, $height, $crop, $quality);
    }
  }
}

/**
 * Compiles a list of records
 * @param database - A database connector object
 * select categories
 */
if(!function_exists('show_image_cck')){
  function show_image_cck($value, $width, $height){
    global $os_cck_configuration;
//    if($field->fid != 1484 && $field->fid != 1485 && $field->fid != 1486){
            
//          } 
    
    //разделение имени файла на имя и расширение
    if($value == '') return false;
    // var_dump(stripos($value, 'https://'));
    if(stripos($value, 'http://') !== false || stripos($value, 'https://') !== false){
      $file_path = $value;  
      $remout_file = true;
    }else{
      $file_path = JPATH_ROOT . $value;
      $remout_file = false;
    }
    // var_dump($file_path);
    $file_inf = pathinfo($file_path);
//   echo '111111111111111111';
    if(!isset($file_inf['extension'])) return false;
    $file_dir = $file_inf['dirname'] . '/';
    $file_type_temp = '.' . $file_inf['extension'];
//    var_dump($file_type);
    $file_type_const = exif_imagetype($file_path);
//    var_dump($file_type_const);
    if($file_type_const !== false){
        switch ($file_type_const){
            case '1':
                $file_type = '.gif';
                break;
            case '2':
                if($file_type_temp == '.jpeg'){
                    $file_type = '.jpeg';
                }else{
                    $file_type = '.jpg';
                }
                break;
            case '3':
                $file_type = '.png';
                break;
            default :
                $file_type = false;
                break;
        }
    }else{
        $file_type = '.' . $file_inf['extension'];
    }
    
//    var_dump($file_type);
//    exit;
    $file_name = $file_inf['filename'];
    // Setting the resize parameters
    // var_dump(getimagesize($file_path));
    
    if($remout_file){
      $file_headers = @get_headers($file_path);    
      if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
        return false;
      }
    }else{
      if(!file_exists($file_path)) return false;
    }
    
    // echo '11111111111111';
    list($width_main, $height_main) = getimagesize($file_path);

    switch ($os_cck_configuration->get('crop_image')){
        case '0':
        $imgCretionType = '_resize';
        break;

        case '1':
        $imgCretionType = '_crop';
        break;

        case '2':
        $imgCretionType = 'original';
        break;
    }
    
    //$imgCretionType = ($os_cck_configuration->get('crop_image'))? '_crop' : '_resize' ;
    if($imgCretionType != 'original'){
        $size = "_" . $width . "_" . $height;
        if (file_exists($file_dir . $file_name . $size  . $imgCretionType . $file_type)) {
          // echo '44444444444';
          // echo $file_dir . $file_name . $size  . $imgCretionType . $file_type; exit;
            return str_replace(JPATH_ROOT, '', $file_dir . $file_name . $size  . $imgCretionType . $file_type);
        } else {
// echo '222222222222222222'; exit;
          if($height != 0){
            if ($width_main < $height_main) {
            if ($height_main > $height) {
                $k = $height_main / $height;
            } else if ($width_main > $width) {
                $k = $width_main / $width;
            } else $k = 1;

          }else{

            if ($width_main > $width) {
                $k = $width_main / $width;
            } else if ($height_main > $height) {
                $k = $height_main / $height;
            } else $k = 1;

          }
        }
         if($height == 0) $k = 1;

          $w_ = $width_main / $k;
          $h_ = $height_main / $k;

        }
// echo '11111111111111'; exit;
        if($os_cck_configuration->get('crop_image','0')){
            $CreateNewImage = createImage($file_path, $file_dir . $file_name . $size  . $imgCretionType . $file_type
                                          , $width, $height);
            return str_replace(JPATH_ROOT, '', $file_dir . $file_name . $size  . $imgCretionType . $file_type);
        }
        // Creating the Canvas
//        var_dump($w_); exit;
        $tn = imagecreatetruecolor(intval($w_), intval($h_));

          if ($file_type == '.png') {
            imagealphablending($tn, false);
            imagesavealpha($tn,true);
            $transparent = imagecolorallocatealpha($tn, 255, 255, 255, 127);
            
            imagefilledrectangle($tn, 0, 0, intval($w_), intval($h_), $transparent);
          }

        //проверка типа
//         var_dump($file_type);
        switch (strtolower($file_type)) {
            case '.png':
                //echo 'type of your image is PNG';
                $source = imagecreatefrompng($file_dir . $file_name . $file_type_temp );
                // var_dump($file_dir . $file_name . $file_type); exit;
                $file = imagecopyresampled($tn, $source, 0, 0, 0, 0, intval($w_), intval($h_), $width_main, $height_main);
                imagepng($tn, $file_dir . $file_name . $size  . $imgCretionType . $file_type);
                break;
            case '.jpg':
                //echo 'type of your image is JPG';
                $source = imagecreatefromjpeg($file_dir . $file_name . $file_type_temp );
//                var_dump($file_type); exit;
                $file = imagecopyresampled($tn, $source, 0, 0, 0, 0, intval($w_), intval($h_), $width_main, $height_main);
                
                imagejpeg($tn, $file_dir . $file_name . $size  . $imgCretionType . $file_type_temp);

                break;
            case '.jpeg':
                //echo 'type of your image is JPEG';
                try {
                    $source = imagecreatefromjpeg($file_dir . $file_name . $file_type_temp);
                } catch (Exception $ex) {
                    echo $ex->getMessage(); exit;
                }
                
                try {
                    $file = imagecopyresampled($tn, $source, 0, 0, 0, 0, intval($w_), intval($h_), $width_main, $height_main);
                } catch (Exception $ex) {
                    echo $ex->getMessage(); exit;
                }
                try {
                    imagejpeg($tn, $file_dir . $file_name . $size  . $imgCretionType . $file_type_temp);
                } catch (Exception $ex) {
                    echo $ex->getMessage(); exit;
                }
                

                break;
            case '.gif':
                //echo 'type of your image is GIF';
                $source = imagecreatefromgif($file_dir . $file_name . $file_type_temp);
                $file = imagecopyresampled($tn, $source, 0, 0, 0, 0, intval($w_), intval($h_), $width_main, $height_main);
                imagegif($tn, $file_dir . $file_name . $size  . $imgCretionType . $file_type_temp);
                break;
            default:
                echo 'not support';
                return;
        }
        // var_dump($imgCretionType); exit;
        return str_replace(JPATH_ROOT, '', $file_dir . $file_name . $size  . $imgCretionType . $file_type);
    }else{
        return str_replace(JPATH_ROOT, '', $file_dir . $file_name . $file_type_temp);
    }
  }
}

if(!function_exists('resize_img')){
  function resize_img($imgSrc, $imgDest, $tmp_width, $tmp_height, $crop = true, $quality = 100) {
      $info = getimagesize($imgSrc, $imageinfo);
      $sWidth = $info[0];
      $sHeight = $info[1];
      $quality = 80;

      if ($tmp_width != '' && ($sHeight / $sWidth > $tmp_height / $tmp_width)) {
          $width = $sWidth;
          $height = round(($tmp_height * $sWidth) / $tmp_width);
          $sx = 0;
          $sy = round(($sHeight - $height) / 3);
      }
      else {
          $height = $sHeight;
          $width = round(($sHeight * $tmp_width) / $tmp_height);
          $sx = round(($sWidth - $width) / 2);
          $sy = 0;
      }

      if (!$crop) {
          $sx = 0;
          $sy = 0;
          $width = $sWidth;
          $height = $sHeight;
      }

      $ext = str_replace('image/', '', $info['mime']);
      $imageCreateFunc = getImageCreateFunction($ext);
      $imageSaveFunc = getImageSaveFunction($ext);

      $sImage = $imageCreateFunc($imgSrc);
      $dImage = imagecreatetruecolor($tmp_width, $tmp_height);

      // Make transparent
      if ($ext == 'png') {
          imagealphablending($dImage, false);
          imagesavealpha($dImage,true);
          $transparent = imagecolorallocatealpha($dImage, 255, 255, 255, 127);
          imagefilledrectangle($dImage, 0, 0, $tmp_width, $tmp_height, $transparent);
      }

      imagecopyresampled($dImage, $sImage, 0, 0, $sx, $sy, $tmp_width, $tmp_height, $width, $height);

      // print_r($dImage.'------');
      // print_r($imgDest.'------');
      // print_r($quality.'------');
      // exit;

      if ($ext == 'png') {
          $imageSaveFunc($dImage, $imgDest,  (($quality)/10)-1);
      }
      else if ($ext == 'gif') {
          $imageSaveFunc($dImage, $imgDest, $quality);
      }
      else {
          $imageSaveFunc($dImage, $imgDest, $quality);
      }
  }
}
if(!function_exists('getImageCreateFunction')){
  function getImageCreateFunction($type) {
      switch ($type) {
          case 'jpeg':
          case 'jpg':
              $imageCreateFunc = 'imagecreatefromjpeg';
              break;

          case 'png':
              $imageCreateFunc = 'imagecreatefrompng';
              break;

          case 'bmp':
              $imageCreateFunc = 'imagecreatefrombmp';
              break;

          case 'gif':
              $imageCreateFunc = 'imagecreatefromgif';
              break;

          case 'vnd.wap.wbmp':
              $imageCreateFunc = 'imagecreatefromwbmp';
              break;

          case 'xbm':
              $imageCreateFunc = 'imagecreatefromxbm';
              break;

          default:
              $imageCreateFunc = 'imagecreatefromjpeg';
      }

      return $imageCreateFunc;
  }
}
if(!function_exists('getImageSaveFunction')){
  function getImageSaveFunction($type) {
      switch ($type) {
          case 'jpeg':
              $imageSaveFunc = 'imagejpeg';
              break;

          case 'png':
              $imageSaveFunc = 'imagepng';
              break;

          case 'bmp':
              $imageSaveFunc = 'imagebmp';
              break;

          case 'gif':
              $imageSaveFunc = 'imagegif';
              break;

          case 'vnd.wap.wbmp':
              $imageSaveFunc = 'imagewbmp';
              break;

          case 'xbm':
              $imageSaveFunc = 'imagexbm';
              break;

          default:
              $imageSaveFunc = 'imagejpeg';
      }

      return $imageSaveFunc;
  }
}

/**
* Legacy function, use {@link JArrayHelper::getValue()} instead
*
* @deprecated  As of version 1.5
*/
if (!function_exists('mosGetParam')) {
     function mosGetParam(&$arr, $name, $def = null, $mask = 0, $filter = "STRING" ) {

        // $bid = mosGetParam($_POST, 'bid', array(0));
        // protectInjectionWithoutQuote($element, $def = '', $filter = "STRING",$bypass_get=false){
        return protectInjectionWithoutQuote($name, $def,$filter) ;
    }
}
//if (!function_exists('mosGetParam')) {
//  function mosGetParam(&$arr, $name, $def = null, $mask = 0)
//  {
//      // Static input filters for specific settings
//      static $noHtmlFilter = null;
//      static $safeHtmlFilter = null;
//
//      $var = ArrayHelper::getValue($arr, $name, $def, '');
//
//      // If the no trim flag is not set, trim the variable
//      if (!($mask & 1) && is_string($var)) {
//          $var = trim($var);
//      }
//
//      // Now we handle input filtering
//      if ($mask & 2) {
//          // If the allow html flag is set, apply a safe html filter to the variable
//          if (is_null($safeHtmlFilter)) {
//              $safeHtmlFilter =  JFilterInput::getInstance(null, null, 1, 1);
//          }
//          $var = $safeHtmlFilter->clean($var, 'none');
//      } elseif ($mask & 4) {
//          // If the allow raw flag is set, do not modify the variable
//          $var = $var;
//      } else {
//          // Since no allow flags were set, we will apply the most strict filter to the variable
//          if (is_null($noHtmlFilter)) {
//              $noHtmlFilter =  JFilterInput::getInstance( /* $tags, $attr, $tag_method, $attr_method, $xss_auto */);
//          }
//          $var = $noHtmlFilter->clean($var, 'none');
//      }
//      return $var;
//  }
//}

/**
* Legacy function, use {@link JEditor::save()} or {@link JEditor::getContent()} instead
*
* @deprecated  As of version 1.5
*/
if (!function_exists('getEditorContents')) {
  function getEditorContents($editorArea, $hiddenField)
  {
      jimport('joomla.html.editor');
      if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
//            jimport('joomla.html.editor');
//            // get editor selected in global settings:
//            $config = JFactory::getConfig();
//            $global_editor = $config->get( 'editor' );
//            // get user's default editor
//            $user_editor = JFactory::getUser()->getParam("editor");
//            if($user_editor && $user_editor !== 'JEditor') {
//                $selected_editor = $user_editor;
//            } else {
//                $selected_editor = $global_editor;
//            }
//            $editor = JEditor::getInstance($selected_editor);
//            // display(string $name, string $html, string $width, string $height, integer $col, integer $row, boolean $buttons = true, string $id = null, string $asset = null, object $author = null, array $params = array()) : string
//            echo $editor->save($hiddenField);
        } else {

          $editor = JFactory::getEditor();
          //var_dump(JEditor::getInstance()); exit;
          //$editor = JFactory::getConfig();
          echo $editor->save($hiddenField);
        }
  }
}

/**
* Legacy function, use {@link JFilterOutput::objectHTMLSafe()} instead
*
* @deprecated  As of version 1.5
*/
if (!function_exists('mosMakeHtmlSafe')) {
  function mosMakeHtmlSafe(&$mixed, $quote_style = ENT_QUOTES, $exclude_keys = '')
  {
      JFilterOutput::objectHTMLSafe($mixed, $quote_style, $exclude_keys);
  }
}


/**
* Legacy function to replaces &amp; with & for xhtml compliance
*
* @deprecated  As of version 1.5
*/
if (!function_exists('mosTreeRecurse')) {
  function mosTreeRecurse($id, $indent, $list, &$children, $maxlevel = 9999, $level = 0, $type = 1)
  {
      jimport('joomla.html.html');
      return JHTML::_('menu.treerecurse', $id, $indent, $list, $children, $maxlevel, $level, $type);
  }
}


if (!function_exists('os_cckTreeRecurse')) {
  function os_cckTreeRecurse($id, $indent, $list, &$children, $maxlevel = 9999, $level = 0, $type = 1)
  {

      if (@$children[$id] && $level <= $maxlevel) {
          $parent_id = $id;
          foreach ($children[$id] as $v) {
              $id = $v->cid;

              if ($type) {
                  $pre = " "; //'<sup>|_</sup>_';
                  $spacer = '. -- ';
              } else {
                  $pre = "- ";
                  $spacer = ' . -';
              }

              if ($v->parent == 0) {
                  $txt = $v->name;
              } else {
                  $txt = $pre . $v->name;
              }
              $pt = $v->parent;
              $list[$id] = $v;
              $list[$id]->name = "$indent$txt";
              //var_dump($children[$id]);
              $list[$id]->children = (isset($children[$id])) ? count($children[$id]) : '0';
              $list[$id]->all_fields_in_list = count(@$children[$parent_id]);

              $list = os_cckTreeRecurse($id, $indent . $spacer, $list, $children, $maxlevel, $level + 1, $type);
          }
      }

      return $list;
  }
}

if (!function_exists('show_search_field')) {
  function show_search_field($field, $value,$params){
    $showSearchOptions = array();
    $fld_name_show = (isset($params['showName_'.$field->db_field_name])) ? 'checked="true"' : "";
    //search params
    if($field->field_type == 'decimal_textfield'){
      $showSearchOptions[] = JHTML::_('select.option','1','Show search by range');
      $showSearchOptions[] = JHTML::_('select.option','2','Show search by value');
      $showSearchOptions[] = JHTML::_('select.option','3','Search by value');
      $showSearchOptions[] = JHTML::_('select.option','0','Hide');
    }elseif($field->field_type == 'text_single_checkbox_onoff'){
      $showSearchOptions[] = JHTML::_('select.option','1','Show');
      $showSearchOptions[] = JHTML::_('select.option','0','Hide');
    }else{
      $showSearchOptions[] = JHTML::_('select.option','1','Show');
      $showSearchOptions[] = JHTML::_('select.option','2','Search');
      $showSearchOptions[] = JHTML::_('select.option','0','Hide');
    }
    if ($field->published != "1") return "";

    $ftype = $field->field_type;
    $global_settings = unserialize($field->global_settings);
    $db_columns = unserialize($field->db_columns);
    if (array_key_exists('value', $db_columns)) $db_columns = $db_columns['value'];
    $sufix = '';
    //search in text field
    if ($ftype == 'decimal_textfield' || $ftype == 'datetime_popup' || $ftype == 'text_radio_buttons' || $ftype == 'text_textfield' || $ftype == 'text_textarea' || $ftype == 'text_url' || $ftype == 'text_single_checkbox_onoff' || $ftype == 'text_select_list') {
      if ($field->multiple != 1) $sufix = '[' . $multiple . ']';
      $selectedFieldTitle = (isset($params['search_params']['cck_search_'.$field->db_field_name]['type'])) ? $params['search_params']['cck_search_'.$field->field_name]['type'] : '';
      $list = '<div><label>'.cck_lang_text("COM_OS_CCK_LABEL_SHOW_FIELD_NAME").'</label> <input type="checkbox" data-field-name="'.$field->field_name.'" name="fi_showName_'. $field->field_name . '" ' . $fld_name_show . ' ></div> ';
      $list .= JHTML::_('select.genericlist',$showSearchOptions, 'os_cck_search_'.$field->db_field_name.'[type]',
                                            'size="1" class="inputbox" ', 'value', 'text',$selectedFieldTitle);
      $list .='<input type="hidden" name="os_cck_search_'.$field->db_field_name.'[fid]" value="'.$field->fid.'">';
      return $list;
    }
  }
}

if (!function_exists('data_transform_cck')){
  function data_transform_cck($date, $format) {
    global $db;
    $db = new os_cckDb();
    if (stripos($date, 'undefined') !== FALSE){
        $date = str_replace('undefined', '1971-01-01', $date);
    }
//    if (strstr($date, "00:00:00") OR strlen($date) < 11) {
//      $formatForDateFormat = 'Y-m-d';
//    } else {
      $formatForDateFormat = 'Y-m-d H:i:s';
//    }

    $formatForCreateObjDate = str_replace("%","",$format);
//    var_dump($date); exit;
    if(function_exists('date_format')){

      $dateObject = date_create_from_format($formatForCreateObjDate, trim($date));
      
      if($dateObject){
        $date = date_format($dateObject, $formatForDateFormat);

      }else{
        $dateObject = date_create_from_format($formatForDateFormat, $date);

        if($dateObject){
          $date = date_format($dateObject, $formatForDateFormat);
        }
      }
      

    }else{
      $query = "SELECT STR_TO_DATE('$date','$format')";
      $db->setQuery($query);
      $normaDat = $db->loadResult();
      if(strlen($normaDat) > 0){
        $date = $normaDat;
      }
    }

    
    return $date;
  }
}

if (!function_exists('date_to_data_ms_CCK')){
  function date_to_data_ms_CCK($data_string){             // 2014-01-25 covetr to date in ms
    global $db;
    $db = new os_cckDb();
    if($data_string){
      $temp_data = explode(' ', trim($data_string));
      $rent_mas = explode('-', trim($temp_data[0]));
      $month=$rent_mas[1];
      $day=$rent_mas[2];
      $year=$rent_mas[0];

      $rent_ms = mktime ( 0 ,0, 0, $month , $day , $year);
      return $rent_ms;
    }else{
      exit;
    }
  }
}
if(!function_exists('cck_getCurrency')){
  function cck_getCurrency($params){
    $currency_string = $params->get("paypal_currency");
    $currency_arr = explode(';', $currency_string);
    $currency_list = array();
    foreach ($currency_arr as $currency) {
      $l = explode("=", $currency);
      if(count($l) == 2){
        $signStr = $l[0];
        $signAlias = $l[0];
        $sign = explode("|", $signStr);
        if(count($sign) == 2){
          $signStr = $sign[0];
          $signAlias = $sign[1];
        }
        $coefficient = $l[1];
        $currency_list[] = array("sign"=>$signStr,"signAlias"=>$signAlias,"coefficient"=>$coefficient);
      }
    }

    return $currency_list;
  }
}

if(!function_exists('calculatePriceCCK')){
  function calculatePriceCCK ($eiid,$ceid,$rent_from,$rent_until,$lid = 0, $price_fields = false){
    global $db, $session, $app, $input, $entityFieldLists;
//    var_dump($rent_from);
//    var_dump($rent_until);
    $db = new os_cckDb();
    $input = JFactory::getApplication()->input;
    $numerFormat = json_decode($input->get('numberFormat', '', 'STRING'));
    if(is_object($numerFormat)){
        $numerFormat = (array) $numerFormat;
    }

    if(!$price_fields){
        $jsonPriceFields = $input->get('jsonPriceFields', '', 'STRING');
        $price_fields = json_decode($jsonPriceFields);
    }
    //var_dump($price_fields); exit;

    $os_cck_config = JComponentHelper::getParams('com_os_cck');
    $entityInstance = new os_cckEntityInstance($db->_db);
    $entityInstance->load(intval($eiid));
    $layout = new os_cckLayout($db->_db);
    $layout->load($entityInstance->fk_lid);
    $layout_params = unserialize($layout->params);
    $layout_fields = $layout_params['fields'];
    $fields = $entityInstance->getFields();
    $coup_id = $input->get('coupon', '');
    if($coup_id == ''){
        $coup_id = $input->get('coupon_id', '');
    }
    
    $price = getCalculatedPrice($price_fields, $eiid, 51, $coup_id);
    if(is_array($price) && isset($price['calculated_price'])){
        $price = $price['calculated_price'];
    }else{
        $price = 0;
    }

    //var_dump($coup_id);


//    foreach ($fields as $field) {
//      if($field->field_type == 'decimal_textfield'){
//          var_dump($layout_fields[$field->db_field_name.'_field_type']);
//        if(isset($layout_fields[$field->db_field_name.'_field_type']) && $layout_fields[$field->db_field_name.'_field_type'] == 1){
//
//          $value = $entityInstance->getFieldValue($field);
//          $price += $value[0]->data;
//        }
//      }
//    }

//    foreach ($fields as $field) {
//      if(stripos($field->field_type, 'pricefield') !== FALSE){
//          //var_dump($layout_fields[$field->db_field_name.'_field_type']);
//        if(isset($layout_fields[$field->db_field_name.'_field_type']) && $layout_fields[$field->db_field_name.'_field_type'] == 1){
//
//          $value = $entityInstance->getFieldValue($field);
//          $price += $value[0]->data;
//        }
//      }
//    }

    $entity = new os_cckEntity($db->_db);
    $entity->load(intval($ceid));
    $lid = $lid?$lid:$app->input->get("current_lid");
    $layout->load($lid);
    $layout_params = unserialize($layout->params);

    $layout_fields = $layout_params['fields'];
    $bootstrap_version = $session->get( 'bootstrap','2');
    $layout_html = $layout->getLayoutHtml($bootstrap_version);
//    $fields = $entity->getFieldList($layout_html);
    $fields = $entityFieldLists[$layout->fk_eid];


    foreach ($fields as $field) {
      if($field->field_type == 'datetime_popup'){

        if(isset($layout_fields[$field->db_field_name.'_field_type']) && $layout_fields[$field->db_field_name.'_field_type'] == 'rent_from')
        {
          $rent_from_format = $layout_fields[$field->db_field_name.'_input_format'];
        }

        if(isset($layout_fields[$field->db_field_name.'_field_type']) && $layout_fields[$field->db_field_name.'_field_type'] == 'rent_to')
        {
          $rent_until_format = $layout_fields[$field->db_field_name.'_input_format'];
        }

      }
    }

//    var_dump($rent_from);
    //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
    if($os_cck_config->get('rent_type') == 2){

      $rent_from = strtotime($rent_from);
      $rent_until = strtotime($rent_until);

      if($rent_from > $rent_until){
        
        $returnArr["price"] = 0;
        $returnArr["currency"] = $entityInstance->instance_currency;
        return $returnArr;
      }

      $price_per_time = isset($layout_params['views']['price_per_period']) ? $layout_params['views']['price_per_period'] : 60;

      $diff = ($rent_until - $rent_from)/60;
      $count_period = $diff/$price_per_time;

      $sum_price = round($count_period * $price);

      $returnVal = calculatedCurrency($entityInstance, $sum_price, '', $numerFormat);
      $returnArr["price"] = $sum_price;
      $returnArr["currency"] = $entityInstance->instance_currency;
      $returnArr["calculatedCurrency"] = $returnVal;
      
      return $returnArr;

    }

//var_dump($rent_from); //exit;
    $rent_from = data_transform_cck($rent_from, $rent_from_format);
    $rent_until = data_transform_cck($rent_until, $rent_until_format);
    
    if($rent_from >$rent_until){
      
      $returnArr["price"] = 0;
      $returnArr["currency"] = $entityInstance->instance_currency;
      return $returnArr;
    }
//    var_dump($rent_from);
    $rent_from_ms = date_to_data_ms_CCK($rent_from);

    $rent_to_ms = date_to_data_ms_CCK($rent_until);

    //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time 
    if($os_cck_config->get("rent_type") != 2){
      $rent_to_ms = $rent_to_ms + (60*60*24);
    }
    //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
    $count_day = (($rent_to_ms - $rent_from_ms)/60/60/24);
    if($os_cck_config->get('rent_type') == 0){
        $count_day = $count_day - 1;
    }
    $sum_price = $count_day * $price;

    $returnVal = calculatedCurrency($entityInstance, $sum_price, '', $numerFormat);

    $returnArr["price"] = $sum_price;
    $returnArr["currency"] = $entityInstance->instance_currency;
    $returnArr["calculatedCurrency"] = $returnVal;
    return $returnArr;
  }
}


  if(!function_exists('styling_options')) {
    function styling_options($layout, $type, $element = ''){

      $input_style = cck_lang_text('COM_OS_CCK_LAYOUT_LABEL_INPUT_STYLE');
      $label_style = cck_lang_text('COM_OS_CCK_LAYOUT_LABEL_ALIAS_STYLE');
      $hover = cck_lang_text('COM_OS_CCK_LAYOUT_LABEL_HOVER_STYLE');
      // $button_style = 'Button style';
      if($type == 'form' || $type == 'col' || $type == 'row' || $element == 'block'){
        $input_style = '';
      }
//      var_dump($layout);
      ?>
      <div id="styling-<?php echo $type?>" class="row">
        <?php
        $align = array();
        $align[] = JHTML::_('select.option','left','Left');
        $align[] = JHTML::_('select.option','center','Center');
        $align[] = JHTML::_('select.option','right','Right');
        $align[] = JHTML::_('select.option','justify','Justify');

        $pdf_type = array();
        $pdf_type[] = JHTML::_('select.option','body','Body');
        $pdf_type[] = JHTML::_('select.option','header','Header');
        $pdf_type[] = JHTML::_('select.option','footer','Footer');


        $animate = get_animated_opt();
      // var_dump($type);
        //var_dump($animate);


        if($type != 'l'){


          if($input_style){?>
            <h2><?php echo $input_style ?></h2>
            <?php
          }?>

          <!-- <h2 class="style-for-block" ><?php //echo $button_style;?></h2> -->
          <div class="style-for-block">
          <div class="cck-margin">

          <div class="table_header">
              <h2>Table header</h2>
              <div>
                <span class="colum-1">
                  <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BACKGROUND_COLOR")?></label>
                </span>
                <span class="colum-2">
                  <input class="background-colorpicker background-table-header-color" type="text" value="" data-opacity="1.00">
                </span>
              </div>

              <div>
                <span class="colum-1">
                  <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_COLOR")?></label>
                </span>
                <span class="colum-2">
                  <input class="font-colorpicker font-table-header-color" type="text" value="" data-opacity="1.00">
                </span>
              </div>
            <h2>Table body</h2>
          </div>
            <?php

            if(stripos($layout->type, 'pdf') !== false && $type == 'row'){

                ?>
                <div class="pdf_type">
                    <span class="colum-1">
                        <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_PDF_TYPE")?></label>
                    </span>
                    <span class="colum-2">
                        <?php echo JHTML::_('select.genericlist', $pdf_type, 'pdf_type', 'size="1" class="inputbox"','value', 'text', 'body');?>

                    </span>
                </div>
            <?php }
              if($type == 'form'){ ?>
              <div>
                  <span class="colum-1">
                    <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_FORM_WIDTH")?> <i title="<?php echo cck_lang_text("COM_OS_CCK_STYLING_FORM_WIDTH_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i></label>
                  </span>
                  <span class="colum-2">
                    <input class="styling_number label-form-width" type="number" value="">
                  </span>
                </div>
          <?php } ?>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_MARGIN")?></label>
            </span>

            <span class="colum-2 option">
              <div class="optionCckl">
                <input id="<?php echo $type?>-margin_px_1" name="<?php echo $type?>-margin_px" class="pixels margin-pixels"  type="radio" value="px" checked="checked">
                <label class="checken" for="<?php echo $type?>-margin_px_1"></label>
              </div>
                <?php if(stripos($layout->type, 'pdf') === false){ ?>
              <div class="optionCckr">
                <input id="<?php echo $type?>-margin_px_2" name="<?php echo $type?>-margin_px" class="pixels margin-pixels" type="radio" value="%">
                <label class="checken" for="<?php echo $type?>-margin_px_2"></label>
              </div>
                <?php } ?>
            </span>

            <span class="colum-3">
              <span class="marg">
                <label>top</label>
                <input class="styling_number margin-top" type="number" value="">
              </span>
              <span class="marg">
                <label>right</label>
                <input class="styling_number margin-right" type="number" value="">
                </span>
                <span class="marg">
                <label>bottom</label>
                <input class="styling_number margin-bottom" type="number" value="">
                </span>
                <span class="marg">
                <label>left</label>
                <input class="styling_number margin-left" type="number" value="">
              </span>
            </span>
          </div>
          <div class="cck-padding">
            <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_PADDING")?></label>
            </span>
            <span class="colum-2 option">
                <div class="optionCckl">
                  <input id="<?php echo $type?>-padding_px_1" name="<?php echo $type?>-padding_px" class="pixels padding-pixels" type="radio" value="px" checked="checked">
                  <label class="checken" for="<?php echo $type?>-padding_px_1"></label>
              </div>
                <?php if(stripos($layout->type, 'pdf') === false){ ?>
              <div class="optionCckr">
                  <input id="<?php echo $type?>-padding_px_2" name="<?php echo $type?>-padding_px" class="pixels padding-pixels" type="radio" value="%">
                  <label class="checken" for="<?php echo $type?>-padding_px_2"></label>
              </div>
                <?php } ?>
            </span>
            <span class="colum-3">
              <span class="marg">
                <label>top</label>
                <input class="styling_number padding-top" type="number" value="">
                </span>
                <span class="marg">
                <label>right</label>
                <input class="styling_number padding-right" type="number" value="">
                </span>
                <span class="marg">
                <label>bottom</label>
                <input class="styling_number padding-bottom" type="number" value="">
                </span>
                <span class="marg">
                <label>left</label>
                <input class="styling_number padding-left" type="number" value="">
                </span>
            </span>
          </div>
              <div id="background-color">
                <span class="colum-1">
                  <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BACKGROUND_COLOR")?></label>
                </span>
                <span class="colum-2">
                  <input class="background-colorpicker background-color" type="text" value="" data-opacity="1.00">
                </span>
              </div>
            <div>
              <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BORDER")?></label>
              </span>
              <span class="colum-2">
                <input class="styling_number border-size" type="number" value="">
              </span>
            </div>
            <div>
              <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BORDER_COLOR")?></label>
              </span>
              <span class="colum-2">
                <input class="border-colorpicker border-color" type="text" value="" data-opacity="1.00">
              </span>
            </div>
          <div id="font-size">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_SIZE")?></label>
            </span>
            <span class="colum-2">
              <input class="styling_number font-size" type="number" value="">
            </span>
          </div>
          <div id="font_weight">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_WEIGHT")?></label>
            </span>
            <span class="colum-2 option">
              <div class="optionCckl_font">
                  <input id="<?php echo $type?>-font_weight_1" name="<?php echo $type?>-font_weight" class="pixels font-weight" type="radio" value="normal" checked="checked">
                  <label class="checken" for="<?php echo $type?>-font_weight_1"></label>
              </div>
              <div class="optionCckr_font">
                  <input id="<?php echo $type?>-font_weight_2" name="<?php echo $type?>-font_weight" class="pixels font-weight" type="radio" value="bold">
                  <label class="checken" for="<?php echo $type?>-font_weight_2"></label>
              </div>
            </span>
          </div>
          <div id="font-color">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_COLOR")?></label>
            </span>
            <span class="colum-2">
              <input class="font-colorpicker font-color" type="text" value="" data-opacity="1.00">
            </span>
          </div>
              <?php if($type == 'f') { ?>
            <div id="text_align">
                <span class="colum-1">
                    <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ALIGNMENT")?></label>
                </span>
                <span class="colum-2">
                    <?php echo JHTML::_('select.genericlist', $align, 'text_align', '','value', 'text', 'left')?>
                </span>
            </div>
              <?php } ?>
              <?php if(stripos($layout->type, 'pdf') === false && checkOsCckVersionProFree() != "free" ){ ?>

                <div>
                    <span class="colum-1">
                        <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ANIMATE")?></label>
                    </span>
                    <span class="colum-2">
                        <?php
                        $attr = array (
                            'list.attr' => '',
                            'id' => 'animate',
                            'list.select' => 'none',
                            'group.items' => null,
                            'option.key.toHtml' => false,
                            'option.text.toHtml' => false
                        );
                        echo  JHTML::_('select.groupedlist',$animate,'animate', $attr);
                        //echo JHTML::_('select.genericlist', $animate, 'animate', '','value', 'text', 'none')?>
                    </span>
                </div>
              <div>
                    <span class="colum-1">
                        <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ANIMATE_OFFSET")?> <i title="<?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ANIMATE_OFFSET_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i></label>
                    </span>
                    <span class="colum-2">
                        <input class="styling_number font-size" id="offset_animate" type="number" value="">
                    </span>
                </div>
              <div>
                    <span class="colum-1">
                        <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_HOVER_ANIMATE")?></label>
                    </span>
                    <span class="colum-2">
                        <?php
                        $attr['id'] = 'hover-animate';
                        echo  JHTML::_('select.groupedlist',$animate,'hover-animate', $attr);//echo JHTML::_('select.genericlist', $animate, 'hover-animate', '','value', 'text', 'none')?>
                    </span>
                </div>

          <div>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_CLASS")?></label>
            </span>
            <span class="colum-2">
              <input class="custom-class" type="text" value="">
            </span>
          </div>
              <?php } ?>
        </div>
            <?php if($type == 'col'){ ?>
          <div id="inline_field">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_INLINE_FIELD")?></label>
            </span>
            <span class="colum-2 option">
              <div class="optionCckl_inline_field">
                  <input id="<?php echo $type?>-inline_field_1" name="<?php echo $type?>-inline_field" class="pixels inline_field" type="radio" value="show" checked="checked">
                  <label width="100%" class="checken" for="<?php echo $type?>-inline_field_1"></label>
              </div>
              <div class="optionCckr_inline_field">
                  <input id="<?php echo $type?>-inline_field_2" name="<?php echo $type?>-inline_field" class="pixels inline_field" type="radio" value="hide">
                  <label class="checken" for="<?php echo $type?>-inline_field_2"></label>
              </div>
            </span>
          </div>
            <div>
              <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FIELD_WIDTH")?> <i title="<?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FIELD_WIDTH_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i></label>
              </span>
              <span class="colum-2">
                <input class="styling_number field_width" type="number" value="">
              </span>
            </div>
            <?php } ?>
            <?php if($type == 'f' && stripos($layout->type, 'pdf') === false) { ?>

              <div class="style-for-block">  <h2 class="style-for-block"><?php echo $hover ?></h2></div>


            <div class="style-for-block" id="hover_background_collor">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_HOVER_BACKGROUND_COLOR")?></label>
            </span>
            <span class="colum-2">
              <input class="font-colorpicker hover_background_collor" type="text" value="" data-opacity="1.00">
            </span>
          </div>
          <div class="style-for-block" id="hover_text_collor">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_HOVER_TEXT_COLOR")?></label>
            </span>
            <span class="colum-2">
              <input class="font-colorpicker hover_text_collor" type="text" value="" data-opacity="1.00">
            </span>
          </div>
            <div class="style-for-block">
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_HOVER_BORDER_COLOR")?></label>
            </span>
            <span class="colum-2">
              <input class="font-colorpicker hover_border_collor" type="text" value="" data-opacity="1.00">
            </span>
          </div>
            <?php }

        }

        if($type != 'form' && $type != 'row' && $type != 'col' && $element != 'block'){?>
          <h2><?php echo $label_style ?></h2>


          <div>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_MARGIN")?></label>
            </span>
            <span class="colum-2 option">
              <div class="optionCckl">
                <input id="<?php echo $type?>-label_margin_px_1" name="<?php echo $type?>-label_margin_px" class="pixels label-margin-pixels"  type="radio" value="px" checked="checked">
                <label class="checken" for="<?php echo $type?>-label_margin_px_1"></label>
              </div>
                <?php if(stripos($layout->type, 'pdf') === false){ ?>
              <div class="optionCckr">
                <input id="<?php echo $type?>-label_margin_px_2" name="<?php echo $type?>-label_margin_px" class="pixels label-margin-pixels" type="radio" value="%">
                <label class="checken" for="<?php echo $type?>-label_margin_px_2"></label>
              </div>
                <?php } ?>
            </span>
            <span class="colum-3">
              <span class="marg">
                <label>top</label>
                <input class="styling_number label-margin-top" type="number" value="">
              </span>
              <span class="marg">
                <label>right</label>
                <input class="styling_number label-margin-right" type="number" value="">
              </span>
              <span class="marg">
                <label>bottom</label>
                <input class="styling_number label-margin-bottom" type="number" value="">
              </span>
              <span class="marg">
                <label>left</label>
                <input class="styling_number label-margin-left" type="number" value="">
              </span>
            </span>
          </div>
            <div>
              <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_PADDING")?></label>
              </span>
              <span class="colum-2 option">
                  <div class="optionCckl">
                    <input id="<?php echo $type?>-label_padding_px_1" name="<?php echo $type?>-label_padding_px" class="pixels label-padding-pixels" type="radio" value="px" checked="checked">
                    <label class="checken" for="<?php echo $type?>-label_padding_px_1"></label>
                </div>
                  <?php if(stripos($layout->type, 'pdf') === false){ ?>
                <div class="optionCckr">
                    <input id="<?php echo $type?>-label_padding_px_2" name="<?php echo $type?>-label_padding_px" class="pixels label-padding-pixels" type="radio" value="%">
                    <label class="checken" for="<?php echo $type?>-label_padding_px_2"></label>
                </div>
                  <?php } ?>
              </span>
              <span class="colum-3">
                <span class="marg">
                  <label>top</label>
                  <input class="styling_number label-padding-top" type="number" value="">
                </span>
                <span class="marg">
                  <label>right</label>
                  <input class="styling_number label-padding-right" type="number" value="">
                </span>
                <span class="marg">
                <label>bottom</label>
                  <input class="styling_number label-padding-bottom" type="number" value="">
                </span>
                <span class="marg">
                <label>left</label>
                  <input class="styling_number label-padding-left" type="number" value="">
                </span>
              </span>
            </div>
          <?php
          if($layout->type == 'instance'){?>
              <div>
                <span class="colum-1">
                  <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BACKGROUND_COLOR")?></label>
                </span>
                <span class="colum-2">
                  <input class="label-background-colorpicker label-background-color" type="text" value="" data-opacity="1.00">
                </span>
              </div>
            <div>
              <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BORDER")?></label>
              </span>
              <span class="colum-2">
                <input class="styling_number label-border-size" type="number" value="">
              </span>
            </div>
            <div>
              <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_BORDER_COLOR")?></label>
              </span>
              <span class="colum-2">
                <input class="label-border-colorpicker label-border-color" type="text" value="" data-opacity="1.00">
              </span>
            </div>
            <?php
          }?>
          <div>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_SIZE")?></label>
            </span>
            <span class="colum-2">
              <input class="styling_number label-font-size" type="number" value="">
            </span>
          </div>
          <div>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_WEIGHT")?></label>
            </span>
            <span class="colum-2 option">
                <div class="optionCckl_font">
                    <input id="<?php echo $type?>-label_font_weight_1" name="<?php echo $type?>-label_font_weight" class="pixels label-font-weight" type="radio" value="normal" checked="checked">
                    <label class="checken" for="<?php echo $type?>-label_font_weight_1"></label>
                </div>
                <div class="optionCckr_font">
                    <input id="<?php echo $type?>-label_font_weight_2" name="<?php echo $type?>-label_font_weight" class="pixels label-font-weight" type="radio" value="bold">
                    <label class="checken" for="<?php echo $type?>-label_font_weight_2"></label>
                </div>
            </span>
          </div>
          <div>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_FONT_COLOR")?></label>
            </span>
            <span class="colum-2">
              <input class="label-font-colorpicker label-font-color" type="text" value="" data-opacity="1.00">
            </span>
          </div>
          <?php if($type == 'f') { ?>
            <div>
                <span class="colum-1">
                    <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ALIGNMENT")?></label>
                </span>
                <span class="colum-2">
                    <?php echo JHTML::_('select.genericlist', $align, 'text_align_label', '','value', 'text', 'left')?>
                </span>
            </div>
              <?php } ?>
          <?php if(stripos($layout->type, 'pdf') === false && checkOsCckVersionProFree() != "free"){ ?>
          <div>
            <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ANIMATE")?></label>
            </span>
            <span class="colum-2">
                <?php
                $attr['id'] = 'label-animate';
                echo  JHTML::_('select.groupedlist',$animate,'label-animate', $attr);
                //echo JHTML::_('select.genericlist', $animate, 'label-animate', '','value', 'text', 'none')?>
            </span>
        </div>
          <div>
            <span class="colum-1">
                <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_ANIMATE_OFFSET")?></label>
            </span>
            <span class="colum-2">
                <input class="styling_number font-size" id="label_offset_animate" type="number" value="">
            </span>
        </div>
          <div>
                    <span class="colum-1">
                        <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_HOVER_ANIMATE")?> <i title="<?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_HOVER_ANIMATE_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i></label>
                    </span>
                    <span class="colum-2">
                        <?php
                        $attr['id'] = 'label-hover-animate';
                        echo  JHTML::_('select.groupedlist',$animate,'label-hover-animate', $attr);
                        //echo JHTML::_('select.genericlist', $animate, 'label-hover-animate', '','value', 'text', 'none')?>
                    </span>
                </div>
          <div>
            <span class="colum-1">
              <label><?php echo cck_lang_text("COM_OS_CCK_STYLING_LABEL_CLASS")?></label>
            </span>
            <span class="colum-2">
              <input class="label-custom-class" type="text" value="">
            </span>
          </div>
          <?php } ?>
          <?php
        } ?>

        <style type="text/css">
          #<?php echo $type?>-label_font_weight_1:checked + label,
          #<?php echo $type?>-label_font_weight_2:checked + label,
          #<?php echo $type?>-label_padding_px_1:checked + label,
          #<?php echo $type?>-label_padding_px_2:checked + label,
          #<?php echo $type?>-label_margin_px_1:checked + label,
          #<?php echo $type?>-label_margin_px_2:checked + label,
          #<?php echo $type?>-font_weight_1:checked + label,
          #<?php echo $type?>-font_weight_2:checked + label,
          #<?php echo $type?>-margin_px_1:checked + label,
          #<?php echo $type?>-margin_px_2:checked + label,
          #<?php echo $type?>-padding_px_1:checked + label,
          #<?php echo $type?>-padding_px_2:checked + label,
          #<?php echo $type?>-inline_field_1:checked + label,
          #<?php echo $type?>-inline_field_2:checked + label {
            z-index: 1;
            background: linear-gradient(top, #1CB09A 0%, #1CB09A 40%, #1B7D6F 100%);
            background: -webkit-linear-gradient(top, #1CB09A 0%, #1CB09A 40%, #1B7D6F 100%);
            background: -moz-linear-gradient(top, #1CB09A 0%, #1CB09A 40%, #1B7D6F 100%);
            box-shadow: 0px 0px 2px 0px #1CB09A;
            -webkit-box-shadow: 0px 0px 2px 0px #1CB09A;
            -moz-box-shadow: 0px 0px 2px 0px #1CB09A;
            -o-box-shadow: 0px 0px 2px 0px #1CB09A;
          }
        </style>
      </div>
      <?php
    }
  }

  if (!function_exists('getEditorContents')) {
    function getEditorContents($editorArea, $hiddenField) {
        jimport('joomla.html.editor');
        $editor = JFactory::getEditor();
        echo $editor->save($hiddenField);
    }
  }

  function getAdminFiledSettingsViewPath ($components, $layoutType, $type, $viewName = 'default'){
      global $os_cck_configuration;
    $fSettingsPath = JPATH_BASE . '/components/' . $components . '/views/layoutFieldSettings/'.$layoutType.'/'.$type.'/tmpl/tmpl_'.$viewName.'.php';
    if(file_exists($fSettingsPath)){
      return $fSettingsPath;
    } else {

        return false;
//      echo "Bad layout path, please write to admin";
//      exit;
    }
  }

  function getSiteAddFiledViewPath ($components, $type, $viewName = 'default'){
    if($type != 'child_select'){
        $addFieldsListPath = JPATH_SITE . '/components/' . $components . '/views/fieldsList/add/'.$type.'/tmpl/tmpl_'.$viewName.'.php';
    }else{
        $addFieldsListPath = JPATH_SITE . '/components/' . $components . '/views/fieldsList/unique/'.$type.'/tmpl/tmpl_'.$viewName.'.php';
    }

    if(file_exists($addFieldsListPath)){
      return $addFieldsListPath;
    } else {

      echo cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH") . ' ' . cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH_FIELD_TYPE") . $type;
      exit;
    }
  }

  function getSiteShowFiledViewPath ($components, $type, $viewName = 'default'){
    $addFieldsListPath = JPATH_SITE . '/components/' . $components . '/views/fieldsList/show/'.$type.'/tmpl/tmpl_'.$viewName.'.php';

    if(file_exists($addFieldsListPath)){
      return $addFieldsListPath;
    } else {

      echo cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH") . ' ' . cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH_FIELD_TYPE") . $type;
      exit;
    }
  }

  function getSiteUniqueFiledViewPath ($components, $type, $viewName = 'default'){
    $addFieldsListPath = JPATH_SITE . '/components/' . $components . '/views/fieldsList/unique/'.$type.'/tmpl/tmpl_'.$viewName.'.php';

    if(file_exists($addFieldsListPath)){
      return $addFieldsListPath;
    } else {

      echo cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH") . ' ' . cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH_FIELD_TYPE") . $type;
      exit;
    }
  }

  function getSiteSearchFiledViewPath ($components, $type, $viewName = 'default'){
    $addFieldsListPath = JPATH_SITE . '/components/' . $components . '/views/fieldsList/search/'.$type.'/tmpl/tmpl_'.$viewName.'.php';

    if(file_exists($addFieldsListPath)){
      return $addFieldsListPath;
    } else {

      echo cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH") . ' ' . cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH_FIELD_TYPE") . $type;
      exit;
    }
  }

  if (!function_exists('show_edite_add_form_field_layout')) {
    function show_edite_add_form_field_layout($field, $showType, $lParams,$layoutType = '',$layout=''){
        global $cck_entity_configuration, $app;
        $gtree = get_group_children_tree_cck($layoutType);
        $path = getAdminFiledSettingsViewPath('com_os_cck', $showType,$field->field_type);
        if($path){
            require $path;
        }else{
            echo '<div id="options-field-'.$field->db_field_name.'">';
            echo cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH") . ' ' . cck_lang_text("COM_OS_CCK_ERROR_BAD_FIELD_PATH_FIELD_TYPE") . $field->field_type;
            echo '</div>';
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_WARNING_ERROR_IN_FIELD"), 'warning');
        }
//      require getAdminFiledSettingsViewPath('com_os_cck', $showType,$field->field_type);
    }
  }


if (!function_exists('avaibleUpdateCCK')) {
  function avaibleUpdateCCK(){



        $avaibleUpdate = false;
        $xml = @simplexml_load_file(JURI::base() . "components/com_os_cck/os_cck.xml");
        $cckV = '';
        $creationDate = '';
        if($xml){
          $cckV = (string)$xml->version;
          $creationDate = (string)$xml->creationDate;

          unset($xml);

          $url="http://ordasoft.com/xml_update/os_cck.xml";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 1);

            $data = curl_exec($ch);
            curl_close($ch);

            $xml = simplexml_load_string($data);
            $updateArticleUrl = '#';
            $cckVArr = explode(".", $cckV);
            if($xml && isset($xml->version)){
              $ordasoftV = (string)$xml->version;
              $ordasoftVArr = explode(".", $ordasoftV);
              $ordasoftCreationDate = (string)$xml->creationDate;
              $updateArticleUrl = (string)$xml->updateArticleUrl;
              foreach ($cckVArr as $k => $cckSubV) {
                if(isset($ordasoftVArr[$k])){
                  if((int)$ordasoftVArr[$k] < (int)$cckSubV){
                    break;
                  }
                  if((int)$ordasoftVArr[$k] > (int)$cckSubV){
                    $avaibleUpdate = true;
                    break;
                  }
                }
              }
            }
            unset($xml);
          }
          return $avaibleUpdate;

  }
}

class cck_additional
{

  // An updated back-end SubMenu helper
  static function addSubmenu($vName)
  {
    $db = new os_cckDb();

      //check update
      $app = JFactory::getApplication();
      $input = $app->input;
      $task = $input->get('task', '', 'STRING');
      $avaibleUpdate = FALSE;
      if ($task == 'about'){

        $avaibleUpdate = avaibleUpdateCCK();
      }
      $query = "SELECT count(i.eiid) FROM #__os_cck_entity_instance as i "
                ."\n LEFT JOIN #__os_cck_layout as l ON l.lid=i.fk_lid "
                ."\n WHERE l.type = 'add_instance' AND i.notreaded = 1";
      $db->setQuery($query);
      $notRead = $db->loadResult();

      $notReadText = '';
      if($notRead)$notReadText = '<span class="cck-not-readed">'.$notRead.'</span>';
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_INSTANCE').$notReadText,
          'index.php?option=com_os_cck&amp;task=show_instance',
          $vName == 'Instances'
      );
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_CATEGORIES'),
          'index.php?option=com_os_cck&amp;task=show_categories',
          $vName == 'Categories'
      );
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_ENTITIES'),
          'index.php?option=com_os_cck&amp;task=manage_entities',
          $vName == 'Manage entities'
      );
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_LAYOUTS'),
          'index.php?option=com_os_cck&amp;task=manage_layout',
          $vName == 'Manage views and layouts'
      );

      $query = "SELECT count(i.eiid) FROM #__os_cck_entity_instance as i "
                ."\n LEFT JOIN #__os_cck_layout as l ON l.lid=i.fk_lid "
                ."\n WHERE l.type = 'request_instance' AND i.notreaded = 1";
      $db->setQuery($query);
      $notRead = $db->loadResult();

      $notReadText = '';
      if($notRead)$notReadText = '<span class="cck-not-readed">'.$notRead.'</span>';
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_SUBMISSIONS').$notReadText,
          'index.php?option=com_os_cck&amp;task=show_requests',
          $vName == 'Requests'
      );

      $query = "SELECT count(i.eiid) FROM #__os_cck_entity_instance as i "
                ."\n LEFT JOIN #__os_cck_layout as l ON l.lid=i.fk_lid "
                ."\n WHERE l.type = 'rent_request_instance' AND i.notreaded = 1";
      $db->setQuery($query);
      $notRead = $db->loadResult();

      $notReadText = '';
      if($notRead)$notReadText = '<span class="cck-not-readed">'.$notRead.'</span>';
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_RENT').$notReadText,
          'index.php?option=com_os_cck&amp;task=show_rent_request_instances',
          $vName == 'Rent'
      );
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_RENT_HISTORY'),
         'index.php?option=com_os_cck&task=users_rent_history', $vName == 'User Rent History'
      );

      $query = "SELECT count(i.eiid) FROM #__os_cck_entity_instance as i "
                ."\n LEFT JOIN #__os_cck_layout as l ON l.lid=i.fk_lid "
                ."\n WHERE l.type = 'buy_request_instance' AND i.notreaded = 1";
      $db->setQuery($query);
      $notRead = $db->loadResult();

      $notReadText = '';
      if($notRead)$notReadText = '<span class="cck-not-readed">'.$notRead.'</span>';
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_BUY').$notReadText,
          'index.php?option=com_os_cck&amp;task=show_buy_request_instances',
          $vName == 'Buy'
      );

      $query = "SELECT count(i.eiid) FROM #__os_cck_entity_instance as i "
                ."\n LEFT JOIN #__os_cck_layout as l ON l.lid=i.fk_lid "
                ."\n WHERE (l.type='review_instance' OR l.type='add_review_instance' ) AND i.notreaded = 1";
      $db->setQuery($query);
      $notRead = $db->loadResult();

      $notReadText = '';
      if($notRead)$notReadText = '<span class="cck-not-readed">'.$notRead.'</span>';
      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_REVIEWS').$notReadText,
          'index.php?option=com_os_cck&amp;task=manage_review',
          $vName == 'Reviews'
      );


      $query = "SELECT count(i.id) FROM #__os_cck_orders as i WHERE i.notreaded = 1";
      $db->setQuery($query);
      $notRead = $db->loadResult();

      $notReadText = '';
      if($notRead)$notReadText = '<span class="cck-not-readed">'.$notRead.'</span>';

      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_ORDERS').$notReadText,
          'index.php?option=com_os_cck&amp;task=orders',
          $vName == 'Orders'
      );

      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_COUPONS'),
          'index.php?option=com_os_cck&amp;task=coupons',
          $vName == 'Coupons'
      );


      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_IMPORT'),
          'index.php?option=com_os_cck&amp;task=import',
          $vName == 'Import'
      );


      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_SETTINGS'),
          'index.php?option=com_config&view=component&component=com_os_cck',
          $vName == 'Settings'
      );
/*		JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_IMPORT_EXPORT'),
          'index.php?option=com_os_cck&amp;task=import_export',
          $vName == 'Import export'
      );
      */
      $notRead = '';
      if($avaibleUpdate)$notRead = '<span class="cck-not-readed">1</span>';

      JSubMenuHelper::addEntry(
          cck_lang_text('COM_OS_CCK_MENU_ABOUT').$notRead,
          'index.php?option=com_os_cck&amp;task=about',
          $vName == 'About'
      );

  }

} // end of cck_additional class


if (!function_exists('set_header_name_cck')) {
  function set_header_name_cck($menu, $Itemid){
    $app = JFactory::getApplication();
    $menu1 = $app->getMenu();
    if (isset($menu1->getItem($Itemid)->title)) {
        $menu_name = $menu1->getItem($Itemid)->title;
        return $menu_name;
    }
  }
}

if (!function_exists('user_guid_cck')) {
  function user_guid_cck($oID){
    global $db, $ueConfig;
    $db = new os_cckDb();
    if ($oID > 0) {
      $query = "SELECT group_id FROM #__user_usergroup_map WHERE user_id  = '" . $oID . "'";
      $db->setQuery($query);
      $gids = $db->loadAssocList();
      if (count($gids) > 0) {
          $ret = '';
          foreach ($gids as $gid) {
              if ($ret != "") $ret .= ',';
              $ret .= $gid['group_id'];
          }
          return $ret;
      } else return 1;
    } else return 1;
  }
}


if (!function_exists('positions_cck')) {
  function positions_cck($position, $params = array()){
    global $app;
    $err_state = ini_get('display_errors');
    ini_set('display_errors', 'Off');
    $plug_row->text = $position; // load the var into plugin_row object
    $plug_row->params = $params;
    JPluginHelper::importPlugin('content');
    $offset = 0;
    $results = $app->triggerEvent('onContentPrepare', array('com_os_cck', &$plug_row, &$plug_params, $offset)); //run mambot onPrepareContent on plug_row object
    echo $plug_row->text; //echo new content out
    ini_set('display_errors', $err_state);
  }
}


if (!function_exists('get_group_children_cck')) {
  function get_group_children_cck(){
    global $acl, $db;
    $db = new os_cckDb();
    $query = 'SELECT `id`,`title` FROM #__usergroups';
    $db->setQuery($query);
    $rows = $db->loadObjectList();
    foreach ($rows as $k => $v) {
        $id_group = $rows[$k]->id;
        $group_name = $rows[$k]->title;
        $groups[$id_group] = $group_name;
    }
    return $groups;
  }
}

if (!function_exists('cckCatOrderDownIcon')) {
  function cckCatOrderDownIcon($i, $n, $index, $task = 'orderdown_category', $alt = 'Move Down'){
      if ($i < $n - 1) {
        return '<a href="#reorder" onclick="return listItemTask(\'cb' . $index . '\',\'' . $task . '\')" title="' . $alt . '">
        <img src="'.JURI::root().'components/com_os_cck/images/arrow_down.png" width="12" height="12" border="0" alt="' . $alt . '" />
        </a>';
      } else return '&nbsp;';
  }
}

if (!function_exists('cckEditorArea')) {
  function cckEditorArea($name, $content, $hiddenField, $width, $height, $col, $row){
    if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
        jimport('joomla.html.editor');
        // get editor selected in global settings:
        $config = JFactory::getConfig();
        $global_editor = $config->get( 'editor' );

        $editor = JEditor::getInstance($global_editor);
        // display(string $name, string $html, string $width, string $height, integer $col, integer $row, boolean $buttons = true, string $id = null, string $asset = null, object $author = null, array $params = array()) : string
        echo $editor->display($hiddenField, $content, $width, $height, $col, $row);
    } else {
        jimport('joomla.html.editor');
        $editor = JFactory::getEditor();

        echo $editor->display($hiddenField, $content, $width, $height, $col, $row);
    }
  }
}

if (!function_exists('cckCatOrderUpIcon')) {
  function cckCatOrderUpIcon($i, $index, $task = 'orderup_category', $alt = 'Move Up')
  {
      if ($i > 0) {
        return '<a href="#reorder" onclick="return listItemTask(\'cb' . $index . '\',\'' . $task . '\')" title="' . $alt . '">
        <img src="'.JURI::root().'components/com_os_cck/images/arrow_up.png" width="12" height="12" border="0" alt="' . $alt . '" />
        </a>';
      } else return '&nbsp;';
  }
}

if (!function_exists('get_group_children_tree_cck')) {
  function get_group_children_tree_cck($layoutType = ''){
    global $acl;
    $group_children_tree = array();
    if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
        $options = JHelperUserGroups::getInstance()->getAll();
    } else {
        include_once(JPATH_SITE . '/administrator/components/com_users/models/groups.php');


        if (version_compare(JVERSION, "3.0.0", "ge")) {
            //echo '111111111111'; exit;
            //$model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
            //$model = JModelLegacy::getInstance('GroupsModel', 'UsersModel', array('ignore_request' => true));
            $model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
        } else {
            $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
        }
        //var_dump($model); exit;
        $options = $model->getItems();
    }
        //var_dump($options); exit;

    //var_dump($model); exit;
    foreach ($g = $options as $k => $v) { // $g contains basic usergroup items info
        $group_title = '.';
        for ($i = 1; $i <= $g[$k]->level; $i++) $group_title .= '-';
        $group_title .= '-' . $g[$k]->title;
        $group_children_tree[0][] = JHTML::_('select.option',$g[$k]->id, $group_title);
        //$group_children_tree[] = JHTML::_('select.option',$g[$k]->id, $group_title);
    }
    // var_dump($layoutType);
    if($layoutType == 'instance'){
        //$group_children_tree['Special Access'][] = JHTML::_('select.option',$g[$k]->id, $group_title);

        $group_children_tree['Special Access'][] = JHTML::_('select.option','owner', '-Owner');
        $group_children_tree['Special Access'][] = JHTML::_('select.option','buyer', '-Buyer');
        //var_dump($grouplist_children_tree_options); exit;
//        $attr = array (
//            'list.attr' => ' class="custom-select" ',
//            'id' => 'filter_menuitem',
//            'list.select' => '',
//            'group.items' => null,
//            'option.key.toHtml' => false,
//            'option.text.toHtml' => false
//        );
//        $group_children_tree = JHTML::_('select.groupedlist',$group_children_tree,'Special Access', $attr);
//        echo $group_children_tree;

//        $group_children_tree[] = JHTML::_('select.option','owner', '-Owner');
//        $group_children_tree[] = JHTML::_('select.option','buyer', '-Buyer');
//        $group_children_tree[] = JHTML::_('select.groupedlist','');
    }elseif($layoutType == 'instance_manager'){
      $group_children_tree['Special Access'][] = JHTML::_('select.option','owner', '-Owner');
    }

    return $group_children_tree;
  }
}

if (!function_exists('get_group_children_tree_cck_without_options')) {
  function get_group_children_tree_cck_without_options($layoutType = ''){
    global $acl;
    $group_children_tree = array();
    if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
        $options = JHelperUserGroups::getInstance()->getAll();
    } else {
        include_once(JPATH_SITE . '/administrator/components/com_users/models/groups.php');
        if (version_compare(JVERSION, "3.0.0", "ge")) {
            $model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
        } else {
            $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
        }
        $options = $model->getItems();
    }
    //var_dump($model->getItems());
    foreach ($g = $options as $k => $v) { // $g contains basic usergroup items info
        $group_title = '.';
        for ($i = 1; $i <= $g[$k]->level; $i++) $group_title .= '-';
        $group_title .= '-' . $g[$k]->title;
        $group_children_tree[$g[$k]->id] = $group_title;
    }
//    if($layoutType == 'instance'){
//        $group_children_tree[] = JHTML::_('select.optgroup','Special Access');
//        $group_children_tree[] = JHTML::_('select.option','owner', '-Owner');
//        $group_children_tree[] = JHTML::_('select.option','buyer', '-Buyer');
//        $group_children_tree[] = JHTML::_('select.optgroup','');
//    }
    //var_dump($layoutType);
    return $group_children_tree;
  }
}

if(!class_exists('CCK_CAT_Utils')){
  class CCK_CAT_Utils
  {

      static function categoryArray($section = "",$fromSearch='', $eid = '0', $fromAdmin = 0, $lang = '*', $categories_sort = 'ordering')
      {
          global $db;
          $db = new os_cckDb();
          // get a list of the menu items

          $query = "SELECT c.*, c.parent_id AS parent"
              . "\n FROM #__os_cck_categories c"
              . "\n WHERE " . (($section != "") ? (" section='" . $section . "' AND ") : (""))
              . "\n c.published = 1";
          if($lang != '*' && $lang != ''){
              $query .= ' AND (c.language = "'.$lang.'" || c.language = "" || c.language = "*") ';
          }
          $query .= "\n ORDER BY $categories_sort";
          $db->setQuery($query);
          $items = $db->loadObjectList();

          //$items = deleteSubCategory($eid, $items);



          if($fromSearch){
              $cat_all = $items;
              $user = JFactory::getUser();
              $cat_all1= array();

              for ($i = 0; $i < count($cat_all); $i++) {
                  if (($cat_all[$i]->params !== implode(',',array_diff(explode(',',$cat_all[$i]->params),$user->groups))) || $cat_all[$i]->params == 1) {
                      $cat_all1[]=$cat_all[$i];
                  }
              }
              $items = $cat_all1;
              if($fromSearch == 2)return $items;
          }
          //echo $db->stderr();
          if($fromAdmin != 0){
              foreach ($items as $key => $item){
                  if($item->fk_eid != $eid && $item->fk_eid != '0'){
                      deleteSubCategory($items, $item->cid);
                      unset($items[$key]);
                  }
              }

          }

          // establish the hierarchy of the menu
          $children = array();
          // first pass - collect children
          foreach ($items as $v) {
              $pt = $v->parent_id;
              $list = @$children[$pt] ? $children[$pt] : array();
              array_push($list, $v);
              $children[$pt] = $list;
          }//print_r($children);exit;
          // second pass - get an indent list of the items
          $array = os_cckTreeRecurse(0, '', array(), $children);
          return $array;
      }

  }
}

function deleteSubCategory($items, $parent_id = '0'){
    foreach ($items as $key => $item){
              if($item->parent_id == $parent_id){
                  deleteSubCategory($items, $item->cid);
                  unset($items[$key]);
              }
          }
}
if (!function_exists('mosReadDirectory')) {
  function mosReadDirectory($path, $filter = '.', $recurse = false, $fullpath = false)
  {
      $arr = array(null);

      // Get the files and folders
      jimport('joomla.filesystem.folder');
      $files = JFolder::files($path, $filter, $recurse, $fullpath);
      $folders = JFolder::folders($path, $filter, $recurse, $fullpath);
      // Merge files and folders into one array
      $arr = array_merge($files, $folders);
      // Sort them all
      asort($arr);
      return $arr;
  }
}

/**
* HTML Class
* Utility class for all HTML drawing classes
* @desc class General HTML creation class. We use it for back/front ends.
*/
if(!class_exists('os_cck_HTML')){
  class os_cck_HTML
  {
      // TODO :: merge categoryList and categoryParentList
      // add filter option ?
      static function categoryList($id,$fromSearch=0,$layout_params = ''){
        $field_styling = (isset($layout_params['field_styling']))? $layout_params['field_styling'] : '';
        $custom_class = (isset($layout_params['custom_class']))? $layout_params['custom_class'] : '';
        $list = CCK_CAT_Utils::categoryArray('com_os_cck',$fromSearch);
        if($fromSearch == 2)return $list;
        $this_treename = '';
        $childs_ids = $options = Array();
        foreach ($list as $item) {
          if (array_key_exists($item->parent_id, $childs_ids))
            $childs_ids[$item->cid] = $item->cid;
        }
        foreach ($list as $item) {
          if ($this_treename) {
            if (strpos($item->title, $this_treename) === false
                && array_key_exists($item->cid, $childs_ids) === false
            ) {
                $options[] = JHTML::_('select.option',$item->cid, $item->title);
            }
          } else {
            $options[] = JHTML::_('select.option',$item->cid, $item->title);
          }
        }
        $parent = JHTML::_('select.genericlist',$options, 'categories[]', $field_styling.' id="catid" multiple="multiple" class="'.$custom_class.' inputbox" size="4" onchange=""', 'value', 'text',$id);
        return $parent;
      }

      static function categoryParentList($id, $action, $options = array(), $fromAdmin = 0, $eid='')
      {
          global $db;
          $db = new os_cckDb();
          $fromSearch = 0;
          $list = CCK_CAT_Utils::categoryArray('com_os_cck',$fromSearch, $fromAdmin);

          if($eid != '' && $eid != 0 && $eid != '*'){
              foreach ($list as $key => $value){
                  if($value->fk_eid != $eid && $value->fk_eid != 0){
                      unset($list[$key]);
                  }
              }
          }

          $cat = new os_cckCategory($db->_db);
          $cat->load($id);
          $this_treename = '';
          $childs_ids = Array();
          foreach ($list as $item) {
              if ($item->cid == $cat->cid || array_key_exists($item->parent_id, $childs_ids))
                  $childs_ids[$item->cid] = $item->cid;
          }
          foreach ($list as $item) {
              if ($this_treename) {
                  if ($item->cid != $cat->cid
                      && strpos($item->title, $this_treename) === false
                      && array_key_exists($item->cid, $childs_ids) === false
                  ) {
                      $options[] = JHTML::_('select.option',$item->cid, $item->name);
                  }
              } else {
                  if ($item->cid != $cat->cid) {
                      $options[] = JHTML::_('select.option',$item->cid, $item->name);
                  } else {
                      $this_treename = "$item->title/";
                  }
              }
          }

          $parent = null;
          $parent = JHTML::_('select.genericlist',$options, 'parent_id',
              'class="inputbox" size="1"', 'value', 'text', $cat->parent_id);
          return $parent;

      }

      static function imageList($name, $active, $javascript = null, $directory = null)
      {
          if (!$javascript) {
              $javascript = "onchange=\"javascript: if (jQuerOs('#$name').val()!='')    " .
                  "{jQuerOs('[name=imagelib_" . $name . "]').attr('src', '" . JURI::ROOT() . "/images/os-cck/' + jQuerOs('#$name').val())} else {jQuerOs('[name=imagelib_" . $name . "]').attr('src', '" . JURI::ROOT() . "components/com_os_cck/images/blank.png')}\"";
          }
          if (!$directory) {
              $directory = '/images/os-cck';
          }

          if (!file_exists(JPATH_SITE . $directory)) {
              @mkdir(JPATH_SITE . $directory, 0777);
          }

          $imageFiles = mosReadDirectory(JPATH_SITE . $directory);
          $images = array(JHTML::_('select.option','', cck_lang_text('COM_OS_CCK_A_SELECT_IMAGE')));
          foreach ($imageFiles as $file) {
              if (preg_match("/bmp|gif|jpeg|jpg|png/i", $file)) {
                  $images[] = JHTML::_('select.option',$file);
              }
          }
          $images = JHTML::_('select.genericlist',$images, $name, 'id="' . $name . '" class="inputbox" size="1" '
              . $javascript, 'value', 'text', $active);
          return $images;

      }

      static function entityList($active){
        global $db;
        $db = new os_cckDb();
        $query = 'SELECT eid, name FROM #__os_cck_entity WHERE published="1" AND approved="1" ';
         $db->setQuery($query);
         $entities = $db->loadObjectList();
         $options[] = JHTML::_('select.option', '*', 'All Entities');
         foreach ($entities AS $entity){
             $options[] = JHTML::_('select.option',$entity->eid, $entity->name);
         }

        $entity_list = JHTML::_('select.genericlist',$options, 'entity_id', 'class="inputbox" size="1"', 'value', 'text', $active);

        return $entity_list;
      }

      static function categoryEntityList($active){
        global $db;
        $db = new os_cckDb();
        $query = 'SELECT eid, name FROM #__os_cck_entity WHERE published="1" AND approved="1" ';
         $db->setQuery($query);
         $entities = $db->loadObjectList();
         $options[] = JHTML::_('select.option', '*', 'All Entities');
         foreach ($entities AS $entity){
             $options[] = JHTML::_('select.option',$entity->eid, $entity->name);
         }

        $entity_list = JHTML::_('select.genericlist',$options, 'entity_id', 'class="inputbox" size="1" onchange="swich_task('."'edit_category'".');lay_type_select();"', 'value', 'text', $active);

        return $entity_list;
      }

  }
}

if (!function_exists('checkAccess_cck')) {
  function checkAccess_cck($accessgroupid, $usersgroupid, $eid=0, $check_type='fields', $eiid = '') {
      global $cck_entity_configuration, $db;
      $db = new os_cckDb();
      // var_dump($accessgroupid);
      if(($eid > 0 && isset($cck_entity_configuration[$eid]) && isset($cck_entity_configuration[$eid]['check_access_'.$check_type]) && $cck_entity_configuration[$eid]['check_access_'.$check_type] == 0)){
          return true;
      }
      if(isset($accessgroupid[0]) && $accessgroupid[0] == '' && !$eid){
          echo '<script>alert("' . cck_lang_text("COM_OS_CCK_INFOTEXT_JS_NO_ACCESS_GROUP_SELECTED") . '");</script>';
          return;
      }

    if(empty($accessgroupid))return 0;
      if (!is_array($usersgroupid)) {
          $usersgroupid = explode(',', $usersgroupid);
      }

      //parse usergroups
      $tempArr = array();
      if (!is_array($usersgroupid)) {
          $tempArr = explode(',', $accessgroupid);
      }elseif(!is_array($accessgroupid)){
         $tempArr[] = $accessgroupid;
      }else{
          $tempArr = $accessgroupid;
      }
      //var_dump($tempArr);
      for ($i = 0; $i < count($tempArr); $i++) {
          if (((!is_array($usersgroupid) && $tempArr[$i] == $usersgroupid) OR
                 (is_array($usersgroupid) && in_array($tempArr[$i], $usersgroupid))) || $tempArr[$i] == 1 || $tempArr[$i] == '' ) {//|| $usersgroupid[$i] == 8//SuperUser
              //allow access
              return true;
          }
      }
      if(in_array('buyer', $accessgroupid) && $eiid != ''){
          $my = JFactory::getUser();
          $query = "SELECT COUNT(ord.id) FROM #__os_cck_orders as ord "
                  . "LEFT JOIN #__os_cck_orders_price as opr ON ord.id = opr.fk_order_id "
                  . "WHERE opr.fk_eiid='$eiid' AND ord.user_email='$my->email' AND ord.status='Completed'";
          $db->setQuery($query);
          $count = $db->loadResult();
          if($count > 0){
              return true;
          }
          //var_dump($count);
      }elseif(in_array('owner', $accessgroupid) && $eiid != ''){
        if(is_array($eiid)){
          $my = JFactory::getUser();
          $to_return = true;
          foreach($eiid as $single_eiid){
            $entityInstanse = new os_cckEntityInstance($db->_db);
            $entityInstanse->load($single_eiid);
            if($my->id != $entityInstanse->fk_userid){
              $to_return = false;
            }  
          }
          return $to_return;
        }else{
          $my = JFactory::getUser();
          $entityInstanse = new os_cckEntityInstance($db->_db);
          $entityInstanse->load($eiid);
          if($my->id == $entityInstanse->fk_userid){
              return true;
          }
        }
      }
        // end for
      //deny access
      return 0;
  }
}

if(!function_exists('checkRentCCK')){


  function checkRentCCK ($from, $until, $rent_from, $rent_until){
      global $os_cck_configuration;
      //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
      if($os_cck_configuration->get('rent_type') != 2){
          $rent_from_temp = new DateTime($rent_from);
          $rent_from = $rent_from_temp->format("Y-m-d");
          $rent_until_temp = new DateTime($rent_until);
          $rent_until = $rent_until_temp->format("Y-m-d");
          $from_temp = new DateTime($from);
          $from = $from_temp->format("Y-m-d");
          $until_temp = new DateTime($until);
          $until = $until_temp->format("Y-m-d");
      }else{
          $rent_from_temp = new DateTime($rent_from);
          $rent_from = $rent_from_temp->format("Y-m-d H:i:s");
          $rent_until_temp = new DateTime($rent_until);
          $rent_until = $rent_until_temp->format("Y-m-d H:i:s");
          $from_temp = new DateTime($from);
          $from = $from_temp->format("Y-m-d H:i:s");
          $until_temp = new DateTime($until);
          $until = $until_temp->format("Y-m-d H:i:s");
      }
//var_dump($from);
//      var_dump($until);
//      var_dump($rent_from);
//      var_dump($rent_until); exit;
        
        //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
        if($os_cck_configuration->get('rent_type') == 2){
              if (( $rent_from > $from &&
                    $rent_from < $until) || ($rent_from <= $from &&
                    $rent_until >= $until) || (
                    $rent_until > $from && $rent_until < $until))
                  {
                      return 'Sorry, this item not is available from " '. $from .' " until " '. $until . '"';
                  }
          //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time                  
          }elseif($os_cck_configuration->get('rent_type') != 0){
              if (( $rent_from >= $from &&
                    $rent_from <= $until) || ($rent_from <= $from &&
                    $rent_until >= $until) || (
                    $rent_until >= $from && $rent_until <= $until))
                  {
                      return 'Sorry, this item not is available from " '. $from .' " until " '. $until . '"';
                  }
          }else{
//              var_dump($rent_from === $rent_until);
//              var_dump($rent_until);
//              exit;
              if($rent_from === $rent_until){
                  return 'Sorry, not one night, not selected';
              }

              if (( $rent_from > $from &&
                    $rent_from < $until) || ($rent_from <= $from &&
                    $rent_until >= $until) || (
                    $rent_until > $from && $rent_until < $until))
                  {

                  return 'Sorry, this item not is available from " '. $from .' " until " '. $until . '"';
              }
          }

  }
}
if(!function_exists('getEntityName')){
    function getEntityName($eid){
        global $db;
        $db = new os_cckDb();
        if($eid == '0'){
            $entity_name = "All entities";
        }else{
            $query = "SELECT name FROM #__os_cck_entity WHERE eid=".$eid;
            $db->setQuery($query);
            $entity_name = $db->loadResult();
        }
        return $entity_name;

    }

}


if(!class_exists('getLayoutPathCCK')){
  class getLayoutPathCCK{

    static function getLayoutPathCom($components,$type, $layout = 'default'){
      $template = JFactory::getApplication()->getTemplate();
      if ( $layout  === "")  $layout = 'default' ;
      $defaultLayout = $layout;

      if (strpos($layout, ':') !== false){
        // Get the template and file name from the string
        $temp = explode(':', $layout);
        $template = ($temp[0] == '_') ? $template : $temp[0];
        $layout = $temp[1];
        $defaultLayout = ($temp[1]) ? $temp[1] : 'default';
      }
      if($type == 'search') $type = 'show_search';
      // Build the template and base path for the layout
      $tPath = JPATH_THEMES . '/' . $template . '/html/' . $components . '/'.$type.'/tmpl_'. $layout . '.php';
      //VlaDOS 29.04.2021
      //$cPath = JPATH_BASE . '/components/' . $components . '/views/'.$type.'/tmpl/tmpl_'.$layout.'.php';
      //VlaDOS 29.04.2021
      $cPath = JPATH_SITE . '/components/' . $components . '/views/'.$type.'/tmpl/tmpl_'.$layout.'.php';
      $dPath = JPATH_BASE . '/components/' . $components . '/views/'.$type.'/tmpl/tmpl_default.php';


      // If the template has a layout override use it
      //print_r(file_exists($tPath));exit;
      // var_dump($cPath);
      if (file_exists($tPath)){
        return $tPath;
      }
      else if (file_exists($cPath)){
        return $cPath;
      }
      else if (file_exists($dPath)){
        return $dPath;
      } else {
  // echo '33333333333';
        echo "Bad layout path, please write to admin";
        exit;
      }
    }


    static function getAdminLayoutViewPath($components, $type, $viewName = 'default'){

      $Path = JPATH_BASE . '/components/' . $components . '/views/'.$type.'/tmpl/tmpl_'.$viewName.'.php';
      $layoutPath = JPATH_BASE . '/components/' . $components . '/views/layoutViews/'.$type.'/tmpl/tmpl_'.$viewName.'.php';
      if (file_exists($Path)){
        return $Path;
      }else if(file_exists($layoutPath)){

        return $layoutPath;
      } else {
        echo "Bad layout path, please write to admin";
        exit;
      }

    }
  }
}

if(!function_exists('return_bytes')){
  function return_bytes($val)
  {
      if (empty($val)){
          return 0;
      }

      $val = trim($val);
      preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);
      $last = '';

      if (isset($matches[2])){
          $last = $matches[2];
      }

      if (isset($matches[1])){
          $val = (int) $matches[1];
      }

      switch (strtolower($last)){
          case 'g':
          case 'gb':
              $val *= 1024;
          case 'm':
          case 'mb':
              $val *= 1024;
          case 'k':
          case 'kb':
              $val *= 1024;
      }

      return (int) $val;
  }
}

if(!function_exists('transforDateFromPhpToJqueryCCK')){
  function transforDateFromPhpToJqueryCCK($format){

      $DateToFormat = str_replace("d",'dd',(str_replace("m",'mm',(str_replace("Y",'yy',(
      str_replace('%','',$format)))))));
    return $DateToFormat;
  }
}


if(!function_exists('get_average_rating')){
  function get_average_rating($field, $layout, $entityInstance){
    global $db;
    $db = new os_cckDb();
    $query = "SELECT AVG(cei.$field->db_field_name) FROM #__os_cck_child_parent_connect as ch "
                ."\n LEFT JOIN #__os_cck_entity_instance as ei ON ch.fid_child = ei.eiid"
                ."\n LEFT JOIN #__os_cck_layout as lay ON lay.lid = ei.fk_lid"
                ."\n LEFT JOIN #__os_cck_content_entity_$entityInstance->fk_eid as cei ON cei.fk_eiid = ei.eiid"
                ."\n WHERE ch.fid_parent=$entityInstance->eiid AND (lay.type='review_instance' OR lay.type='add_review_instance' )";
    $db->setQuery($query);
    $value[0] = new stdClass();
    //$value[0]->data = round($db->loadResult() * 2) / 2;
    $value[0]->data = $db->loadResult() * 2;


    return $value;
  }
}

if(!function_exists('getLayoutType')){
  function getLayoutType($type){
    switch($type){
      case "add_instance":
          $type = "Add Instance";
        break;

      case "all_categories":
        $type = "All Categories";
        break;

      case "all_instance":
        $type = "All Instance";
        break;

      case "calendar":
        $type = "Calendar";
        break;

      case "category":
        $type = "Show Category";
        break;

      case "instance":
        $type = "Show Instance";
        break;

      case "search":
        $type = "Show Search";
        break;

      case "request_instance":
        $type = "Add Request Instance";
        break;

      case "rent_request_instance":
        $type = "Add Rent Request Instance";
        break;

      case "buy_request_instance":
        $type = "Add Buy Request Instance";
        break;

      case "review_instance":
        $type = "Add Review Instance";
        break;

      case "show_review_instance":
        $type = "Show Review Instance";
        break;

      case "user_instances":
        $type = "User Instances";
        break;

      case "parent_child":
        $type = "Parent-Child";
        break;

      case "cart":
        $type = "Cart";
        break;
      case "all_categories_pdf":
        $type = "All Categories PDF";
        break;
      case "all_instance_pdf":
        $type = "All Instance PDF";
        break;
      case "parent_child_pdf":
        $type = "Parent-Child PDF";
        break;
      case "pdf":
        $type = "Show Instance PDF";
        break;
      case "category_pdf":
        $type = "Show Category PDF";
        break;
      case "user_instances_pdf":
        $type = "User Instances PDF";
        break;
    }
    return $type;
  }
}

if (!function_exists('get_align_styles')) {
  function get_align_styles($field, $layout){
    $layout_params = unserialize($layout->params);
    $params = new JRegistry;

    if(is_string($field) && $field != ''){
        if(isset($layout_params['fields']['Params_'.$field])){
            $params = $params->loadString($layout_params['fields']['Params_'.$field]);
        }else{
            return '';
        }

    }elseif($field->db_field_name == 'form-'.$layout->lid){
      $params = $params->loadString($layout_params['form_params']);
    }else{

      if(isset($layout_params['fields']['Params_'.$field->db_field_name])){
        $params = $params->loadString($layout_params['fields']['Params_'.$field->db_field_name]);
      }
    }

    $align = ($params->get('text_align',''))? $params->get('text_align') : '';

    $align_style = 'style="display:block;';

    //text-align
    if($align)
      $align_style .= 'text-align:'.$align.';';
    $align_style .= '"';

    return $align_style;
  }
}


if (!function_exists('get_hover_css_style')) {
    function get_hover_css_style($field, $layout_params, $type = 'field', $unique_class = false){
        $field_from_params = $layout_params["fields"];
          $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);
//          var_dump($field);
          $hover_border_collor = '';
          $hover_background_color = '';
          $hover_text_color = '';
          $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($type == 'layout' && $unique_class){
              $hover_class = $unique_class . '>div>div>input[type=button]';
          }else{
              $hover_class = $field->db_field_name;
          }

          $hover =
          '<style type="text/css"> .' . $hover_class . ':hover{
                color: ' . $hover_text_color . ' !important;
                border-color: ' . $hover_border_collor . ' !important;
                background-color: ' . $hover_background_color . ' !important;

            }
        </style>';
          return ($hover);

    }
}

if (!function_exists('processing_php_show')) {
    function processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout){
        $func_result = replaceMaskCustomCodePHP($entityInstance,$php_if, $layout_params, $layout_html, $layout);
      //  
        extract($func_result['variables_arr']);
        // var_dump($func_result); exit;
        try {
          $processing_result = eval($func_result['custom_code_str']);
        } catch (Exception $ex) {
          echo $ex->getMessage(); exit;
        }
        
        //var_dump($processing_result);
        return $processing_result;
    }
}

if(!function_exists('calculatedCurrency')){
    function calculatedCurrency($entityInstance, $value, $converTo = '', $numberFormat = array()){
        global $os_cck_configuration, $session;

        $select_currency = $session->get('currency', '');
        $paypal_currency = isset($entityInstance->instance_currency)?$entityInstance->instance_currency:'';
        // var_dump($paypal_currency);
        $currencys = explode(';', $os_cck_configuration->get('paypal_currency',''));
        // var_dump($currencys);
        if($paypal_currency == ''){
            $paypal_currency = substr($currencys[0], 0, strpos($currencys[0], '='));
        }
        // var_dump($paypal_currency); exit;
        if($select_currency == ''){
            $select_currency = $paypal_currency;
        }
        if($converTo != ''){
            $select_currency = $converTo;
            $paypal_currency = $converTo;
        }
        $select_currency = trim($select_currency);
          $currencyArr = array();
          $currentCurrency = '';

          
          foreach ($currencys as $oneCurency) {
            $oneCurrArr = explode('=', $oneCurency);
            // var_dump($oneCurrArr);
            if(!empty($oneCurrArr[0]) && !empty($oneCurrArr[1])){
             $currencyArr[$oneCurrArr[0]] = $oneCurrArr[1];
             if(isset($paypal_currency) && stripos($oneCurrArr[0], trim($paypal_currency)) !== FALSE){
               $currentCurrency = $oneCurrArr[0];
             }
           }
         }
         
        $currencys_price = array();
        // var_dump($currencyArr);
        foreach ($currencyArr as $key=>$value2) {
          if (!isset($currentCurrency)) {
              
              if(stripos($key, $select_currency ) !== FALSE){
                $currencys_price[$key] = round($value2, 2);
              }
          } else {
            //VlaDOS 04.02.2023
            // S etoy proverkoy ne pereklyu4autsa valuty, vernul staruyu proverku, za4em my ee menyali ya v upor ne pomnyu
            //  if(stripos($key, $currentCurrency ) !== FALSE){
              //VlaDOS 04.02.2023 END
              if(stripos($key, $select_currency ) !== FALSE){
                // var_dump($currentCurrency); exit;
                //$currencys_price[$key] = round(($value2 / $currentCurrency) * $value[0]->price_value, 2);
                $currencys_price[$key] = round($value2 * $value, 2);
                // var_dump($currencys_price);
                // $currencys_price[$key] = round((($value2 / $currentCurrency) * $value), 2);
              }
          }
        }

        $val = array();
        
        foreach ($currencys_price as $key => $value2){
            if(!empty($numberFormat)){
                $value2 = number_format(
                    $value2,
                    $numberFormat['digits_points'],
                    $numberFormat['decimal_separator'],
                    $numberFormat['thousands_separator']
                );
            }
            $carrency_symbol = explode('|', $key);
            if(isset($carrency_symbol[1])){
                $carrency_symbol = $carrency_symbol[1];
            }else{
                $carrency_symbol = $carrency_symbol[0];
            }
          if($os_cck_configuration->get('currency_position','0')){
            $val[] = $carrency_symbol.' '.$value2;
            $val[] = $value2;
            //$val .= (isset($value[0]->data))? $value[0]->data : '0';
          }else{
            $val[] = $value2 . ' '.$carrency_symbol;
            $val[] = $value2;
            //$val.= ' '.$paypal_currency;
          }
        }

        return $val;
    }
}

if(!function_exists('getCalculatedPrice')){
    function getCalculatedPrice($price_fields, $eiid = -1, $orderingCalculateField=51, $coup_id = ''){
      global $db;

      $db = new os_cckDb();
      $field_list = array();

      if(empty($price_fields)){
          return;
      }

      $fk_order_id = 0 ;
      foreach ($price_fields as $price_filed){

        if( isset($price_filed->price_type) && $price_filed->price_type == 'coupon'){
          continue ;
        }        

        if(!$price_filed || $price_filed == null || 
            (  !property_exists($price_filed, 'fid') 
              && !property_exists($price_filed, 'fk_fid') ) ) continue;

        if( property_exists($price_filed, 'fid')  ) $fid = $price_filed->fid ;
        elseif( property_exists($price_filed, 'fk_fid')  ) $fid = $price_filed->fk_fid ;

        if(isset($price_filed->calculated) && $price_filed->calculated == 0){continue;}

        $field = new os_cckEntityField($db->_db);
        $field->load($fid);
        if( !isset($field->fid) ) continue; //sanity test, when in cart products fro old export 

        if( $eiid == -1 )  $eiid = $price_filed->fk_eiid ; //need for coupon calculate        
        if( isset($price_filed->fk_order_id) && $price_filed->fk_order_id > 0 )  $fk_order_id = $price_filed->fk_order_id ; //need for coupon calculate        

        $layout = new os_cckLayout($db->_db);
        if( isset($price_filed->lid) ) $layout->load($price_filed->lid);
        else {
           $lid = $layout->getDefaultLayout($price_filed->fk_eid, 'instance');
           $layout->load($lid);
        }
        $layout_params = (isset($layout->params) )?( unserialize($layout->params) ): "";

        $calculate_ordering = (isset($layout_params['fields'][$field->db_field_name . '_calculation_order'])) ? $layout_params['fields'][$field->db_field_name . '_calculation_order'] : 0;
        $calculate_type = (isset($layout_params['fields'][$field->db_field_name . '_price_type'])) ? $layout_params['fields'][$field->db_field_name . '_price_type'] : 'base';


        if( isset($price_filed->value) ){
          //$query = "SELECT price_value FROM #__os_cck_prices WHERE fk_fid='$price_filed->fid' AND fk_eiid='$eiid' AND ordering='$price_filed->value'";
          $query = "SELECT price_value FROM #__os_cck_content_instances_price WHERE price_id='$price_filed->value'";
          $db->setQuery($query);
          $value = $db->loadResult();
        }

        $temp_field = new stdClass;
        $temp_field->calculate_ordering = $calculate_ordering;
        $temp_field->calculate_type = $calculate_type;
        if(isset($price_filed->quantity)){
            $temp_field->quantity = $price_filed->quantity;
        }else{
            $temp_field->quantity = 1;
        }

        if(isset($value) ){
          $temp_field->value = $value;
        } else {
          $temp_field->value = $price_filed->price_value;
        }
        $field_list[] = $temp_field;
      }

      uasort($field_list, function($f1, $f2){
          if($f1->calculate_ordering < $f2->calculate_ordering) return -1;
          elseif($f1->calculate_ordering > $f2->calculate_ordering) return 1;
          else return 0;
      } );

      $calculated_price = 0;
      foreach ($field_list as $field){
          if($field->calculate_ordering <= $orderingCalculateField){
            if($field->calculate_type == 'val+' || $field->calculate_type == 'base_price' || $field->calculate_type == 'base'){
                $calculated_price = $calculated_price + ($field->value * $field->quantity);
            }else if($field->calculate_type == 'val-'){
                $calculated_price = $calculated_price - ($field->value * $field->quantity);
            }else if($field->calculate_type == 'percent+'){
                $calculated_price = $calculated_price + ($calculated_price/100 * $field->value);
            }else if($field->calculate_type == 'percent-'){
                $calculated_price = $calculated_price - ($calculated_price/100 * $field->value);
            }
          }
      }
      $price_without_coupon = $calculated_price ;;
      
      $coupon_discount = 0;
      
      if($coup_id != '' && $coup_id != -1){
        $coupon = new os_cckCoupons($db->_db);

        $is_coupon_valid = false;
        if( $fk_order_id > 0 ){
          //if order exist, search coupon in order details
          $coupon = $coupon->loadByOrderId($fk_order_id);
          $is_coupon_valid = checkCouponInstance($coupon->coup_id, $eiid);
        }
        if( $fk_order_id == 0 || $coupon == null ) {
          $coupon->load($coup_id);
          $is_coupon_valid = checkCouponInstance($coup_id, $eiid);
        }       

        if( $is_coupon_valid ){
            if($coupon->type == 'percent'){
                $coupon_discount = round(($calculated_price/100 * $coupon->value), 2);
            }else{
                $coupon_discount = round($coupon->value, 2);
            }
            $calculated_price = $calculated_price - $coupon_discount;
        }
      }

      $calculated_price = round($calculated_price, 2);
      return array( 'calculated_price' => $calculated_price, 'coupon_discount' => $coupon_discount, 'price_without_coupon' => $price_without_coupon);
    }
}

if(!function_exists('getValuesForChildEnteties')){
    function getValuesForChildEnteties($childEntityFields, $eid, $order_by = '', $search = '', $sql_where = ''){
        global $db, $entityFieldLists, $entities_type, $app;
        $db = new os_cckDb();

        $order_by_string = '';
        $where = '';
//        var_dump($entities_type[$eid]);
        if(!isset($entities_type[$eid])){
            return array();
        }
//        var_dump($entities_type[$eid]); exit;
        if($entities_type[$eid] == 'os_cck_entity'){
            if($order_by == 'id') $order_by = 'fk_eiid';
            $order_join = '';
            if($order_by != ''){
                if(stripos($order_by, 'pricefield_number') !== false){
                    $fid = substr(trim($order_by, "'"), strripos($order_by, '_')+1);
//                    $order_join = ' LEFT JOIN #__os_cck_content_instances_price as pr ON pr.fk_eiid = ei.eiid ';
                    $order_by_string = ' ORDER BY pr.price_value ';
                    $where = ' AND pr.fk_fid='.$fid ;
                }elseif(stripos($order_by, 'categoryfield') !== false){
                    $fid = substr(trim($order_by, "'"), strripos($order_by, '_')+1);
//                    $order_join = ' LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = ei.eiid '
//                            . ' LEFT JOIN #__os_cck_categories as cat ON cat.cid = cc.fk_cid ';
                    $order_by_string = ' ORDER BY cat.title ';
                    //$where = ' AND cc.fk_cid='.$fid ;
                }elseif(stripos($order_by, 'filefield') !== false){
                    $order_join = ' LEFT JOIN #__os_cck_files as file ON file.fid = ce.'.$order_by.'_fid ';

                    $order_by_string = ' ORDER BY file.filename ';
                }else{
                    $order_by_string = ' ORDER BY ce.'. trim($order_by, "'") . ' ';
                }
            }
            $query = "SELECT DISTINCT ei.eiid FROM #__os_cck_entity_instance as ei "
                . "LEFT JOIN #__os_cck_entity as ent ON ent.eid = ei.fk_eid "
                . "LEFT JOIN #__os_cck_layout as lay ON lay.lid = ei.fk_lid "
                . "LEFT JOIN #__os_cck_content_entity_$eid as ce ON ce.fk_eiid = ei.eiid "
                . "LEFT JOIN #__os_cck_content_instances_price as pr ON pr.fk_eiid = ei.eiid "
                . "LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = ei.eiid "
                . "LEFT JOIN #__os_cck_categories as cat ON cat.cid = cc.fk_cid "
                . $order_join
                . "WHERE ei.fk_eid=$eid AND lay.type='add_instance' $where $sql_where $order_by_string";
        }elseif ($entities_type[$eid]  == 'joomla_user') {
            $request_details = getJoinForOrderByJoomlaUser($order_by);
            $query = "SELECT DISTINCT us.id as eiid FROM #__users as us "
                    . "LEFT JOIN #__user_usergroup_map as ugm ON ugm.user_id = us.id "
                    . "LEFT JOIN #__usergroups as ug ON ug.id = ugm.group_id "
                    . "LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id "
                    . "LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                    . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
            //$query .= $request_details['join'];
            $query .= ' WHERE block=0 ' . $sql_where;
            $query .= $request_details['where'] . ' ' . $request_details['order_by'];

        }elseif($entities_type[$eid]  == 'custom_sql'){
            $entity = new os_cckEntity($db->_db);
            $entity->load($eid);

//            var_dump($entityFieldLists[$eid]['custom_sql_id']);
//            var_dump($entity); exit;
            $query = "SELECT DISTINCT t.".$entityFieldLists[$eid]['custom_sql_id']->fid." as eiid FROM ($entity->sql_select) as t";
//            var_dump($query); exit;
        }

        $db->setQuery($query);
//        echo $query; exit;
        $instensiesId = $db->loadObjectList();
//        var_dump($instensiesId);
        $childEntityFields = array_unique(explode(',', $childEntityFields));
        //var_dump($childEntityFields);
        $field_values = array();
        if($search === ''){
            $field_values[] = JHTML::_('select.option', 0, 'Select value', "value", "text");
            if ($entities_type[$eid]  == 'joomla_user') {
                $field_values[] = JHTML::_('select.option', 'owner', 'Owner', "value", "text");
            }
        }
        if(count($instensiesId) > 0){
            //var_dump($instensiesId);
            for($i=0;$i<count($instensiesId); $i++){
                if($entities_type[$eid]  == 'os_cck_entity'){
                    $entityInstance = new os_cckEntityInstance($db->_db);
                    $entityInstance->load($instensiesId[$i]->eiid);
                    $print_var = '';
                    foreach($childEntityFields as $childEntityField){
                        if($childEntityField != 'id'){
                            $field = new os_cckEntityField($db->_db);
                            $field->load($childEntityField);
                            if(property_exists($field, 'fid') && $field->fid){
                              $value = $entityInstance->getFieldValue($field);
                            }else{
                              $data = new stdClass();
                              $data->data = '';
                              $value = array($data);
                              
                            }
//                            $value = $entityInstance->getFieldValue($field);
                            if($field->field_type == 'text_select_list'){

                                $value[0]->data = json_decode($value[0]->data);
                                if(is_array($value[0]->data)){
                                    $temp_val = '';
                                    foreach ($value[0]->data as $data){
                                        $temp_val .= $data . ', ';
                                    }
                                    $value[0]->data = substr($temp_val, 0, -2);
                                }

                            }elseif($field->field_type == 'pricefield_number'){
                                $value[0]->data = $value[0]->price_value;
                            }elseif($field->field_type == 'categoryfield'){
                                $value[0]->data = $value[0]->title;
                            }
                            $print_var .= $value[0]->data . ', ';
                        }else{
                            $print_var .= $instensiesId[$i]->eiid . ', ';
                        }
                    }

                }elseif ($entities_type[$eid]  == 'joomla_user') {

                      //var_dump($user->id);
                    $field_list = $entityFieldLists[$eid];
                    $instance = ConvertEntityInstanceToUser($eid, $instensiesId[$i]->eiid);
                    $user = JFactory::getUser($instensiesId[$i]->eiid);
                    $print_var = '';
                    $temp_field_list = array();
                    foreach($field_list as $field){
                        foreach($childEntityFields as $childEntityField){

                            if($field->fid == $childEntityField){
                                $temp_field_list[] = $field;

                            }

                        }
                    }
                    $profile_and_custom_field_init = check_profile_and_custom_field_init($temp_field_list);
                    if($profile_and_custom_field_init){

                        JPluginHelper::importPlugin('user');
                        JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
                        $user_profile_form = JForm::getInstance('com_users.user', 'profile');
                        $results2 = $app->triggerEvent('onContentPrepareData', array('com_users.user', $user));
                        $results = $app->triggerEvent('onContentPrepareForm', array($user_profile_form, $user));
                        $user_profile_form->bind($user);
                    }else{
                        $user_profile_form = '';
                    }
                    foreach($temp_field_list as $field){
                        $value = $instance->getFieldValue($field, $entities_type[$eid] , $user_profile_form, $user);
                        $print_var .= $value[0]->data . ', ';
                    }

                    //var_dump($profile_and_custom_field_init);
                }elseif ($entities_type[$eid]  == 'custom_sql') {
                    $field_list = $entityFieldLists[$eid];
//                    var_dump($instensiesId[$i]->eiid);
                    $entityInstance = ConvertEntityInstanceToCustomSql($entity, $instensiesId[$i]->eiid);
//                    $entityInstance->load($instensiesId[$i]->eiid);
                    $print_var = '';
//                    var_dump($childEntityFields);
                    foreach($childEntityFields as $childEntityField){
                        if($childEntityField != 'id'){
//                            echo '11111111111111';
                            foreach($field_list as $temp_field){
//                                foreach($childEntityFields as $childEntityField){

                                    if($temp_field->fid == $childEntityField){
                                        $field = $temp_field;

                                    }

//                                }
                            }

                            $value = $entityInstance->getFieldValue($field, 'custom_sql');
//                            var_dump($field);
                            if($field->field_type == 'text_select_list'){

                                $value[0]->data = json_decode($value[0]->data);
                                if(is_array($value[0]->data)){
                                    $temp_val = '';
                                    foreach ($value[0]->data as $data){
                                        $temp_val .= $data . ', ';
                                    }
                                    $value[0]->data = substr($temp_val, 0, -2);
                                }

                            }elseif($field->field_type == 'pricefield_number'){
                                $value[0]->data = $value[0]->price_value;
                            }elseif($field->field_type == 'categoryfield'){
                                $value[0]->data = $value[0]->title;
                            }
                            $print_var .= $value[0]->data . ', ';
                        }else{
                            $print_var .= $instensiesId[$i]->eiid . ', ';
                        }
                    }
                }
                $print_var = substr($print_var, 0, -2);
                //if(stripos($print_var, $search) !== false)
                if($search === ''){
                    $field_values[] = JHTML::_('select.option', $instensiesId[$i]->eiid, $print_var, "value", "text");
                }elseif(stripos($print_var, $search) !== false){
                    $field_values[] = array('value' => $instensiesId[$i]->eiid, 'label' => $print_var);
                }
            }
        }
        return $field_values;
    }
}

if(!function_exists('getChildEntityFieldValue')){
    function getChildEntityFieldValue($entityInstance, $childEntityFieldName){
        global $db;
        $db = new os_cckDb();
        $query = "SELECT fid_child FROM #__os_cck_child_parent_connect WHERE fid_parent='$entityInstance->eiid' AND media_type='$childEntityFieldName'";
        $db->setQuery($query);
        $value = $db->loadObjectList();

        if(!$value){
            $value = 0;
        }
        return $value;
    }
}

if(!function_exists('getChildInstance')){
    function getChildInstance($child_entity, $entityInstance, $childEntity){
        global $db;
        $db = new os_cckDb();
        if(!is_object($entityInstance)) return;
        $pos = strpos($child_entity->data_field_name,'_'.$child_entity->childEntityFields);
        $field_mask = substr($child_entity->data_field_name, 0 , $pos);
        if($field_mask == 'owner' && $childEntity->type == 'joomla_user'){
            if(is_object($entityInstance)){
                $child_instance = $entityInstance->fk_userid;
            }else{
                $child_instance = $entityInstance;
            }
        }else{
            $query = "SELECT fid_child FROM #__os_cck_child_parent_connect WHERE fid_parent='$entityInstance->eiid' AND media_type='$field_mask'";
            $db->setQuery($query);
            $child_instance = $db->loadResult();
        }

        return $child_instance;
    }
}

if(!function_exists('getChildInstancies')){
    function getChildInstancies($child_entities, $entityInstance){
        global $db, $entities_type, $entityFieldLists;
        $db = new os_cckDb();
        $child_istancies = array();

        $child_instancies_fields = array();
        //var_dump($child_entities);
        foreach($child_entities as $child_entity){
            //var_dump($child_entity);
            $pos = strrpos($child_entity->data_field_name,'_'.$child_entity->childEntityFields);
            $field_mask = substr($child_entity->data_field_name, 0 , $pos);
            if($field_mask == 'owner' && $entities_type[$child_entity->childEntityId] == 'joomla_user'){
                $child_instance = $entityInstance->fk_userid;
                if(!isset($child_istancies[$child_entity->childEntityId][$child_instance])){
                    $child_istancies[$child_entity->childEntityId][$child_instance] = ConvertEntityInstanceToUser($child_entity->childEntityId, $child_instance);
                }
                $child_instancies_fields[$child_entity->childEntityId][$child_instance][] = $child_entity;
            }else{
                if($entities_type[$child_entity->childEntityId] == 'custom_sql' && $entities_type[$entityInstance->fk_eid] == 'custom_sql'){
//                    var_dump($child_entity);
                    $field_mask == 'sql_entity';
                    $childEntity = new os_cckEntity($db->_db);
                    $childEntity->load($child_entity->childEntityId);
                    $entity = new os_cckEntity($db->_db);
                    $entity->load($entityInstance->fk_eid);
                    $childFieldLists = $entityFieldLists[$child_entity->childEntityId];
                    $related_fields = explode(';', $child_entity->related_fields);
                    $child_instance_id = explode('_', $child_entity->data_field_name);
//                    var_dump($child_instance_id); exit;
                    $child_instance_id = $child_instance_id[0];
                    $child_instance_id_field = $childFieldLists['custom_sql_id'];
//                    foreach($childFieldLists as $childField){
//                        if($childField->custom_field_type == 'child_id'){
//                            $childIdField = $childField;
//                        }
//                    }
//                    var_dump($childFieldLists); exit;
//                    var_dump($entityInstance->eiid);
                    $query = "SELECT DISTINCT child_query.".$childFieldLists['custom_sql_id']->fid." as fid_child FROM ($entity->sql_select) as parent_query "
                            . "LEFT JOIN ($childEntity->sql_select) as child_query ON child_query.".$related_fields[1] . " = parent_query.".$related_fields[0]." "
                            . "WHERE parent_query.".$entityFieldLists[$entityInstance->fk_eid]['custom_sql_id']->fid." = $entityInstance->eiid "
                            . "AND child_query.$child_instance_id_field->fid = $child_instance_id";
//                    echo $query;
//                    var_dump($query); exit;
                }else{
                    $query = "SELECT fid_child FROM #__os_cck_child_parent_connect WHERE fid_parent='$entityInstance->eiid' AND media_type='$field_mask'";
                }
//                var_dump($entities_type[$child_entity->childEntityId]);
//                var_dump($entityInstance);


                $db->setQuery($query);
                $child_instance = $db->loadResult();
//                echo $query; exit;
//                var_dump($child_instance);
                if(!isset($child_istancies[$child_entity->childEntityId][$child_instance])){
                    if($entities_type[$child_entity->childEntityId] == 'os_cck_entity'){
                        if(!isset($GLOBALS['instancies'][$child_instance])){
                            $child_instance_class = new os_cckEntityInstance($db->_db);
                            $child_instance_class->load($child_instance);
                            $child_istancies[$child_entity->childEntityId][$child_instance] = $child_instance_class;
                            $GLOBALS['instancies'][$child_instance] = $child_instance_class;
                        }else{
                            $child_instance_class = $GLOBALS['instancies'][$child_instance];
                            $child_istancies[$child_entity->childEntityId][$child_instance] = $child_instance_class;
                        }
                    }elseif($entities_type[$child_entity->childEntityId] == 'joomla_user'){
                        $child_istancies[$child_entity->childEntityId][$child_instance] = ConvertEntityInstanceToUser($child_entity->childEntityId, $child_instance);
                    }elseif($entities_type[$child_entity->childEntityId] == 'custom_sql'){
//                        var_dump($child_instance);
                        $entity = new os_cckEntity($db->_db);
                        $entity->load($child_entity->childEntityId);
                        if(!isset($childIdField)){
                            $childIdField = false;
                        }

                        $child_istancies[$child_entity->childEntityId][$child_instance] = ConvertEntityInstanceToCustomSql($entity, $child_instance, $childIdField);
                    }
                }
                $child_instancies_fields[$child_entity->childEntityId][$child_instance][] = $child_entity;
            }

        }
        //var_dump($child_instancies_fields);
//
        return array('child_istancies'=>$child_istancies, 'child_instancies_fields'=>$child_instancies_fields);
    }
}

if(!function_exists('get_options_for_layout_select_list')){
    function get_options_for_layout_select_list($type='instance', $eid=0, $lid=0, $lang='*'){
        global $db, $entities_type;
        $db = new os_cckDb();
//        var_dump($eid); exit;
        $lang_where = '';
        if($lang != '*' && $lang != ''){
            $lang_where = " AND c.language='$lang' ";
        }
        if($type == 'instance'){
            $query = "SELECT c.title, c.lid ,c.params,c.type FROM #__os_cck_layout as c "
              ."\n WHERE (type = 'parent_child' OR c.type='instance') "
              ."\n AND c.fk_eid = $eid"
              ."\n AND c.published = '1' $lang_where ";
        }else{
            $query = "SELECT c.title, c.lid ,c.params,c.type FROM #__os_cck_layout as c "
              ."\n WHERE type = 'category' "
              ."\n AND c.fk_eid = $eid"
              ."\n AND c.published = '1' $lang_where ";
        }
        //var_dump($query); exit;
          $db->setQuery($query);
          $layout_list = $db->loadObjectList('lid');
          $instance_layout_list  = array();
          $instanceLayout = array();
          $instanceLayout[] = JHTML::_('select.option','-1','None');
          foreach ($layout_list as $value) {
              $instance_layout_list[$value->lid] = $value->lid;
              $instanceLayout[] =  JHTML::_('select.option',$value->lid,$value->title);
          }
          if(isset($entities_type[$eid]) && $entities_type[$eid] == 'joomla_user'){
              $query = "SELECT COUNT(*) FROM #__extensions WHERE type='component' AND element='com_simplemembership'";
              $db->setQuery($query);
              $simplemembership = $db->loadResult();

              if($simplemembership > 0){
                  $instanceLayout[] = JHTML::_('select.option','sms','Simplemembership profile');
              }
              //var_dump($simplemembership);
          }
          //var_dump($eid);

          return $instanceLayout;
    }
}

if(!function_exists('getPricesForSearch')){
    function getPricesForSearch($eid){
        global $db, $entities_type;
        $db = new os_cckDb();
        $base_price_fields = getBasePriceFields($eid);
        if($entities_type[$eid] == 'custom_sql'){
            $entity = new os_cckEntity($db->_db);
            $entity->load($eid);

            $base_price_fields = explode(',', $base_price_fields);
            $prices = array();
            foreach($base_price_fields as $field){
                $query = "SELECT t.$field as price_value FROM ($entity->sql_select) as t";
                $db->setQuery($query);
                $field_prices = $db->loadColumn();
                $prices = array_merge($prices, $field_prices);
            }
//            var_dump($base_price_fields);
        }else{
            $query = "SELECT price_value FROM #__os_cck_content_instances_price WHERE fk_eid='$eid' AND fk_fid IN ($base_price_fields)";
            $query = "SELECT ei.instance_price FROM #__os_cck_entity_instance as ei "
                    . "LEFT JOIN #__os_cck_layout as lay ON lay.lid = ei.fk_lid "
                    . " WHERE lay.type = 'add_instance' AND ei.fk_eid = '$eid'";
            $db->setQuery($query);
            $prices = $db->loadColumn();
        }


        return $prices;
    }
}

if(!function_exists('getBasePriceFields')){
    function getBasePriceFields($eid){
        global $db, $entityFieldLists, $entities_type;
        $db = new os_cckDb();
        $query = "SELECT lid FROM #__os_cck_layout WHERE fk_eid='$eid' AND type='instance'";
        $db->setQuery($query);
        $lids = $db->loadObjectList();
        $base_price_fields = array();

//        var_dump($entityFieldLists[$eid]);
        foreach ($lids as $lid){
            $layout = new os_cckLayout($db->_db);
            $layout->load($lid->lid);

            $field_list = $entityFieldLists[$eid];
//            var_dump($field_list);
            $layout_params = unserialize($layout->params);

            foreach($field_list as $field){
                if(stripos($field->field_type, 'pricefield') !== FALSE){
                    $price_type = isset($layout_params['fields'][$field->db_field_name . '_price_type']) ? $layout_params['fields'][$field->db_field_name . '_price_type'] : '';
                    if($price_type == 'base_price' && !in_array($field->fid, $base_price_fields)){
                        $base_price_fields[] = $field->fid;
                    }
                }
            }
        }

        $base_price_fields = implode(', ', $base_price_fields);
        return $base_price_fields;
    }
}

if (!function_exists('getWhereUsergroupsConditionCCK')) {

  function getWhereUsergroupsConditionCCK($table_alias) {
      $my = JFactory::getUser();
      if (isset($my->id) AND $my->id != 0)
          $usergroups_sh = getGroupsByUserCCK($my->id, '');
      else
          $usergroups_sh = array();
      $usergroups_sh[] = 1;
      $s = '';
      for ($i = 0; $i < count($usergroups_sh); $i++) {
          $g = $usergroups_sh[$i];
          $s.= " $table_alias.access LIKE '%,{$g},%' ";
          if (($i + 1) < count($usergroups_sh))
              $s.= ' or ';
      }
      return $s;
  }

}

if (!function_exists('getWhereUsergroupsConditionWithoutLikeCCK')) {

  function getWhereUsergroupsConditionWithoutLikeCCK($table_alias) {
      $my = JFactory::getUser();
      if (isset($my->id) AND $my->id != 0)
          $usergroups_sh = getGroupsByUserCCK($my->id, '');
      else
          $usergroups_sh = array();
      $usergroups_sh[] = 1;
      $s = '';
      for ($i = 0; $i < count($usergroups_sh); $i++) {
          $g = $usergroups_sh[$i];
          $s.= " $table_alias.access = '{$g}' ";
          if (($i + 1) < count($usergroups_sh))
              $s.= ' or ';
      }
      return $s;
  }

}

if (!function_exists('getGroupsByUserCCK')) {

  function getGroupsByUserCCK($uid, $recurse) {
      if (version_compare(JVERSION, "1.6.0", "lt")) {

      } else if (version_compare(JVERSION, "1.6.0", "ge")) {
          $database = JFactory::getDBO();
          // Custom algorythm
          $usergroups = array();
          if ($recurse == 'RECURSE') {
              // [1]: Recurse getting the usergroups
              $id_group = array();
              $q1 = "SELECT group_id FROM `#__user_usergroup_map` WHERE user_id={$uid}";
              $database->setQuery($q1);
              $rows1 = $database->loadObjectList();
              foreach ($rows1 as $v)
                  $id_group[] = $v->group_id;
              for ($k = 0; $k < count($id_group); $k++) {
                  $q = "SELECT g2.id FROM `#__usergroups` g1 "
                   . " LEFT JOIN `#__usergroups` g2 ON g1.lft > g2.lft AND g1.lft < g2.rgt "
                   . " WHERE g1.id={$id_group[$k]} ORDER BY g2.lft";
                  $database->setQuery($q);
                  $rows = $database->loadObjectList();
                  foreach ($rows as $r)
                      $usergroups[] = $r->id;
              }
              $usergroups = array_unique($usergroups);
          }
          // [2]: Non-Recurse getting usergroups
          $q = "SELECT * FROM #__user_usergroup_map WHERE user_id = {$uid}";
          $database->setQuery($q);
          $rows = $database->loadObjectList();
          foreach ($rows as $k => $v)
              $usergroups[] = $rows[$k]->group_id;
          // If user is unregistered, Joomla contains it into standard group (Public by default).
          // So, groupId for anonymous users is 1 (by default).
          // But custom algorythm doesnt do this: if user is not autorised, he will NOT connected to any group.
          // And groupId will be 0.
          if (count($rows) == 0)
              $usergroups[] = - 2;
          return $usergroups;
      } else {
          echo "Sanity test. Error version check!";
          exit;
      }
  }
}

if(!function_exists('get_price_details')){
    function get_price_details($price_fields, $eiid = -1, $coup_id = -1, $numberFormat=array()){
        global $db;
        $db = new os_cckDb();

          $html = '';
          $field_list = array();

          $fk_order_id = 0 ;
          foreach ($price_fields as $price_filed){

            if( isset($price_filed->price_type) && $price_filed->price_type == 'coupon'){
              continue ;
            }

            $entityInstance = new os_cckEntityInstance($db->_db);
            if( $eiid == -1 )  $eiid = $price_filed->fk_eiid ;
            $entityInstance->load($eiid);

            $instance_currency = $entityInstance->instance_currency;

              if(!$price_filed || 
                  (  !property_exists($price_filed, 'fid') 
                    && !property_exists($price_filed, 'fk_fid') ) ) continue;

              if( property_exists($price_filed, 'fid')  ) $fid = $price_filed->fid ;
              elseif( property_exists($price_filed, 'fk_fid')  ) $fid = $price_filed->fk_fid ;

              $field = new os_cckEntityField($db->_db);
              $field->load($fid);
              if( !isset($field->fid) ) continue; //sanity test, when in cart products from old export 

              if( isset($price_filed->fk_order_id) && $price_filed->fk_order_id > 0 )  $fk_order_id = $price_filed->fk_order_id ; //need for coupon calculate   
      
              $layout = new os_cckLayout($db->_db);
              if( isset($price_filed->lid) ) $layout->load($price_filed->lid);
              else {
                 $lid = $layout->getDefaultLayout($price_filed->fk_eid, 'instance');
                 $layout->load($lid);
              }
              $layout_params = (isset($layout->params) )?( unserialize($layout->params) ): "";


              $calculate_ordering = (isset($layout_params['fields'][$field->db_field_name . '_calculation_order'])) ? $layout_params['fields'][$field->db_field_name . '_calculation_order'] : 0;
              $calculate_type = (isset($layout_params['fields'][$field->db_field_name . '_price_type'])) ? $layout_params['fields'][$field->db_field_name . '_price_type'] : 'base';
              $field_alias = (isset($layout_params['fields'][$field->db_field_name . '_alias'])) ? $layout_params['fields'][$field->db_field_name . '_alias'] : '';
              
              if( isset($price_filed->value) ){
                $price_filed_value = protectInjectionWithoutQuote($price_filed->value, '', 'INT', true);

                if(!$price_filed_value) continue;

                //$query = "SELECT price_value FROM #__os_cck_prices WHERE fk_fid='$price_filed->fid' AND fk_eiid='$eiid' AND ordering='$price_filed->value'";
                $query = "SELECT price_value, price_name FROM #__os_cck_content_instances_price WHERE price_id='$price_filed_value'";

                $db->setQuery($query);
                $value = $db->loadObjectList();
                if(!isset($value[0])){
                  echo ":Error find price:".$query; exit;
                }
              }
 
              $temp_field = new stdClass;
              $temp_field->calculate_ordering = $calculate_ordering;
              $temp_field->calculate_type = $calculate_type;
              if(isset($price_filed->quantity)){
                  $temp_field->quantity = $price_filed->quantity;
              }else{
                  $temp_field->quantity = 1;
              }
              if(isset($value) && isset($value[0]) ){
                $temp_field->value = $value[0]->price_value;
                $temp_field->price_name = cck_lang_text($value[0]->price_name);
              } else {
                $temp_field->value = $price_filed->price_value;
                $temp_field->price_name = cck_lang_text($price_filed->price_name);

              }
              $temp_field->field_alias = $field_alias;
              $field_list[] = $temp_field;
          }
          //var_dump($field_list);
          uasort($field_list, function($f1, $f2){
              if($f1->calculate_ordering < $f2->calculate_ordering) return -1;
              elseif($f1->calculate_ordering > $f2->calculate_ordering) return 1;
              else return 0;
          } );
          $html .= '<div class="price_detail">';
          $calculated_price = 0;
          $quantity = 1;
          if(empty($field_list) && isset($price_fields[0]) && property_exists($price_fields[0], 'quantity')){
              $quantity = $price_fields[0]->quantity;
          } 

          foreach ($field_list as $field){

              if($field->calculate_ordering <= 51){

                if($field->calculate_type == 'base_price'){
                    $calculated_currency = calculatedCurrency($entityInstance, ($field->value * $field->quantity), '', $numberFormat);
                    $not_quantity_calculated_currency = calculatedCurrency($entityInstance, $field->value, '', $numberFormat);
                    $tmp_price_quant = ($field->quantity>1) ? '(' . $not_quantity_calculated_currency[1] . ' x ' . $field->quantity . ')' : '';
                    if($field->quantity>1) {$quantity = $field->quantity;}
                    $html .= '<div class="base_price">' . $field->field_alias . ' ' . $calculated_currency[0] . ' ' . $tmp_price_quant . '</div>';
                    $calculated_price = $calculated_price + ($field->value * $field->quantity);
                }elseif($field->calculate_type == 'val+'){
                    $calculated_currency = calculatedCurrency($entityInstance, ($field->value * $quantity), '', $numberFormat);
                    $not_quantity_calculated_currency = calculatedCurrency($entityInstance, $field->value, '', $numberFormat);
                    $price_name = $field->field_alias . ': ' . $field->price_name;
                    $tmp_price_quant = ($quantity>1) ? '(' . $not_quantity_calculated_currency[1] . ' x ' . $quantity . ')' : '';
                    $html .= '<div class="val-plus"><span class="val-plus-price-name">'.$price_name.'</span><span class="val-plus-plus"> +</span><span class="val-plus-price-value">' . $calculated_currency[0] . ' ' . $tmp_price_quant . '</span></div>';
                    $calculated_price = $calculated_price + ($field->value * $quantity);
                }else if($field->calculate_type == 'val-'){
                    $calculated_currency = calculatedCurrency($entityInstance, ($field->value * $quantity), '', $numberFormat);
                    $not_quantity_calculated_currency = calculatedCurrency($entityInstance, $field->value, '', $numberFormat);
                    $tmp_price_quant = ($quantity>1) ? '(' . $not_quantity_calculated_currency[1] . ' x ' . $quantity . ')' : '';
                    $html .= '<div class="val-minus"><span class="val-minus-price-name">'.$price_name.'</span><span class="val-minus-minus"> -</span><span class="val-minus-price-value">' . $calculated_currency[0] . ' ' . $tmp_price_quant . '</span></div>';
                    $calculated_price = $calculated_price - ($field->value * $quantity);
                }else if($field->calculate_type == 'percent+' && $field->value != '0.00'){
                    $calculated_currency = calculatedCurrency($entityInstance, ($field->value * $quantity), '', $numberFormat);
                    $calculate_value = calculatedCurrency($entityInstance, round($calculated_price/100 * $field->value, 2), '', $numberFormat);
                    $price_name = $field->field_alias . ': ' . $field->price_name;
                    $html .= '<div class="percent-plus"><span class="percent-plus-price-name">' . $price_name . '</span><span class="percent-plus-plus"> +</span><span class="percent-plus-price-value">' . $calculate_value[0] . ' ('. $field->value . ' %)</span></div>';
                    $calculated_price = $calculated_price + (round($calculated_price/100 * $field->value, 2));
                }else if($field->calculate_type == 'percent-' && $field->value != '0.00'){
                    $price_name = $field->field_alias . ': ' . $field->price_name;
                    $calculated_currency = calculatedCurrency($entityInstance, ($field->value * $quantity), '', $numberFormat);
                    $calculate_value = calculatedCurrency($entityInstance, round($calculated_price/100 * $field->value, 2), '', $numberFormat);
                    $html .= '<div class="percent-minus"><span class="percent-minus-price-name">' . $price_name . '</span><span class="percent-minus-minus"> -</span><span class="percent-minus-price-value">' . $calculate_value[0] . ' ('. $field->value . ' %)</span></div>';
                    $calculated_price = $calculated_price - (round($calculated_price/100 * $field->value, 2));
                }
              }
          }
          if($coup_id != -1 && $coup_id != ''){
              $coupon = new os_cckCoupons($db->_db);


              $is_coupon_valid = false;
              if( $fk_order_id > 0 ){
                //if order exist, search coupon in order details
                $coupon = $coupon->loadByOrderId($fk_order_id);
                $is_coupon_valid = checkCouponInstance($coupon->coup_id, $eiid);
              }
              if( $fk_order_id == 0 || $coupon == null ) {
                $coupon->load($coup_id);
                $is_coupon_valid = checkCouponInstance($coup_id, $eiid);
              }  

              //check so coupon exist, or this ONLY old coupon
              $coupon_tmp = new os_cckCoupons($db->_db);
              $coupon_tmp->load($coup_id);
              if( !isset( $coupon_tmp->coup_id ) || intval($coupon_tmp->coup_id) < 1 ){
                $html .= "<div color='red'>This Coupon already Not Exist, so we can't correct show all discounts</div>";
              }

              if($coupon->type == 'percent'){
                  if(  $is_coupon_valid ){
                      $coupon_discount = round($calculated_price/100 * $coupon->value, 2);
                      $coupon_discount_currency = calculatedCurrency($entityInstance, $coupon_discount);
                      $html .= '<div class="coupon_discount">Coupon: - '. $coupon_discount_currency[0] . '(' . $coupon->value. '%)</div>';
                  }else{
                      $html .= '<div class="coupon_discount">Coupon: - 0 (' . cck_lang_text("COM_OS_CCK_ERROR_MESSAGE_COUPON_NOT_THIS_PRODUCT"). ')</div>';
                  }
              }else{
                  if( $is_coupon_valid ){
                      $coupon_discount = round($coupon->value, 2);
                      $coupon_discount_currency = calculatedCurrency($entityInstance, $coupon_discount);
                      $html .= '<div class="coupon_discount">Coupon: - '. $coupon_discount_currency[0] . '</div>';
                  }else{
                      $html .= '<div class="coupon_discount">Coupon: - 0 (' . cck_lang_text("COM_OS_CCK_ERROR_MESSAGE_COUPON_NOT_THIS_PRODUCT"). ')</div>';
                  }
              }

          }
          $html .= '</div>';


          return array('html'=>$html, 'quantity'=>$quantity);
    }
}

if(!function_exists('getProductCurrency')){
    function getProductCurrency(){
        global $os_cck_configuration, $session;
        $session_currency = cck_getCurrentCurrency();
//        $session_currency = $session->get('currency', '');
        $currency = $session_currency;
//        if($session_currency == ''){
//            $currencys = explode(';' , $os_cck_configuration->get('paypal_currency'));
//            $currency = explode('|', explode('=', $currencys[0])[0]);
//            if(isset($currency[1])){
//                $currency = $currency[1];
//            }else{
//                $currency = $currency[0];
//            }
//        }

        return $currency;
    }
}

if(!function_exists('getInstanceTitle')){
    function getInstanceTitle($instance){
        global $db;
        $db = new os_cckDb();
        if($instance->meta_title != ''){
            return $instance->meta_title;
        }elseif($instance->title != ''){
            return $instance->title;
        }
        return '';

    }
}

if(!function_exists('get_animated_opt')){
    function get_animated_opt(){
        $animate = array();

        $animate[0][] = JHTML::_('select.option','none','None');

        //$animate[] = JHTML::_('select.groupedlist','Attention Seekers');
        $animate['Attention Seekers'][] = JHTML::_('select.option','bounce','bounce');
        $animate['Attention Seekers'][] = JHTML::_('select.option','flash','flash');
        $animate['Attention Seekers'][] = JHTML::_('select.option','pulse','pulse');
        $animate['Attention Seekers'][] = JHTML::_('select.option','rubberBand','rubberBand');
        $animate['Attention Seekers'][] = JHTML::_('select.option','shake','shake');
        $animate['Attention Seekers'][] = JHTML::_('select.option','swing','swing');
        $animate['Attention Seekers'][] = JHTML::_('select.option','tada','tada');
        $animate['Attention Seekers'][] = JHTML::_('select.option','wobble','wobble');
        $animate['Attention Seekers'][] = JHTML::_('select.option','jello','jello');
        //$animate[] = JHTML::_('select.groupedlist','');

        //$animate[] = JHTML::_('select.groupedlist','Bouncing Entrances');
        $animate['Bouncing Entrances'][] = JHTML::_('select.option','bounceIn','bounceIn');
        $animate['Bouncing Entrances'][] = JHTML::_('select.option','bounceInDown','bounceInDown');
        $animate['Bouncing Entrances'][] = JHTML::_('select.option','bounceInLeft','bounceInLeft');
        $animate['Bouncing Entrances'][] = JHTML::_('select.option','bounceInRight','bounceInRight');
        $animate['Bouncing Entrances'][] = JHTML::_('select.option','bounceInUp','bounceInUp');
        //$animate['Bouncing Entrances'][] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Bouncing Exits');
        $animate['Bouncing Exits'][] = JHTML::_('select.option','bounceOut','bounceOut');
        $animate['Bouncing Exits'][] = JHTML::_('select.option','bounceOutDown','bounceOutDown');
        $animate['Bouncing Exits'][] = JHTML::_('select.option','bounceOutLeft','bounceOutLeft');
        $animate['Bouncing Exits'][] = JHTML::_('select.option','bounceOutRight','bounceOutRight');
        $animate['Bouncing Exits'][] = JHTML::_('select.option','bounceOutUp','bounceOutUp');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Fading Entrances');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeIn','fadeIn');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInDown','fadeInDown');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInDownBig','fadeInDownBig');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInLeft','fadeInLeft');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInLeftBig','fadeInLeftBig');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInRight','fadeInRight');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInRightBig','fadeInRightBig');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInUp','fadeInUp');
        $animate['Fading Entrances'][] = JHTML::_('select.option','fadeInUpBig','fadeInUpBig');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Fading Exits');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOut','fadeOut');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutDown','fadeOutDown');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutDownBig','fadeOutDownBig');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutLeft','fadeOutLeft');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutLeftBig','fadeOutLeftBig');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutRight','fadeOutRight');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutRightBig','fadeOutRightBig');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutRightBig','fadeOutRightBig');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutUp','fadeOutUp');
        $animate['Fading Exits'][] = JHTML::_('select.option','fadeOutUpBig','fadeOutUpBig');
//        $animate[] = JHTML::_('select.groupedlist','');
//        $animate[] = JHTML::_('select.groupedlist','Flippers');
        $animate['Flippers'][] = JHTML::_('select.option','flip','flip');
        $animate['Flippers'][] = JHTML::_('select.option','flipInX','flipInX');
        $animate['Flippers'][] = JHTML::_('select.option','flipInY','flipInY');
        $animate['Flippers'][] = JHTML::_('select.option','flipOutX','flipOutX');
        $animate['Flippers'][] = JHTML::_('select.option','flipOutY','flipOutY');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Lightspeed');
        $animate['Lightspeed'][] = JHTML::_('select.option','lightSpeedIn','lightSpeedIn');
        $animate['Lightspeed'][] = JHTML::_('select.option','lightSpeedOut','lightSpeedOut');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Rotating Entrances');
        $animate['Rotating Entrances'][] = JHTML::_('select.option','rotateIn','rotateIn');
        $animate['Rotating Entrances'][] = JHTML::_('select.option','rotateInDownLeft','rotateInDownLeft');
        $animate['Rotating Entrances'][] = JHTML::_('select.option','rotateInDownRight','rotateInDownRight');
        $animate['Rotating Entrances'][] = JHTML::_('select.option','rotateInUpLeft','rotateInUpLeft');
        $animate['Rotating Entrances'][] = JHTML::_('select.option','rotateInUpRight','rotateInUpRight');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Rotating Exits');
        $animate['Rotating Exits'][] = JHTML::_('select.option','rotateOut','rotateOut');
        $animate['Rotating Exits'][] = JHTML::_('select.option','rotateOutDownLeft','rotateOutDownLeft');
        $animate['Rotating Exits'][] = JHTML::_('select.option','rotateOutDownRight','rotateOutDownRight');
        $animate['Rotating Exits'][] = JHTML::_('select.option','rotateOutUpLeft','rotateOutUpLeft');
        $animate['Rotating Exits'][] = JHTML::_('select.option','rotateOutUpRight','rotateOutUpRight');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Sliding Entrances');
        $animate['Sliding Entrances'][] = JHTML::_('select.option','slideInUp','slideInUp');
        $animate['Sliding Entrances'][] = JHTML::_('select.option','slideInDown','slideInDown');
        $animate['Sliding Entrances'][] = JHTML::_('select.option','slideInLeft','slideInLeft');
        $animate['Sliding Entrances'][] = JHTML::_('select.option','slideInRight','slideInRight');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Sliding Exits');
        $animate['Sliding Exits'][] = JHTML::_('select.option','slideOutUp','slideOutUp');
        $animate['Sliding Exits'][] = JHTML::_('select.option','slideOutDown','slideOutDown');
        $animate['Sliding Exits'][] = JHTML::_('select.option','slideOutLeft','slideOutLeft');
        $animate['Sliding Exits'][] = JHTML::_('select.option','slideOutRight','slideOutRight');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Zoom Entrances');
        $animate['Zoom Entrances'][] = JHTML::_('select.option','zoomIn','zoomIn');
        $animate['Zoom Entrances'][] = JHTML::_('select.option','zoomInDown','zoomInDown');
        $animate['Zoom Entrances'][] = JHTML::_('select.option','zoomInLeft','zoomInLeft');
        $animate['Zoom Entrances'][] = JHTML::_('select.option','zoomInRight','zoomInRight');
        $animate['Zoom Entrances'][] = JHTML::_('select.option','zoomInUp','zoomInUp');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Zoom Exits');
        $animate['Zoom Exits'][] = JHTML::_('select.option','zoomOut','zoomOut');
        $animate['Zoom Exits'][] = JHTML::_('select.option','zoomOutDown','zoomOutDown');
        $animate['Zoom Exits'][] = JHTML::_('select.option','zoomOutLeft','zoomOutLeft');
        $animate['Zoom Exits'][] = JHTML::_('select.option','zoomOutRight','zoomOutRight');
        $animate['Zoom Exits'][] = JHTML::_('select.option','zoomOutUp','zoomOutUp');
        //$animate[] = JHTML::_('select.groupedlist','');
        //$animate[] = JHTML::_('select.groupedlist','Specials');
        $animate['Specials'][] = JHTML::_('select.option','hinge','hinge');
        $animate['Specials'][] = JHTML::_('select.option','jackInTheBox','jackInTheBox');
        $animate['Specials'][] = JHTML::_('select.option','rollIn','rollIn');
        $animate['Specials'][] = JHTML::_('select.option','rollOut','rollOut');
//        $animate[] = JHTML::_('select.groupedlist','');

        return $animate;
    }
}

if(!function_exists('clear_os_cart')){
    function clear_os_cart(){
        global $session;

        $session->set('cart', '');
    }
}

if(!function_exists('checkCouponInstance')){
    function checkCouponInstance($coup_id, $eiid){
        global $db;
        $db = new os_cckDb();
        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->load($eiid);

        $coupon = new os_cckCoupons($db->_db);
        $coupon->load($coup_id);
        
        if(stripos($coupon->entities, ',-1,') === FALSE && stripos($coupon->entities, ','.$entityInstance->fk_eid.',') === FALSE){
            return false;
        }

        if($coupon->category_ids != '' && $coupon->category_ids != 0){
            $query = "SELECT COUNT(*) FROM #__os_cck_categories_connect WHERE fk_eiid=$eiid AND fk_cid IN (".trim($coupon->category_ids, ',').")";
            //var_dump($query); exit;
            $db->setQuery($query);
            $category_count = $db->loadResult();
        }
        if($coupon->category_ids != '' && $coupon->category_ids != 0 && $category_count == 0){
            return false;
        }
        return true;
    }
}

if(!function_exists('file_force_download')){
    function file_force_download($file, $filetype) {
      if (file_exists($file)) {
        // сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт
        // если этого не сделать файл будет читаться в память полностью!
        if (ob_get_level()) {
          ob_end_clean();
        }
        // заставляем браузер показать окно сохранения файла
        header('Content-Description: File Transfer');
        header('Content-Type: '.$filetype);
        header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        // читаем файл и отправляем его пользователю
        if ($fd = fopen($file, 'rb')) {
          while (!feof($fd)) {
            print fread($fd, 1024);
          }
          fclose($fd);
        }
        unlink($file);
        exit;
      }
    }
}

if(!function_exists('get_custom_mask_list')){
    function get_custom_mask_list($entity_id){
        global $db, $entities_type, $entityFieldLists;
        $db = new os_cckDb();
        //get fields for custom code modal
        if(isset($entities_type[$entity_id])){
            if($entities_type[$entity_id] == 'os_cck_entity'){
              $custom_fields = array();
              $id_field = new stdClass();
              $id_field->title = 'cck_instance_id';
              $id_field->fid = 'cck_instance_id';
              $id_field->field_type = 'unique';
              $id_field->params = '';
              $id_field->name = cck_lang_text("COM_OS_CCK_INSTANCE_ID");
              $id_field->fk_eid = $entity_id;
              
              $custom_fields[] = $id_field;

              $number_of_views_field = new stdClass();
              $number_of_views_field->title = 'cck_number_of_views';
              $number_of_views_field->fid = 'cck_number_of_views';
              $number_of_views_field->field_type = 'unique';
              $number_of_views_field->params = '';
              $number_of_views_field->name = cck_lang_text("COM_OS_CCK_NUMBER_OF_VIEWS");
              $number_of_views_field->fk_eid = $entity_id;
              
              $custom_fields[] = $number_of_views_field;

              $query = "SELECT db_field_name as title, fid, field_type, params, field_name as name, fk_eid FROM #__os_cck_entity_field as f "
                      ."\n WHERE f.published = '1' AND fk_eid = ".$entity_id . " ORDER BY field_name";
              $db->setQuery($query);
              $field_list = $db->loadObjectList('fid');

              $field_mask_list = array_merge($custom_fields, $field_list);
            }else{
                $temp_field_mask_list = $entityFieldLists[$entity_id];
                $field_mask_list = array();
                if(is_array($temp_field_mask_list) && !empty($temp_field_mask_list)){

//                    var_dump($temp_field_mask_list);
                    foreach($temp_field_mask_list as $key => $field){
//                        var_dump($key);
//                        var_dump($key === 'custom_sql_id' || $key === 'custom_sql_title');
                        if($key === 'custom_sql_id' || $key === 'custom_sql_title') continue;
//                        var_dump($field);
                        $temp_field = clone $field;
                        $temp_field->title = $temp_field->db_field_name;
                        $temp_field->name = $temp_field->field_name;
                        $field_mask_list[] = $temp_field;
                    }
                }
            }

              //var_dump($temp_entity)
              if(!empty($field_mask_list)){
                $params = new JRegistry;
                $childs_list = [];
                //var_dump($fields);
                foreach ($field_mask_list as $value) {
//                    var_dump($value->params);
                    if($value->params){
                        try {
                            $params->loadString($value->params);
                        } catch (Exception $ex) {

                        }
                    }


                    $childs_list = array_merge($childs_list, explode('|',$params->get('child_select', '')));
                }
                $childs_list = array_unique($childs_list);

                foreach ($field_mask_list as $k=>$one_field_list){
                    if(in_array($one_field_list->fid, $childs_list)){
                          unset($field_mask_list[$k]);
                    }
                }

                foreach($field_mask_list as $custom_field){
                  $custom_field->mask = '{|'.$custom_field->title.'|}';
                }
                // var_dump($field_mask_list);
                return $field_mask_list;
              }
        }
          return;
    }
}


if(!function_exists('cck_checkReferer')){
    function cck_checkReferer(){
      global $os_cck_configuration;
        if($os_cck_configuration->get('check_referer', '1') == '0'){
          return true;
        }


        $input = JFactory::getApplication()->input;

        $refer = $input->server->get('HTTP_REFERER', null, 'SERVER');
        $refer_host = parse_url($refer, PHP_URL_HOST);

        $host = parse_url(JURI::root(), PHP_URL_HOST);

        if($refer_host == $host){
            return true;
        }else{
            return false;
        }

    }
}

if(!function_exists('isСorrectMaxItemsLimit')){
    function isСorrectMaxItemsLimit($eid, $userId = false){
        global $cck_entity_configuration, $db;
        $db = new os_cckDb();
        if($userId){
            $user = jFactory::getUser($userId);
            if($user->id == null){
                $user = jFactory::getUser();
            }
        }else{
            $user = jFactory::getUser();
        }
        $max_items = -1;
        foreach($user->groups as $group){
            if(isset($cck_entity_configuration[$eid]['max_items'][$group])
                    && $cck_entity_configuration[$eid]['max_items'][$group] > $max_items){
                $max_items = $cck_entity_configuration[$eid]['max_items'][$group];
            }
            if($max_items == -1){
                return true;
            }
        }
//        var_dump($userId);
        $query = "SELECT COUNT(*) FROM #__os_cck_entity_instance WHERE fk_eid=$eid AND published=1 AND fk_userid=$user->id";
//        echo $query; exit;
        $db->setQuery($query);
        $count_items = $db->loadResult();
//        var_dump($count_items+1);
//        var_dump($max_items);
        if($count_items+1 > $max_items){
            return false;
        }else{
            return true;
        }

    }
}

//if(!function_exists('cut_params')){
//    function cut_params($layout_html, $cut_elem){
//        $start_pos = stripos($layout_html, '<input class="' . $cut_elem.'-params');
//        $end_pos = stripos($layout_html, '>', $start_pos);
//
//        $str = substr($layout_html, $start_pos, ($end_pos - $start_pos)+1);
//
//        $layout_html = str_replace($str, '', $layout_html);
//
//        if(stripos($layout_html, '<input class="' . $cut_elem.'-params') !== false){
//            $layout_html = cut_params($layout_html, $cut_elem);
//        }
//
//        return $layout_html;
//    }
//}

if(!function_exists('cut_params')){
    function cut_params($layout_html){
        if(stripos($layout_html, '<input class="f-params') !== false){
            $start_pos = stripos($layout_html, '<input class="f-params');
            $end_pos = stripos($layout_html, '>', $start_pos);

            $str = substr($layout_html, $start_pos, ($end_pos - $start_pos)+1);

            $layout_html = str_replace($str, '', $layout_html);

            if(stripos($layout_html, '<input class="f-params') !== false){
                $layout_html = cut_params($layout_html);
            }
        }

        if(stripos($layout_html, '<input class="col-params') !== false){
            $start_pos = stripos($layout_html, '<input class="col-params');
            $end_pos = stripos($layout_html, '>', $start_pos);

            $str = substr($layout_html, $start_pos, ($end_pos - $start_pos)+1);

            $layout_html = str_replace($str, '', $layout_html);

            if(stripos($layout_html, '<input class="col-params') !== false){
                $layout_html = cut_params($layout_html);
            }
        }

        if(stripos($layout_html, '<input class="row-fluid-params') !== false){
            $start_pos = stripos($layout_html, '<input class="row-fluid-params');
            $end_pos = stripos($layout_html, '>', $start_pos);

            $str = substr($layout_html, $start_pos, ($end_pos - $start_pos)+1);

            $layout_html = str_replace($str, '', $layout_html);

            if(stripos($layout_html, '<input class="row-fluid-params') !== false){
                $layout_html = cut_params($layout_html);
            }
        }

        return $layout_html;
    }
}

if(!function_exists('remove_admin_classes')){
    function remove_admin_classes($layout_html){
        $layout_html = str_replace('drop-area', '', $layout_html);
        $layout_html = str_replace('column-sortable', '', $layout_html);
        $layout_html = str_replace('ui-resizable', '', $layout_html);
        $layout_html = str_replace('ui-droppable', '', $layout_html);
        $layout_html = str_replace('ui-sortable', '', $layout_html);
        $layout_html = str_replace('ui-sortable-handle', '', $layout_html);


        return $layout_html;
    }
}

if (!function_exists('checkJavaScriptIncludedCCK')) {
  function checkJavaScriptIncludedCCK($name) {

      $doc = JFactory::getDocument();

      foreach($doc->_scripts as $script_path=>$value){
        if(strpos( $script_path, $name ) !== false ) return true ;
      }

      return false;
  }
}

//return true - if this file added before
//$is_check_only_file_name - not check full path - only file_name
if (!function_exists('includeJavaScriptCCK')) {
  function includeJavaScriptCCK($name,$is_check_only_file_name=false) {

      if(defined($name) ) return false;

      $file_name = $name;//check fult path
      if( $is_check_only_file_name && strrpos($name, '/') != false ) $file_name = substr($name, strrpos($name, '/')+1);

      $doc = JFactory::getDocument();
      foreach($doc->_scripts as $script_path=>$value){
        if(strpos( $script_path, $file_name ) !== false ) {
          define($name, 1);
          return false;          
        }
      }

      if( strpos($name, "//" ) !== 0 
        && strpos($name, "http://" ) !== 0 
        && strpos($name, "https://" ) !== 0 ){

        $doc->addScript(JUri::root() . $name );
      } else $doc->addScript( $name );  

      define($name, 1);
      return true;
  }
}

if (!function_exists('checkStylesIncludedCCK')) {
  function checkStylesIncludedCCK($name) {

      $doc = JFactory::getDocument();

      foreach($doc->_styleSheets as $script_path=>$value){
        if(strpos( $script_path, $name ) !== false ) return true ;
      }
      return false;
  }
}

//return true - if this file added before
//$is_check_only_file_name - not check full path - only file_name
if (!function_exists('includeStylesCCK')) {
  function includeStylesCCK($name,$is_check_only_file_name=false) {

      if(defined($name) ) return false;

      $file_name = $name;//check fult path
      if( $is_check_only_file_name && strrpos($name, '/') != false ) $file_name = substr($name, strrpos($name, '/')+1);

      $doc = JFactory::getDocument();
      foreach($doc->_styleSheets as $script_path=>$value){
        if(strpos( $script_path, $file_name ) !== false ) {
          define($name, 1);
          return false;          
        } 
      }

      if( strpos($name, "//" ) !== 0 
        && strpos($name, "http://" ) !== 0 
        && strpos($name, "https://" ) !== 0 ){

        $doc->addStyleSheet(JUri::root() . $name );
      } else $doc->addStyleSheet( $name );  

      define($name, 1);
      return true ;
  }
}

if(!function_exists('addCodeMirrorsScript')){
    function addCodeMirrorsScript(){
        global $doc;

        $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/lib/codemirror.css");
        $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/addon/fold/foldgutter.css");
        $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/addon/dialog/dialog.css");
        $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/theme/monokai.css");
        $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/addon/display/fullscreen.css");
        $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/addon/hint/show-hint.css");



        $doc->addScript(JURI::root() . "/media/editors/codemirror/lib/codemirror.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/search/searchcursor.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/search/search.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/dialog/dialog.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/edit/matchbrackets.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/edit/closebrackets.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/comment/comment.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/wrap/hardwrap.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/fold/foldcode.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/fold/brace-fold.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/mode/javascript/javascript.js");
        $doc->addScript(JURI::root() . "/components/com_os_cck/assets/codemirror/mode/php/php.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/mode/htmlmixed/htmlmixed.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/mode/htmlmixed/htmlmixed.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/mode/css/css.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/mode/xml/xml.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/mode/clike/clike.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/hint/show-hint.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/hint/anyword-hint.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/hint/css-hint.js");

        $doc->addScript(JURI::root() . "/media/editors/codemirror/keymap/sublime.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/selection/active-line.js");
        $doc->addScript(JURI::root() . "/media/editors/codemirror/addon/display/fullscreen.js");
    }
}

if(!function_exists('addCodeMirrorsScriptJ4')){
    function addCodeMirrorsScriptJ4(){
        global $doc;

        $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/lib/codemirror.css");
        $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/addon/fold/foldgutter.css");
        $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/addon/dialog/dialog.css");
        $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/theme/monokai.css");
        $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/addon/display/fullscreen.css");
        $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/addon/hint/show-hint.css");



        $doc->addScript(JURI::root() . "/media/vendor/codemirror/lib/codemirror.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/search/searchcursor.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/search/search.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/dialog/dialog.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/edit/matchbrackets.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/edit/closebrackets.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/comment/comment.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/wrap/hardwrap.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/fold/foldcode.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/fold/brace-fold.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/mode/javascript/javascript.js");
        $doc->addScript(JURI::root() . "/components/com_os_cck/assets/codemirror/mode/php/php.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/mode/htmlmixed/htmlmixed.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/mode/htmlmixed/htmlmixed.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/mode/css/css.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/mode/xml/xml.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/mode/clike/clike.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/hint/show-hint.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/hint/anyword-hint.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/hint/css-hint.js");

        $doc->addScript(JURI::root() . "/media/vendor/codemirror/keymap/sublime.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/selection/active-line.js");
        $doc->addScript(JURI::root() . "/media/vendor/codemirror/addon/display/fullscreen.js");
    }
}

if(!function_exists('addCodeMirrorsScriptJ5')){
  function addCodeMirrorsScriptJ5(){
      global $doc;

      $doc->addStyleSheet("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css");
      $doc->addStyleSheet("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/foldgutter.min.css");
      $doc->addStyleSheet("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/dialog/dialog.min.css");
      $doc->addStyleSheet("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/theme/monokai.min.css");
      $doc->addStyleSheet("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/display/fullscreen.min.css");
      $doc->addStyleSheet("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/hint/show-hint.min.css");
      // /home/vlados/public_html/joomla5/media/plg_editors_codemirror/js
      // $doc->addScript(JURI::root() . "/media/plg_editors_codemirror/joomla.asset.json");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/keymap/sublime.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/comment/comment.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/comment/continuecomment.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/dialog/dialog.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/display/autorefresh.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/display/fullscreen.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/display/panel.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/display/placeholder.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/display/placeholder.min.js");

      // $doc->addScript(JURI::root() . "/media/vendor/codemirror/lib/codemirror.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/search/searchcursor.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/search/search.min.js");
      
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/edit/matchbrackets.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/edit/closebrackets.min.js");
      
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/wrap/hardwrap.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/foldcode.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/brace-fold.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/javascript/javascript.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/php/php.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/htmlmixed/htmlmixed.min.js");
      
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/css/css.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/xml/xml.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/clike/clike.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/hint/show-hint.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/hint/anyword-hint.min.js");
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/hint/css-hint.min.js");

      
      $doc->addScript("//cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/selection/active-line.min.js");
      
  }
}

if(!function_exists('ConvertEntityInstanceToUser')){
    function ConvertEntityInstanceToUser($eid, $user_id){
        global $db;
        $db = new os_cckDb();
        $user = JFactory::getUser($user_id);
        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->eiid = $user_id;
        $entityInstance->fk_eid = $eid;
        $entityInstance->title = $user->name;
        $entityInstance->published = 1;
        $entityInstance->approved = 1;
        $entityInstance->created = $user->registerDate;
        $entityInstance->featured_clicks = 0;
        $entityInstance->featured_shows = 0;
        $entityInstance->meta_title = $user->name;


//        var_dump($entityInstance);
//        var_dump($user);
        return $entityInstance;
    }
}

if(!function_exists('ConvertEntityInstanceToCustomSql')){
    function ConvertEntityInstanceToCustomSql($entity, $eiid, $id_field = false, $related_parent_fid = false, $related_child_fid = false, $parent_eid = false){
        global $db, $entityFieldLists;
        $db = new os_cckDb();
//        if(!$id_field){
//            $id_field = new stdClass();
//        }
//        var_dump($entity);
//        var_dump($eiid);
//        var_dump($id_field);
        if(!$eiid) return false;
        $title_field = new stdClass();

        foreach($entityFieldLists[$entity->eid] as $field){
            if(!$id_field){
                if($field->custom_field_type == 'id') $id_field = $field;
            }
            if($field->custom_field_type == 'title') $title_field = $field;
        }

        $query = "SELECT t.$id_field->fid as eiid, t.$title_field->fid as title FROM ($entity->sql_select) as t WHERE t.$id_field->fid=$eiid";
        $db->setQuery($query);
//        echo $query; exit;
        try {
            $rows = $db->loadObjectList();
        } catch (Exception $ex) {
            echo $aaaaa;
            echo $query;            var_dump($eiid);exit;
        }
//        if(empty($rows)){
//            echo $aaaaa;
//            echo $query;            var_dump($rows);exit;
//        }
//        var_dump($rows);
        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->eiid = $eiid;
        $entityInstance->fk_eid = $entity->eid;
        $entityInstance->title = (isset($rows[0])) ? $rows[0]->title : '';
        $entityInstance->published = 1;
        $entityInstance->approved = 1;

        $entityInstance->featured_clicks = 0;
        $entityInstance->featured_shows = 0;
        $entityInstance->meta_title = (isset($rows[0])) ? $rows[0]->title : '';
        $entityInstance->related_parent_fid = $related_parent_fid;
        $entityInstance->related_child_fid = $related_child_fid;
        $entityInstance->parent_eid = $parent_eid;

        return $entityInstance;
    }
}

if(!function_exists('getJoinForOrderByJoomlaUser')){
    function getJoinForOrderByJoomlaUser($field, $rand='ASC'){
        global $db, $input;
        $db = new os_cckDb();
        $letindex = $input->get('letindex', '');
        //AND LOWER(instance." . $_REQUEST['now_indexed'] . ") LIKE '$search%' ";
        //var_dump($field);
        if($field == 'ceid' || $field == 'id'){
            $join = '';
            $orderBy = ' ORDER BY us.id';
            $where = '';
        }else{
            $field_name = explode('_', $field);
            $fieldset_name = $field_name[1];

            if($fieldset_name == 'standart'){
                $join = '';
                if($field_name[2] == 'last'){
                    $field_name ='us.lastvisitDate';
                }elseif($field_name[2] == 'register'){
                    $field_name ='us.registerDate';
                }else{
                  $field_name = 'us.'.$field_name[2];
                }
                $orderBy = ' ORDER BY '. $field_name;
                $where = '';
                if($letindex != '' && $letindex != 'all'){
                    $where .= " AND LOWER(" . $field_name . ") LIKE '$letindex%' ";
                }
            }elseif($fieldset_name == 'profile'){
                $join = " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id ";
                $orderBy = " ORDER BY prof.profile_value ";
                $where = " AND prof.profile_key = 'profile.$field_name[2]' ";
                if($letindex != '' && $letindex != 'all'){
                    $where .= " AND LOWER(prof.profile_value) LIKE '$letindex%' ";
                }
            }else{
                $join = " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                        . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
                $orderBy = " ORDER BY val.value ";
                $where = " AND fi.name = '$field_name[2]' ";
                if($letindex != '' && $letindex != 'all'){
                    $where .= " AND LOWER(val.value) LIKE '$letindex%' ";
                }
            }
        }
        if($rand == 'RAND()'){
            $orderBy = " ORDER BY ";
        }
        $return_arr = array();
        $return_arr['join'] = $join;
        $return_arr['order_by'] = $orderBy;
        $return_arr['where'] = $where;
        return $return_arr;
    }
}

if(!function_exists('os_cck_initialization')){
  function os_cck_initialization(){
      global $db, $fieldsets, $user_profile_form, $app;

      $db = new os_cckDb();
      $query = "SELECT eid, type, custom_fields, sql_select FROM #__os_cck_entity";
      $db->setQuery($query);
      $entities = $db->loadObjectList('eid');

      $cck_entities = array();
      $joomla_user_entities = array();
      $custom_select_entities = array();

      $entities_type = array();

      $fields = array();

      foreach($entities as $entity){
          switch($entity->type){
              case 'os_cck_entity':
                  $cck_entities[] = $entity->eid;
                  break;

              case 'joomla_user':
                  $joomla_user_entities[] = $entity->eid;
                  break;

              case 'custom_sql':
                  $custom_select_entities[] = $entity->eid;
                  break;

              default :
                  $cck_entities[] = $entity;
          }
          $entities_type[$entity->eid] = $entity->type;
      }

      if(!empty($cck_entities)){
          $query = ' SELECT f.* FROM #__os_cck_entity_field AS f FORCE INDEX(fk_eid_field_name)'.
              ' WHERE f.fk_eid IN (' . implode(',', $cck_entities) . ') ORDER BY field_name';
          $db->setQuery($query);
          $result = $db->loadObjectList();
          //select only exist layout field for NEXT update/store function
          foreach($result as $field){
              $fields[$field->fk_eid][$field->fid] =  $field;
          }

          //$fields = $result;

      }

      if(!empty($joomla_user_entities)){
          if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
              $joom_user = JFactory::getUser();

              JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
              JPluginHelper::importPlugin('user');
              JForm::addFormPath(JPATH_SITE . '/components/com_users/forms');

              $user_profile_form = JForm::getInstance('com_users.user', 'profile');

              $offset = 0;
              $plug_params = 1;
               //run mambot onPrepareContent on plug_row object
              // Trigger the onContentPrepare event.
              $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array("com_users.user", $joom_user));
              $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $joom_user));

              $user_profile_form->bind($joom_user);

              $user_profile = JUserHelper::getProfile($joom_user->id);
              $fieldsets = $user_profile_form->getFieldsets();

          }else{
              $user = JFactory::getUser();
              // Load the fields helper
              JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
              // Gets the fields associated with the 'com_users.user' instance
              // Since we give an actual object instance (and not, for example, just the id), in returned $customFields there will be a 'value' property for every additional fields
              $customFields = FieldsHelper::getFields('com_users.user');

              $dispatcher = JDispatcher::getInstance();
              JPluginHelper::importPlugin('user');
              JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');

              $user_profile_form = JForm::getInstance('com_users.user', 'profile');
              $results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.user', $user));
              $results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $user));
              $user_profile_form->bind($user);

              $user_profile = JUserHelper::getProfile($user->id);
              $fieldsets = $user_profile_form->getFieldsets();
          }
          $GLOBALS['user_profile_form'] = $user_profile_form;
            foreach($joomla_user_entities as $entity){

                $fild_list = unserialize($entities[$entity]->custom_fields);
                //$fields = array();

                foreach($fild_list['standart'] as $key => $temp_field){
                    if($temp_field != '0' && $temp_field != 'custom_child_ids'){
                        switch ($temp_field){
                            case 'text':
                            case 'title':
                                $field_type = 'text_textfield';
                                break;

                            case 'textarea':
                                $field_type = 'text_textarea';
                                break;

                            case 'img':
                                $field_type = 'imagefield';
                                break;

                            case 'date':
                                $field_type = 'datetime_popup';
                                break;

                            case 'number':
                                $field_type = 'decimal_textfield';
                                break;

                            case 'url':
                                $field_type = 'text_url';
                                break;

                            default :
                                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_FIELD_TYPE_ERROR"), 'warning');
                                return false;

                        }
                        $field = new os_cckEntityField($db->_db);
                        $field->fid = $key;
                        $field->fk_eid = $entity;
                        $field->field_name = ucfirst($key);
                        $field->field_type = $field_type;
                        $field->db_field_name = 'user_'.'standart_'.$key;
                        $field->published = 1;
                        $fields[$entity][] = $field;
                        if($temp_field == 'title') $fields[$entity]['user_title'] = $field;
                    }
                }

                foreach ($fieldsets as $fieldset){
                    if($fieldset->name == 'actionlogs'){continue;}
                    if(isset($fild_list[$fieldset->name])){
                        $temp_field_list = $user_profile_form->getFieldset($fieldset->name);

                        foreach($temp_field_list as $temp_field){
                            if(isset($fild_list[$fieldset->name][$temp_field->fieldname]) && $fild_list[$fieldset->name][$temp_field->fieldname] != '0' && $fild_list[$fieldset->name][$temp_field->fieldname] != 'custom_child_ids'){
                                switch ($fild_list[$fieldset->name][$temp_field->fieldname]){
                                    case 'text':
                                    case 'id':
                                    case 'title':
                                        $field_type = 'text_textfield';
                                        break;

                                    case 'textarea':
                                        $field_type = 'text_textarea';
                                        break;

                                    case 'img':
                                        $field_type = 'imagefield';
                                        break;

                                    case 'date':
                                        $field_type = 'datetime_popup';
                                        break;

                                    case 'number':
                                        $field_type = 'decimal_textfield';
                                        break;

                                    case 'url':
                                        $field_type = 'text_url';
                                        break;




                                    default :
                                        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_FIELD_TYPE_ERROR"), 'warning');
                                        return false;

                                }
                                $field = new os_cckEntityField($db->_db);
                                $field->fid = $temp_field->fieldname;
                                $field->fk_eid = $entity;
                                //var_dump(trim(strip_tags($temp_field->label)));
                                $field->field_name = trim(trim(strip_tags($temp_field->label)), ':');
                                $field->field_type = $field_type;
                                $field->db_field_name = 'user_'.$fieldset->name.'_'.$temp_field->fieldname;
                                $field->published = 1;
                                $fields[$entity][] = $field;
                            }

                        }

                    }


                }
          }
            //var_dump($fild_list);

      }

      if(!empty($custom_select_entities)){
          foreach($custom_select_entities as $entity){
                $fild_list = unserialize($entities[$entity]->custom_fields);

                if(!$fild_list) continue;
                foreach($fild_list as $key => $temp_field){

                    if($temp_field != '0'  && $temp_field != 'custom_child_ids' && $key != 'custom_child_ids'){

                        switch ($temp_field){
                            case 'text':
                            case 'title':
                            case 'id':
                                $field_type = 'text_textfield';
                                break;

                            case 'textarea':
                                $field_type = 'text_textarea';
                                break;

                            case 'img':
                                $field_type = 'imagefield';
                                break;

                            case 'date':
                                $field_type = 'datetime_popup';
                                break;

                            case 'number':
                                $field_type = 'decimal_textfield';
                                break;

                            case 'url':
                                $field_type = 'text_url';
                                break;

                            case 'pricefield_number':
                                $field_type = 'pricefield_number';
                                break;

                            case 'child_id':
                                $field_type = 'text_textfield';
                                break;

                            default :
                                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_FIELD_TYPE_ERROR"), 'warning');
                                return false;

                        }
                        $field = new os_cckEntityField($db->_db);
                        $field->fid = $key;
                        $field->fk_eid = $entity;
                        $field->field_name = ucfirst($key);
                        $field->field_type = $field_type;
                        $field->custom_field_type = $temp_field;
                        $field->db_field_name = 'custom_sql_'.str_replace(' ', '_', $key);
                        $field->published = 1;
                        // var_dump($field);
                        $fields[$entity][] = $field;
                        if($temp_field == 'id') $fields[$entity]['custom_sql_id'] = $field;
                        if($temp_field == 'title') $fields[$entity]['custom_sql_title'] = $field;
                    }
                }


          }
      }
      $db = new os_cckDb();
      $query = "SELECT lid, type FROM #__os_cck_layout";
      $db->setQuery($query);
      $layouts = $db->loadAssocList('lid', 'type');
//        var_dump($layouts);

      $GLOBALS['entityFieldLists'] = $fields;
      $GLOBALS['entities_type'] = $entities_type;
      $GLOBALS['layouts_type'] = $layouts;



      //var_dump($fields[8]);
  }
}

if(!function_exists('get_layout_type')){
    function get_layout_type($lid){
        global $db;
        $db = new os_cckDb();
        //var_dump($lid);
        $query = "SELECT type FROM #__os_cck_layout WHERE lid=$lid";
        $db->setQuery($query);
        $layout_type = $db->loadResult();
        return $layout_type;
    }
}

if(!function_exists('check_profile_and_custom_field_init')){
    function check_profile_and_custom_field_init($field_list){
        global $entities_type, $entityFieldLists;
        //var_dump($field_list);
        $eid = (property_exists($field_list[0], 'childEntityId')) ? $field_list[0]->childEntityId : $field_list[0]->fk_eid;
        //$fid = (property_exists($field_list[0], 'childEntityFields')) ? $field_list->childEntityFields : $field_list->fid;
        if($entities_type[$eid] != 'joomla_user'){
            return false;
        }else{
            foreach($field_list as $child_field){
                $fid = (property_exists($child_field, 'childEntityFields')) ? $child_field->childEntityFields : $child_field->fid;
                $fid_arr = explode('_', $fid);
                $child_field_list = $entityFieldLists[$eid];
                foreach ($child_field_list as $temp_field){
                    if(!empty($fid_arr) && isset($fid_arr[1])){
                        if($temp_field->fid == $fid_arr[1]){
                            $field = $temp_field;
                            break;
                        }
                    }else{

                        if($temp_field->fid == $fid){
                            $field = $temp_field;
                            break;
                        }
                    }
                }
                if(isset($field) && is_object($field) && property_exists($field, 'db_field_name')){
                    $field = explode('_', $field->db_field_name);
                }else{
                    $field = array();
                }
                if(isset($field[1]) && $field[1] != 'standart'){
                    return true;
                }

            }

        }
        return false;
    }
}

if(!function_exists('checkUserFieldType')){
    function checkUserFieldType($eid, $field_name){
        global $entityFieldLists;

        foreach($entityFieldLists[$eid] as $field){
            if($field->db_field_name == $field_name){
                if($field->field_type == 'text_textfield'){
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    }
}

if(!function_exists('getRequestDetailsForAlphabeticalJoomlaUser')){
    function getRequestDetailsForAlphabeticalJoomlaUser($field){
        global $db, $input;
        $db = new os_cckDb();
        if($field == ''){
            $return_arr = array();
            $return_arr['join'] = '';
            $return_arr['field_name'] = '';
            $return_arr['where'] = '';
            $return_arr['where2'] = '';
            return $return_arr;
        }
        if($field == 'ceid'){
            $field = 'user_standart_id';
        }
        $field_name_array = explode('_', $field);
        //var_dump($field_name_array);
        $fieldset_name = $field_name_array[1];

        $letindex = $input->get('letindex', '');

        if($fieldset_name == 'standart'){
            $join = '';
            if($field_name_array[2] == 'last'){
                $field_name ='us.lastvisitDate';
            }elseif($field_name_array[2] == 'register'){
                $field_name ='us.registerDate';
            }else{
              $field_name = 'us.'.$field_name_array[2];
            }
            //$orderBy = ' ORDER BY '. $field_name;
            $where = '';
            $where2 = '';
            if($letindex != '' && $letindex != 'all'){
                $where2 .= " AND LOWER(" . $field_name . ") LIKE '$letindex%' ";
            }
        }elseif($fieldset_name == 'profile'){
            $join = " LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id ";
            $field_name = "prof.profile_value";
            $where = " AND prof.profile_key = 'profile.$field_name_array[2]' ";
            $where2 = '';
            if($letindex != '' && $letindex != 'all'){
                $where2 .= " AND LOWER(" . $field_name . ") LIKE '$letindex%' ";
            }
        }else{
            $join = " LEFT JOIN #__fields_values as val ON us.id = val.item_id "
                    . "LEFT JOIN #__fields as fi ON val.field_id = fi.id ";
            $field_name = "val.value";
            $where = " AND fi.name = '$field_name_array[2]' ";
            $where2 = '';
            if($letindex != '' && $letindex != 'all'){
                $where2 .= " AND LOWER(" . $field_name . ") LIKE '$letindex%' ";
            }
        }

        $return_arr = array();
        $return_arr['join'] = $join;
        $return_arr['field_name'] = $field_name;
        $return_arr['where'] = $where;
        $return_arr['where2'] = $where2;
        return $return_arr;
    }
}

if(!function_exists('getJoomlaUserField')){
    function getJoomlaUserField($field_name, $eid){
        global $entityFieldLists;

        $field_list = $entityFieldLists[$eid];

        if(!empty($field_list)){

            foreach ($field_list as $field){
//                var_dump($field);
//                var_dump($field_name);
                if($field->db_field_name == $field_name){
                    return $field;
                }
            }
        }
    }
}

if(!function_exists('getFieldsResultsForRangeSearchNumberfield')){
    function getFieldsResultsForRangeSearchNumberfield($db_field_name, $eid){
        global $db, $entities_type;
        $db = new os_cckDb();
        if($entities_type[$eid] == 'os_cck_entity'){
            $query = "SELECT ent.".$db_field_name." FROM #__os_cck_content_entity_".$eid." as ent"
              ."\n LEFT JOIN #__os_cck_entity_instance inst ON inst.eiid = ent.fk_eiid"
              ."\n LEFT JOIN #__os_cck_layout as lay ON lay.lid = inst.fk_lid WHERE lay.type ='add_instance'";
              //var_dump($query); exit;
            $db->setQuery($query);
            $prices = $db->loadColumn();
        }elseif($entities_type[$eid] == 'joomla_user'){
            $field_name_array = explode('_', $db_field_name);



            if($field_name_array[1] == 'profile'){
                $query = "SELECT prof.profile_value FROM #__user_profiles as prof "
                        . "WHERE prof.profile_key='profile.$field_name_array[2]'";
                $db->setQuery($query);
                $prices = $db->loadColumn();
            }else{
                $query = "SELECT val.value FROM #__fields_values as val "
                        . "LEFT JOIN #__fields as fi ON fi.id = val.field_id "
                        . "WHERE fi.name='$field_name_array[2]'";
                $db->setQuery($query);
                $prices = $db->loadColumn();
            }
            //var_dump($prices); exit;
        }elseif($entities_type[$eid] == 'custom_sql'){
            $name = str_replace('custom_sql_', '', $db_field_name);
            $entity = new os_cckEntity($db->_db);
            $entity->load($eid);
            $query = "SELECT t.$name FROM($entity->sql_select) as t";
            $db->setQuery($query);
            $prices = $db->loadColumn();

        }

        return $prices;
    }
}

if (!function_exists('checkLendOutTermOsCck')) {
    function checkLendOutTermOsCck($lend_from, $lend_until, $oneTerm_lend_from, $oneTerm_lend_until) {
        if (($lend_from >= $oneTerm_lend_from
            && $lend_from <= $oneTerm_lend_until)
            || ($lend_from <= $oneTerm_lend_from
            && $lend_until >= $oneTerm_lend_until)
            || ($lend_until >= $oneTerm_lend_from
                && $lend_until <= $oneTerm_lend_until)) {
            echo "<script> alert('" . _BOOKLIBRARY_SORRY_OBJECT_ALREADY_LEND_OUT . " " .
                    $oneTerm_lend_from . " until " . $oneTerm_lend_until . "'); 
                    window.history.go(-1); </script>\n";
            exit();
        }
    }
}

if (!function_exists('updateOsCck')) {
    function updateOsCck()
    {
        $config = JFactory::getConfig();
        $path = $config->get('tmp_path').'/pkg_os_cck_pro.zip';
        $data = file_get_contents('php://input');
        $obj = json_decode($data);
        $method = $obj->method;
        $data = $method($obj->package);
        $file = fopen($path, "w+");
        fputs($file, $data);
        fclose($file);
        if (JVERSION >= '4.0.0') {
            $archive = new Joomla\Archive\Zip();
            $archive->extract($path, $config->get('tmp_path').'/pkg_os_cck_pro');
        } else {
            JArchive::extract($path, $config->get('tmp_path').'/pkg_os_cck_pro');
        }

        $installer = JInstaller::getInstance();
        $result = $installer->update($config->get('tmp_path').'/pkg_os_cck_pro');
        JFile::delete($path);
        JFolder::delete($config->get('tmp_path').'/pkg_os_cck_pro');
        exit;
    }
}


if (!function_exists('checkOsCckState')) {
    function checkOsCckState()
    {
        $db = new os_cckDb();
        $query = "SELECT `key` FROM #__os_cck_api WHERE `service`='os_cck'";
        $db->setQuery($query);
        $data = $db->loadResult();
        if (empty($data)) {
            $obj = new stdClass();
            $obj->key = $data = '{}';
            $obj->service = 'os_cck';
            $db->insertObject('#__os_cck_api', $obj);
            $obj = new stdClass();
            $obj->key = $data = '{}';
            $obj->service = 'os_cck_activation';
            $db->insertObject('#__os_cck_api', $obj);
        }

        return $data;
    }
}

if (!function_exists('setOsCckLicense')) {
    function setOsCckLicense($info)
    {

      $db = new os_cckDb();
        $query = "SELECT * FROM #__os_cck_api WHERE `service`='os_cck'";
        $db->setQuery($query);
        $data = $db->loadObject();
        $data->key = json_decode($data->key);
        $data->key->data = $info;
        $data->key = json_encode($data->key);
        $db->updateObject('#__os_cck_api', $data, 'id');
        $query = "SELECT * FROM #__os_cck_api WHERE `service`='os_cck_activation'";
        $db->setQuery($query);
        $data = $db->loadObject();
        if($info == ''){
            $data->key = '{}';
        }else{
            $data->key = '{"data":"active"}';
        }
        $db->updateObject('#__os_cck_api', $data, 'id');

        if($info == ''){
            echo json_encode(array('msg'=>cck_lang_text('COM_OS_CCK_SUCCESSFULY_DEACTIVATED')));
        }else{
            echo json_encode(array('msg'=>cck_lang_text('COM_OS_CCK_YOUR_LICENSE_ACTIVE')));
        }
        exit;
    }
}

if (!function_exists('checkOsCckVersionProFree')) {
    function checkOsCckVersionProFree(){

      if( defined('OS_CCK_VERSION') ) return OS_CCK_VERSION;

        $activationNeed = false;
        $xml = @simplexml_load_file(JPATH_SITE . "/administrator/components/com_os_cck/os_cck.xml");
        if($xml){
            $version = (string)$xml->tag;
            unset($xml);

            define('OS_CCK_VERSION', $version);
            return $version;
        }

        define('OS_CCK_VERSION', "free");
        return "free" ;
    }
}

if (!function_exists('checkOsCckVersionNumber')) {
    function checkOsCckVersionNumber(){

        $activationNeed = false;
        $xml = @simplexml_load_file(JPATH_BASE . "/components/com_os_cck/os_cck.xml");
        if($xml){

            $version = (string)$xml->version;
            unset($xml);

            return $version;
        }
        return "" ;
    }
}

if (!function_exists('checkOsCckVersionDate')) {
    function checkOsCckVersionDate(){

        $activationNeed = false;
        $xml = @simplexml_load_file(JPATH_BASE . "/components/com_os_cck/os_cck.xml");
        if($xml){
            $date = (string)$xml->creationDate;
            unset($xml);

            return $date;
        }
        return "" ;
    }
}

if (!function_exists('checkOsCckActivationNeed')) {
    function checkOsCckActivationNeed(){

        $activationNeed = false;
        $version = checkOsCckVersionProFree() ;

        if($version == "pro") {
            $state = checkOsCckState();

            if (!empty($state)) {

                $state = json_decode($state);

                if(isset($state->data) && $state->data != "" ) $activationNeed = false;
                else $activationNeed = true;

            } else  $activationNeed = true;

        }


        return $activationNeed ;
    }
}

if (!function_exists('setOsCckAppLicenseActivation')) {
    function setOsCckAppLicenseActivation()
    {
        $db = new os_cckDb();
        $query = "SELECT * FROM #__os_cck_api WHERE `service`='os_cck_activation'";
        $db->setQuery($query);
        $package = $db->loadObject();
        $package->key = '{}';
        $db->updateObject('#__os_cck_api', $package, 'id');

        $query = "SELECT * FROM #__os_cck_api WHERE `service`='os_cck'";
        $db->setQuery($query);
        $package = $db->loadObject();
        $package->key = '{}';
        $db->updateObject('#__os_cck_api', $package, 'id');
    }
}

if (!function_exists('checkOsCckActivation')) {
    function checkOsCckActivation()
    {
        $version = checkOsCckVersionProFree() ;
        if($version == "pro") {
            $db = new os_cckDb();
            $query = "SELECT `key` FROM #__os_cck_api WHERE `service`='os_cck_activation'";
            $db->setQuery($query);
            $package = $db->loadResult();
            if($package){
              $state = json_decode($package);
            }else{
              $state = false;
            }
            return $state;
        }else{
            $state = new stdClass();
            $state->data = true;

            return $state;
        }
//        return true;
    }
}

if(!function_exists('copyfilefield')){
    function copyfilefield($file_id, $new_eiid){
        global $db;
        $db = new os_cckDb();
        if($file_id == '' || !$file_id) return;
        $query = "SELECT * FROM #__os_cck_files WHERE fid=$file_id";
        $db->setQuery($query);
        $file = $db->loadObjectList();
        $old_filepath = $file[0]->filepath;
        $new_timestamp = time();

        if(isset($file[0])){
            $file[0]->filepath = str_replace($file[0]->timestamp, $new_timestamp, $file[0]->filepath);

            $file[0]->timestamp = $new_timestamp;
            unset($file[0]->fid);
        }

        $col = '';
        $val = '';
        foreach($file[0] as $column => $value){
            $col .= $column . ",";
            $val .= $db->quote($value) . ",";
        }
        $column = '(' . trim($col, ',') . ')';
        $value = '(' . trim($val, ',') . ')';

        $query = "INSERT INTO #__os_cck_files " . $column . " VALUE " . $value;
        //var_dump($query); exit;
        $db->setQuery($query);
        $db->execute();

        $new_fid = $db->insertid();
        copy(JPATH_SITE . $old_filepath, JPATH_SITE . $file[0]->filepath);

        $request = array();
        $request['filepath'] = $file[0]->filepath;
        $request['new_fid'] = $new_fid;

        return $request;

    }
}

if(!function_exists('copygalleryfield')){
    function copygalleryfield($data, $new_eiid, $galleryfield_id){
        global $db;

        $db = new os_cckDb();
        if($data){
          $data = json_decode($data);
        }

        if (is_array($data) || is_object($data)) {
            foreach ($data as $key => $val) {
                $old_filename = $val->file;
                $temp_filename = substr($old_filename, 0, strripos($old_filename, '.')) . '-' . $new_eiid;
                $new_filename = $temp_filename . substr($old_filename, strripos($old_filename, '.'));

                $filepath_orig = JPATH_SITE . '/images/com_os_cck' . $galleryfield_id . '/original/';
                $filepath_thumb = JPATH_SITE . '/images/com_os_cck' . $galleryfield_id . '/thumbnail/';

                copy($filepath_orig . $old_filename, $filepath_orig . $new_filename);
                copy($filepath_thumb . $old_filename, $filepath_thumb . $new_filename);
                $data[$key]->file = $new_filename;
            }
        }

        return json_encode($data);
    }
}

if(!function_exists('cloneInstance')){
    function cloneInstance($eiid, $db_field_name = '', $date = ''){
        global $db;
        $db = new os_cckDb();
          $query = "SELECT * FROM #__os_cck_entity_instance WHERE eiid=".$eiid;
          $db->setQuery($query);
          $instance = $db->loadObjectList();
          if(empty($instance)){
              return false;
          }
          $eid = $instance[0]->fk_eid;
          unset($instance[0]->eiid);
          $instance[0]->hits = '0';
          $instance[0]->checked_out = '0';
          $instance[0]->checked_out_time = '0000-00-00 00:00:00';

          //andrew comment - I not understand what is it  5.04.2026 ?
          // $query = "SELECT * FROM #__os_cck_entity_instance LIMIT 1";
          // $db->setQuery($query);
          // $inst = $db->loadObjectList();
          // $isset_quantity = false;
          // foreach ($inst[0] as $key => $value){
          //     if($key == 'quantity') $isset_quantity = true;
          // }
          // if($isset_quantity && property_exists($instance[0], 'quantity') && empty($instance[0]->quantity ) )  $instance[0]->quantity = 0 ;


          $col = '';
          $val = '';
          foreach($instance[0] as $column => $value){
              $col .= $column . ",";
              $val .= $db->quote($value) . ",";
          }
          $column = '(' . trim($col, ',') . ')';
          $value = '(' . trim($val, ',') . ')';

          $query = "INSERT INTO #__os_cck_entity_instance " . $column . " VALUE " . $value;
          //var_dump($query); exit;
          $db->setQuery($query);
          $db->execute();

          $new_eiid = $db->insertid();

          $query = "SELECT * FROM #__os_cck_content_entity_$eid WHERE fk_eiid=$eiid";
          $db->setQuery($query);
          $content_instance = $db->loadObjectList();
          if(empty($content_instance)){
              return false;
          }

          if($db_field_name != '' && property_exists($content_instance[0], $db_field_name)){
              $content_instance[0]->$db_field_name = $date;
          }
          unset($content_instance[0]->ceid);
          $content_instance[0]->fk_eiid = $new_eiid;
          $col = '';
          $val = '';
          $file_path = '';
          $galleryfield_id = '';
          foreach($content_instance[0] as $column => $value){
              // var_dump($column);
              // var_dump($value);
              if((stripos($column, 'filefield') !== false || stripos($column, 'imagefield') !== false) && stripos($column, '_fid') !== false && $value != '0'){
                  $new_file = copyfilefield($value, $new_eiid);
                  $value = $new_file['new_fid'];
                  $file_path = $new_file['filepath'];
              }
              if((stripos($column, 'filefield') !== false || stripos($column, 'imagefield') !== false) && stripos($column, '_data') !== false){
                  $value = $file_path;
              }
              if(stripos($column, 'galleryfield_') !== false && stripos($column, '_fid') !== false){
                  $galleryfield_id = $value;
              }
              if(stripos($column, 'galleryfield_') !== false && stripos($column, '_data') !== false){

                  //below commented while $galleryfield_id get from other column(befor)
                  // $galleryfield_id = $column;
                  // $galleryfield_id = str_replace('galleryfield_', '', $galleryfield_id);
                  // $galleryfield_id = str_replace('_fid', '', $galleryfield_id);
                  $value = copygalleryfield($value, $new_eiid, $galleryfield_id);
//                  $value = $new_file['new_fid'];
//                  $file_path = $new_file['filepath'];
              }
              if(stripos($column, 'decimal_textfield_') !== false && $value == ''){
                  $value = 0;
              }
              if(!is_null($value) && $value != 'null'){
                // var_dump($column);
                // var_dump($value);
                  $col .= $column . ",";
                  $val .= $db->quote($value) . ",";
              }

          }
          $column = '(' . trim($col, ',') . ')';
          $value = '(' . trim($val, ',') . ')';

          $query = "INSERT INTO #__os_cck_content_entity_$eid " . $column . " VALUE " . $value;
          //var_dump($query); exit;
          $db->setQuery($query);
        try {
            $db->execute();
        }catch (Exception $e){
            echo $e->getMessage();
            echo $query; exit;
        }


          $query = "SELECT fk_cid FROM #__os_cck_categories_connect WHERE fk_eiid=$eiid";
          $db->setQuery($query);
          $categories = $db->loadObjectList();

          if(!empty($categories)){
              foreach($categories as $category){

                  $query = "INSERT INTO #__os_cck_categories_connect (fk_eiid, fk_cid) VALUE ($new_eiid, $category->fk_cid)";
                  //var_dump($query); exit;
                  $db->setQuery($query);
                  $db->execute();
              }
          }

          $query = "SELECT * FROM #__os_cck_child_parent_connect WHERE (fid_parent=$eiid OR fid_child=$eiid) AND media_type != 'instance'";
          $db->setQuery($query);
          $p_ch_instances = $db->loadObjectList();

          if(!empty($p_ch_instances)){
              foreach ($p_ch_instances as $p_ch){
                  unset($p_ch->id);
                  if($p_ch->fid_parent == $eiid){
                      $p_ch->fid_parent = $new_eiid;
                  }elseif($p_ch->fid_child == $eiid){
                      $p_ch->fid_child = $new_eiid;
                  }

                  $col = '';
                  $val = '';
                  foreach($p_ch as $column => $value){
                      $col .= $column . ",";
                      $val .= $db->quote($value) . ",";
                  }
                  $column = '(' . trim($col, ',') . ')';
                  $value = '(' . trim($val, ',') . ')';

                  $query = "INSERT INTO #__os_cck_child_parent_connect " . $column . " VALUE " . $value;
                  //var_dump($query); exit;
                  $db->setQuery($query);
                  $db->execute();
              }
          }

          $query = "SELECT * FROM #__os_cck_content_instances_price WHERE fk_eiid=$eiid ORDER BY price_id";
          $db->setQuery($query);
          $price_content_instances = $db->loadObjectList();
//          var_dump($price_content_instances); exit;
          if(!empty($price_content_instances)){
              foreach ($price_content_instances as $price){
                  unset($price->price_id);
                  $price->fk_eiid = $new_eiid;

                  $col = '';
                  $val = '';
                  foreach($price as $column => $value){
                      $col .= $column . ",";
                      $val .= $db->quote($value) . ",";
                  }
                  $column = '(' . trim($col, ',') . ')';
                  $value = '(' . trim($val, ',') . ')';

                  $query = "INSERT INTO #__os_cck_content_instances_price " . $column . " VALUE " . $value;
                  //var_dump($query); exit;
                  $db->setQuery($query);
                  $db->execute();
              }
          }

          $query = "SELECT * FROM #__os_cck_video_source WHERE fk_eiid=$eiid";
          $db->setQuery($query);
          $video_sources = $db->loadObjectList();

          if(!empty($video_sources)){
              foreach ($video_sources as $video){
                  unset($video->id);
                  $video->fk_eiid = $new_eiid;
                  if($video->src){
                      if( stripos($video->src,"https://") === 0 || stripos($video->src,"http://") === 0  ){
                        //remout URL - only copy value, so do nothing
                      }else{
                        //local file - do file copy
                        $old_src = $video->src;
                        $file_path = substr($old_src, 0, strripos($old_src, '/'));
                        $file_name = substr($old_src, strripos($old_src, '/'));
                        $temp_filename = substr($file_name, 0, strripos($file_name, '.')) . '-' . $new_eiid;
                        $new_file = $file_path . $temp_filename . substr($old_src, strripos($old_src, '.'));

                        copy(JPATH_SITE . '/' . $old_src, JPATH_SITE . '/' . $new_file);
                  
                        $video->src = $new_file;
                      }
                  }

                  $col = '';
                  $val = '';
                  foreach($video as $column => $value){
                      $col .= $column . ",";
                      $val .= $db->quote($value) . ",";
                  }
                  $column = '(' . trim($col, ',') . ')';
                  $value = '(' . trim($val, ',') . ')';

                  $query = "INSERT INTO #__os_cck_video_source " . $column . " VALUE " . $value;
                  //var_dump($query); exit;
                  $db->setQuery($query);
                  $db->execute();
              }
          }

          $query = "SELECT * FROM #__os_cck_track_source WHERE fk_eiid=$eiid";
          $db->setQuery($query);
          $track_sources = $db->loadObjectList();

          if(!empty($track_sources)){
              foreach ($track_sources as $track){
                  unset($track->id);
                  $track->fk_eiid = $new_eiid;
                  if($track->src){

                      if( stripos($track->src,"https://") === 0 || stripos($track->src,"http://") === 0  ){
                        //remout URL - only copy value, so do nothing
                      }else{
                        //local file - do file copy
                        $old_src = $track->src;
                        $file_path = substr($old_src, 0, strripos($old_src, '/'));
                        $file_name = substr($old_src, strripos($old_src, '/'));
                        $temp_filename = substr($file_name, 0, strripos($file_name, '.')) . '-' . $new_eiid;
                        $new_file = $file_path . $temp_filename . substr($old_src, strripos($old_src, '.'));

                        copy(JPATH_SITE . '/' . $old_src, JPATH_SITE . '/' . $new_file);

                        $track->src = $new_file;
                      }                    
                  }

                  $col = '';
                  $val = '';
                  foreach($track as $column => $value){
                      if (($column == 'fk_fid' && $value == '') || ($column == 'sequence_number' && $value == '')) {
                          $value = '0';
                      }                      
                      $col .= $column . ",";
                      $val .= $db->quote($value) . ",";
                  }
                  $column = '(' . trim($col, ',') . ')';
                  $value = '(' . trim($val, ',') . ')';

                  $query = "INSERT INTO #__os_cck_track_source " . $column . " VALUE " . $value;
                  $db->setQuery($query);
                  $db->execute();
              }
          }

          $query = "SELECT * FROM #__os_cck_audio_source WHERE fk_eiid=$eiid";
          $db->setQuery($query);
          $audio_source = $db->loadObjectList();

          if(!empty($audio_source)){
              foreach ($audio_source as $audio){
                  unset($audio->id);
                  $audio->fk_eiid = $new_eiid;
                  if($audio->src){
                      if( stripos($audio->src,"https://") === 0 || stripos($audio->src,"http://") === 0  ){
                        //remout URL - only copy value, so do nothing
                      }else{
                        //local file - do file copy
                        $old_src = $audio->src;
                        $file_path = substr($old_src, 0, strripos($old_src, '/'));
                        $file_name = substr($old_src, strripos($old_src, '/'));
                        $temp_filename = substr($file_name, 0, strripos($file_name, '.')) . '-' . $new_eiid;
                        $new_file = $file_path . $temp_filename . substr($old_src, strripos($old_src, '.'));

                        copy(JPATH_SITE . '/' . $old_src, JPATH_SITE . '/' . $new_file);

                        $audio->src = $new_file;
                      }

                  }

                  $col = '';
                  $val = '';
                  foreach($audio as $column => $value){
                      $col .= $column . ",";
                      if (($column == 'fk_fid' && $value == '') || ($column == 'sequence_number' && $value == '')) {
                          $value = '0';
                      }
                      $val .= $db->quote($value) . ",";
                  }
                  $column = '(' . trim($col, ',') . ')';
                  $value = '(' . trim($val, ',') . ')';

                  $query = "INSERT INTO #__os_cck_audio_source " . $column . " VALUE " . $value;
                  $db->setQuery($query);
                  $db->execute();
              }
          }

          return true;
    }
}
if(!function_exists('getSortingOptionsForChildFields')){
    function getSortingOptionsForChildFields($childEntityFields, $child_eid){
        global $entityFieldLists, $entities_type;

        $selected_field = array_unique(explode(',', $childEntityFields));
        //var_dump($child_eid);
//        echo $aaa;
        $child_entity_type = $entities_type[$child_eid];
        $child_entity_field_list = $entityFieldLists[$child_eid];
        //var_dump($child_entity_field_list);
        $child_entity_field_list_opt = array();
        $selected_field_list = array();
        if($child_entity_type = 'os_cck_entity'){

            foreach($selected_field as $select_field){
                if($select_field == 'id'){
                    $child_entity_field_list_opt[] = JHTML::_('select.option','id','ID');
                }else{
                    foreach($child_entity_field_list as $child_entity_field){
                        if($select_field == $child_entity_field->fid){
                            $selected_field_list[] = $child_entity_field;
                        }
                    }
                }
            }
            //var_dump($selected_field_list);
            //var_dump($child_entity_field_list);
        }

        foreach($selected_field_list as $field_list){
            $child_entity_field_list_opt[] = JHTML::_('select.option',$field_list->db_field_name,$field_list->field_name);
        }
        return $child_entity_field_list_opt;
    }
}
if(!function_exists('getDatesFromRange')){
    function getDatesFromRange($start, $end, $format = 'Y-m-d') {
        $array = array();
        $interval = new DateInterval('P1D');

        $realEnd = new DateTime($end);
        $realEnd->add($interval);

        $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

        foreach($period as $date) {
            $array[] = $date->format($format);
        }

        return $array;
    }
}
if(!function_exists('getWhereForSqlShowJoomlaUser')){
    function getWhereForSqlShowJoomlaUser($field){

        $field_name_array = explode('_', $field);
        //var_dump($field_name_array);
        $fieldset_name = $field_name_array[1];

        //$letindex = $input->get('letindex', '');

        if($fieldset_name == 'standart'){
            $join = '';
            if($field_name_array[2] == 'last'){
                $field_name ='us.lastvisitDate';
            }elseif($field_name_array[2] == 'register'){
                $field_name ='us.registerDate';
            }else{
              $field_name = 'us.'.$field_name_array[2];
            }
            return $field_name.'=';
            //$orderBy = ' ORDER BY '. $field_name;

        }elseif($fieldset_name == 'profile'){
            $field_name = "prof.profile_value";
            $where = " AND prof.profile_key = \'profile.$field_name_array[2]\' ";
            $where2 = " AND LOWER(" . $field_name . ") = ";
            return $where . $where2;
            //}
        }else{
            $field_name = "val.value";
            $where = " AND fi.name = \'$field_name_array[2]\' ";
            $where2 = " AND LOWER(" . $field_name . ") =";
            return $where . $where2;
        }


    }
}
if(!function_exists('get_pdf_layout_options')){
    function get_pdf_layout_options($eid, $parent_layout){
        global $db;
        $db = new os_cckDb();
        if($parent_layout->type == 'instance'){
            $type = 'pdf';
        }elseif($parent_layout->type == 'category'){
            $type = 'category_pdf';
        }elseif($parent_layout->type == 'all_instance'){
            $type = 'all_instance_pdf';
        }elseif($parent_layout->type == 'user_instances'){
            $type = 'user_instances_pdf';
        }elseif($parent_layout->type == 'parent_child'){
            $type = 'parent_child_pdf';
        }elseif($parent_layout->type == 'all_categories'){
            $type = 'all_categories_pdf';
        }

        $query = "SELECT lid, title FROM #__os_cck_layout WHERE type='$type' AND fk_eid='$eid'";
        $db->setQuery($query);
        $layouts = $db->loadObjectList();

        $layout_opt = array();
        foreach ($layouts as $layout){
            $layout_opt[] = JHTML::_('select.option',$layout->lid,$layout->title);
        }

        return $layout_opt;
    }
}

if(!function_exists('getOrderByOptions')){
    function getOrderByOptions($layout, $fields_from_params, $entity_id, $mod_type, $lid){
        global $db, $entities_type, $entityFieldLists;
        $db = new os_cckDb();
        if(!$entity_id){
          return $fields_from_params;
        }
        if(isset($fields_from_params['views']['custom_order_by'][0])){
          $fields_from_params['views']['custom_order_by'][0] = str_replace('ORDER BY', '', $fields_from_params['views']['custom_order_by'][0]);
        }
        // var_dump($fields_from_params["fields"]['order_by_fields_'.$layout]);
        $fields_from_params["views"]["sortField"][] = isset($fields_from_params["fields"]["indexed_".$layout])?$fields_from_params["fields"]["indexed_".$layout]:array();

          $fields_list = $entityFieldLists[$entity_id];
//          var_dump($fields_from_params['views']['custom_order_by_alias']);
          if(isset($fields_from_params["fields"]['order_by_fields_'.$layout]) && isset($fields_from_params["views"]["sortField"][0])){
            foreach ($fields_from_params["fields"]['order_by_fields_'.$layout] as $key => $value) {
              //  var_dump($value);
              if($value != $fields_from_params["views"]["sortField"][0]){

                $fields_from_params["views"]["sortField"][$key] = array();
                if($value == 'hits'){
                    $fields_from_params["views"]["sortField"][$key]['value'] = $value;
                    $fields_from_params["views"]["sortField"][$key]['text'] = cck_lang_text('COM_OS_CCK_NUMBER_OF_VIEWS');
                }elseif($value == 'custom_order'){
                    $fields_from_params["views"]["sortField"][$key]['value'] = $value;
                    $fields_from_params["views"]["sortField"][$key]['text'] = isset($fields_from_params['views']['custom_order_by_alias']) ? $fields_from_params['views']['custom_order_by_alias'] : '';
                }elseif($value == 'last_review_date'){
                    $fields_from_params["views"]["sortField"][$key]['value'] = 'last_review';
                    $fields_from_params["views"]["sortField"][$key]['text'] = cck_lang_text('COM_OS_CCK_LAST_REVIEW_DATE');
                }
                foreach ($fields_list as $entity_field) {
                  if($entity_field->db_field_name == $value){
                    $fields_from_params["views"]["sortField"][$key]['value'] = $value;
                    $fields_from_params["views"]["sortField"][$key]['text'] = $entity_field->field_name;
                    $fields_from_params['views']['order_by_fields'][] = $value;

                  }
                }
              }
            }
          }


          //end
          //get params after reload page with new order direction
          //session need if we are used pagination(save our sort params in all pages)
          //default value set in cat layout params

          $item_session = JFactory::getSession();
          $session_selected = $item_session->get('selected', array());
          $session_order_direction = $item_session->get('order_direction', array());
          // var_dump($fields_from_params["fields"]["indexed_".$layout]);
          //$item_session->destroy();

//          var_dump($lid);
        //  var_dump($session_order_direction); exit;

          if($mod_type == 0){

              if(isset($_REQUEST['order_direction']) && !empty($_REQUEST['order_direction'])){
                  $fields_from_params["fields"]["sortType_".$layout] = protectInjectionWithoutQuote('order_direction','');//need for order by desc//asc
              //}elseif($item_session->get('order_direction','')){
              }elseif(isset($session_order_direction[$lid])){
                  $fields_from_params["fields"]["sortType_".$layout] = $session_order_direction[$lid];
              }
          } else{
            $fields_from_params["views"]["sortType_".$layout] = isset($fields_from_params["fields"]["sortType_".$layout]) ? $fields_from_params["fields"]["sortType_".$layout] : '';
          }
          $fields_from_params["views"]["sortType_".$layout] = isset($fields_from_params["fields"]["sortType_".$layout]) ? $fields_from_params["fields"]["sortType_".$layout] : '';
          // var_dump($_REQUEST['order_field']);
            if(isset($_REQUEST['order_field']) && !empty($_REQUEST['order_field'])){
              // echo '111111111111111';
                $query = "SELECT * FROM #__os_cck_content_entity_$entity_id LIMIT 0,1";
                $db->setQuery($query);
                $collumns = $db->loadObjectList();
                if($entities_type[$entity_id] == 'joomla_user' || $entities_type[$entity_id] == 'custom_sql' || (!empty($collumns) && property_exists($collumns[0], $_REQUEST['order_field'])) || $_REQUEST['order_field'] == 'hits' || $_REQUEST['order_field'] == 'custom_order' || stripos($_REQUEST['order_field'], 'pricefield_number_') !== false || $_REQUEST['order_field'] == 'ceid' || $_REQUEST['order_field'] == 'last_review'){
                  // echo '11111111111111';
                    $fields_from_params["views"]["selected"] = $_REQUEST['order_field'];
                    // var_dump($fields_from_params["views"]["selected"]);
                }else{
                    $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_".$layout])?$fields_from_params["fields"]["indexed_".$layout]:'';
                }
              //$fields_from_params["views"]["selected"] = protectInjectionWithoutQuote('order_field','');//need for order by field name
            //}elseif($item_session->get('selected','')){
            }elseif(isset($session_selected[$lid])){
// echo '2222222222222';
                $query = "SELECT * FROM #__os_cck_content_entity_$entity_id LIMIT 0,1";
                $db->setQuery($query);
                $collumns = $db->loadObjectList();
                //var_dump($collumns);
                if($entities_type[$entity_id] == 'joomla_user' || $entities_type[$entity_id] == 'custom_sql' || (!empty($collumns) && property_exists($collumns[0], $session_selected[$lid])) || $session_selected[$lid] == 'hits' || $session_selected[$lid] == 'custom_order' || $session_selected[$lid] == 'custom_order' || $session_selected[$lid] == 'last_review'){
                    $fields_from_params["views"]["selected"] = $session_selected[$lid];
                }else{
                    $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_".$layout])?$fields_from_params["fields"]["indexed_".$layout]:'';
                }
          //$fields_from_params["views"]["selected"] = $session->get('selected');
            }else
              $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_".$layout])?$fields_from_params["fields"]["indexed_".$layout]:'';
              //end sort params
// echo '333333333333333';
            if( isset($fields_from_params['views']['selected']) && $fields_from_params['views']['selected'] != 'hits' && $fields_from_params['views']['selected'] !='last_review' && $fields_from_params['views']['selected'] != 'custom_order' && stripos($fields_from_params['views']['selected'], 'pricefield_number_') === false &&
                 ( !isset( $fields_from_params['views']['order_by_fields'] ) || !is_array( $fields_from_params['views']['order_by_fields'] ) ||
                  ( is_array( $fields_from_params['views']['order_by_fields'] ) && !in_array($fields_from_params["views"]["selected"],$fields_from_params['views']['order_by_fields']) && $fields_from_params['views']['selected'] != 'ceid'
                  )
                 )
                )
             {
                  $fields_from_params["views"]["selected"] = isset($fields_from_params["fields"]["indexed_".$layout])?$fields_from_params["fields"]["indexed_".$layout]:'';
             }
// var_dump($fields_from_params["views"]["selected"]);
             return $fields_from_params;
    }
}

if(!function_exists('saveRentCCK')){
    function saveRentCCK($option, $eiid,$task = ""){
        global $db, $app, $os_cck_configuration, $os_cck_state, $Itemid;
        $db = new os_cckDb();

        $itemid = protectInjectionWithoutQuote('itemid','');
        // $Itemid = ( !isset($Itemid) || $Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        $rent_id = protectInjectionWithoutQuote("return_id", '');
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }

        $rent_from_input = date("Y-m-d H:i:s", strtotime(protectInjectionWithoutQuote('rent_from','')));
        $rent_until_input =date("Y-m-d H:i:s", strtotime(protectInjectionWithoutQuote( 'rent_until','')));        
        if($task == 'save_rent' || $task == 'add_rent_confirm' ){
          if (!is_array($rent_id) || count($rent_id) <> 1 || $rent_id[0] == 0) {
            echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
            exit;
          }

          //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
          if($os_cck_configuration->get('rent_type') == 0){
            
            try {

              $rent_from_temp = new DateTime($rent_from_input);
              $rent_from_temp = $rent_from_temp->format("Y-m-d");
              $rent_until_temp = new DateTime($rent_until_input);
              $rent_until_temp = $rent_until_temp->format("Y-m-d");

              if($rent_from_temp === $rent_until_temp){
                echo "<script> alert('Sorry, not one night, selected'); window.history.go(-1); </script>\n";
                exit;
              }
            } catch (Exception $ex) {
                echo "<script> alert('Sorry, not one night, selected!'); window.history.go(-1); </script>\n";
                exit;
            }   

          }
        }

        if ($eiid == "" ) {
          echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
          exit;
        }
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->load($eiid);
        $assoc_instance = unserialize($entityInstance->associate_instances);

        if(empty($assoc_instance)){
            $assoc_instance[] = $eiid;
        }
        $rent_from = array();
        $rent_until = array();
        foreach ($assoc_instance as $key => $eiid){
            if( isset($rent_id[0] ) && $rent_id[0] > 0 )
               $query = "SELECT * FROM #__os_cck_rent where fk_eiid= " . $eiid . " AND rent_return is NULL and id != ".$rent_id[0];
            else $query = "SELECT * FROM #__os_cck_rent where fk_eiid= " . $eiid . " AND rent_return is NULL";
            $db->setQuery($query);
            $rentTerm = $db->loadObjectList();

            $rent_from[$key] = $rent_from_input ;
            $rent_until[$key] = $rent_until_input ;
            if (empty($rent_until[$key]) || strlen($rent_until[$key]) < 2) $rent_until[$key] = protectInjectionWithoutQuote('rent_until','');
            //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
            if($os_cck_configuration->get('rent_type') == 2){
                foreach ($rentTerm as $oneTerm){
                        $returnMessage = checkRentCCK (($oneTerm->rent_from),($oneTerm->rent_until),
                         $rent_from[$key], $rent_until[$key]);

                        if(strlen($returnMessage) > 0){
                          echo "<script> alert('$returnMessage'); window.history.go(-1); </script>\n";
                          exit;
                        }
                      }
            } else {
                foreach ($rentTerm as $oneTerm){
                        $oneTerm->rent_from = substr($oneTerm->rent_from, 0, 10);
                        $oneTerm->rent_until = substr($oneTerm->rent_until, 0, 10);
    //                    var_dump($oneTerm);
    //                    var_dump($rent_from);
    //                    var_dump($rent_until);
    //                    exit;
                        $returnMessage = checkRentCCK (($oneTerm->rent_from),($oneTerm->rent_until),
                         substr($rent_from[$key], 0 , 10), substr($rent_until[$key], 0 , 10));

                        if(strlen($returnMessage) > 0){
                          echo "<script> alert('$returnMessage'); window.history.go(-1); </script>\n";
                          exit;
                        }
                      }
            }
            if(!isset($os_cck_state->data) ){
                echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
                return ;
            }

            if ($rent_from[$key] > $rent_until[$key]) {
              echo "<script> alert('" . $rent_from[$key] . " more then " . $rent_until[$key] . "'); window.history.go(-1); </script>\n";
              exit ();
            }
            // $rent_from = substr($rent_from, 0, 10);
            // $rent_until = substr($rent_until, 0, 10);

            if (isset($rentTerm[0]) ) {
              for ($e = 0, $m = count($rentTerm); $e < $m; $e++) {

                if (( $task == "save_rent" ) && isset($rent_id[0]) && $rent_id[0] == $rentTerm[$e]->id)
                  continue;
                // $rentTerm[$e]->rent_from = substr($rentTerm[$e]->rent_from, 0, 10);
                // $rentTerm[$e]->rent_until = substr($rentTerm[$e]->rent_until, 0, 10);

                //rent check
                //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
                if($os_cck_configuration->get('rent_type') == 2){    

                  if (($rent_from[$key] >= $rentTerm[$e]->rent_from && $rent_from[$key] < $rentTerm[$e]->rent_until) ||
                  ($rent_from[$key] <= $rentTerm[$e]->rent_from && $rent_until[$key] >= $rentTerm[$e]->rent_until) ||
                  ($rent_until[$key] > $rentTerm[$e]->rent_from && $rent_until[$key] <= $rentTerm[$e]->rent_until)) {

                    echo "<script> alert('Sorry , this object already rent out from " . $rentTerm[$e]->rent_from . " to " . $rentTerm[$e]->rent_until . "'); window.history.go(-1); </script>\n";
                    exit ();
                  }
                //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
                }elseif($os_cck_configuration->get('rent_type')){

                   $rent_from[$key] = date('Y-m-d',strtotime($rent_from[$key]));
                  $rent_until[$key] = date('Y-m-d',strtotime($rent_until[$key]));
                  $rentTerm[$e]->rent_from = date('Y-m-d',strtotime($rentTerm[$e]->rent_from));
                  $rentTerm[$e]->rent_until = date('Y-m-d',strtotime($rentTerm[$e]->rent_until));

                  if (($rent_from[$key] >= $rentTerm[$e]->rent_from && $rent_from[$key] <= $rentTerm[$e]->rent_until) ||
                  ($rent_from[$key] <= $rentTerm[$e]->rent_from && $rent_until[$key] >= $rentTerm[$e]->rent_until) ||
                  ($rent_until[$key] >= $rentTerm[$e]->rent_from && $rent_until[$key] <= $rentTerm[$e]->rent_until)) {

                    echo "<script> alert('Sorry , this object already rent out from " . $rentTerm[$e]->rent_from . " to " . $rentTerm[$e]->rent_until . "'); window.history.go(-1); </script>\n";
                    exit ();
                  }

                }else{  //by night

                  $rent_from[$key] = date('Y-m-d',strtotime($rent_from[$key]));
                  $rent_until[$key] = date('Y-m-d',strtotime($rent_until[$key]));
                  $rentTerm[$e]->rent_from = date('Y-m-d',strtotime($rentTerm[$e]->rent_from));
                  $rentTerm[$e]->rent_until = date('Y-m-d',strtotime($rentTerm[$e]->rent_until));

                  if (($rent_from[$key] > $rentTerm[$e]->rent_from && $rent_from[$key] < $rentTerm[$e]->rent_until) ||
                  ($rent_from[$key] < $rentTerm[$e]->rent_from && $rent_until[$key] > $rentTerm[$e]->rent_until) ||
                  ($rent_until[$key] > $rentTerm[$e]->rent_from && $rent_until[$key] < $rentTerm[$e]->rent_until)) {

                    echo "<script> alert('Sorry , this object already rent out from " . $rentTerm[$e]->rent_from . " to " . $rentTerm[$e]->rent_until . "'); window.history.go(-1); </script>\n";
                    exit ();
                  }

                }

              }
            }
        }


    //    $rent->fk_eiid = $eiid;
    //    var_dump($assoc_instance); exit;
        foreach ($assoc_instance as $eiid){
            $rent = new mosCCK_rent($db->_db);
            if( ( $task == "save_rent" ) && isset( $rent_id[0]) ) $rent->load( $rent_id[0] );
              $userid = protectInjectionWithoutQuote( 'userid','' );
            if( $userid == "-1" ) {
              $rent->user_name = protectInjectionWithoutQuote( 'user_name', '');
              $rent->user_email = protectInjectionWithoutQuote( 'user_email', '');
            }else{
              $rent->fk_userid = intval( $userid );
              $query = "SELECT name, email FROM #__users WHERE id=$userid";
              $db->setQuery($query);
              $user = $db->loadObjectList();
              $rent->user_name = $user[0]->name;
              $rent->user_email = $user[0]->email;
            }

            $rent->fk_eiid = $eiid;
            $rent->rent_from = $rent_from[$key];
            $rent->rent_until = $rent_until[$key];
            $rent->checked_out_time = get_curent_site_time();
            if (!$rent->check($rent)) {
              echo "<script> alert('" . addslashes($rent->getError()) . "'); window.history.go(-1); </script>\n";
              exit ();
            }
            if (!$rent->store()) {
              echo "<script> alert('" . addslashes($rent->getError()) . "'); window.history.go(-1); </script>\n";
              exit ();
            }

        }
        $rent->checkin();
        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;
          }
        }
//        $app->redirect("index.php?option=$option&task=show_instance",'ok');
        if($check){
            $app->enqueueMessage('ok', 'success');
            $app->redirect("index.php?option=" . $_REQUEST['option'] . "&eiid=$eiid&task=edit_rent&Itemid=$Itemid");
        }else{
            $app->enqueueMessage('ok', 'success');
            $app->redirect("index.php?option=$option&task=show_instance");
        }
    }
}

if(!function_exists('rentReturnCCK')){
    function rentReturnCCK($option, $lids){
        global $db, $app, $os_cck_state, $Itemid;
        $db = new os_cckDb();
        $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');

            return;
        }
        if (!is_array($lids) || count($lids) < 1 || $lids[0] == 0) {
          echo "<script> alert('Select an item to return'); window.history.go(-1);</script>\n";
          exit;
        }
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $lids_with_assoc = array();
        foreach($lids as $rent_id){
            $rent = new mosCCK_rent($db->_db);
            $rent->load($rent_id);

            $eiid = $rent->fk_eiid;

            $entityInstance = new os_cckEntityInstance($db->_db);
            $entityInstance->load($eiid);
            $assoc_instance = unserialize($entityInstance->associate_instances);

            if(empty($assoc_instance)){
                $lids_with_assoc[] = $rent_id;
            }else{

                $assoc_instance = implode(',', $assoc_instance);
                $query = "SELECT id FROM #__os_cck_rent WHERE fk_eiid IN ($assoc_instance) AND rent_from='$rent->rent_from' AND rent_until='$rent->rent_until' AND rent_return IS NULL";
                $db->setQuery($query);
                $eiids = $db->loadColumn();
                $lids_with_assoc = array_merge($lids_with_assoc, $eiids);
    //            var_dump($lids_with_assoc); exit;

            }



        }
        for ($i = 0, $n = count($lids_with_assoc); $i < $n; $i++) {
          $rent = new mosCCK_rent($db->_db);
          $rent->load($lids_with_assoc[$i]);
          if ($rent->rent_return != null) {
            echo "<script> alert('Item already returned'); window.history.go(-1);</script>\n";
            exit;
          }
          $rent->rent_return = date("Y-m-d H:i:s");
          if (!$rent->store()) {
            echo "<script> alert('" . addslashes($rent->getError()) . "'); window.history.go(-1); </script>\n";
            exit ();
          }
        }
        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){
            $app->enqueueMessage('ok', 'success');
            $app->redirect("index.php?option=" . $_REQUEST['option'] . "&task=edit_rent&eiid[]=$rent->fk_eiid&Itemid=$Itemid");
        }else{
            $app->enqueueMessage('ok', 'success');
            $app->redirect("index.php?option=$option&task=show_instance");
        }
    }

}

if(!function_exists('getCCKLangWhere')){
    function getCCKLangWhere(){
        $lang = JFactory::getLanguage();
        $lang_tag = $lang->getTag();

        $lang_where = " AND ( ei.language='$lang_tag' OR ei.language='*' OR ei.language='' OR ei.language IS NULL) ";
        return $lang_where;
    }
}

if(!function_exists('setLayoutLangCCK')){
    function setLayoutLangCCK($layout){
        $lang = JFactory::getLanguage();
        if($layout->language != '' && $layout->language != '*'){
              if($layout->language != $lang->getTag()){
                  $layout_assoc_list = unserialize($layout->associate_layout);
                  if(isset($layout_assoc_list[$lang->getTag()])){
                      $lid = $layout_assoc_list[$lang->getTag()];
                      $layout->load($lid);
                  }
              }
          }
          return $layout;

    }
}

if(!function_exists('cckConvertFieldList')){
    function cckConvertFieldList($field_list){
        $new_field_list = array();

        foreach($field_list as $field){
            $new_field_list[$field->fid] = $field;
        }
        
        return $new_field_list;

    }
}

if(!function_exists('not_available_times_in_day_cck_from')){
    function not_available_times_in_day_cck_from($available_times,$step_time){
        $not_available_time = array();
        $interval = new DateInterval('PT'.$step_time.'M');
        $not_interval = true;
        //loop for all available_times, where $key - day week
        foreach($available_times as $key => $time){
//            var_dump($time);
            if(is_array($time)){
                $not_interval = false;
                if($time[0] != '00:00'){
                    $not_available_time[$key][] = array('00:00', $time[0]);
                }
                foreach ($time as $k => $minutes){
                    
                    $timeMinutes = new DateTime($minutes);
                    $timeMinutes->add($interval);
                    $temptime = $timeMinutes->format('H:i');
//                    var_dump($temptime);
                    $next_time = isset($time[$k+1]) ? $time[$k+1] : false;
//                    var_dump($next_time);
                    if($temptime != $next_time && $next_time !== false){
                        $not_available_time[$key][] = array($minutes, $time[$k+1]);
                    }elseif($temptime != $next_time && $next_time === false){
                        $not_available_time[$key][] = array($minutes, '23:59');
                    }
                }
            }else{
                $not_available_time[$key][] = array('00:00', '23:59');
            }
        }
        //var_dump($not_available_time); exit ;
        if($not_interval){
            return array();
        }else{
            return $not_available_time;
        }
    }
}

if(!function_exists('not_available_times_in_day_cck_to')){
    function not_available_times_in_day_cck_to($available_times,$step_time){
        $not_available_time = array();
        $interval = new DateInterval('PT'.$step_time.'M');
        $not_interval = true;
//        var_dump($available_times);
        //loop for all available_times, where $key - day week
        foreach($available_times as $key => $time){
            if(is_array($time)){
                $not_interval = false;
                if($time[0] != '00:00'){
                    //add yet 1 inteval, because TO
                    $not_available_time[$key][] = array('00:00', $time[1]);
                }
                foreach ($time as $k => $minutes){
                    $timeMinutes = new DateTime($minutes);
                    $timeMinutes->add($interval);
                    $temptime = $timeMinutes->format('H:i');
//                    var_dump($temptime);
                    $next_time = isset($time[$k+1]) ? $time[$k+1] : false;
                    if($temptime != $next_time && $next_time !== false && $temptime !== '00:00'){
                        //add the end avaliable span, add yet 1 interval, because TO
                        if(!isset($time[$k+2])){
//                            var_dump($k+2);
//                            var_dump($time[$k+1]);
//                            var_dump($temptime);
                        }
                        if(isset($time[$k+2])){
                            $not_available_time[$key][] = array($temptime, $time[$k+2]);
                        }else{
                            $not_available_time[$key][] = array($temptime, '23:59');
                        }
                    }elseif($temptime != $next_time && $next_time === false && $temptime == '00:00'){
//                        var_dump($time[$k]);
//                        $not_available_time[$key][] = array($time[$k], '23:59');
                    }elseif($temptime != $next_time && $next_time === false){
                        $not_available_time[$key][] = array($temptime, '23:59');
                    }
                }
            }else{
                $not_available_time[$key][] = array('00:00', '23:59');
            }
        }
//        var_dump($not_available_time); //exit ;
        if($not_interval){
            return array();
        }else{
            return $not_available_time;
        }
    }
}

if(!function_exists('weekDayTransformToJs')){
    function weekDayTransformToJs($day){
        switch ($day){
            case '0':
                return '6';
                break;
            case '1':
                return '0';
                break;
            case '2':
                return '1';
                break;
            case '3':
                return '2';
                break;
            case '4':
                return '3';
                break;
            case '5':
                return '4';
                break;
            case '6':
                return '5';
                break;
        }
        return false;
    }
}

if(!function_exists('get_available_time_opt')){
    function get_available_time_opt($step_time){
        $available_times = array();
          $starttime = '00:00';
          $time = new DateTime($starttime);
          $interval = new DateInterval('PT'.$step_time.'M');
          $temptime = $time->format('H:i');
//          var_dump($starttime);
//          var_dump($temptime);
//          exit;
          do {
              $available_times[]  = JHTML::_('select.option',$temptime,$temptime);
//              echo $temptime . '<br />';
              $time->add($interval);
              $temptime = $time->format('H:i');
          } while ($temptime !== $starttime);
          $available_times[]  = JHTML::_('select.option','00:00','00:00');

          return $available_times;
    }
}

if(!function_exists('get_curent_site_time')){
    function get_curent_site_time($date_time = "now"){
        global $app;
        $tz  = new DateTimeZone($app->get('offset'));
        $now = JFactory::getDate();
        if($date_time !== "now" ) $now->modify($date_time); 
        $now->setTimezone($tz);

        $now_string = $now->__toString();

        return $now_string;
    }
}

if(!function_exists('session_set_order_data')){
    function session_set_order_data($order_direction, $selected, $layoutId){
        global $session;
        
        $session_order_direction = $session->get('order_direction', array());
        if(!is_array($session_order_direction)){
            $session_order_direction = array();
        }
        $session_order_direction[$layoutId] = $order_direction;
        
        $session_selected = $session->get('selected', array());
        if(!is_array($session_selected)){
            $session_selected = array();
        }
        $session_selected[$layoutId] = $selected;
        
        $session->set('order_direction', $session_order_direction);
        $session->set('selected', $session_selected);
        
        
    }
}
if(!function_exists('str_lreplace')){
    function str_lreplace($search, $replace, $subject)
    {
        $pos = strrpos($subject, $search);

        if($pos !== false)
        {
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
        }

        return $subject;
    }
}
if(!function_exists('getTextfieldOptons')){
    function getTextfieldOptons($eid, $field_name){
        global $db, $entities_type;
        $db = new os_cckDb();
//        var_dump($field_name); exit;
        if($entities_type[$eid] == 'os_cck_entity'){
            $query = "SELECT DISTINCT LOWER($field_name) FROM #__os_cck_content_entity_$eid";
            $db->setQuery($query);
            $column = $db->loadColumn();
        }elseif($entities_type[$eid] == 'joomla_user'){
            $subkey_arr = explode('_', $field_name);
            
            if($subkey_arr[1] == 'standart'){
                $query = "SELECT DISTINCT LOWER($subkey_arr[2]) FROM #__users";
                $db->setQuery($query);
                $column = $db->loadColumn();
//                var_dump($column); exit;
            }elseif($subkey_arr[1] == 'profile'){
                $query = "SELECT DISTINCT LOWER(profile_value) FROM #__user_profiles WHERE profile_key='profile.$subkey_arr[2]'";
                $db->setQuery($query);
                $column = $db->loadColumn();
            }else{
                $query = "SELECT DISTINCT LOWER(val.value) FROM #__fields_values as val "
                        . "LEFT JOIN #__fields as fi ON val.field_id = fi.id "
                        . "WHERE fi.name='$subkey_arr[2]'";
//                echo $query; exit;
                $db->setQuery($query);
                $column = $db->loadColumn();
//                var_dump($subkey_arr);
            }

        }else{
            $entity = new os_cckEntity($db->_db);
            $entity->load($eid);
            $subkey = str_replace('custom_sql_', '', $field_name);
//            var_dump($subkey);
            $query = "SELECT DISTINCT LOWER(t.$subkey) FROM ($entity->sql_select) as t ";
            $db->setQuery($query);
            $column = $db->loadColumn();
        }
        
        return $column;
        
    }
}

if(!function_exists('cck_getCurrentCurrency')){
    function cck_getCurrentCurrency(){
        $session = \JFactory::getSession() ;

        $currency = JFactory::getApplication()->input->get("currency", "");
        if ($currency != "" ) {
           $session->set('currency', $currency );

           return $currency;
        }

        $currency = $session->get('currency', '');
        if ($currency != "" ) {
           return $currency;
        }

        $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
        $currency_list = cck_getCurrency($os_cck_configuration);  
        
        foreach ($currency_list as $carrencyArr) {
          if( $carrencyArr['coefficient'] == 1 ) {
           $session->set('currency', $carrencyArr['sign']);
           return $carrencyArr['sign']; 
          }
        }      

        $session->set('currency', $currency_list[0]['sign']);
        return $currency_list[0]['sign'] ;

    }
}

if(!function_exists('cck_getSubCategories')){
    function cck_getSubCategories($cids, $cats_arr = array()){
        global $db;
        $db = new os_cckDb();
        if(!is_array($cids)) $cids = array($cids);
        foreach ($cids as $cid){
            if(!in_array($cid, $cats_arr)){
                $cats_arr[] = $cid;
                $query = "SELECT cid FROM #__os_cck_categories WHERE parent_id=".$cid;
                $db->setQuery($query);
                $child_cats = $db->loadColumn();
        //        var_dump($child_cats);
                if(!empty($child_cats)){
                    foreach ($child_cats as $child_cat){
                        $child_sub_cats = cck_getSubCategories($child_cat);
                    }
                }
                if(isset($child_sub_cats) && !empty($child_sub_cats)){
                    foreach ($child_sub_cats as $child_sub_cat){
                        $cats_arr[] = $child_sub_cat;
                    }
                }
            }
        }
        return $cats_arr;
    }
    
}
if(!function_exists('br2nl')){
    function br2nl($text)
    {
            return  preg_replace('/<br\\s*?\/??>/i', '', $text);
    }
}

if(!function_exists('recursiveRemoveDir')){
    function recursiveRemoveDir($dir) {

      $includes = new FilesystemIterator($dir);

      foreach ($includes as $include) {

        if(is_dir($include) && !is_link($include)) {

          recursiveRemoveDir($include);
        }

        else {

          unlink($include);
        }
      }

      rmdir($dir);
    }
}

if(!function_exists('checkingUser')){
  function checkingUser($userId) {
    global $db;
    $db = new os_cckDb();
    $query = "SELECT * FROM #__users WHERE id=$userId";
    $db->setQuery($query);
    $user = $db->loadObjectList();

    if(empty($user)){
      return false;
    }else{
      return true;
    }
  }
}

if(!function_exists('rcopy')){
  function rcopy($src, $dst) {
      if (file_exists ( $dst ))
        recursiveRemoveDir ( $dst );
      if (is_dir ( $src )) {
          mkdir ( $dst );
          $files = scandir ( $src );
          foreach ( $files as $file )
              if ($file != "." && $file != "..")
                  rcopy ( "$src/$file", "$dst/$file" );
      } else if (file_exists ( $src ))
          copy ( $src, $dst );
  }
}

if (!function_exists('importJsLibrary')) {
  function importJsLibrary()
  {
      $config = JFactory::getConfig();
      $path = $config->get('tmp_path').'/importJsLibrary.zip';
      $data = file_get_contents('php://input');
      $obj = json_decode($data);
      $method = $obj->method;
      
      $data = $method($obj->package);
      // var_dump($data); exit;
      $file = fopen($path, "w+");
      fputs($file, $data);
      fclose($file);
      // if (JVERSION >= '4.0.0') {
      //     $archive = new Joomla\Archive\Zip();
      //     $archive->extract($path, $config->get('tmp_path').'/pkg_os_cck_pro');
      // } else {
      //     JArchive::extract($path, $config->get('tmp_path').'/pkg_os_cck_pro');
      // }

      // $installer = JInstaller::getInstance();
      // $result = $installer->update($config->get('tmp_path').'/pkg_os_cck_pro');
      // JFile::delete($path);
      // JFolder::delete($config->get('tmp_path').'/pkg_os_cck_pro');
      exit;
  }
}

if (!function_exists('checkInstanceManagerItem')) {
  function checkInstanceManagerItem($menu_params)
  {
    $entity_list = $menu_params->get('entity_list',array());
     // var_dump($entity_list);
    if(empty($entity_list)){
      return false;
    }else{
      return true;
    }
      
  }
}

if (!function_exists('get_menu_url_alias_cck')) {

  function get_menu_url_alias_cck($Itemid,$view,$task_param) {
      global $db,$task  ;
      $db = new os_cckDb();
      $app = JFactory::getApplication();
      $menu_item = $app->getMenu()->getItem($Itemid);
      $menu = new JTableMenu($db->_db);
      $menu->load($Itemid);

      $url_alias = "" ;

      $task = $task_param ;
  
      $query_view = "";
      if( isset($menu_item->query['view']) ) $query_view = $menu_item->query['view'];
      else if( isset($menu_item->query['task']) ) $query_view = $menu_item->query['task']; 

   // echo ":444444444444444444444:".$Itemid; 
   // print_r( $menu_item ); 
    // echo ":1111111111111111111112222222:".$view."::".$task."::".$view."::".$query_view."::".$catid."::";
     //print_r( $menu_item->alias ); 

   //echo ":1111111111111111111112222222:".is_menu_item_rem($Itemid);
// var_dump($view);
// var_dump($query_view);
      //if in some menu item but not in child
      if (isset( $view ) && $view == $query_view  
          &&  is_menu_item_cck($Itemid) )  
      {
          $url_alias = trim( $menu->alias ) ;
      }

      return $url_alias ;
  }

}

if (!function_exists('is_menu_item_cck')) {
  function is_menu_item_cck($Itemid ) {
      global $db,$task  ;
      $db = new os_cckDb();
      $app = JFactory::getApplication();

      $menu = new JTableMenu($db->_db);
      $menu->load($Itemid);
      $params = new JRegistry;
      if($menu->params){
          $params->loadString($menu->params);
      }
      $menu_item = $app->getMenu()->getItem($Itemid);
      $query_view = "";
      if( isset($menu_item->query['view']) ) $query_view = $menu_item->query['view'];
      else if( isset($menu_item->query['task']) ) $query_view = $menu_item->query['task']; 

         // echo ":111111111111101:";
         // var_dump($query_view); 
         // echo ":111111111111102:";
         // var_dump($Itemid); 

      // $single_category = $params->get('single_category') ;
      // $catid = $app->input->getInt('catid', null);
      // $house_id = $params->get('house');
      // $id = $app->input->getInt('id', null);
//echo ":11111111111111111:".$query_view.":111111111111:".$task;
// echo ":11111111111111111:".$single_category.":111111111111:".$catid;
      //check:
      //- this some menu item 
      // - not some child task for that menu item 
      // var_dump($query_view);

      if (isset( $query_view ) && ( 
          ( $query_view == 'cck_layout' && $task == $query_view ) ) )  {

//echo ":111111111111103:";
                        return true ;
      }

      return false ;
  }

}

if(!function_exists('cck_lang_text')){
  function cck_lang_text($const){
    if(defined('_JEXEC')){
      return JText::_($const);
    }else{
      return __($const);
    }

  }
}

if(!function_exists('cck_is_site')){
  function cck_is_site(){
    global $app, $doc;
    if (version_compare(JVERSION, "4.0.0", "ge")) {
      if ($app->isClient('site') && $doc->getType() == 'html'){
        $is_site = true;
      }else{
        $is_site = false;
      }
    }else{
      if ($app->isSite() && $doc->getType() == 'html'){
        $is_site = true;
      }else{
        $is_site = false;
      }
    }
    return $is_site;
  }
}

if(!function_exists('replace_custom_code_field')){
  function replace_custom_code_field($layout_html, $layout, $layout_params){
    // $custom_class = get_field_custom_class($field, $layout);
    // $offset_animation = get_field_offset_animation($field, $layout);
    // $layout_params['field_styling'] = $field_styling;
    // $layout_params['custom_class'] = $custom_class;
    
    //start render custom code
    if(isset($layout_params['custom_fields']) && 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);

            }
          }
          // $dispatcher->trigger('onContentPrepare', array('com_os_cck', &$plug_row, &$plug_params, 0));
          // $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'];
          $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_replace("{|this_entity_filesfolder|}", JURI::root() . '/components/com_os_cck/files/entity_files_'.$layout->fk_eid.'/', $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
          $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_replace("{|cck_images_folder|}", JURI::root() . 'images/os-cck/', $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
          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);
          }
        }
      }
    }

    return $layout_html;
  }
}

if(!function_exists('cckUpdateOrderStatus')){
  function cckUpdateOrderStatus($orderId, $order_status, $comment = '', $option = 'com_os_cck', $data_array = array()){
      global $db, $option,$app, $os_cck_state, $entityFieldLists;
      $db = new os_cckDb();
      
      $query = "SELECT * FROM #__os_cck_orders WHERE id = ".$orderId."";
        $db->setQuery($query);
        $old_order = $db->loadObjectList();

        $request_instance = new os_cckEntityInstance($db->_db);
        $request_instance->load($old_order[0]->fk_request_id);
        
        $request_layout = new os_cckLayout($db->_db);
        $request_layout->load($request_instance->fk_lid);
        
        $request_layout_mail = unserialize($request_layout->mail);
        $request_layout_params = unserialize($request_layout->params);
        $layout_html = urldecode($request_layout->getLayoutHtml('3'));
        $cartInstIds = array();

        //start old code - where we can have ONE mail field in layout
        if(!isset($request_layout_params['mail_fields']) && strpos($layout_html,"{|f-cck_mail|}")){
            $app->enqueueMessage(cck_lang_text("Email send not work. Please create new email fieled in (Buy/Rent)_Request layout!!!"), 'warning');
        }  
        // end old code - where we can have ONE mail field in layout




    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ){

      $coupon_id = "";
      $price_fields_assoc = array() ;
      $parentIdsArr = array() ;
      $fields_for_mail_parent = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc,$orderId );
      $fields_for_mail_request = getInstanceFieldsData( $old_order[0]->fk_request_id );

      $mail_data = array(); 
      $mail_data['mail'] = $request_layout_mail;
      $mail_data['request_instance_fields_data'] = $fields_for_mail_request ; 
      $mail_data['mail_fields'] = $request_layout_params['mail_fields'] ;
      $mail_data['order_id'] = $orderId ;
      $mail_data['parent_instances_fields_data'] = $fields_for_mail_parent ;
      if( isset($coupon_id) && $coupon_id != ''){
        $mail_data['coupon_id'] = $coupon_id ;
        if( !isset($coupon) ){
          $coupon = new os_cckCoupons($db->_db);
          $coupon->load($coupon_id);
        } 
        $mail_data['coupon'] = $coupon ;
      } 

      $mail_data['mail_event'] = $order_status ;
      if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
          && isset($parent_instance_id) && $parent_instance_id != 0  )
            $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

      cckSendMailEvent($mail_data, $parentIdsArr, $request_instance );
    }



        $old_status = $old_order[0]->status;

        if(empty($data_array)){

          if($order_status == 'Completed'){
              $sql = "UPDATE #__os_cck_orders SET status = '".$order_status."', order_date = '".get_curent_site_time()."', number_of_downloads=0 WHERE id = ".$orderId."";

              if($old_order[0]->instance_type == 'Rent'){
                  $request = new os_cckEntityInstance($db->_db);
                  $request->load($old_order[0]->fk_request_id);
                  if($request->eiid){
                      AdminRent_request::accept_rent_requests('com_os_cck', array($old_order[0]->fk_request_id), 0);
                  }
  //                $request_id = $old_order[0]->fk_request_id;
  //
  ////                var_dump($request); exit;
  //                $request->accept();
              }elseif($old_order[0]->instance_type == 'Buy'){
                  $request = new os_cckEntityInstance($db->_db);
                  $request->load($old_order[0]->fk_request_id);
                  if($request->eiid){
                      AdminBuy_request::accept_buying_requests('com_os_cck', array($old_order[0]->fk_request_id), 0);
                  }
              }

          }else{
              $sql = "UPDATE #__os_cck_orders SET status = '".$order_status."', order_date = NOW() WHERE id = ".$orderId."";
          }
          if(!isset($os_cck_state->data) ){
              echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
              return ;
          }
          //var_dump($sql); exit;
          $db->setQuery($sql);
          $db->execute();
          $sql = "SELECT * FROM #__os_cck_orders WHERE id = ".$orderId."";
          $db->setQuery($sql);
          $order = $db->loadobjectList();
          $order = $order['0'];
          $order->txn_type = 'Order status changed (set:'.$order_status.') by the administrator';
  //        var_dump($order->quantity);
          $user = JFactory::getUser();
          $comment = "Comment administrator " . $user->username . ": " . $comment;
          $sql = "INSERT INTO #__os_cck_orders_details( fk_order_id, fk_user_id, fk_instance_id,
                                                                instance_title, user_email, user_name, status,
                                                                order_date,txn_type, txn_id, payer_id, payer_status,
                                                                payment_details, quantity, comment, row_data)
                          VALUES ('".$order->id."','".$order->fk_user_id."','". $order->fk_instance_id ."',
                                  '".$order->instance_title."','".$order->user_email."','".$order->user_name."','".$order->status."',
                                  '".get_curent_site_time()."','".$order->txn_type."','".$order->txn_id."',  '".$order->payer_id."',
                                  '".$order->payer_status."', ".$db->Quote($raw_data).", ".$db->Quote(($order->quantity) ? $order->quantity: 1).", ".$db->Quote($comment).", '')";
          $db->setQuery($sql);
  //        print_r($sql); exit;
          $db->execute();
        }else{

          $sql = "UPDATE #__os_cck_orders SET order_date = now(), status='" . $order_status . "',
                        payer_id='".$data_array['payer_id']."',
                        order_price='".$data_array['mc_gross']."',
                        order_currency='".$data_array['order_currency_code']."',
                        txn_id='".$data_array['txn_id']."',
                        txn_type='".$data_array['txn_type']."',
                        paid_price='".$data_array['mc_gross']."',
                        notreaded=1,
                        paid_currency='".$data_array['order_currency_code']."',
                        payer_status='".$data_array['payer_status']."' WHERE id = '".$orderId."'";
                $db->setQuery($sql);
                $db->execute();

                $sql = "INSERT INTO #__os_cck_orders_details( fk_order_id, fk_user_id, fk_instance_id,
                                                              instance_title, user_email, user_name, status,
                                                              order_date,txn_type, txn_id, payer_id, payer_status,
                                                              order_price, order_currency, payment_details, comment, row_data)
                        VALUES ('".$orderId."','".intval($data_array['userId'])."','". $data_array['instId'] ."',
                                '".$data_array['itemName']."','".$data_array['userEmail']."','".$data_array['userName']."','".$order_status."',
                                now(),'".$data_array['txn_type']."','".$data_array['txn_id']."',  '".$data_array['payer_id']."',
                                '".$data_array['payer_status']."',  '".$data_array['mc_gross']."', '".$data_array['order_currency_code']."',
                                ".$db->Quote($data_array['raw_data']).", '".$comment."', '')";
                $db->setQuery($sql);
                $db->execute();
        }
        
        $sql = "SELECT * FROM #__os_cck_orders_price WHERE fk_order_id=".$orderId;
        $db->setQuery($sql);
        $order_prices = $db->loadObjectList();
        
        foreach($order_prices as $order_price){
            if($order_price->quantity > 0){
                $sql = "SELECT quantity FROM #__os_cck_content_instances_price WHERE price_id=" . $order_price->fk_price_id;
                $db->setQuery($sql);
                $old_quantity = $db->loadResult();
                if($old_quantity > -1) {
                    if ($order_status == 'Completed') {
                        $quantity = $old_quantity - $order_price->quantity;
                    } elseif ($old_status != 'Completed') {
                        $quantity = $old_quantity;
                    } else {
                        $quantity = $old_quantity + $order_price->quantity;
                    }

                    $sql = "UPDATE #__os_cck_content_instances_price SET quantity = '$quantity' WHERE price_id=" . $order_price->fk_price_id;
                    $db->setQuery($sql);
                    $db->execute();
                }
            }
        }
      
  }
}

if(!function_exists('get_custom_owner_mail_field_option')){
    function get_custom_owner_mail_field_option($field_list){
        $option_list = array();
        foreach($field_list as $field){
            if($field->field_type == 'text_textfield'){
                $option_list[] = JHTML::_('select.option',$field->fid,$field->field_name);
            }
        }
        return $option_list;
    }
}

if(!function_exists('removeGalleryImageCck')){
  function removeGalleryImageCck(){
      $fid = protectInjectionWithoutQuote('fid', 0, 'INT');
      $file = protectInjectionWithoutQuote('image_name', '', 'STRING');

      $img_path = JPATH_SITE . '/images/com_os_cck'.$fid.'/original/';
      $thmb_path = JPATH_SITE . '/images/com_os_cck'.$fid.'/thumbnail/';

      if(file_exists($img_path . $file)){
        unlink($img_path . $file);
      }
      if(file_exists($thmb_path . $file)){
        unlink($thmb_path . $file);
      }

      return json_encode(array('success' => true));
  }
}

if(!function_exists('strftime_cck')){
  function strftime_cck(string $format, $timestamp = null, string $locale = null)
  {
    // var_dump($format);
    // var_dump($timestamp);
    // var_dump($locale);
    if (null === $timestamp) {
      $timestamp = new \DateTime;
    }
    elseif (is_numeric($timestamp)) {
      $timestamp = date_create('@' . $timestamp);

      if ($timestamp) {
        $timestamp->setTimezone(new \DateTimezone(date_default_timezone_get()));
      }
    }
    elseif (is_string($timestamp)) {
      $timestamp = date_create($timestamp);
    }

    if (!($timestamp instanceof \DateTimeInterface)) {
      throw new \InvalidArgumentException('$timestamp argument is neither a valid UNIX timestamp, a valid date-time string or a DateTime object.');
    }

    $locale = substr((string) $locale, 0, 5);

    $intl_formats = [
      'D' => 'EEE',	// An abbreviated textual representation of the day	Sun through Sat
      'l' => 'EEEE',	// A full textual representation of the day	Sunday through Saturday
      
      'M' => 'MMM',	// Abbreviated month name, based on the locale	Jan through Dec
      'F' => 'MMMM',	// Full month name, based on the locale	January through December
      
    ];

    $intl_formatter = function (\DateTimeInterface $timestamp, string $format) use ($intl_formats, $locale) {
      $tz = $timestamp->getTimezone();
      $date_type = \IntlDateFormatter::FULL;
      $time_type = \IntlDateFormatter::FULL;
      $pattern = '';

      // %c = Preferred date and time stamp based on locale
      // Example: Tue Feb 5 00:45:10 2009 for February 5, 2009 at 12:45:10 AM
      if ($format == '%c') {
        $date_type = \IntlDateFormatter::LONG;
        $time_type = \IntlDateFormatter::SHORT;
      }
      // %x = Preferred date representation based on locale, without the time
      // Example: 02/05/09 for February 5, 2009
      elseif ($format == '%x') {
        $date_type = \IntlDateFormatter::SHORT;
        $time_type = \IntlDateFormatter::NONE;
      }
      // Localized time format
      elseif ($format == '%X') {
        $date_type = \IntlDateFormatter::NONE;
        $time_type = \IntlDateFormatter::MEDIUM;
      }
      else {
        $pattern = $intl_formats[$format];
      }

      return (new \IntlDateFormatter($locale, $date_type, $time_type, $tz, null, $pattern))->format($timestamp);
    };

    // Same order as https://www.php.net/manual/en/function.strftime.php
    $translation_table = [
      // Day
      'D' => $intl_formatter,
      'l' => $intl_formatter,
      
      'd' => 'd',
      'j' => function ($timestamp) {
        return sprintf('% 2u', $timestamp->format('j'));
      },
      'z' => function ($timestamp) {
        // Day number in year, 001 to 366
        return sprintf('%03d', $timestamp->format('z')+1);
      },
      'N' => 'N',
      'w' => 'w',

      // Week
      // 'W' => function ($timestamp) {
      //   // Number of weeks between date and first Sunday of year
      //   $day = new \DateTime(sprintf('%d-01 Sunday', $timestamp->format('Y')));
      //   return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7);
      // },
      'W' => 'W',
      // '%W' => function ($timestamp) {
      //   // Number of weeks between date and first Monday of year
      //   $day = new \DateTime(sprintf('%d-01 Monday', $timestamp->format('Y')));
      //   return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7);
      // },

      // Month
      'M' => $intl_formatter,
      'F' => $intl_formatter,
      // '%h' => $intl_formatter,
      'm' => 'm',
      'n' => 'n',
      't' => 't',

      // Year
      // '%C' => function ($timestamp) {
      //   // Century (-1): 19 for 20th century
      //   return floor($timestamp->format('Y') / 100);
      // },
      '%g' => function ($timestamp) {
        return substr($timestamp->format('o'), -2);
      },
      'o' => 'o',
      'y' => 'y',
      'Y' => 'Y',
      'L' => 'L',
      'X' => 'X',
      'x' => 'x',

      // Time
      'H' => 'H',
      // '%k' => function ($timestamp) {
      //   return sprintf('% 2u', $timestamp->format('G'));
      // },
      'h' => 'h',
      'g' => function ($timestamp) {
        return sprintf('% 2u', $timestamp->format('g'));
      },
      'i' => 'i',
      'A' => 'A', // AM PM (this is reversed on purpose!)
      'a' => 'a', // am pm
      // '%r' => 'h:i:s A', // %I:%M:%S %p
      // '%R' => 'H:i', // %H:%M
      's' => 's',
      'u' => 'u',
      'v' => 'v',
      // '%T' => 'H:i:s', // %H:%M:%S
      // '%X' => $intl_formatter, // Preferred time representation based on locale, without the date

      // Timezone
      'O' => 'O',
      'T' => 'T',

      // Time and Date Stamps
      // '%c' => $intl_formatter,
      // '%D' => 'm/d/Y',
      // '%F' => 'Y-m-d',
      'U' => 'U',
      // '%x' => $intl_formatter,
    ];

    $out = preg_replace_callback('/([a-zA-Z])/', function ($match) use ($translation_table, $timestamp) {
      // var_dump($translation_table);
      if ($match[1] == '%n') {
        return "\n";
      }
      elseif ($match[1] == '%t') {
        return "\t";
      }

      if (!isset($translation_table[$match[1]])) {
        throw new \InvalidArgumentException(sprintf('Format "%s" is unknown in time format', $match[1]));
      }

      $replace = $translation_table[$match[1]];

      if (is_string($replace)) {
        return $timestamp->format($replace);
      }
      else {
        return $replace($timestamp, $match[1]);
      }
    }, $format);

    $out = str_replace('%%', '%', $out);
    return $out;
  }
}

if (!function_exists('get_group_for_layout_cache_access_cck')) {
  function get_group_for_layout_cache_access_cck(){
    global $acl;
    $group_children_tree = array();
    if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
        $options = JHelperUserGroups::getInstance()->getAll();
    } else {
        include_once(JPATH_SITE . '/administrator/components/com_users/models/groups.php');


        if (version_compare(JVERSION, "3.0.0", "ge")) {
            //echo '111111111111'; exit;
            //$model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
            //$model = JModelLegacy::getInstance('GroupsModel', 'UsersModel', array('ignore_request' => true));
            $model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
        } else {
            $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
        }
        //var_dump($model); exit;
        $options = $model->getItems();
    }
        //var_dump($options); exit;

//    var_dump($options); exit;
    foreach ($g = $options as $k => $v) { // $g contains basic usergroup items info
        $group_title = '.';
        if($k == 1){
            $group_title .= '-' . cck_lang_text("COM_OS_CCK_SELECT_OPT_ALL_USERS");
        }else{
            $group_title .= '-' . $g[$k]->title;
        }
//        for ($i = 1; $i <= $g[$k]->level; $i++) $group_title .= '-';
//        $group_title .= '-' . $g[$k]->title;
        $group_children_tree[0][] = JHTML::_('select.option',$g[$k]->id, $group_title);
        //$group_children_tree[] = JHTML::_('select.option',$g[$k]->id, $group_title);
    }
    

    return $group_children_tree;
  }
}

if (!function_exists('checkLayoutCacheAccess_cck')) {
  function checkLayoutCacheAccess_cck() {
      global $cck_entity_configuration, $db, $user, $moduleId, $Itemid;
      $db = new os_cckDb();
      
      $lid = protectInjectionWithoutQuote('lid', 0, 'INT');
      
      if($lid == 0){
          $moduleId = (($moduleId == 0 || empty($moduleId)) && isset($_REQUEST['moduleId'])) ? intval($_REQUEST['moduleId']) : $moduleId;
      
            if(!$moduleId){
              $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval(protectInjectionWithoutQuote('Itemid', 0, 'INT')) : $Itemid;
              // Params(cck component menu)
              $menu = new JTableMenu($db->_db);
              $menu->load($Itemid);
              $params = new JRegistry;
              if($menu->params){
                $params->loadString($menu->params);
              }
            }else{
              $mod_row = JTable::getInstance ( 'Module', 'JTable' );//load module tables and params
              if (! $mod_row->load ( $moduleId )) {

                throw new Exception($mod_row->getError (), 500);
              }
              //module params
              if (version_compare(JVERSION, '3.0', 'ge')) {
                $params = new JRegistry;
                $params->loadString($mod_row->params);
              } else {
                $params = new JRegistry($mod_row->params);
              }//end
              if($params->get('ItemId', '') != ''){
                $Itemid = $params->get('ItemId', '');
              }
            }
            
            $lid = $params->get('layout');
      }
      
      $layout = new os_cckLayout($db->_db);
      $layout->load($lid);
      if($layout->params){
        $params = unserialize($layout->params);
      }else{
        $params = array();
      }  

      if( !isset( $layout->params ) ){
          return false;
      }
      $params = unserialize($layout->params);
      
      if(!isset($params['views']['cache_access'])){
          return true;
      }
      
      $access_group = $params['views']['cache_access'];
      if(!is_array($access_group) || empty($access_group)){
          return true;
      }
      foreach ($access_group as $group){
          if($group == 1){
              return true;
          }
          foreach($user->groups as $usergroup){
            if($usergroup == $group){
                return true;
            }
          }
          
      }
      return false;
      
  }
}

if(!function_exists("auto_include")){
    function auto_include($path_to_files)
    {
        //for absolut path
        $component_path = JPath::clean( $path_to_files);
        if (is_dir($component_path) && ($files_in_folder = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
            foreach ($files_in_folder as $i => $file) {
                require_once($file);
            }
        }else{
            //for relative path
            $component_path = JPath::clean(JPATH_SITE . $path_to_files);
            if (is_dir($component_path) && ($files_in_folder = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
                foreach ($files_in_folder as $i => $file) {
                    require_once($file);
                }
            }            
        }
    }
}

if(!function_exists("auto_include_with_global")){
    function auto_include_with_global($path_to_files)
    {
        $component_path = JPath::clean(JPATH_SITE . $path_to_files);
        if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
            foreach ($component_layouts as $i => $file) {
                require_once($file);
                $file_name = substr($file, strrpos($file, '/')+1);
                $file_name = explode('.', $file_name);
                $pos = strripos($file_name[1], '_');
                $entity_id = substr($file_name[1], $pos+1);
                
                if($entity_id != '' && isset(${"cck_entity_configuration_$entity_id"})){
                    $GLOBALS['cck_entity_configuration'][$entity_id] = ${"cck_entity_configuration_$entity_id"};
                }
            }
        }
    }
}

if(!function_exists("getDateFields")){
    function getDateFields($eid)
    {
        global $db;
        
        $db = new os_cckDb();
        
        $query = "SELECT fid, field_name FROM #__os_cck_entity_field WHERE fk_eid=$eid AND field_type='datetime_popup'";
        $db->setQuery($query);
        $dateFields = $db->loadObjectList();
        
        return $dateFields;
        
    }
}

if(!function_exists("get_next_available_date")){
    function get_next_available_date($date, $not_available_times_in_day_from, $input_format)
    {
//        var_dump($not_available_times_in_day_from);
//        var_dump(date($input_format, strtotime($date)));
//        if(!$temp_date){
//            $temp_date = date($input_format, strtotime($date));
//        }
        $day_week = date('N', strtotime($date));
//        var_dump($not_available_times_in_day_from[$day_week-1]);
//        var_dump(isset($not_available_times_in_day_from[$day_week-1]) && is_array($not_available_times_in_day_from[$day_week-1]) && $not_available_times_in_day_from[$day_week-1][0][0] == '00:00' && $not_available_times_in_day_from[$day_week-1][0][1] == '23:59' );
        if(isset($not_available_times_in_day_from[$day_week-1]) && is_array($not_available_times_in_day_from[$day_week-1]) && $not_available_times_in_day_from[$day_week-1][0][0] == '00:00' && $not_available_times_in_day_from[$day_week-1][0][1] == '23:59' ){
             $date = get_next_available_date(date($input_format, strtotime($date . ' +1 day')), $not_available_times_in_day_from, $input_format);
        }
//        var_dump($date); 
//        else{
//            var_dump($temp_date);
//            
//        }
        
        return $date;
    }
}

    // code for mail send - where we can have many mails fields in layout
    // $mail_data = array(); 
    // $mail_data['mail'] = $mail ; -- mail fields settings, for all mail fields in layout
    // $mail_data['request_instance_fields_data'] - data for replace placeholders with real data from request instance; 
    // $mail_data['mail_fields'] = $layout_params['mail_fields'] ; - list of all "mail fields names"
    // $mail_data['order_id'] - [order_id - if exist
    // $mail_data['parent_instances_fields_data']  - data for replace placeholders with real data from Parent instance (requestED)
    // if( isset($coupon_id) && $coupon_id != '') $mail_data['coupon_id'] = $coupon_id ; - if coupon exist - set here it ID here
    // $mail_data['mail_event'] - array event when we send email array("create", ...);  
    // $parentIdsArr - is array with parent_ids for $requested_instance, array with some product(s) 
    //   - which we whant buy(rent, request, review), empty - can be for Request
    // if( !isset($parentIdsArr) && $parent_instance_id != 0 ) $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;
    // run:
    //  if( strpos($layout_html,"{|f-cck_mail_") ) - check in layout exist mail field 
    //     cckSendMailEvent($mail_data, $parentIdsArr, $request_instance )
    // $requested_instance - rent_request, buy_request, review, request
    
if(!function_exists("cckSendMailEvent") ){
    function cckSendMailEvent($mail_data, $parentIdsArr, $request_instance )
    {
      global $db,$entityFieldLists ;

      //new code - where we can have many mails fields
      if(isset($mail_data['request_instance_fields_data']) && !empty($mail_data['request_instance_fields_data']) ){

          foreach($mail_data['mail_fields'] as $mail_field){

              // if(!in_array('create', $mail_data['mail'][$mail_field.'_events'])) continue;
              if( !isset($mail_data['mail'][$mail_field.'_events']) 
                || !in_array($mail_data['mail_event'], $mail_data['mail'][$mail_field.'_events']) ) continue;

              //check user group access. '_access' == '1' - in free version or we not use this field - so ACCESS == true
              if(isset($mail_data['mail'][$mail_field.'_access'])
                  && $mail_data['mail'][$mail_field.'_access'] != '1'){
                $user = JFactory::getUser();
                if(!checkAccess_cck($mail_data['mail'][$mail_field.'_access'], $user->groups, $request_instance->fk_eid, 'fields')){
                  continue;
                }
              }   

              //check PHP access
              // $php_if = isset($mail_data['mail'][$mail_field.'_php_show']) ? $mail_data['mail'][$mail_field.'_php_show'] : '';
              // $php_result = true;
              // if($php_if != ''){
              //   $php_result = eval($php_if);
              //   if(!$php_result) contunue ;      
              // }
           
              //1. check send email to waren owners or not, and as in CART can be many ware owners,
              //if we not send to many owners or owners 1 - send emails exactly as other email
              //if we send to many owners - so to every owners we send only about their waren
              $is_send_small_email_to_many_owners = false ; //this only for Cart, and many waren in Cart
              $is_send_big_email = false ; //this only for Cart, and many waren in Cart
              $big_email_recipients = array(); //if owner 1, or when we no need devide email for evey ware
              $parent_owners_email_recipients = array(); //if owners many - and we send email to evary, about they waren
              if(isset($mail_data['mail'][$mail_field.'_recipients_type'])){

                  foreach($mail_data['mail'][$mail_field.'_recipients_type'] as $recipient_type){

                      if($recipient_type == 'custom'){
                          $big_email_recipients = array_merge($big_email_recipients, explode(",", $mail_data['mail'][$mail_field.'_recipient'] ) );
                      }

                      // elseif($recipient_type == 'owner' && isset($request_instance->fk_userid) && $request_instance->fk_userid != 0 ){
                      //    //need rebuild, 'buyer' == "owner" !!!!!!!!!
                      //    //owner of this instance - need for instace(as exemple when this instance change, 
                      //    //or when we want send confirm email) 
                      //    $inst_owner = JFactory::getUser($request_instance->fk_userid);

                      //    if(isset($inst_owner->email) && !empty($inst_owner->email) ) $big_email_recipients[] = $inst_owner->email;

                      // }
                      elseif( $recipient_type == 'parent_owner' 
                          && isset($parentIdsArr) && count($parentIdsArr) > 0 ) {

                          $tmp_cart_items = array();
                          foreach($parentIdsArr as $parent_eiid => $parent_eiid_value){
                           $tmp_cart_items[] = ' ei.eiid = "'.$parent_eiid.'"';
                          }

                          $tmp_cart_items_sql = implode(' OR ', $tmp_cart_items);

                           //owner of parent instance - when buy request or rent request to some other instance 
                          $query = "SELECT distinct u.email FROM #__users AS u "
                                  . " inner JOIN #__os_cck_entity_instance AS ei ON u.id = ei.fk_userid " 
                                  . " and ( " .$tmp_cart_items_sql. ")" ;
                          $db->setQuery($query);
                          $parent_owner_email = $db->loadColumn(); 
                          
                          if(isset($parent_owner_email) && !empty($parent_owner_email) && count($parent_owner_email) > 0 ) {

                              //owner of parent instance - when buy request or rent request to some other instance 
                              $query = "SELECT u.email,u.id,ei.eiid FROM #__users AS u "
                                  . " inner JOIN #__os_cck_entity_instance AS ei ON u.id = ei.fk_userid " 
                                  . " and ( " .$tmp_cart_items_sql. ")" ;
                              $db->setQuery($query);
                              $parent_owners_email_recipients = $db->loadObjectList("eiid"); 

                          } elseif(isset($parent_owner_email) && !empty($parent_owner_email) && count($parent_owner_email) ) { 
                              $big_email_recipients = array_merge($big_email_recipients, $parent_owner_email );
                          }
                      }elseif($recipient_type == 'owner' ){
                          //rebuilded, 'buyer' == "owner" !!!!!!!!!
                          //owner of this instance - need for instace(as exemple when this instance change, 
                          //or when we want send confirm email) 
                          $owner_type_mail = $mail_data['mail'][$mail_field.'_owner_recipient_type'];

                          if($owner_type_mail == 'profile'){
                              if(property_exists($request_instance, 'fk_user_id')){
                                  $owner_id = $request_instance->fk_user_id;
                              }else{
                                  $owner_id = 0;
                              }
                              if($owner_id > 0){
                                $buyer = JFactory::getUser($owner_id);
                                $owner_email = $buyer->email;
                              }else{
                                  $owner_email = '';
                              }

                          }elseif($owner_type_mail == 'field'){
                              $field = $mail_data['mail'][$mail_field.'_owner_field_mail'];
                              $field = $entityFieldLists[$request_instance->fk_eid][$field];
                              $value = $request_instance->getFieldValue($field);
                              if(isset($value[0]) && property_exists($value[0], 'data')){
                                  $owner_email = $value[0]->data;
                              }else{
                                  $owner_email = '';
                              }
                          }

                          if(isset($owner_email) && !empty($owner_email) ) $big_email_recipients[] = $owner_email;

                      }else{
                          $query = "SELECT us.email FROM #__user_usergroup_map as map "
                                  . " LEFT JOIN #__users as us ON us.id = map.user_id "
                                  . " WHERE block != 1 and map.group_id='$recipient_type' ";
                          $db->setQuery($query);
                          $user_emails = $db->loadColumn();

                          $big_email_recipients = array_merge($big_email_recipients, $user_emails );                              
                      }
                  }
              }
             
              $big_email_recipients = array_unique($big_email_recipients);
              $big_email_recipients_str = implode(',', $big_email_recipients);

              if( count($big_email_recipients) > 0 ) $is_send_big_email = true ;
              if( count($parent_owners_email_recipients) > 0 ) $is_send_small_email_to_many_owners = true ;

              if( $is_send_small_email_to_many_owners || $is_send_big_email ){

                  //small emails to all owners(to every owner about their waren) 
                  //or send big email (with all waren) to 1 owner, or send big email (with all waren) to other recipients 

                  //first: set Parents fields()
                  foreach($mail_data['parent_instances_fields_data'] as $cart_item)
                  {
                    foreach($cart_item as $cart_item_key=>$instance_field){
                      //there may be only 1 element in array (if 1 order in cart or if this some request for 1 item)
                      //$cart_item_key === eiid
                      $parentIdsArr[$cart_item_key]['mail_body'] = $mail_data['mail'][$mail_field.'_body'];

                      foreach($instance_field as $key=>$field){
                        $parentIdsArr[$cart_item_key]['mail_body'] = 
                          str_replace("{|".$key."|}", $field, $parentIdsArr[$cart_item_key]['mail_body']);
                      }
                    }
                  }

                  //second: set Request fields
                  //send to some instance which haven't parent => create $parentIdsArr
                  if(count($parentIdsArr) == 0 ) $parentIdsArr[0]['mail_body'] = $mail_data['mail'][$mail_field.'_body'];
                  
                  foreach($parentIdsArr as $key1=>$field1){
                      foreach($mail_data['request_instance_fields_data'] as $key2=>$field2){
                        
                        //if parent_instances_fields_data - empty:  
                        if( !isset( $parentIdsArr[$key1]['mail_body'] ) ) 
                          $parentIdsArr[$key1]['mail_body'] = $mail_data['mail'][$mail_field.'_body'];

                        // if( !isset($field2) ) $field2 = "";
                        if( stripos( $parentIdsArr[$key1]['mail_body'], "{|".$key2."|}" ) ) 
                          $parentIdsArr[$key1]['mail_body'] 
                            = str_replace("{|".$key2."|}", $field2, $parentIdsArr[$key1]['mail_body'] );
                      }
                  }

                  if(stripos($mail_data['mail'][$mail_field.'_body'], '{os_cck_coupon}') !== false){
                    
                    if(isset($mail_data['coupon_id']) && $mail_data['coupon_id'] != '' ){
                      foreach($parentIdsArr as $key1=>$field1){
                        $parent_instance = new os_cckEntityInstance($db->_db);
                        $parent_instance->load($key1);

                        $coupon_text = $mail_data['coupon']->name . ' - ' .$mail_data['coupon']->value ;
                        if($mail_data['coupon']->type == 'percent'){
                            $coupon_text .= '%';
                        }else{
                            $coupon_text .= calculatedCurrency($parent_instance, $mail_data['coupon']->value)[0];
                        }

                        $coupon_text .= ', '. cck_lang_text("COM_OS_CCK_COUPON_DISCOUNT").':'. $parentIdsArr[$key1]['coupon_discount'] . ', '. cck_lang_text("COM_OS_CCK_RESULT_PRICE").':'. $parentIdsArr[$key1]['result_price'];
                        
                        if($parentIdsArr[$key1]['coupon_discount'] == 0 ){ 
                            $parentIdsArr[$key1]['mail_body'] 
                                = str_replace("{os_cck_coupon}", '', $parentIdsArr[$key1]['mail_body'] );
                        } else{
                            $parentIdsArr[$key1]['mail_body'] 
                                = str_replace("{os_cck_coupon}", $coupon_text, $parentIdsArr[$key1]['mail_body'] );
                        }
                      }
                    }else{
                      foreach($parentIdsArr as $key1=>$field1){
                          $parentIdsArr[$key1]['mail_body']  
                              = str_replace("{os_cck_coupon}", '', $parentIdsArr[$key1]['mail_body'] );
                      }
                    }
                  }

                  if(stripos($mail_data['mail'][$mail_field.'_body'], '{os_cck_order_id}') !== false ){
                    // if( !isset($mail_data['order_id'])  ) $mail_data['order_id'] = "";
                    foreach($parentIdsArr as $key1=>$field1){
                      $parentIdsArr[$key1]['mail_body'] 
                          = str_replace("{os_cck_order_id}", $mail_data['order_id'], $parentIdsArr[$key1]['mail_body']);
                    }
                  }
                  
                  if(stripos($mail_data['mail'][$mail_field.'_body'], '{os_cck_order_status}') !== false){
                    $order_status_arr = array('Cancel','Chargeback','Completed','Pending','Refund');
                    $order_status = 'Pending' ;
                    if( in_array( $mail_data['mail_event'],$order_status_arr) ) $order_status = $mail_data['mail_event'] ; 
                    foreach($parentIdsArr as $key1=>$field1){
                      $parentIdsArr[$key1]['mail_body'] 
                        = str_replace("{os_cck_order_status}", $order_status, $parentIdsArr[$key1]['mail_body']);
                    }
                  }

                  $mail_body = "";
                  //send big email with all waren
                  if( $is_send_big_email ){
                    //create 1 big email with many waren
                    foreach($parentIdsArr as $key1=>$field1){
                        if($mail_body != "" ) $mail_body .= '<br>'.$parentIdsArr[$key1]['mail_body'] ;
                        else $mail_body .= $parentIdsArr[$key1]['mail_body'] ;
                    }
                    sendMailCck($mail_body, $mail_data['mail'][$mail_field.'_subject'],'',$big_email_recipients_str, $mail_data['mail'][$mail_field.'_encoding']);
                  }

                  //send small emails with one waren for every owner, buy waren with help cart
                  if( $is_send_small_email_to_many_owners ){
                    foreach($parent_owners_email_recipients as $key1=>$field1){
                      //send many emails
                      sendMailCck($parentIdsArr[$key1]['mail_body'], 
                        $mail_data['mail'][$mail_field.'_subject'],'',$parent_owners_email_recipients[$key1]->email, $mail_data['mail'][$mail_field.'_encoding']);     
                    }
                  }
              }
          }
      }
    }
}

//eiid - instance id - for which gethering data
//orderid - may exist for $layout_mail->type == 'buy_request_instance' || 'rent_request_instance' - so find it
if(!function_exists("getInstanceFieldsData") ){
  function getInstanceFieldsData($eiid, &$orderId = 0){
    global $entityFieldLists, $db;

    $fields_data = array();
    
    if( $orderId == 0 && intval($eiid) > 0 ){
      $query = "SELECT * FROM #__os_cck_orders WHERE fk_request_id = ".$eiid."";
      $db->setQuery($query);
      $order = $db->loadObjectList();
      if( count($order) > 0 ) $orderId = $order[0]->id ;
    }
 

    $instance = new os_cckEntityInstance($db->_db);
    $instance->load($eiid);
    foreach($entityFieldLists[$instance->fk_eid] as $field){
       $field_val = $instance->getFieldValue($field);
        if(stripos($field->field_type, 'pricefield') !== false) {
          if( count($field_val) > 0 ) $fields_data[$field->db_field_name] = calculatedCurrency($instance, $field_val[0]->price_value)[0];
        }

        if(isset($field_val[0])) $field_val = $field_val[0];

        if(isset($field_val->data))
        {
            $fields_data[$field->db_field_name] = $field_val->data;
        }elseif(!isset($fields_data[$field->db_field_name])){
            $fields_data[$field->db_field_name] = '';
        }

        if($field->field_type == 'imagefield'){
          if( empty($field_val->data) ) $fields_data[$field->db_field_name] = "" ;
          else $fields_data[$field->db_field_name] = '<img width="250px" src="'.JURI::root() . $field_val->data .'">';
        }

        if ($field->field_type == 'filefield') {
          if( empty($field_val->data) ) $fields_data[$field->db_field_name] = "" ;
          else $fields_data[$field->db_field_name] = '<a href="'.JURI::root().
            'index.php?option=com_os_cck&task=fileDownload&fid='.$field_val->fid.'&field='.$field->fid.'&eiid='.$eiid.'" > download </a>';
        }
 
        // if($field->field_type == 'datetime_popup'){

        //     if(isset($instance->_layout_params[$field->db_field_name.'_field_type']) && $instance->_layout_params[$field->db_field_name.'_field_type'] == 'rent_from'){
        //       if($input->get('fi_'.$field->db_field_name, "")){
        //         $fields_data[$field->db_field_name] = $input->get('fi_'.$field->db_field_name, "");
        //       }
        //     }
        //     if(isset($instance->_layout_params[$field->db_field_name.'_field_type']) && $instance->_layout_params[$field->db_field_name.'_field_type'] == 'rent_to'){
        //       if($input->get('fi_'.$field->db_field_name, "")){
        //         $fields_data[$field->db_field_name] = $input->get('fi_'.$field->db_field_name, "");
        //       }
        //     }

        // }

        if($field->field_type == 'categoryfield'){
            $fields_data[$field->db_field_name] = $field_val->title;
        }
      }

      return $fields_data;  
    }
}
//
if(!function_exists("getParentsFieldsData") ){
  function getParentsFieldsData( &$coupon_id="", &$parentIdsArr = array(), &$price_fields_assoc = array(), $orderId = 0 ){
    global $entityFieldLists, $db;

    if( $orderId > 0 && count($price_fields_assoc) == 0 ){
      $query = "SELECT * FROM #__os_cck_orders_price WHERE fk_order_id=$orderId";
      $db->setQuery($query);
      $price_fields = $db->loadObjectList();

      $temp_price_count = 0;
      foreach($price_fields as $price){

        if($price && property_exists($price, 'fk_fid') && $price->fk_fid != 0) {
          //in price_fields - can be coupon item, by pass it
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid] = $price;
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->value = $price->fk_price_id;
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->fid = $price->fk_fid;
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->calculated = 1;
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->quantity = $price->quantity;
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->fid = $price->fk_fid;

          $entityInstance = new os_cckEntityInstance($db->_db);
          $entityInstance->load( $price->fk_eiid );
          $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->lid = $entityInstance->fk_lid;
          $temp_price_count++;
        } else {
          //coupon
          $coupon_id = $price->fk_price_id;
        }
      }
    }

    if( $orderId > 0 ){
      $query = "SELECT сart_item, fk_eiid as eiid FROM #__os_cck_orders_price WHERE fk_order_id=$orderId GROUP BY сart_item";
      $db->setQuery($query);
      $parentIdsArrTmp = $db->loadAssocList("eiid");
    }

    if( isset($parentIdsArrTmp) && count($parentIdsArrTmp) > 0 && isset($parentIdsArr) && count($parentIdsArr) > 0 ) {
        $parentIdsArr = array_merge($parentIdsArr, $parentIdsArrTmp) ;  
    }elseif(isset($parentIdsArrTmp) && count($parentIdsArrTmp) > 0 && isset($parentIdsArr) && count($parentIdsArr) == 0 ){
        $parentIdsArr = $parentIdsArrTmp ;  
    }

    $cart_item = 0 ; //if $parentIdsArr input param for this function, so $parent['сart_item'] - not defined
    $fields_for_mail_parent = array();
    foreach($parentIdsArr as $parent){
      $parent_eiid = $parent['eiid'];
      if( isset($parent['сart_item']) ) $cart_item = $parent['сart_item'];

      if( isset($price_fields_assoc)  && count($price_fields_assoc) > 0 ){
        $field_tmp = $price_fields_assoc[$cart_item][$parent_eiid];
        $calculated_price = getCalculatedPrice($field_tmp, $parent_eiid, 51, $coupon_id);
       
        $parentIdsArr[$parent_eiid]['price_without_coupon'] = $calculated_price['price_without_coupon'];
        $parentIdsArr[$parent_eiid]['coupon_discount'] = $calculated_price['coupon_discount'];
        $parentIdsArr[$parent_eiid]['result_price'] =  $calculated_price['calculated_price'];
      }
      $parent_instance_mail = new os_cckEntityInstance($db->_db);
      $parent_instance_mail->load($parent_eiid);

        foreach($entityFieldLists[$parent_instance_mail->fk_eid] as $field){

          $field_val = $parent_instance_mail->getFieldValue($field);

          if(stripos($field->field_type, 'pricefield') !== false) {
            if (isset($price_fields_assoc[$cart_item][$parent_eiid][$field->fid])) {
               foreach ($field_val as $val) {

                   if ($val->price_id == $price_fields_assoc[$cart_item][$parent_eiid][$field->fid]->value) {

                       if($val->price_value == $val->price_name) {
                           $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = 
                            calculatedCurrency($parent_instance_mail, $val->price_value)[0];

                           if($price_fields_assoc[$cart_item][$parent_eiid][$field->fid]->quantity > 1){
                               $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] .= ' x ' . $price_fields_assoc[$cart_item][$parent_eiid][$field->fid]->quantity;
                           }
                       }else{

                           $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = $val->price_name . ' ' . calculatedCurrency($parent_instance_mail, $val->price_value)[0];
                       }
                   }
               }

            }else{
               if(isset($field_val[0])){
                   $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = calculatedCurrency($parent_instance_mail, $field_val[0]->price_value)[0];
               }
            }
          }

          if(isset($field_val[0])) $field_val = $field_val[0];

          if(isset($field_val->data))
          {
            $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = $field_val->data;
          }elseif(!isset($fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name])){
             $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = '';
          }
          if($field->field_type == 'imagefield'){
            if( empty($field_val->data) ) $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = "" ;
            else $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] 
              = '<img width="250px" src="'.JURI::root() . $field_val->data .'">';
          }
        
          if ($field->field_type == 'filefield') {
            if( empty($field_val->data) ) $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = "" ;
            else $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] 
               = '<a href="'.JURI::root().'index.php?option=com_os_cck&task=fileDownload&fid='.
                $field_val->fid.'&field='.$field->fid.'&eiid='.$eiid.'" > download </a>';
          }          

          if($field->field_type == 'datetime_popup'){

            // if(isset($instance->_layout_params[$field->db_field_name.'_field_type']) && $instance->_layout_params[$field->db_field_name.'_field_type'] == 'rent_from'){
            //   if($input->get('fi_'.$field->db_field_name, "")){
            //    $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = $input->get('fi_'.$field->db_field_name, "");
            //   }
            // }
            // if(isset($instance->_layout_params[$field->db_field_name.'_field_type']) && $instance->_layout_params[$field->db_field_name.'_field_type'] == 'rent_to'){
            //   if($input->get('fi_'.$field->db_field_name, "")){
            //    $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = $input->get('fi_'.$field->db_field_name, "");
            //   }
            // }

          }

          if($field->field_type == 'categoryfield'){
             $fields_for_mail_parent[$cart_item][$parent_eiid][$field->db_field_name] = $field_val->title;
          }
        }

        //if $parentIdsArr input param for this function, so $parent['сart_item'] - not defined
        if( !isset($parent['сart_item']) ) $cart_item++; 
      }


      return $fields_for_mail_parent;  
    }
}
