<?php
/**
* @package OrdaSoft Joomla 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 Joomla Content Construction Kit
*/

defined('_JEXEC') or die;
 
includeStylesCCK("components/com_os_cck/assets/css/front_end_style.css");

$rand = rand();
if(isset($params) && $params->get('show_type','')){
  $show_type = $params->get('show_type');
}elseif(isset($layout_params['show_type'])){
  $show_type = $layout_params['show_type'];
}else{
  $show_type = 1;
}

?>
<div class="cck-body">
  <script  type="text/javascript" >
    var checkExpr = [];
  </script>
  <?php
  $hidden = '';

  if(!$layout) {
    echo "</div>"; //close <div class="cck-body">
    return;
  }

  if(isset($layout_params['views']['show_layout_title']) && $layout_params['views']['show_layout_title'])
  {
    echo "<h3>";
      echo $layout_params['views']['layout_title'];
    echo "</h3>";
  }

  $fields_list = $layout->field_list;
  $layout_type = $layout->type;
  $unique_form_id = $layout_type.'_Form_'.$layout->parent_eiid.$moduleId.rand();
  $field_from_params = $layout_params['fields'];
  $layout_html = urldecode($layout->layout_html);

  //add child selects fields to layout (for dependences fields)
  $addChildSelectToLayout = addChildSelectToLayout($fields_list, $entityInstance, $layout_params, $layout_html, $layout);
  $layout_html = $addChildSelectToLayout['layout_html'];

  //remove only after addChildSelectToLayout !!!!!!
  $layout_html = cut_params($layout_html);
  $layout_html = remove_admin_classes($layout_html);
  $layout_html = str_replace('data-label-styling', 'style',  $layout_html);

  $layout_params = $addChildSelectToLayout['layout_params'];
  $parent = $addChildSelectToLayout['select_parent'];
  $layout->params = serialize($layout_params);
  //add child selects to layout
  
  $available_times_in_day = array();
  $available_times_in_day[0] = (isset($layout_params['views']['available_times_1'])) ? $layout_params['views']['available_times_1'] : '';
  $available_times_in_day[1] = (isset($layout_params['views']['available_times_2'])) ? $layout_params['views']['available_times_2'] : '';
  $available_times_in_day[2] = (isset($layout_params['views']['available_times_3'])) ? $layout_params['views']['available_times_3'] : '';
  $available_times_in_day[3] = (isset($layout_params['views']['available_times_4'])) ? $layout_params['views']['available_times_4'] : '';
  $available_times_in_day[4] = (isset($layout_params['views']['available_times_5'])) ? $layout_params['views']['available_times_5'] : '';
  $available_times_in_day[5] = (isset($layout_params['views']['available_times_6'])) ? $layout_params['views']['available_times_6'] : '';
  $available_times_in_day[6] = (isset($layout_params['views']['available_times_7'])) ? $layout_params['views']['available_times_7'] : '';
  

  $step_time = (isset($layout_params['views']['step_time'])) ? $layout_params['views']['step_time'] : 15;
  
  $not_available_times_in_day_from = not_available_times_in_day_cck_from($available_times_in_day,$step_time);
  $not_available_times_in_day_to = not_available_times_in_day_cck_to($available_times_in_day,$step_time);
  if($show_type == 3){
    $Itemid  = protectInjectionWithoutQuote('Itemid');
    // if(isset($layout->fk_eid)){
    //   $link_eiid = "&eiid=$layout->parent_eiid";
    // }
    // $link = JRoute::_(JURI::root()."index.php?option=com_os_cck&task=show_request_layout$link_eiid&lid=".$layout->lid."&Itemid=$Itemid");
    $div_styling = isset($button_style['div_styling']) ? $button_style['div_styling'] : ''; 
     $field_styling = isset($button_style['field_styling']) ? $button_style['field_styling'] : '';
     $custom_class = isset($button_style['custom_class']) ? $button_style['custom_class'] : '';
     $offset_animation = isset($button_style['offset_animation']) ? $button_style['offset_animation'] : '';
    ?>
  <div <?php echo $div_styling; ?>>
    <!--<a <?php echo $button_style['field_styling'];?> class="button <?php echo $button_style['custom_class'];?>" <?php echo $button_style['offset_animation']; ?> href="<?php echo $link ?>">
      <?php echo ($layout_params['button_name'])?$layout_params['button_name'] : cck_lang_text('COM_OS_CCK_BUTTON_SHOW_FORM_RENT_REQUEST'); ?>
    </a>-->
      <form name="show_request_layout_<?php echo $rand; ?>" id="show_request_layout_<?php echo $rand; ?>" method="post" 
        action="<?php echo JRoute::_('index.php'); ?>" enctype="multipart/form-data" >
        <input type="hidden" name="option" value="com_os_cck">   
        <input type="hidden" name="task" value="show_request_layout">
        <input type="hidden" name="eiid" value="<?php echo $layout->parent_eiid; ?>">
        <input type="hidden" name="lid" value="<?php echo $layout->lid; ?>">
        <input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>">
        <input type="hidden" name="price_fields" value="">
        <input type="button" class="button btn-info <?php echo $custom_class;?>" <?php echo $offset_animation; ?> <?php echo $field_styling;?> onclick="javascript:submit_show_request_layout<?php echo $unique_form_id; ?>('show_request_layout_<?php echo $rand; ?>')" value="<?php echo ($layout_params['button_name'])?$layout_params['button_name'] : cck_lang_text('COM_OS_CCK_BUTTON_SHOW_FORM_RENT_REQUEST'); ?>">
    </form>
  </div>
  <script type="text/javascript">
        function submit_show_request_layout<?php echo $unique_form_id; ?>(form_name){
            //var form = document.forms.form_name;
            var form = jQuerOs('[name='+form_name+']');
            //document.forms
            //console.log('1111111111', document.forms.form_name)
            // var price_fields = jQuerOs(".hidden-price");
            var price_fields = jQuerOs(form).parents('.instance_body').find('.hidden-price');

            var json_price_fields = [];
            for(index = 0; index < price_fields.length; ++index){
                var fid = jQuerOs(price_fields[index]).attr('fid');
                var lid = jQuerOs(price_fields[index]).attr('lid');
                var calculated = jQuerOs(price_fields[index]).attr('calculated');
                if (calculated == 1){
                    json_price_fields[index] ={};
                    json_price_fields[index]['fid'] = fid;
                    json_price_fields[index]['lid'] = lid;
                    json_price_fields[index]['value'] = jQuerOs(price_fields[index]).val();
                }
            }
            json_price_fields = JSON.stringify(json_price_fields);
            jQuerOs('[name=price_fields]').val(json_price_fields);
            form.submit();
        }
    </script>
    <?php
    echo "</div>"; //close <div class="cck-body">
    return;
  }

  $from = false;
  $to = false;

  
  foreach ($fields_list as $value) {
      
    if($value->field_type == 'datetime_popup'){
      if(isset($field_from_params[$value->db_field_name.'_field_type']) == 'rent_from'){
        $field_from_capt = $value->db_field_name;
        $from = true;
      }
      if(isset($field_from_params[$value->db_field_name.'_field_type']) == 'rent_to'){
        $field_to_capt = $value->db_field_name;
        $to = true;
      }
    }
  }

  if(!($from && $to)){
    $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_NO_RENT_CALENDAR"), 'warning');
    echo "</div>"; //close <div class="cck-body">
    return;
  }

  if($show_type == 2){
     $div_styling = isset($button_style['div_styling']) ? $button_style['div_styling'] : ''; 
     $field_styling = isset($button_style['field_styling']) ? $button_style['field_styling'] : '';
     $custom_class = isset($button_style['custom_class']) ? $button_style['custom_class'] : '';
     $offset_animation = isset($button_style['offset_animation']) ? $button_style['offset_animation'] : '';?>
  <div <?php echo $div_styling; ?>>
    <input <?php echo $field_styling;?> type="button" class="button btn btn-info <?php echo $custom_class;?>" <?php echo $offset_animation; ?> value="<?php echo ($layout_params['button_name'])?$layout_params['button_name'] : cck_lang_text('COM_OS_CCK_BUTTON_SHOW_FORM_RENT_REQUEST'); ?>"
        onclick="jQuerOs('#request_wrapper_<?php echo $layout_type?><?php echo $unique_form_id; ?><?php echo ($moduleId) ? '_cckmod_'.$moduleId : '' ;?>').stop().fadeToggle();"/>
  </div>
    <div class="rent_request_wrapper" id="request_wrapper_<?php echo $layout_type?><?php echo $unique_form_id; ?><?php echo ($moduleId) ? '_cckmod_'.$moduleId : '' ;?>" style="display: none;">
    <?php
  }
  
  if($show_type == 4){
     $div_styling = isset($button_style['div_styling']) ? $button_style['div_styling'] : ''; 
     $field_styling = isset($button_style['field_styling']) ? $button_style['field_styling'] : '';
     $custom_class = isset($button_style['custom_class']) ? $button_style['custom_class'] : '';
     $offset_animation = isset($button_style['offset_animation']) ? $button_style['offset_animation'] : '';?>
  <div <?php echo $div_styling; ?> class="col_box cck_hover_layout">
    <input <?php echo $field_styling;?> type="button" class="button btn btn-info <?php echo $custom_class;?>" <?php echo $offset_animation; ?> value="<?php echo ($layout_params['button_name'])?$layout_params['button_name'] : cck_lang_text('COM_OS_CCK_BUTTON_SHOW_FORM_RENT_REQUEST'); ?>"/>
  
  <ul class="os_cck_hover_child">
    
    <?php
  }
  
  if($show_type == 5){
     $div_styling = isset($button_style['div_styling']) ? $button_style['div_styling'] : ''; 
     $field_styling = isset($button_style['field_styling']) ? $button_style['field_styling'] : '';
     $custom_class = isset($button_style['custom_class']) ? $button_style['custom_class'] : '';
     $offset_animation = isset($button_style['offset_animation']) ? $button_style['offset_animation'] : '';?>
  <div <?php echo $div_styling; ?> class="col_box">
    <button <?php echo $field_styling;?> type="button" class="button btn btn-info <?php echo $custom_class;?>" <?php echo $offset_animation; ?>  data-toggle="os_cck_modal" data-target="#show_request_layout_<?php echo $rand; ?>">
        <?php echo ($layout_params['button_name'])?$layout_params['button_name'] : cck_lang_text('COM_OS_CCK_BUTTON_SHOW_FORM_RENT_REQUEST'); ?>
    </button>
  
    <div class="fade os_cck_modal" id="show_request_layout_<?php echo $rand; ?>" 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">
            
          
    
    <?php
  }

  $field = new stdClass();
  $field->db_field_name = 'form-'.$layout->lid;
  $form_styling = get_field_styles($field, $layout);
  $form_custom_class = get_field_custom_class($field, $layout);
  $form_offset_animation = get_field_offset_animation($field, $layout);
  $form_hover_animation = get_field_hover_animation($field, $layout);
  ?>
  <form class="<?php echo $form_custom_class; ?>" <?php echo $form_styling; ?> <?php echo $form_offset_animation; ?> 
    <?php echo $form_hover_animation; ?> action="<?php echo JRoute::_('index.php'); ?>" method="post" 
    name="<?php echo $unique_form_id?>" id="<?php echo $unique_form_id?>" enctype="multipart/form-data">
    
    <?php
    if(isset($layout_params['title'])){
      echo '<input type="hidden" name="title" value="'.$layout_params['title'].'">';
    }

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

      $html='';
      $value='';
      $field = $fields_list[$i];
      $field_styling = get_field_styles($field, $layout);
      $params_field = isset($field_from_params['Params_'.$field->db_field_name]) ? $field_from_params['Params_'.$field->db_field_name] : '';
        $params_field = json_decode($params_field);
        
        $hover_border_collor = (isset($params_field->hover_border_collor)) ? $params_field->hover_border_collor : '';
        $hover_background_color = (isset($params_field->hover_background_collor)) ? $params_field->hover_background_collor : '';
        $hover_text_color = (isset($params_field->hover_text_collor)) ? $params_field->hover_text_collor : '';
        
        if($hover_border_collor != '' || $hover_background_color != ''
                                      || $hover_text_color != ''){
            ?>
      <style type="text/css"> .<?php echo $field->db_field_name; ?>:hover{
            color: <?php echo $hover_text_color ?> !important;
            border-color: <?php echo $hover_border_collor ?> !important;
            background-color: <?php echo $hover_background_color ?> !important;

        }
        </style>
        <?php } 
      $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;

      require getSiteUniqueFiledViewPath('com_os_cck', 'custom_code');
      //start render custom code
//       if(count($layout_params['custom_fields'])){
//         foreach ($layout_params['custom_fields'] as $cust_key => $custom_field) {
//           if(strpos($layout_html,"{|f-custom_code_field_".$cust_key."|}")){
//             //check access
//             if(isset($custom_field['custom_code_field_'.$cust_key.'_access'])
//                 && $custom_field['custom_code_field_'.$cust_key.'_access'] != '1'){
//               $user = JFactory::getUser();
//               if(!checkAccess_cck($custom_field['custom_code_field_'.$cust_key.'_access'], $user->groups, $layout->fk_eid, 'fields')){
//                 $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", '', $layout_html);
//                 continue;
//               }
//             }
// //            $dispatcher = JDispatcher::getInstance();
//             JPluginHelper::importPlugin('content');
//             $plug_row = new stdClass();
//             $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
//             preg_match_all('#\{loadmoduleid [0-9]*\}#', $plug_row->text, $matches);
//             foreach($matches as $res){
//               foreach($res as $str){
                
//                 $moduleId = str_replace('{loadmoduleid ', '', $str);
//                 $moduleId = str_replace('}', '', $moduleId);

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

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

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

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

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

//               }
//             }
//             // JFactory::getApplication()->triggerEvent('onContentPrepare', array('com_os_cck', &$plug_row, &$plug_params, 0));
//             $plug_row->text = str_replace("{|this_entity_filesfolder|}", JURI::root() . '/components/com_os_cck/files/entity_files_'.$layout->fk_eid.'/', $plug_row->text);
//             $plug_row->text = str_replace("{|cck_images_folder|}", JURI::root() . 'images/os-cck/', $plug_row->text);
//             $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = $plug_row->text;
//             //if below fn works , that this is add_instance view
//             $code_type = $custom_field['custom_code_field_'.$cust_key.'_custom_code_type'];
//             if($code_type == 'SCRIPT'){
//               $custom_code = '<script type="text/javascript">';
//               $custom_code .= $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
//               $custom_code .= '</script>';
//               $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_code, $layout_html);
//             }elseif($code_type == 'PHP'){
//               ob_start();
//               $custom_code = eval($custom_field['custom_code_field_'.$cust_key.'_custom_code']);
//               $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", ob_get_contents(), $layout_html);
//               ob_end_clean();
//             }elseif($code_type == 'CSS'){
//               $custom_css = '<style>'.$custom_field['custom_code_field_'.$cust_key.'_custom_code'].'</style>';
//               $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_css, $layout_html);
//             }else{
//               $custom_code = $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
//               $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_code, $layout_html);
//             }
//           }
//         }
//       }

      //delete inappropriate short cods
      if(strpos($layout_html,"{|f-cck_mail|}")){
        $layout_html = str_replace("{|f-cck_mail|}",'', $layout_html);
      }
      if(isset($layout_params['mail_fields'])){
            foreach($layout_params['mail_fields'] as $mail_fields){
                $layout_html = str_replace("{|f-$mail_fields|}",'', $layout_html);
            }
        }
      //delete inappropriate short cods
  
      if(strpos($layout_html,"{|f-".$field->fid."|}")){
          $php_if = isset($layout_params['fields'][$field->db_field_name.'_php_show']) ? $layout_params['fields'][$field->db_field_name.'_php_show'] : '';
           $php_result = true;
           if($php_if != ''){
                $php_result = processing_php_show($php_if, $entityInstance, $layout_params, $layout_html, $layout);
           }
           
          if($php_result){
            //publish\unpublish check
            if((!isset($field_from_params[$field->db_field_name.'_published']) 
                || $field_from_params[$field->db_field_name.'_published'] != 'on')){
              $layout_html = str_replace("{|f-".$field->fid."|}", '', $layout_html);
              continue;
            }
            //publish\unpublish check

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

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

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

            $data = (isset($value[0]->data)) ? $value[0]->data : '';
            $hidden = '';


              $fromSearch = 0;
              $field_from_params['ceid'] = $layout->fk_eid;
              $field_from_params['eiid'] = $layout->parent_eiid;
              $field_from_params['lay_type'] = $layout_type;
              $field_from_params['form_id'] = $unique_form_id ;
              $field_from_params['field_styling']= $field_styling;
              $field_from_params['custom_class']= $custom_class;
              ob_start();
              require getSiteAddFiledViewPath('com_os_cck', $field->field_type);
              $html .= ob_get_contents();
              ob_end_clean();
            //}

            //add _suffix  
            if(isset($field_from_params[$field->db_field_name.'_add_icon_suffix_prefix']) && !empty($field_from_params[$field->db_field_name.'_add_icon_suffix_prefix'])){
                $html .= '<span class="fa '.$field_from_params[$field->db_field_name.'_add_icon_suffix_prefix'].'"></span>';
            }
            if(!empty($field_from_params[$field->db_field_name.'_suffix'])){
              $html.= '<span ' . $layout_params['field_styling'] . 'class="'.$field->db_field_name.'_suffix'.'">'.$field_from_params[$field->db_field_name.'_suffix'].'</span>';
            }
            if(isset($field_from_params[$field->db_field_name.'_add_icon_suffix_suffix']) && !empty($field_from_params[$field->db_field_name.'_add_icon_suffix_suffix'])){
                $html .= '<span class="fa '.$field_from_params[$field->db_field_name.'_add_icon_suffix_suffix'].'"></span>';
            }
            //add _suffix
          }
        //add field to layout / replace shortcode
        $layout_html = str_replace("{|f-".$field->fid."|}", $html, $layout_html);
      }
    }
    
    if(strpos($layout_html,"{|f-coupon|}")){
        $field = new stdClass();
        $field->db_field_name = 'coupon';
        $html = '';
        $layout_html = str_replace($field->db_field_name."-label-hidden", '', $layout_html);
        $field_styling = get_field_styles($field, $layout);

        $hover_styling = get_hover_css_style($field, $layout_params);
        echo $hover_styling;
        $custom_class = get_field_custom_class($field, $layout);
        $offset_animation = get_field_offset_animation($field, $layout);

        ob_start();
        require getSiteUniqueFiledViewPath('com_os_cck', $field->db_field_name);
        $html .= ob_get_contents();
        ob_end_clean();

        $layout_html = str_replace("{|f-coupon|}", $html, $layout_html);

    }
    
    if(strpos($layout_html,"{|f-total_price|}")){
        $field = new stdClass();
        $field->db_field_name = 'total_price';
        $html = '';
        $layout_html = str_replace($field->db_field_name."-label-hidden", '', $layout_html);
        $field_styling = get_field_styles($field, $layout);

        $hover_styling = get_hover_css_style($field, $layout_params);
        echo $hover_styling;
        $custom_class = get_field_custom_class($field, $layout);
        $offset_animation = get_field_offset_animation($field, $layout);

        ob_start();
        require getSiteUniqueFiledViewPath('com_os_cck', $field->db_field_name);
        $html .= ob_get_contents();
        ob_end_clean();

        $layout_html = str_replace("{|f-total_price|}", $html, $layout_html);

    }

    //end render
    if(isset($layout_params['attachedModule'])){
      foreach ($layout_params['attachedModule'] as $attachedModule) {
        if($attachedModule){
          if(strpos($layout_html,"{|m-".$attachedModule->id."|}")){
              $field = new stdClass();
            $field->field_name = 'm_'.$attachedModule->id;
            $field_styling = get_field_styles($field, $layout);
            $custom_class = isset($layout_params['fields'][$field->field_name.'_custom_class'])?$layout_params['fields'][$field->field_name.'_custom_class']:'';
            $offset_animation = get_field_offset_animation($field, $layout);
            $module = JModuleHelper::getModule($attachedModule->type,$attachedModule->title);
            $options  = array('style' => 'xhtml');
            $html = '<div class="'.$custom_class.'" ' . $offset_animation . ' '.$field_styling.'>'.JModuleHelper::renderModule($module,$options).'</div>';
            $layout_html = str_replace("{|m-".$attachedModule->id."|}", $html, $layout_html);
          }
        }
      }
    }
    $field = new stdClass();
    $field->db_field_name = 'cck_send_button';
    $field_styling = get_field_styles($field, $layout);
    $custom_class = get_field_custom_class($field, $layout);
    $params_field = isset($field_from_params['Params_'.$field->db_field_name]) ? $field_from_params['Params_'.$field->db_field_name] : '';
    $params_field = json_decode($params_field);
    
    $hover_border_collor = (isset($params_field->hover_border_collor)) ? $params_field->hover_border_collor : '';
    $hover_background_color = (isset($params_field->hover_background_collor)) ? $params_field->hover_background_collor : '';
    $hover_text_color = (isset($params_field->hover_text_collor)) ? $params_field->hover_text_collor : '';
    
    if($hover_border_collor != '' || $hover_background_color != ''
                                  || $hover_text_color != ''){
        ?>
  <style type="text/css"> .<?php echo $field->db_field_name; ?>:hover{
        color: <?php echo $hover_text_color ?> !important;
        border-color: <?php echo $hover_border_collor ?> !important;
        background-color: <?php echo $hover_background_color ?> !important;

    }
    </style>
    <?php } 
    $offset_animation = get_field_offset_animation($field, $layout);
    $div_styling = get_align_styles($field, $layout);
    $reqire_login = (isset($layout_params['fields']['reqiredLogin_' . $field->db_field_name]) && $layout_params['fields']['reqiredLogin_' . $field->db_field_name] == 'on') ? true : false;
    $login_url = isset($layout_params['fields'][$field->db_field_name.'_login_url']) ? $layout_params['fields'][$field->db_field_name.'_login_url'] : '';
    if (version_compare(JVERSION, "4.0.0", "ge")) {
      if ($app->isClient('site')){
        $check = true;
      }else{
        $check = false;
      }
    }else{
      if ($app->isSite()){
        $check = true;
      }else{
        $check = false;
      }
    }
    if($check &&  isset($layout_params['fields']['reqirectBack_' . $field->db_field_name]) && $layout_params['fields']['reqirectBack_' . $field->db_field_name] == 'on'){
        
        $return_url = 'index.php?';
        $iter = 0;
        foreach($_REQUEST as $key => $req){
            if($iter == 0){
                $return_url .= $key.'='.$req;
            }else{
              
              if(!is_array($req)){
                $return_url .= '&'.$key.'='.$req;
              }else{
                $return_url .= '&'.$key.'=['.implode(',', $req) . ']';
              }
            }
            $iter ++;
        }
        if(stripos($login_url, '?') !== false){
            $login_url .= '&return='.base64_encode($return_url); 
        }else{
            $login_url .= '?return='.base64_encode($return_url); 
        }
//        $url = 'index.php?option=com_users&view=login'; 
//        $url .= '&return='.base64_encode($return_url); 
//        $login_url = $url;

    }
    ob_start();
    echo '<div '.$div_styling.'>';
    echo $hidden;
    $buttonText = isset($layout_params["views"]["layout_button_text"])
                  && !empty($layout_params["views"]["layout_button_text"])?$layout_params["views"]["layout_button_text"]:cck_lang_text('COM_OS_CCK_BUTTON_FORM_RENT_REQUEST');
    ?>
    <input <?php echo $field_styling; ?> type="button" name="rent_request_button" value="<?php echo $buttonText; ?>"
           class="button btn-info <?php echo $custom_class; ?> <?php echo $field->db_field_name; ?>" <?php echo $offset_animation; ?> onclick="javascript:sendRequest<?php echo $unique_form_id; ?>('send_rent_request','<?php echo $unique_form_id?>');">
    <?php    
    echo '</div>';
    $layout_html = str_replace("{|f-cck_send_button|}", ob_get_contents(), $layout_html);
    ob_end_clean();

    //render layout
    echo $layout_html; 
    ?>

    <!--<div class="message-here"></div>-->
    <input type="hidden" name="calculated_price" value="">
    <input type="hidden" name="rent_from" value="">
    <input type="hidden" name="rent_until" value="">
    <input type="hidden" name="time_from" value="">
    <input type="hidden" name="time_until" value="">
    <input type="hidden" name="option" value="com_os_cck"/>
    <input type="hidden"  name="price_fields" value='<?php echo $price_fields; ?>'>
    <input type="hidden" name="lay_type" value="<?php echo $layout->lid?>"/>
    <input type="hidden" name="eid" value="<?php echo $layout->fk_eid?>"/>
    <input type="hidden" name="task" value="save_instance"/>
    <input type="hidden" name="Itemid" value="<?php echo protectInjectionWithoutQuote('Itemid')?>"/>
    <input type="hidden" name="moduleId" value="<?php echo $moduleId ?>"/>
    <input type="hidden" name="catid" value="<?php echo protectInjectionWithoutQuote('catid',''); ?>"/>
    <input type="hidden" name="fk_eiid" value="<?php echo (isset($layout->parent_eiid) && !empty($layout->parent_eiid))? $layout->parent_eiid : '' ?>"/>
    <input type="hidden" name="lid" value="<?php echo (protectInjectionWithoutQuote('lid',''))?protectInjectionWithoutQuote('lid'):$layout->lid ; ?>"/>
    <input type="hidden" name="requireLogin" value="<?php echo $reqire_login; ?>"/>
    <input type="hidden" name="login_url" value="<?php echo $login_url; ?>"/>
    <input type="hidden" name="start_time" value="<?php echo (isset($start_time_to_form)) ?  $start_time_to_form :  0; ?>"/>
    <input type="hidden" name="finish_time" value="<?php echo (isset($finish_time_to_form)) ?  $finish_time_to_form :  0; ?>"/>
    <input type="hidden"  name="coupon_id" id="coupon_id" value="">
    <input type="hidden"  name="coupon" id="coupon_value" value="">
  </form>

  <?php if($show_type == 2) echo "</div>";
  if($show_type == 4) echo "</ul></div>";
  if($show_type == 5){ ?>
      </div>
          
        </div>
      </div>
    </div>
  </div>
  <?php }
 
  ?>

<script type="text/javascript" >
    loadAddLayout();
    not_available_times_in_day_from = JSON.parse('<?php echo json_encode($not_available_times_in_day_from); ?>');
    // for(var i = 0; i < not_available_times_in_day_from.length; i++){
    //     if(not_available_times_in_day_from[i].length == 1 && not_available_times_in_day_from[i][0][0] == '00:00' && not_available_times_in_day_from[i][0][1] == '23:59'){
    //         not_available_times_in_day_from[i] = 'dayOff'
    //     }
    // }
    not_available_times_in_day_to = JSON.parse('<?php echo json_encode($not_available_times_in_day_to); ?>');
    // for(var i = 0; i < not_available_times_in_day_to.length; i++){
    //     if(not_available_times_in_day_to[i].length == 1 && not_available_times_in_day_to[i][0][0] == '00:00' && not_available_times_in_day_to[i][0][1] == '23:59'){
    //         not_available_times_in_day_to[i] = 'dayOff'
    //     }
    // }      
    available_times_in_day = JSON.parse('<?php echo json_encode($available_times_in_day); ?>');
    
    const captchaKey<?php echo $unique_form_id; ?> = Joomla.getOptions('plg_captcha_recaptcha_os.siteKey', '');
    const actionSelector<?php echo $unique_form_id; ?> = 'input.plg-captcha-recaptcha-os-action';
    const answerSelector<?php echo $unique_form_id; ?> = 'input.plg-captcha-recaptcha-os-hidden';
    const findAction<?php echo $unique_form_id; ?> = function (form) {
            if (form.hasAttribute('class') && form.getAttribute('class') !== '') {
                    let matchClass;
                    form.getAttribute('class').split(/\s+/).forEach((className) => {
                            if (className.match(/^(com|mod|plg)\-/)) {
                                    matchClass = className;
                            }
                    });
                    if (matchClass) {
                            return matchClass;
                    }
            }
            if (form.hasAttribute('id') && form.getAttribute('id') !== '') {
                    return form.getAttribute('id');
            }
            if (form.hasAttribute('name') && form.getAttribute('name') !== '') {
                    return form.getAttribute('name');
            }
            return 'submit';
    }
    const getAction<?php echo $unique_form_id; ?> = form => findAction<?php echo $unique_form_id; ?>(form).replace(/[^a-z0-9]+/gi, '_');
    
    var send_request = null;
    var send_buy_request = null;
    var review_captcha_request = null;
    var check_captcha_request_<?php echo $layout->type?> = null;
    (function ($) {
      check_captcha_request_<?php echo $layout->type?> = function (moduleId,form,type) {
        var status = "";
        if(moduleId){
          form=form+'_'+moduleId;
        }
        $.post("index.php?option=com_os_cck&captcha_type="+type+"&task=checkCaptcha&format=raw", $(form.keyguest).serialize(),
        function (data) {
          if (data.status == '<?php echo cck_lang_text("COM_OS_CCK_SUCCESS"); ?>') {
            form.submit();
          }else{

            reload_captcha_<?php echo $layout->type?>(moduleId,type);
            jQuerOs("[name='keyguest']").val('');
            alert("<?php echo cck_lang_text("COM_OS_CCK_INFOTEXT_JS_WRONG_CAPTCHA");?>");
          }
        } , 'json' );
      }
    })(jQuerOs);


    function sendRequest<?php echo $unique_form_id; ?>(task,form_name){

      var form = document.forms[form_name];
      
      //rent request fields must be whole filled
      if(task == 'send_rent_request'){

        rent_from = jQuerOs(form).find('[name=rent_from]').val() ;
//        console.log('111111111111', jQuerOs(form).find('[name=rent_from]'))
        if( rent_from == undefined){
          alert("Please in RentRequest layout create(set) Date->RentFrom and Date->RentTo");
          return;
        }

        rent_until = jQuerOs(form).find('[name=rent_until]').val() ;
        if( rent_until == undefined){
          alert("Please in RentRequest layout create(set) Date->RentFrom and Date->RentTo");
          return;
        }
        
        if( rent_from == ''){
          alert("Please enter a start date for the rental");
          return;
        }

        if( rent_until == ''){
          alert("Please enter a rental end date");
          return;
        }
//        console.log('11111111111111111', '<?php echo  $os_cck_configuration->get('rent_type');?>')
//        console.log('22222222222222222', rent_from)
//        console.log('33333333333333333', rent_until)
//        if(rent_from < rent_until){
//            console.log ('4444444444444444')
//        }else{
//            console.log ('5555555555555555')
//        }
//        return;
        if('<?php echo  $os_cck_configuration->get('rent_type');?>' == 2){
          //if rent with time

          time_from = jQuerOs(form).find('[name=time_from]').val() ;
          if( time_from == ''){
            alert("Please, choose time from");
            return;
          }
          time_until = jQuerOs(form).find('[name=time_until]').val() ;
          if( time_until == ''){
            alert("Please, choose time until");
            return;
          }
          if( rent_from == rent_until && time_from == time_until ){
            alert("Please, select some time interval");
            return;
          } 
          if( rent_from == rent_until && time_from > time_until ){
            alert("Time From must be less Time To-");
            return;
          }                    
        }

      }
      
      checkUploadedFiles(form, <?php echo return_bytes(ini_get('post_max_size')) ?>, <?php echo return_bytes(ini_get('upload_max_filesize')) ?>, <?php echo ini_get('file_uploads') ?>,
        "<?php echo cck_lang_text('COM_OS_CCK_SETTINGS_VIDEO_ERROR_UPLOAD_OFF'); ?>", "<?php echo cck_lang_text('COM_OS_CCK_SETTINGS_VIDEO_ERROR_POST_MAX_SIZE'); ?>", "<?php echo cck_lang_text('COM_OS_CCK_SETTINGS_VIDEO_ERROR_UPLOAD_MAX_SIZE'); ?>",
        "<?php echo cck_lang_text('COM_OS_CCK_ADMIN_INFOTEXT_JS_TRACK_KIND'); ?>", "<?php echo cck_lang_text('COM_OS_CCK_ADMIN_INFOTEXT_JS_TRACK_LANGUAGE'); ?>", "<?php echo cck_lang_text('COM_OS_CCK_ADMIN_INFOTEXT_JS_TRACK_TITLE'); ?>")

      if(typeof sceditor != 'undefined'){
//            console.log("44444444444444", text_area_arr)
          for(var i=0; i < text_area_arr.length; i++){
            var editor = window[text_area_arr[i]]
//            console.log('1111111111111111', text_area_arr)
//            var value = editor.instance(textarea).val()
            var value = sceditor.instance(editor).val()
//            console.log('1111111111111111', value)
            var textarea_field = jQuerOs('[name=fi_'+text_area_arr[i]+']')
            if(textarea_field.length >0){
              jQuerOs(textarea_field[0]).val(value)
            }

            
          }
      }

      ret = false;
      if(!ret) checkRequireFields(form_name);
      if(!ret) checkStepNumberFields();
      if(!ret) check_reg_expr(form_name);
           
      if(ret){
        if(ret_scroll != -1){
          window.scrollTo(0,ret_scroll);
        }
        return;
      }
        
        
        if(form.price_fields.value == ''){
            var price_fields = jQuerOs(form).parents('.instance_body').find(".hidden-price");
            var json_price_fields = [];

            for(index = 0; index < price_fields.length; ++index){
                var fid = jQuerOs(price_fields[index]).attr('fid');

                var lid = jQuerOs(price_fields[index]).attr('lid');
                var calculated = jQuerOs(price_fields[index]).attr('calculated');
                // if (calculated == 1){
                    json_price_fields[index] ={}
                    json_price_fields[index]['fid'] = fid;
                    json_price_fields[index]['lid'] = lid;
                    json_price_fields[index]['value'] = jQuerOs(price_fields[index]).val();
                    json_price_fields[index]['calculated'] = calculated;
                // }
            }
            json_price_fields = JSON.stringify(json_price_fields);
            form.price_fields.value = json_price_fields;
        }

        if(task == 'send_buy_request'){
          type = 'buy_request_instance';
          form.task.value = 'send_buy_request';
        }else if(task == 'send_rent_request'){
          type = 'rent_request_instance';
          form.task.value = 'send_rent_request';
        }else if(task == 'send_request'){
          type = 'request_instance';
          form.task.value = 'send_request';
        }else if(task == 'send_review_request'){
          type = 'review_instance';
          form.task.value = 'send_review_request';
        }else{
          type = 'add_instance';
        }
        
        jQuerOs('#coupon_value').val(jQuerOs('#os_cck_coupon').val())
        
        
        if(form.querySelector('div[id^="captcha-block"]')){
          check_captcha_request_<?php echo $layout->type?>(0,form,type);
        }else if(form.querySelector('#recaptcha')){
          var actionElement = jQuerOs(form).find(actionSelector<?php echo $unique_form_id; ?>);
          if(actionElement.length > 0){  
                grecaptcha.ready(function () {
      
                      var actionElement = jQuerOs(form).find(actionSelector<?php echo $unique_form_id; ?>);
                      if(actionElement.length > 0){
                          actionElement = actionElement[0]
                      }
      
                      actionElement.value = getAction<?php echo $unique_form_id; ?>(submitEvent.target);

                      grecaptcha.execute(captchaKey<?php echo $unique_form_id; ?>, {action: actionElement.value}).then(function (token) {
                          jQuerOs(form).find(actionSelector<?php echo $unique_form_id; ?>).val(token)
//                          console.log('11111111111111', jQuerOs(form).find(actionSelector<?php echo $unique_form_id; ?>))
//                          return
//                              submitEvent.target.querySelector(answerSelector<?php echo $unique_form_id; ?>).value = token;
//                              submitEvent.target.submit();
                              form.submit();    
                      });
              });
          }else{
          
                var recaptcha_count = jQuerOs(form).find('.recaptcha_field').attr('recaptcha_count')
                var recaptcha_name = jQuerOs(form).find('[name=recaptcha_namespace]').attr('value')
                var response = grecaptcha.getResponse(recaptcha_count);

                  if(response.length > 0){
                    form.submit();    
                  }else{
                    var target_top= jQuerOs('#recaptcha').offset().top;
                    jQuerOs('html, body').animate({scrollTop:target_top}, 'slow');
                    jQuerOs('#recaptcha iframe').css('border', '1px solid')
                    jQuerOs('#recaptcha iframe').css('border-color', 'red')
                  }

          }
        }else{
          form.submit();
        }
    }
    //jQuerOs("*[class*='hide-field-name-'] , .delete-field, .delete-row").remove();
    jQuerOs(".delete-field, .delete-row").remove();
    //jQuerOs("span.cck-help-string").remove();
    jQuerOs(function () {
      jQuerOs('[data-toggle="tooltip"]').tooltip()
    })
    
  </script>
</div>
