<?php

defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright 2020 OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;
use OrdaSoft\os_lib\os_libHtmlInputs;

if( !class_exists("os_libMain") ){
    try{
        $ss = new os_libMain();
    }catch( Exception $e ){
        die("Please reinstall OrdaSoft Joomla CCK Package!");
    }
}
class os_cckEntityInstance extends JTable
{
  /** @var array with all fields */
  //first table fileds 
  var $eiid = null;
  var $fk_lid = null;
  var $fk_eid = null;
  var $title = null;
  var $asset_id = null;
  var $fk_userid = null;
  var $published = null;
  var $approved = null;
  var $created = null;
  var $changed = null;
  var $last_review = null;
  var $checked_out = null;
  var $checked_out_time = null;
  var $teid = null;
  var $hits = null;
  var $instance_price = 0;
  var $instance_currency = null;
  var $notreaded = null;
  var $featured_clicks = null;
  var $featured_shows = null;
  var $access = null;
  var $meta_title = '';
  var $meta_description = '';
  var $meta_keywords = '';
  var $meta_robots = '';
  var $language = '';
  var $layout_type = '';
  var $associate_instances = '';
  
  

  /**
   * @param database - A database connector object
   */
  function __construct(&$db)
  {
      parent::__construct('#__os_cck_entity_instance', 'eiid', $db);
  }
  
  function checkMimeTypeFromFiles($ext) {
    $this->_db->setQuery("SELECT mime_ext FROM #__os_cck_mime_types WHERE mime_type=".$this->_db->quote($ext));
    $type = $this->_db->loadColumn();
    if(!$type)
      $type = 'unknown';
    return $type;
  }

  function check($admin = false){

    $db =  JFactory::getDBO();
    $layout_params = $this->_layout_params;
    
    foreach ($this->_field_list as $field) {
      

        //captcha_field
      if(!$this->eiid > 0){
          if($admin === false && $field->field_type == 'captcha_field'){


              if(os_cck_site_controller::SecondcheckCaptcha() === false){
                echo "<script> alert('".cck_lang_text('COM_OS_CCK_INFOTEXT_JS_WRONG_CAPTCHA')."'); 
                      window.history.go(-1); </script>\n";
                exit;
              }


          }
      }
      
      //image-field
      if($field->field_type == 'imagefield'  && $_FILES['fi_'.$field->db_field_name]['error'] == ""){
//          var_dump($_FILES); exit;
        $imagesize = getimagesize($_FILES['fi_'.$field->db_field_name]['tmp_name']);
        $width = $imagesize[0];
        $height = $imagesize[1];
        $max_upload_size = (int)$layout_params[$field->db_field_name . "_max_upload_size"];//mb

        $allow_ext = trim($layout_params[$field->db_field_name . "_allow_ext"]);
        if(strlen($allow_ext)<1){
          $allow_ext = "jpg,jpeg,png,gif";
        }
        $allow_ext = str_ireplace(' ', '', $allow_ext);
        $allow_ext_array = explode(',', $allow_ext);
        
        $max_width = (int)$layout_params[$field->db_field_name . "_max_width"];
        $max_height = (int)$layout_params[$field->db_field_name . "_max_height"];

        $ext = $this->checkMimeTypeFromFiles($_FILES['fi_'.$field->db_field_name]['type']);

        if($ext == 'unknown'){
          $ext = pathinfo($_FILES['fi_'.$field->db_field_name]['name'], PATHINFO_EXTENSION);
          if(isset($allow_ext_array) && is_array($allow_ext_array) && array_search($ext, $allow_ext_array) === false){
            echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                  window.history.go(-1); </script>\n";
            exit;
          }
        }else{
            if(isset($allow_ext_array) && is_array($allow_ext_array)){
                $temp_array = array_intersect($ext, $allow_ext_array) ;
            }else{
                $temp_array = array();
            }
          if(isset($allow_ext_array) && is_array($allow_ext_array) && empty($temp_array) ){
            echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                  window.history.go(-1); </script>\n";
            exit;
          }
        }

        //max upload size
        if($max_upload_size != 0 && $_FILES['fi_'.$field->db_field_name]['size'] > ($max_upload_size*1000000)){
           echo "<script> alert('". $_FILES['fi_'.$field->db_field_name]['name'] ." ".cck_lang_text('COM_OS_CCK_IMAGE_FILE_TOO_LARGE')." " . $max_upload_size . "mb'); 
             window.history.go(-1); </script>\n";
           exit;
        }

        //max width & max height
        if($max_width != 0 && $width>$max_width){
          echo "<script> alert('".cck_lang_text('COM_OS_CCK_MAX_WIDTH_FOR_IMAGE')." ". $max_width ."px'); 
                window.history.go(-1); </script>\n";
          exit;
        }elseif($max_height != 0 && $height>$max_height){
          echo "<script> alert('".cck_lang_text('COM_OS_CCK_MAX_HEIGHT_FOR_IMAGE')." ". $max_height ."px'); 
                window.history.go(-1); </script>\n";
          exit;
        }

      }
     
      //file-field
      if($field->field_type == 'filefield' && $_FILES['fi_'.$field->db_field_name]['error'] == ""){
 
        $max_upload_size = (int)$layout_params[$field->db_field_name . "_max_upload_size"];//mb
        $allow_ext = trim($layout_params[$field->db_field_name . "_allow_ext"]);
        $allow_ext = str_ireplace(' ', '', $allow_ext);
        if($allow_ext != ""){
          $allow_ext_array = explode(',', $allow_ext);
        }

        $ext = $this->checkMimeTypeFromFiles($_FILES['fi_'.$field->db_field_name]['type']);

        if($ext == 'unknown'){
          $ext = pathinfo($_FILES['fi_'.$field->db_field_name]['name'], PATHINFO_EXTENSION);
          if(isset($allow_ext_array) && is_array($allow_ext_array) && array_search($ext, $allow_ext_array) === false){
            echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                  window.history.go(-1); </script>\n";
            exit;
          }
        }else{
          if(isset($allow_ext_array) && is_array($allow_ext_array)){
            $temp_array = array_intersect($ext, $allow_ext_array) ;
          }else{
              $temp_array = array();
          }
          if(isset($allow_ext_array) && is_array($allow_ext_array) && empty($temp_array) ){
            echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                  window.history.go(-1); </script>\n";
            exit;
          }
        }

        if($max_upload_size != 0 && $_FILES['fi_'.$field->db_field_name]['size'] > ($max_upload_size*1000000)){
           echo "<script> alert('". $_FILES['fi_'.$field->db_field_name]['name'] ." ".cck_lang_text('COM_OS_CCK_FILE_TOO_LARGE')." " . $max_upload_size . "mb'); 
             window.history.go(-1); </script>\n";
           exit;
        }

      }

      //audiofield
      if($field->field_type == 'audiofield'){
        
        for($i=1;isset($_FILES['new_upload_audio'.$i]);$i++){

          $max_upload_size = (int)$layout_params[$field->db_field_name . "_max_upload_size"];//mb
          $allow_ext = trim($layout_params[$field->db_field_name . "_allow_ext"]);
          $allow_ext = str_ireplace(' ', '', $allow_ext);
          if($allow_ext != ""){
            $allow_ext_array = explode(',', $allow_ext);
          }

          $ext = $this->checkMimeTypeFromFiles($_FILES['new_upload_audio'.$i]['type']);

          if($ext == 'unknown'){
            $ext = pathinfo($_FILES['new_upload_audio'.$i]['name'], PATHINFO_EXTENSION);
            if(isset($allow_ext_array) && is_array($allow_ext_array) && array_search($ext, $allow_ext_array) === false){
              echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                    window.history.go(-1); </script>\n";
              exit;
            }
          }else{
              if(isset($allow_ext_array) && is_array($allow_ext_array)){
                  $temp_array = array_intersect($ext, $allow_ext_array) ;
              }else{
                  $temp_array = array();
              }
            if(isset($allow_ext_array) && is_array($allow_ext_array) && empty($temp_array) ){
              echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                    window.history.go(-1); </script>\n";
              exit;
            }
          }

          if($max_upload_size != 0 && $_FILES['new_upload_audio'.$i]['size'] > ($max_upload_size*1000000)){
             echo "<script> alert('". $_FILES['new_upload_audio'.$i]['name'] ." ".cck_lang_text('COM_OS_CCK_AUDIO_FILE_TOO_LARGE')." " . $max_upload_size . "mb'); 
               window.history.go(-1); </script>\n";
             exit;
          }
        }

      }

      //videofield
      if($field->field_type == 'videofield' ){
      
        for($i=1;isset($_FILES['new_upload_video'.$i]);$i++){

          $max_upload_size = (int)$layout_params[$field->db_field_name . "_max_upload_size"];//mb
          $allow_ext = trim($layout_params[$field->db_field_name . "_allow_ext"]);
          
          $allow_ext = str_ireplace(' ', '', $allow_ext);
          
          if($allow_ext != ""){ 
            $allow_ext_array = explode(',', $allow_ext);
          }else{
              $allow_ext_array = '';
          }

          $ext = $this->checkMimeTypeFromFiles($_FILES['new_upload_video'.$i]['type']);
          
          if($ext == 'unknown'){
            $ext = pathinfo($_FILES['new_upload_video'.$i]['name'], PATHINFO_EXTENSION);
            if(isset($allow_ext_array) && is_array($allow_ext_array) && array_search($ext, $allow_ext_array) === false){
              echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                    window.history.go(-1); </script>\n";
              //exit;
            }
          }else{
            if(isset($allow_ext_array) && is_array($allow_ext_array)){
                $temp_array = array_intersect($ext, $allow_ext_array) ;
            }else{
                $temp_array = array();
            }
            
            if(isset($allow_ext_array) && is_array($allow_ext_array) && empty($temp_array) ){
              echo "<script> alert('".cck_lang_text('COM_OS_CCK_EXT_NOT_SUPPORTED')." ".$allow_ext."'); 
                    window.history.go(-1); </script>\n";
              exit;
            }
          }

          if($max_upload_size != 0 && $_FILES['new_upload_video'.$i]['size'] > ($max_upload_size*1000000)){
             echo "<script> alert('". $_FILES['new_upload_video'.$i]['name'] ." ".cck_lang_text('COM_OS_CCK_VIDEO_FILE_TOO_LARGE')." " . $max_upload_size . "mb'); 
               window.history.go(-1); </script>\n";
             exit;
          }

        }

      }
      
    }

    // Forbidden string in extension (e.g. php matched .php, .xxx.php, .php.xxx and so on)
      // 'forbidden_extensions'       => array(
      //   'php', 'phps', 'pht', 'phtml', 'php3', 'php4', 'php5', 'php6', 'php7', 'inc', 'pl', 'cgi', 'fcgi', 'java', 'jar', 'py',

   
  }

  function quoteName($name){
    $return = $this->_db->quoteName($name);
    return $return;
  }

  function load($id = null, $bool = true){
    // var_dump(parent::load());
    // var_dump($this);
    if(!parent::load($id)){
    // parent::load($id);
    // var_dump($aaaa);
      echo $this->getError();
      // var_dump($this->getError()); exit;
    }
//    var_dump($this);
    if($this->fk_eid && $this->eiid){
        $query = "SELECT * FROM #__os_cck_content_entity_$this->fk_eid WHERE fk_eiid=$this->eiid";
        //var_dump($query); exit;
        $this->_db->setQuery($query);
        $fields_val = $this->_db->loadAssoc();
        $this->_field_value_list = $fields_val;
    }
//    var_dump($this);
//    var_dump($fields_val);
  }

  public function getReviews($parent_fields_from_params){
    global $limitstart, $input, $review_limit, $review_max_items;
    $limitstart_review = $input->get('start', false, 'INT');

    if($limitstart_review !== false){
      $limitstart  = $limitstart_review;
    }
    if($review_limit){
      $limit = $review_limit;
    }else{
      $limit = 0;
    } 
    if($review_max_items){
      $max_items = $review_max_items;
    } else{
      $max_items = 0;
    }
    
    $query = "SELECT COUNT(ei2.eiid) FROM #__os_cck_entity_instance as ei"
              ."\n LEFT JOIN #__os_cck_child_parent_connect as pc ON pc.fid_parent = ei.eiid"
              ."\n LEFT JOIN #__os_cck_entity_instance as ei2 ON pc.fid_child = ei2.eiid"
              ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = ei2.fk_lid"
              ."\n LEFT JOIN #__users as u ON u.id = ei2.fk_userid"
              ."\n WHERE fid_parent=$this->eiid AND l.type='review_instance' AND ei2.published = 1 AND ei2.approved = 1";
// echo $query; exit;
    $this->_db->setQuery($query);
    $total = $this->_db->loadResult();

    // var_dump($total);

    if($max_items != '0' && $max_items < $total ) {
      if($limit > $max_items )$limit = $max_items;
      $total = $max_items;
    }

    $pageNav = new os_libPagination($total, $limitstart, $limit);

    $query = "SELECT ei2.*,u.*,l.params FROM #__os_cck_entity_instance as ei"
              ."\n LEFT JOIN #__os_cck_child_parent_connect as pc ON pc.fid_parent = ei.eiid"
              ."\n LEFT JOIN #__os_cck_entity_instance as ei2 ON pc.fid_child = ei2.eiid"
              ."\n LEFT JOIN `#__os_cck_content_entity_$this->fk_eid` as instance ON instance.`fk_eiid` = ei2.eiid "
              ."\n LEFT JOIN #__os_cck_layout as l ON l.lid = ei2.fk_lid"
              ."\n LEFT JOIN #__users as u ON u.id = ei2.fk_userid"
              ."\n WHERE fid_parent=$this->eiid AND l.type='review_instance' AND ei2.published = 1 AND ei2.approved = 1 ";
              //ORDER BY ei2.eiid DESC
// var_dump($parent_fields_from_params);
    if(isset($parent_fields_from_params["fields"]["indexed_cck_review_order_by"])) { // if selected sortable field

      $orderby = (!empty($parent_fields_from_params["fields"]["sortType_cck_review_order_by"])) ? $parent_fields_from_params["fields"]["sortType_cck_review_order_by"] : 'ASC';
      if($orderby != 'RAND()') {
        
          if (isset($parent_fields_from_params["views"]["selected"]) && !empty($parent_fields_from_params["views"]["selected"])) {
            // echo '22222222222222'; exit;
              $index = 0;
              // var_dump($fields_from_params["fields"]["indexed_all_instance_order_by"]);
              

                
                if($orderby != 'RAND()') {
                    if ($parent_fields_from_params["views"]["selected"] == 'title') {

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

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

                        $query .= " ORDER BY ei2.hits $orderby";
                    } elseif ($parent_fields_from_params["views"]["selected"] == 'custom_order') {

                        $query .= ' ORDER BY ' . $parent_fields_from_params['views']['custom_order_by'][0] . " $orderby ";
                    } elseif (stripos($parent_fields_from_params["views"]["selected"], 'pricefield_number_') !== false) {

                        $query .= " AND price.fk_fid = " . str_replace('pricefield_number_', '', $parent_fields_from_params["views"]["selected"]) . " GROUP BY ei.eiid ORDER BY price.price_value $orderby";
                    } else {

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

              
          } elseif ($parent_fields_from_params["fields"]["indexed_all_instance_order_by"] == 'ceid') {
              $query .= " ORDER BY ei2.eiid $orderby ";
          } elseif ($parent_fields_from_params["fields"]["indexed_all_instance_order_by"] == 'title') {
              $query .= " ORDER BY ei2.title $orderby ";
          } elseif ($parent_fields_from_params["fields"]["indexed_all_instance_order_by"] == 'hits') {
              $query .= " ORDER BY ei2.hits $orderby ";
          } elseif ($parent_fields_from_params["fields"]["indexed_all_instance_order_by"] == 'custom_order') {
              $query .= ' ORDER BY ' . $parent_fields_from_params['views']['custom_order_by'][0] . " $orderby ";
          } elseif (isset($parent_fields_from_params["fields"]["indexed_all_instance_order_by"]) && stripos($parent_fields_from_params["fields"]["indexed_all_instance_order_by"], 'categoryfield') !== FALSE) {
              $query .= " ORDER BY cat.name $orderby ";
          } elseif (stripos($parent_fields_from_params["fields"]["indexed_all_instance_order_by"], 'pricefield_number_') !== false) {

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

                  $query .= " ORDER BY instance.`{$parent_fields_from_params["fields"]["indexed_all_instance_order_by"]}` $orderby ";



          }
      }else{
          $query .= " ORDER BY $orderby ";
      }
      
    }

    $query .= " LIMIT $pageNav->limitstart, $pageNav->limit ";
    // echo $query;
    $this->_db->setQuery($query);
    // var_dump($query); exit;
    $GLOBALS['review_pagenav'] = $pageNav;
    return array('reviews' => $this->_db->loadObjectList(), 'pagenav' => $pageNav);
  }

  /**
   * Binds a named array/hash to this object
   *
   * Can be overloaded/supplemented by the child class
   *
   * @access  public
   * @param $from mixed An associative array or object
   * @param $ignore mixed An array or space separated list of fields not to bind
   * @return  boolean
   */
  function bind($from, $ignore = array()){
    $fromArray = is_array($from);
    $fromObject = is_object($from);
    if (!$fromArray && !$fromObject) {
      $this->setError(get_class($this) . '::bind failed. Invalid from argument');
      return false;
    }
    if (!is_array($ignore)) {
      $ignore = explode(' ', $ignore);
    }
    foreach ($this->getProperties() as $k => $v) {
      // internal attributes of an object are ignored
      if (!in_array($k, $ignore)) {
        if ($fromArray && isset($from[$k])) {
            $this->$k = $from[$k];
        } else if ($fromObject && isset($from->$k)) {
            $this->$k = $from->$k;
        }
      }
    }
    return true;
  }
  
  function require_check(){
    $db = new os_cckDb();
     
    foreach ($this->_field_list as $field) {
      if($field->field_type == 'captcha_field' || $field->field_type == 'galleryfield')continue;
      if(!isset($this->_layout_params[$field->db_field_name.'_required']) || $this->_layout_params[$field->db_field_name.'_required'] != 'on' || !isset($_REQUEST['fi_'.$field->db_field_name])) continue;
      if($this->_layout_params[$field->db_field_name.'_published'] != 'on') continue;
      if($field->published == 0) continue;
      $field->value = '';
      
      foreach ($this->fields_data as $key => $var) {
        if($field->field_type == 'pricefield_number' && stripos($key, $field->db_field_name . '_') !== false){
          $field->value = $var;
        }
        
        if ($field->db_field_name == $key)
          $field->value = $var;
      }
      if($field->field_type=='filefield' || $field->field_type=='imagefield'){
        $file = new os_cckFile($db->_db);
        $old_data = $this->getFieldValue($field);
        if(empty($old_data) && (!$old_data['0']->fid && $_FILES['fi_'.$field->db_field_name]['error'] == 4)){
            
          return false;
        }
      }
      if($field->field_type=='videofield'){
        $old_data = $this->getFieldValue($field);
        
        if(empty($old_data[0]) && ($_FILES['fi_'.$field->db_field_name]['error'] == 4)){
            
          return false;
        }
      }
      if($field->field_type=='audio'){
        $old_data = $this->getFieldValue($field);
        if(empty($old_data['audio']) || ($_FILES['fi_'.$field->db_field_name]['error'] == 4)){
            
          return false;
        }
      }
      if($field->field_type == 'locationfield') {
        $adress = protectInjectionWithoutQuote('fi_'.$field->db_field_name . "_map_address");
        $vlat = protectInjectionWithoutQuote('fi_'.$field->db_field_name   . "_map_latitude");
        $vlong = protectInjectionWithoutQuote('fi_'.$field->db_field_name  . "_map_longitude");
        $zoom = protectInjectionWithoutQuote('fi_'.$field->db_field_name   . "_map_zoom");
        if(empty($adress)
          || empty($vlat)
          || empty($vlong)
          || empty($zoom)){
            
          return false;
      }
      }
      if ($field->field_type == 'text_url') {
        if(strlen($field->value) < 8){
            var_dump($field); exit;
          return false;
        }
      }
      if ($field->field_type == 'text_select_list') {
        if(empty($field->value) || $field->value === 0){
              
          return false;
        }
      }
      if ($field->field_type == 'categoryfield') {
        $categories = protectInjectionWithoutQuote("categories","");
        if(!isset($categories[0]) && empty($categories[0])){
          
          return false;
        }
      }
      
      if($field->field_type!='filefield'
        && $field->field_type!='text_single_checkbox_onoff'
        && $field->field_type!='text_radio_buttons'
        && $field->field_type!='locationfield'
        && $field->field_type!='text_select_list'
        && $field->field_type!='imagefield'
        && $field->field_type!='text_url'
        && $field->field_type!='videofield'
        && $field->field_type!='audiofield'
        && $field->field_type!='categoryfield'
        && !$field->value && $field->value !== '0' && isset($_REQUEST['fi_'.$field->db_field_name])){
          
          return false;
      }
    }
    return true;
  }
  
  /**
   * Inserts a new row if id is zero or updates an existing row in the database table
   *
   * Can be overloaded/supplemented by the child class
   *
   * @access public
   * @param boolean If false, null object variables are not updated
   * @return null|string null if successful otherwise returns and error message
   */
  function store($updateNulls = false){
    global $app, $global_settings, $input;
    // var_dump($this); exit;
    if(!parent::store()){
        // var_dump($this);
        // var_dump($this->getError()); exit;
        echo $this->getError();
        return false;
    }
    $query = "SHOW TABLES LIKE '".$this->_db->getprefix()."os_cck_content_entity_".$this->fk_eid."' ";
    $this->_db->setquery($query);
    $table_exists = $this->_db->loadresult();
    if (isset($this->_price_fields)){
        foreach ($this->_price_fields as $price_field){
            $query = "SELECT * FROM #__os_cck_content_instances_price WHERE fk_fid='$price_field->fid' AND fk_eiid='$this->eiid' AND ordering='$price_field->ordering'";
            $this->_db->setQuery($query);
            $result = $this->_db->loadResult();
            if($price_field->quantity == null){
                $price_field->quantity = 0;
            }
            if($price_field->price_value == ''){
                $price_field->price_value = 0;
            }
            if(!$result){

                $query = "INSERT INTO #__os_cck_content_instances_price (fk_eid, fk_eiid, fk_fid, price_name, price_value, quantity, ordering) "
                    . "VALUE ('$this->fk_eid', '$this->eiid', '$price_field->fid', '$price_field->price_name', '$price_field->price_value', '$price_field->quantity', '$price_field->ordering')";
            }else{
                
                $query = "UPDATE #__os_cck_content_instances_price SET "
                        . " fk_eid = '$this->fk_eid', "
                        . " fk_eiid = '$this->eiid', "
                        . " fk_fid = '$price_field->fid', "
                        . " price_name = '$price_field->price_name', "
                        . " price_value = '$price_field->price_value', "
                        . " quantity = '$price_field->quantity', "
                        . " ordering = '$price_field->ordering' "
                        . " WHERE fk_fid='$price_field->fid' AND fk_eiid='$this->eiid'  AND ordering='$price_field->ordering'";
                //var_dump($query);
            }
//            print_r ($query); exit;
//            var_dump($price_field->price_value); exit;
            $this->_db->setQuery($query);
            $this->_db->execute();
        }
    }
    
//    if (isset($this->_child_entity_fields)){
//                
//        foreach($this->_child_entity_fields as $key => $child_entity_fields){
//            $query = "DELETE FROM #__os_cck_child_parent_connect WHERE fid_parent='$this->eiid' AND media_type='$key'";
//            $this->_db->setQuery($query);
//            $this->_db->execute();
//            foreach($child_entity_fields as $child_entity_field){
//                
//                $query = "INSERT INTO #__os_cck_child_parent_connect (fid_parent, fid_child, media_type)"
//                        . "VALUE('$this->eiid', '$child_entity_field', '$key')"; 
//                $this->_db->setQuery($query);
//                $this->_db->execute();
//            }
//        }
//        //var_dump($this->_child_entity_fields); exit;
//    }
//    
    if (isset($this->_child_entity_fields)){
        foreach($this->_child_entity_fields as $key => $child_entity_fields){
//            var_dump($key);
//            var_dump($child_entity_fields);
            foreach($child_entity_fields as $child_entity_field){
                //var_dump($child_entity_field);
                $query = "SELECT COUNT(*) FROM #__os_cck_child_parent_connect WHERE fid_parent='$this->eiid' AND media_type='$key'";
                $this->_db->setQuery($query);
                $count = $this->_db->loadResult();
                //var_dump($count);
                if($child_entity_field > 0){
                    
                    if($count > 0){
                        $query = "UPDATE #__os_cck_child_parent_connect SET "
                                . " fid_parent = '$this->eiid', "
                                . " fid_child = '$child_entity_field', "
                                . " media_type = '$key' "
                                . " WHERE fid_parent='$this->eiid' AND media_type='$key'";
                    }else{

                        $query = "INSERT INTO #__os_cck_child_parent_connect (fid_parent, fid_child, media_type)"
                                . "VALUE('$this->eiid', '$child_entity_field', '$key')"; 
                    }
                    $this->_db->setQuery($query);
                    $this->_db->execute();
                }else{
                    if($count > 0){
                        $query = "DELETE FROM #__os_cck_child_parent_connect WHERE fid_parent='$this->eiid' AND media_type='$key'";
                        $this->_db->setQuery($query);
                        $this->_db->execute();
                    }
                }
            }
        }
    }
    
    //exit;
    if ($table_exists) {
      $query = " SELECT * FROM #__os_cck_content_entity_" . $this->fk_eid . " WHERE fk_eiid='" . $this->eiid . "' ";
      $this->_db->setQuery($query);
      $result = $this->_db->loadResult();
      if (!$result) {
          // var_dump($this); exit;
        $query = " INSERT INTO #__os_cck_content_entity_" . $this->fk_eid . " SET fk_eiid='" . $this->eiid . "' ";
        $this->_db->setQuery($query);
        $this->_db->execute();
      }
    }

    if(isset($this->_field_list)){
      foreach ($this->_field_list as $field) {
  	    if($field->published == 0) continue;
          $field->value = '';
        foreach ($this->fields_data as $key => $var) {
          if ($field->db_field_name == $key)
            $field->value = $var;
        }
        
        if($field->field_type == 'categoryfield'){
          $query = " DELETE FROM  #__os_cck_categories_connect WHERE fk_eiid='" . $this->eiid . "' ";
          $this->_db->setQuery($query);
          
          try {
              $this->_db->execute();
          } catch (RuntimeException $e) {
              echo $e->getMessage();
          }
          //echo $this->_db->getErrorMsg();
          if (count($this->categories) > 0) {
            $insert = array();
            foreach ($this->categories as $temp) {
              $insert[] = " ( " . $this->eiid . ", " . $temp . " ) ";
            }
            $query = " INSERT INTO #__os_cck_categories_connect (fk_eiid, fk_cid) VALUES " . implode(", ", $insert);
            $this->_db->setQuery($query);
            $this->_db->execute();
          }
        }
        
        if ($field->field_type == 'text_url') {
          if(strlen($field->value) < 8)$field->value = '';
        }
        if($field->field_type == 'decimal_textfield'){
          if(empty($field->value) && $field->value != '0'){
            $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid . 
              " SET " . $this->_db->quoteName($field->db_field_name) . "= NULL WHERE fk_eiid='" . $this->eiid . "' ";
            $this->_db->setQuery($query);
            $this->_db->execute();
            continue;                       
          }
          if(isset($this->instance_currency) && !empty($this->instance_currency) && $this->instance_currency != ''){
              $query = " UPDATE #__os_cck_entity_instance" . 
              " SET instance_currency= '" . $this->instance_currency . "'  WHERE eiid='" . $this->eiid . "' ";
      //var_dump($query); exit;
            $this->_db->setQuery($query);
            $this->_db->execute();
          }
         
        }
        
        if ($field->field_type == 'datetime_popup') {
            
          if(isset($global_settings['default_field_value']) && $global_settings['default_field_value'] == 'CHANGE'){
            $date = new DateTime();
            $field->value = $date->format('Y-m-d H:i:s');
          }
          if(isset($global_settings['default_field_value']) && $global_settings['default_field_value'] == 'CREATE'){
            $query = " SELECT created FROM #__os_cck_entity_instance WHERE eiid='" . $this->eiid . "' ";
            $this->_db->setQuery($query);
            $field->value = $this->_db->loadResult();
          }
          
          if(trim($field->value) == '' || trim($field->value) == '00:00:00'){
              $field->value = '0000-00-00 00:00:00';
          }else{
//              var_dump($field->value); exit;
              $field->value = date('Y-m-d H:i:s',strtotime($field->value));  
          }
          
          
        }
        
        if ($field->field_type == 'filefield' || $field->field_type == 'imagefield') { 
            
            
          if ($field != $this->_insertFiles($field)){
            
              
              continue;
          }
        }
        
        if ($field->field_type == 'locationfield') {
          $adress = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_address",null,"STRING"));
          $country = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_country",null,"STRING"));
          $city = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_city",null,"STRING"));
          $region = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_region]",null,"STRING"));
          $zip = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_zip_code",null,"STRING"));
          $latitude = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_latitude",0,"STRING"));
          $longitude = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_longitude",0,"STRING"));
          $zoom = $this->_db->Quote($app->input->get('fi_'.$field->db_field_name . "_map_zoom",0,"STRING"));
          
          $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid . " SET " .
              $this->_db->quoteName($field->db_field_name."_vlat")." = ".$latitude.",".
              $this->_db->quoteName($field->db_field_name."_vlong")."=".$longitude.",".
              $this->_db->quoteName($field->db_field_name."_zoom")."=".$zoom.",".
              $this->_db->quoteName($field->db_field_name."_country")."=".$country.",".
              $this->_db->quoteName($field->db_field_name."_city")."=".$city.",".
              $this->_db->quoteName($field->db_field_name."_region")."=".$region.",".
              $this->_db->quoteName($field->db_field_name."_zipcode")."=".$zip.",".              
              $this->_db->quoteName($field->db_field_name."_address")."=".$adress."  ".
                " WHERE fk_eiid='" . $this->eiid . "' ";
          $this->_db->setQuery($query);
          $this->_db->execute();
        } else if($field->field_type == 'videofield'){ 
      ////////////////////////////STORE video/track functions START\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
          for ($j = 1;isset($_FILES[$field->fid . '_new_upload_video' . $j]) 
            || array_key_exists($field->fid . '_new_upload_video_url' . $j, $_POST) 
            || array_key_exists($field->fid . '_new_upload_video_youtube_code' . $j, $_POST);$j++) { 
              
              $video_name = '';
              if (isset($_FILES[$field->fid . '_new_upload_video' . $j]) && $_FILES[$field->fid . '_new_upload_video' . $j]['name'] != "") {
                //storing e-Document
                //$video = protectInjectionWithoutQuote($field->fid . '_new_upload_video' . $j, '', 'files');
                $video = $input->files->get($field->fid . '_new_upload_video' . $j, '');
                $ext = pathinfo($video['name'], PATHINFO_EXTENSION);
                $type = $this->checkMimeType($ext);
                $code = $this->guid();
                $video_name = $code . '_' . $this->filter($video['name']);
                if (intval($video['error']) > 0 && intval($video['error']) < 4) {
                  echo "<script> alert('" . COM_OS_CCK_LABEL_VIDEO_UPLOAD_ERROR . " - " .
                                         $video_name . "'); window.history.go(-1); </script>\n";
                  exit();
                } else if (intval($video['error']) != 4) {
                  $video_new = JPATH_SITE . '/components/com_os_cck/files/video/'  . $video_name;
                  if (!move_uploaded_file($video['tmp_name'], $video_new)) {
                    echo "<script> alert('" . COM_OS_CCK_LABEL_VIDEO_UPLOAD_ERROR . " - " .
                                         $video_name . "'); window.history.go(-1); </script>\n";
                    exit();
                  }
                  $this->saveVideos($video_name, $this->eiid, $type, $field->fid);
                }
              }
              if (array_key_exists($field->fid . '_new_upload_video_url' . $j, $_POST) && $_POST[$field->fid . '_new_upload_video_url' . $j] != "") {
                  
                //$uploadVideoURL = protectInjectionWithoutQuote($field->fid . '_new_upload_video_url' . $j, '', 'post');
                $uploadVideoURL = $input->get($field->fid . '_new_upload_video_url' . $j, '', 'STRING');
                
                $uploadVideoURL = strip_tags(trim($uploadVideoURL));
                
                $end = explode(".", $uploadVideoURL);
                
                $ext = end($end);
                
                $type = $this->checkMimeType($ext);
                
                if(empty($video_name) && !empty($uploadVideoURL)){
                    $this->saveVideos($uploadVideoURL, $this->eiid, $type, $field->fid);
                } 
              }
              if (array_key_exists($field->fid . '_new_upload_video_youtube_code' . $j, $_POST) 
                && $_POST[$field->fid . '_new_upload_video_youtube_code' . $j] != "") {
                  //$uploadVideoYoutubeCode = protectInjectionWithoutQuote($field->fid . '_new_upload_video_youtube_code' . $j, '', 'post');
                  $uploadVideoYoutubeCode = $input->get($field->fid . '_new_upload_video_youtube_code' . $j, '');
                  $uploadVideoYoutubeCode = strip_tags(trim($uploadVideoYoutubeCode));
                  $this->saveYouTubeCode($uploadVideoYoutubeCode, $this->eiid, $field->fid);
              }
          }

          for ($j = 1;isset($_FILES[$field->fid . '_new_upload_track' . $j]) 
            || array_key_exists($field->fid . '_new_upload_track_url' . $j, $_POST);$j++) { 
              $track_name = '';
              if (isset($_FILES[$field->fid . '_new_upload_track' . $j]) && $_FILES[$field->fid . '_new_upload_track' . $j]['name'] != "") {
                //storing e-Document
                //$track = protectInjectionWithoutQuote($field->fid . '_new_upload_track' . $j, '', 'files');
                  $track = $input->files->get($field->fid . '_new_upload_track' . $j, '');
                  // var_dump($code);
                  // 
                $code = $this->guid();
                // var_dump($track); exit;
                $track_name = $code . '_' . $this->filter($track['name']);
                
                if (intval($track['error']) > 0 && intval($track['error']) < 4) {
                  echo "<script> alert('" . COM_OS_CCK_LABEL_TRACK_UPLOAD_ERROR . " - " .
                                       $track_name . "'); window.history.go(-1); </script>\n";
                  exit();
                } else if (intval($track['error']) != 4) {
                  $track_new = JPATH_SITE .'/components/com_os_cck/files/track/'. $track_name;
                  if (!move_uploaded_file($track['tmp_name'], $track_new)) {
                    echo "<script> alert('" . COM_OS_CCK_LABEL_TRACK_UPLOAD_ERROR . " - " .
                                         $track_name . "'); window.history.go(-1); </script>\n";
                    exit();
                  }
                }
              }
              if (array_key_exists($field->fid . '_new_upload_track_kind' . $j, $_POST) 
                && $_POST[$field->fid . '_new_upload_track_kind' . $j] != "") {
                  //$uploadTrackKind = protectInjectionWithoutQuote($field->fid . '_new_upload_track_kind' . $j, '', 'post');
                  $uploadTrackKind = $input->get($field->fid . '_new_upload_track_kind' . $j, '');
                  $uploadTrackKind = strip_tags(trim($uploadTrackKind));
              }
              if (array_key_exists($field->fid . '_new_upload_track_scrlang' . $j, $_POST) 
                && $_POST[$field->fid . '_new_upload_track_scrlang' . $j] != "") {
                  //$uploadTrackScrlang = protectInjectionWithoutQuote($field->fid . '_new_upload_track_scrlang' . $j, '', 'post');
                  $uploadTrackScrlang = $input->get($field->fid . '_new_upload_track_scrlang' . $j, '');
                  $uploadTrackScrlang = strip_tags(trim($uploadTrackScrlang));
              }
              if (array_key_exists($field->fid . '_new_upload_track_label' . $j, $_POST) 
                && $_POST[$field->fid . '_new_upload_track_label' . $j] != "") {
                  //$uploadTrackLabel = protectInjectionWithoutQuote($field->fid . '_new_upload_track_label' . $j, '', 'post');
                  $uploadTrackLabel = $input->get($field->fid . '_new_upload_track_label' . $j, '');
                  $uploadTrackLabel = strip_tags(trim($uploadTrackLabel));
              }
              if (array_key_exists($field->fid . '_new_upload_track_url' . $j, $_POST) 
                  && $_POST[$field->fid . '_new_upload_track_url' . $j] != "") {
                //$uploadTrackURL = protectInjectionWithoutQuote($field->fid . '_new_upload_track_url' . $j, '', 'post');
                $uploadTrackURL = $input->get($field->fid . '_new_upload_track_url' . $j, '', 'STRING');
                $uploadTrackURL = strip_tags(trim($uploadTrackURL));

                if (empty($track_name) && !empty($uploadTrackURL))
                  $this->saveTracks($this->eiid, $uploadTrackURL, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel, $field->fid);          
              }

              if (!empty($track_name)) 
                $this->saveTracks($this->eiid, $track_name, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel, $field->fid);
          }

      ////////////////////////////STORE video/track functions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
      ////////////////////////////DELETE video/track functions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
          $this->deleteTracks($this->eiid);
          $this->deleteVideos($this->eiid);
      ////////////////////////////DELETE video/track functions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
        }else if($field->field_type == 'audiofield'){
////////////////////////////STORE audio functions START\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
          for ($j = 1;isset($_FILES[$field->fid . '_new_upload_audio' . $j]) 
                || array_key_exists($field->fid . '_new_upload_audio_url' . $j, $_POST);$j++) {
            if (isset($_FILES[$field->fid . '_new_upload_audio' . $j]) && $_FILES[$field->fid . '_new_upload_audio' . $j]['name'] != "") {
              //storing e-Document
              $audio = $input->files->get($field->fid . '_new_upload_audio' . $j, '');
              $ext = pathinfo($audio['name'], PATHINFO_EXTENSION);
              $type = $this->checkMimeType($ext);
              $code = $this->guid();
              $audio_name = $code . '_' . $this->filter($audio['name']);
              //mime_content_type($file_name);
              //if( !isset($_FILES['new_upload_file'.$i]) ) continue;
              if (intval($audio['error']) > 0 && intval($audio['error']) < 4) {
                  echo "<script> alert('" . cck_lang_text('COM_OS_CCK_LABEL_AUDIO_UPLOAD_ERROR') . " - " . 
                    $audio_name . "'); window.history.go(-1); </script>\n";
                  exit();
              } else if (intval($audio['error']) != 4) {
                  $audio_new = JPATH_SITE . '/components/com_os_cck/files/audio/' . $audio_name;
                  if (!move_uploaded_file($audio['tmp_name'], $audio_new)) {
                      echo "<script> alert('" . cck_lang_text('COM_OS_CCK_LABEL_AUDIO_UPLOAD_ERROR') . " - " . 
                        $audio_name . "'); window.history.go(-1); </script>\n";
                      exit();
                  }
                  $this->saveAudios($audio_name, $this->eiid, $type, $field->fid);
              }
            }
            if (array_key_exists($field->fid . '_new_upload_audio_url' . $j, $_POST) 
                  && $_POST[$field->fid . '_new_upload_audio_url' . $j] != "") {
              if (isset($_FILES[$field->fid . '_new_upload_audio' . $j]) 
                    && $_FILES[$field->fid . '_new_upload_audio' . $j]['name'] == "") {
                  //$uploadAudioURL = protectInjectionWithoutQuote($field->fid . '_new_upload_audio_url' . $j, '', 'post');
                  $uploadAudioURL = $input->get($field->fid . '_new_upload_audio_url' . $j, '', 'STRING');
                  $uploadAudioURL = strip_tags(trim($uploadAudioURL));
                  $end = explode(".", $uploadAudioURL);
                  $ext = end($end);
                  $type = $this->checkMimeType($ext);
                  $this->saveAudios($uploadAudioURL, $this->eiid, $type, $field->fid);
              }
            }
          }
////////////////////////////STORE audio functions STOP\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
////////////////////////////DELETE AUDIO functions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
          $this->deleteAudios($this->eiid);
////////////////////////////DELETE AUDIO functions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
        }else if ($field->field_type == "imagefield"
                  || $field->field_type == "filefield"
                ) {  
            $old_data = $this->getFieldValue($field);
            if($field->field_type == "imagefield" && $field->fid == ''){
                $field->fid = '0';
            }
          $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid . " SET " .
              $field->db_field_name . "_fid  ='" . $field->fid . "' , " .
              $field->db_field_name . "_list ='0' , " .
              $field->db_field_name . "_data  =" . $this->_db->quote($field->value) . "  " .
              " WHERE fk_eiid='" . $this->eiid . "' ";
//      var_dump($query); exit;
          $this->_db->setQuery($query);
          $this->_db->execute();
         
        }elseif ($field->field_type == "galleryfield") {
            $old_data = $this->getFieldValue($field);
          if($old_data['0']->data != $field->value){
              $this->deleteGalleryImage($field);
          }
          
          $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid . " SET " .
              $field->db_field_name . "_fid  ='" . $field->fid . "' , " .
              $field->db_field_name . "_list ='0' , " .
              $field->db_field_name . "_data  ='" . $field->value . "'  " .
              " WHERE fk_eiid='" . $this->eiid . "' ";
          //var_dump($query); exit;
          $this->_db->setQuery($query);
          $this->_db->execute();
                
        }elseif ($field->field_type == "text_select_list"){
            
//            if(is_array($field->value) && $field->value[0] == '0'){
//                unset($field->value[0]);
//            }
            
            $select_value = json_encode($field->value);
            
            $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid . 
            " SET " . $this->_db->quoteName($field->db_field_name) . "=" . $this->_db->Quote($select_value) . 
            " WHERE fk_eiid='" . $this->eiid . "' ";
          $this->_db->setQuery($query);
          $this->_db->execute();
            //var_dump($select_value); exit;
        }elseif ($field->field_type == "text_radio_buttons"){
            if($field->value != '') {
                if ($field->value == 0) {
                    $field->value = '-1';
                }
                $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid .
                    " SET " . $this->_db->quoteName($field->db_field_name) . "=" . $this->_db->Quote($field->value) .
                    " WHERE fk_eiid='" . $this->eiid . "' ";
                $this->_db->setQuery($query);
                $this->_db->execute();
            }
        }elseif(stripos($field->field_type, 'pricefield') !== FALSE){
            
        }
       
        else{ 
//            var_dump($field->value);
            if($field->field_type == "text_single_checkbox_onoff" && $field->value == ''){
                 $field->value = 0;
             }elseif($field->field_type == 'text_textfield' || $field->field_type == 'text_textarea'){

              if ($field->field_type == 'text_textfield' || $field->field_type == 'text_textarea') {
               if(isset($this->_layout_params[$field->db_field_name . '_cut_tags'])
                       && $this->_layout_params[$field->db_field_name . '_cut_tags'] == 1){
                         $field->value = strip_tags($field->value);
                   
                       }
               }
               
          }
            //  echo '11111111111111111 ';
            //if($field->value != ''){ //cannot enter null value while editing instance
//            var_dump($field->value);
              $query = " UPDATE #__os_cck_content_entity_" . $this->fk_eid . 
                " SET " . $this->_db->quoteName($field->db_field_name) . "=" . $this->_db->Quote($field->value) . 
                " WHERE fk_eiid='" . $this->eiid . "' ";
//               echo $query; echo '<br>'; 
              $this->_db->setQuery($query);
              $this->_db->execute();
            //}
        }
      }
     
//      exit;
    }
    
    //end foreach _list_field
  }
  
  function deleteGalleryImage($field){
      $old_data = $this->getFieldValue($field);
      $img_path = JPATH_SITE . '/images/com_os_cck' . $field->fid . '/original/';
      $tmb_path = JPATH_SITE . '/images/com_os_cck' . $field->fid . '/thumbnail/';
      
      $new_value = json_decode($field->value);
      // var_dump($old_data); exit;
      if($old_data['0']->data){
        $old_value = json_decode($old_data['0']->data);
      }else{
        $old_value = array();
      }
      
      $new_files = array();
      if($new_value){
          foreach ($new_value as $value){
              $new_files[] = $value->file;
          }
      }
      $old_files = array();
      foreach ($old_value as $value){
          $old_files[] = $value->file;
      }
      
      $images = array();
      foreach ($old_files as $value){
          if(!in_array($value, $new_files)){
              $images[] = $img_path . $value;
              $images[] = $tmb_path . $value;
          }
      }
      
      foreach ($images as $file){
          if(file_exists($file)){
              unlink($file);
          }
      }
     
  }
  function _insertFiles($field){
      global $os_cck_configuration;
      $db = new os_cckDb();
      $file = new os_cckFile($db->_db);
      @ $uploadPath = ($field->field_type == 'imagefield') ?
          JPATH_SITE . '/components/com_os_cck/files/images/' .
                      $field->db_field_name . "_" . time() . "_" .
                      $_FILES["fi_" . $field->db_field_name]['name'] :
          JPATH_SITE . '/components/com_os_cck/'.$os_cck_configuration->get('filehosting_folder', 'files').'/' . $field->db_field_name . "_" .
                      time() . "_" . $_FILES["fi_" . $field->db_field_name]['name'];
              
      $old_data = $this->getFieldValue($field);
      
      $file = $this->_saveFile($field, $uploadPath, '', $old_data[0]);
      
      if($file){
          $field->fid = $file->fid;
      }else{
          if($old_data[0]->fid){
              $field->fid = $old_data[0]->fid;
          }
      }
      //$field->fid = ($file) ? $file->fid : $old_data[0]->fid;
      
      $field->value = ($file) ? $file->filepath : $old_data[0]->data;
      return $field;
  }

  function _saveFile($field, $uploadPath, $multiple_num, $old_data){
      //prepare for multiple or not multiple
      $fieldName = $field->db_field_name;
      $db = new os_cckDb();
      $file = new os_cckFile($db->_db);
      // var_dump($old_data);
      
      if (isset($_REQUEST["delete_fi_" . $fieldName]) || isset($_REQUEST["delete_fi_" . $fieldName . "_" . $multiple_num])) {
          $file_del = ($multiple_num === '') ?
              protectInjectionWithoutQuote("delete_fi_" . $fieldName) : protectInjectionWithoutQuote("delete_fi_" . $fieldName . "_" . $multiple_num);
          //var_dump($_REQUEST["delete_fi_" . $fieldName]);
          if (isset($file_del) && $file_del != '') {
            
              $file->load($old_data->fid);
              
              $file->delete();
              $file->fid = '';
              $file->filepath = '';
              $file->filename = '';
              return $file;
          }
      }
      
      $fieldName = "fi_" . $fieldName;
      // var_dump($field);
      if(($field->field_type == 'imagefield' || $field->field_type == 'filefield')
         && (!empty($_FILES[$fieldName]['name'] ) && $old_data->fid)){ 
          // echo '33333333333'; exit;
          $file->load($old_data->fid);
          $file->delete();
          $file->fid = '';
          $file->filepath = '';
          $file->filename = '';
      }
      // echo '22222222222222'; exit;
      if (!(isset($_FILES[$fieldName]) || isset($_FILES[$fieldName . "_" . $multiple_num]['name'])))
          return false;
      
      $array['error'] = ($multiple_num === '') ? $_FILES[$fieldName]['error'] : $_FILES[$fieldName . "_" . $multiple_num]['error'];
      $array['name'] = ($multiple_num === '') ? $_FILES[$fieldName]['name'] : $_FILES[$fieldName . "_" . $multiple_num]['name'];
      $array['tmp_name'] = ($multiple_num === '') ? $_FILES[$fieldName]['tmp_name'] : $_FILES[$fieldName . "_" . $multiple_num]['tmp_name'];
      $array['type'] = ($multiple_num === '') ? $_FILES[$fieldName]['type'] : $_FILES[$fieldName . "_" . $multiple_num]['type'];
      $array['size'] = ($multiple_num === '') ? $_FILES[$fieldName]['size'] : $_FILES[$fieldName . "_" . $multiple_num]['size'];
      
      if ($array['name'] == '')
          return false;
      
      if ($array['error'] > 0) {
          switch ($array['error']) {
              case 1:
                  echo cck_lang_text('COM_OS_CCK_LABEL_FILE_TO_LARGE_PHP');
                  return false;
              case 2:
                  echo cck_lang_text('COM_OS_CCK_LABEL_FILE_TO_LARGE_HTML');
                  return false;
              case 3:
                  echo cck_lang_text('COM_OS_CCK_LABEL_ERROR_PARTIAL_UPLOAD');
                  return false;
              case 4:
                  echo cck_lang_text('COM_OS_CCK_LABEL_ERROR_NO_FILE');
                  return false;
          }
      }
      //Dobavleny parametry dlya otklyu4eniya proverki vozmojnyh vredonosnyh filov Joomla
      //if (!JFile::upload($array['tmp_name'], $uploadPath)) {
      if (!JFile::upload($array['tmp_name'], $uploadPath, false, true)) {
          echo cck_lang_text('COM_OS_CCK_LABEL_ERROR_MOVING_FILE');
          echo "<pre>";
          var_dump($fieldName);
          print_r($_FILES);
          print_r("----" . $uploadPath);
          print_r($array);
          echo "</pre>";
          return false;
      }

      $file->filename = $array['name'];
      $file->filepath = str_replace(JPATH_SITE, '', $uploadPath);
      $file->filemime = $array['type'];
      $file->filesize = $array['size'];
      $file->status = 1;
      $file->timestamp = time();
      $file->store();
      return $file;
  }

//  function getFields( $reload = false ){
//    $query = "SELECT * FROM #__os_cck_entity_field WHERE published='1' AND fk_eid='" . $this->fk_eid .
//       "' ORDER BY fk_eid, fid ";
//    $this->_db->setQuery($query);
//    return $this->_db->loadObjectList();
//  }

  function getField($fid){
    
    $query = "SELECT * FROM #__os_cck_entity_field WHERE fid = '".$fid."'";
    $this->_db->setQuery($query);
    return $this->_db->loadObject();
    
  }

  function getSelectFieldValue($fid){
    if(!$this->eiid) return '';

      $query = " SELECT " . $this->_db->quoteName('text_select_list_'.(int)$fid) . 
        " AS data FROM #__os_cck_content_entity_" . $this->fk_eid . " WHERE fk_eiid='" . $this->eiid . "' ";
      $this->_db->setQuery($query);
      $result = $this->_db->loadResult();
    
    return $result;
  }


  function getFieldValue($field, $entity_type = 'os_cck_entity', $user_profile_form = '', $user = '', $child_id = false, $parent_instance = false, $related_fields = false){
      global $entityFieldLists;
//      $query = "SELECT type FROM #__os_cck_entity WHERE eid=$this->fk_eid";
//      $this->_db->setQuery($query);
//      $entity_type = $this->_db->loadResult();
        
      if($entity_type == 'os_cck_entity'){
            if(!$this->eiid)return '';
            if ($field->field_type == 'videofield') {
              $query = " SELECT * FROM #__os_cck_video_source ".
              " WHERE fk_eiid='" . $this->eiid . "' AND fk_fid='$field->fid'  ORDER BY id";
              $this->_db->setQuery($query);
              $result[0] = $this->_db->loadObjectList();
              $query = " SELECT * FROM #__os_cck_track_source " .
                " WHERE fk_eiid='" . $this->eiid . "' AND fk_fid='$field->fid'  ORDER BY id";
              $this->_db->setQuery($query);
              $result[1] = $this->_db->loadObjectList();
            }elseif ($field->field_type == 'audiofield') {
              $query = " SELECT * FROM #__os_cck_audio_source " .
                " WHERE fk_eiid='" . $this->eiid . "' AND fk_fid='$field->fid'  ORDER BY id";
              $this->_db->setQuery($query);
              $result = $this->_db->loadObjectList();
            }elseif ($field->field_type == 'categoryfield') {
              $query = "SELECT cc.title AS title ,cc.cid as catid, cc.image as image" .
                  "\n FROM #__os_cck_entity_instance AS jei " .
                  "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
                  "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
                  "\n WHERE jei.eiid=$this->eiid";
              if(property_exists($field, 'sorting')){
                $query .= " ORDER BY cc.".$field->sorting;
              }else{
                $query .= " ORDER BY cc.ordering";
              }    
              $this->_db->setQuery($query);
              $result = $this->_db->loadObjectList();
            }elseif ($field->field_type == 'imagefield' || $field->field_type == 'filefield') {
                
                if(isset($this->_field_value_list[$field->db_field_name.'_data'])){
                    $result = array();
                    $temp_result = new stdClass();
                    $temp_result->data = $this->_field_value_list[$field->db_field_name.'_data'];
                    $temp_result->fid = $this->_field_value_list[$field->db_field_name.'_fid'];
                    $result[] = $temp_result;
                }else{
//                    var_dump($field); exit;
                    $query = " SELECT " . $field->db_field_name . "_data AS data, " . 
                    $field->db_field_name . "_fid AS fid FROM #__os_cck_content_entity_" . $this->fk_eid . 
                    " WHERE fk_eiid='" . $this->eiid . "' ";
                    $this->_db->setQuery($query);
                    $result = $this->_db->loadObjectList();
                    
                }
            }elseif ($field->field_type == 'locationfield'){
                if(isset($this->_field_value_list[$field->db_field_name.'_address'])){
                    $result = array();
                    $temp_result = new stdClass();
                    $temp_result->address = $this->_field_value_list[$field->db_field_name.'_address'];
                    $temp_result->vlat = $this->_field_value_list[$field->db_field_name.'_vlat'];
                    $temp_result->vlong = $this->_field_value_list[$field->db_field_name.'_vlong'];
                    $temp_result->zoom = $this->_field_value_list[$field->db_field_name.'_zoom'];
                    $temp_result->country = $this->_field_value_list[$field->db_field_name.'_country'];
                    $temp_result->region = $this->_field_value_list[$field->db_field_name.'_region'];
                    $temp_result->city = $this->_field_value_list[$field->db_field_name.'_city'];
                    $temp_result->zipcode = $this->_field_value_list[$field->db_field_name.'_zipcode'];
                    $result[] = $temp_result;
                }else{
                      $query = " SELECT ".$field->db_field_name . "_address AS address, ".
                          $field->db_field_name . "_vlat AS vlat, ".
                          $field->db_field_name . "_vlong AS vlong, ".
                          $field->db_field_name . "_zoom AS zoom, ".
                          $field->db_field_name . "_country AS country, ".
                          $field->db_field_name . "_region AS region, ".
                          $field->db_field_name . "_city AS city, ".
                          $field->db_field_name . "_zipcode AS zipcode".
                          " FROM #__os_cck_content_entity_" . $this->fk_eid . 
                          " WHERE fk_eiid='" . $this->eiid . "' ";
                      $this->_db->setQuery($query);
                      $result = $this->_db->loadObjectList();
                }
            }elseif ($field->field_type == 'galleryfield'){
                if(isset($this->_field_value_list[$field->db_field_name.'_data'])){
                    $result = array();
                    $temp_result = new stdClass();
                    $temp_result->data = $this->_field_value_list[$field->db_field_name.'_data'];
                    $temp_result->fid = $this->_field_value_list[$field->db_field_name.'_fid'];
                    $result[] = $temp_result;
                }else{
                      $query = " SELECT " . $field->db_field_name . "_data AS data, " . 
                        $field->db_field_name . "_fid AS fid FROM #__os_cck_content_entity_" . $this->fk_eid . 
                        " WHERE fk_eiid='" . $this->eiid . "' ";
                      $this->_db->setQuery($query);
                      $result = $this->_db->loadObjectList();
                }
            }elseif($field->field_type == 'pricefield_number' || $field->field_type == 'pricefield_select_list'
                    || $field->field_type == 'pricefield_radio_buttons'){
                $query = "SELECT * FROM #__os_cck_content_instances_price WHERE fk_fid='$field->fid' AND fk_eiid='$this->eiid' ORDER BY price_id ASC";
                $this->_db->setQuery($query);
                $result = $this->_db->loadObjectList();

            }else{
              if(isset($this->_field_value_list[$field->db_field_name])){
                  $result = array();
                  $temp_result = new stdClass();
                  $temp_result->data = $this->_field_value_list[$field->db_field_name];
                  $result[] = $temp_result;
              }else{
                  $query = " SELECT " . $this->_db->quoteName($field->db_field_name) . 
                    " AS data FROM #__os_cck_content_entity_" . $this->fk_eid . " WHERE fk_eiid='" . $this->eiid . "' ";
            //var_dump($field); exit;
                  $this->_db->setQuery($query);
                  $result = $this->_db->loadObjectList();
              }
            }
      }elseif($entity_type == 'joomla_user'){
          //var_dump($user);
          $result= array();
          
          $field_name = explode('_', str_replace('e-p-ch-'.$this->fk_eid.'_', '', $field->db_field_name));
          //var_dump($field_name); 
          if(!isset($field_name[1])){
              $val = new stdClass();
              $val->data = 'Error! Undefined field!';
              $result[] = $val;
              return $result;
          }
          
          $fieldset_name = $field_name[1];
          
          if($field_name[1] == 'standart'){
              if($field_name[2] == 'last'){
                  $field_name ='lastvisitDate';
              }elseif($field_name[2] == 'register'){
                  $field_name ='registerDate';
              }else{
                $field_name = $field_name[2];
              }
//              var_dump($user);
              $data = $user->$field_name;
//              var_dump($data);
//              var_dump($user);
              $val = new stdClass();
              $val->data = $data;
              $result[] = $val;
          }else{
              //var_dump($field_name);
              if(count($field_name) > 3){
                  $temp_field_name = '';
                  for($i=2; $i < count($field_name); $i++){
                      $temp_field_name .= $field_name[$i].'_';
                  }
                  $field_name = trim($temp_field_name, '_');
              }elseif(isset($field_name[2])){
                  //var_dump($field_name);
                  $field_name = $field_name[2];
              }
              
              $fields = $user_profile_form->getFieldset($fieldset_name);
              //var_dump($user);
              if(empty($fields)){
                  $val = new stdClass();
                  $val->data = 'ERROR!';
                  $result[] = $val;
              }
              foreach ($fields as $temp_field){
//                  var_dump($temp_field->fieldname);
//                  var_dump($field_name);
                  if($temp_field->fieldname == $field_name){
                      //var_dump($temp_field->value);
                      $val = new stdClass();
                      $val->data = $temp_field->value;
                      $result[] = $val;
                      break;
                  }
              }
              //var_dump($result);  
          }

      }elseif($entity_type == 'custom_sql'){
//          var_dump($this);
          $entity = new os_cckEntity($this->_db);
          
          $entity->load($this->fk_eid);
//          var_dump($this);
          $id_field = new stdClass();
          foreach($entityFieldLists[$entity->eid] as $temp_field){
            // var_dump($temp_field);
              if($temp_field->custom_field_type == 'id'){
                  $id_field = $temp_field;
              }
//              }elseif($temp_field->custom_field_type == 'child_id' && $child_id){
//                  $id_field = $temp_field;
//              }
          }
          // var_dump($id_field);
          if(property_exists($id_field, 'fid')){
              if(!$child_id && (!property_exists($this, 'related_parent_fid') || !$this->related_parent_fid)){
                $query = "SELECT t.`$field->fid` as data FROM ($entity->sql_select) as t WHERE t.$id_field->fid=$this->eiid";
              }else{
//                  var_dump($this);
                  $parent_entity = new os_cckEntity($this->_db);
                  $parent_eid = ($parent_instance) ? $parent_instance->fk_eid : $this->parent_eid;
                  $parent_entity->load($parent_eid);
                  $parent_eiid = ($parent_instance) ? $parent_instance->eiid : $this->parent_eiid;
                  $parent_id_field = $entityFieldLists[$parent_eid]['custom_sql_id'];
                  if(!property_exists($this, 'related_parent_fid') || !$this->related_parent_fid){
                    $related_fields = explode(';', $related_fields);
                  }else{
                      $related_fields = array();
                      $related_fields[] = $this->related_parent_fid;
                      $related_fields[] = $this->related_child_fid;
                  }
                  $query = "SELECT t.`$field->fid` as data FROM ($entity->sql_select) as t "
                          . " LEFT JOIN ($parent_entity->sql_select) as p ON t.$related_fields[1]=p.$related_fields[0]"
                          . " WHERE t.$id_field->fid=$this->eiid AND p.$parent_id_field->fid=$parent_eiid";
              }
             // echo $query . '<br>';
              $this->_db->setQuery($query);
              try {
                  $result = $this->_db->loadObjectList();
                  // var_dump($result);
              } catch (Exception $ex) {
                  // var_dump($field);
                  // echo $query;
                  // echo $aaaa;
                  // echo $ex->getMessage();
                  // var_dump($id_field); 
                  // exit;
              }
          }else{
              $result = [];
              $class = new stdClass();
              $class->data = '';
              $result[] = $class;
          }
          
          
      }
      
    return $result;
  }

    function getFieldValueCalImport($field_name, $location = false){

    if($field_name == '-1' || !$this->eiid){
      $emptyObject = new stdClass();
      $emptyObject->data = '';
      return $emptyObject;
    }
    if ($location){
      $query = " SELECT ".$field_name . "_address AS address, ".
          $field_name . "_vlat AS vlat, ".
          $field_name . "_vlong AS vlong, ".
          $field_name . "_zoom AS zoom, ".
          $field_name . "_country AS country, ".
          $field_name . "_region AS region, ".
          $field_name . "_city AS city, ".
          $field_name . "_zipcode AS zipcode".
          " FROM #__os_cck_content_entity_" . $this->fk_eid . 
          " WHERE fk_eiid='" . $this->eiid . "' ";
      $this->_db->setQuery($query);
      $result = $this->_db->loadObject();
    }else{
      $query = " SELECT " . $this->_db->quoteName($field_name) . 
        " AS data FROM #__os_cck_content_entity_" . $this->fk_eid . " WHERE fk_eiid='" . $this->eiid . "' ";
      $this->_db->setQuery($query);
      $result = $this->_db->loadObject();
    }

    return $result;
  }

  function delete($oid = null){
      global $entityFieldLists;
      $k = $this->_tbl_key;
      if ($oid) {
        $this->$k = $oid;
      }
      // var_dump($this);
      $query = " DELETE FROM  #__os_cck_categories_connect WHERE fk_eiid='" . $this->eiid . "' ";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }

        
      foreach ($entityFieldLists[$this->fk_eid] as $field) {
        if ($field->field_type == 'filefield' || $field->field_type == 'imagefield'
            || $field->field_type == 'videofield' || $field->field_type == 'audiofield' 
            || $field->field_type == 'galleryfield') {
          $file = new os_cckFile($this->_db);
          $value = $this->getFieldValue($field);
          //var_dump($value);
          if($field->field_type == 'videofield'){
            foreach ($value as $video) {
                foreach ($video as $vid){
                
                  if(file_exists(JPATH_SITE . '/' . $vid->src))
                    unlink(JPATH_SITE . '/' . $vid->src);
                }
            }
//            foreach ($value['track'] as $track) {
//              if(file_exists(JPATH_SITE .'/' . $track->src))
//                unlink(JPATH_SITE .'/' . $track->src); 
//            }
          }
          if($field->field_type == 'audiofield'){
            foreach ($value as $audio) { 
              if(file_exists(JPATH_SITE . '/' . $audio->src))
                unlink(JPATH_SITE . '/' . $audio->src); 
            }
          }
          if($field->field_type == 'galleryfield'){
              $field->value = '';
              $this->deleteGalleryImage($field);
              
          }
          if($field->field_type == 'imagefield' || $field->field_type == 'filefield'){
            $query = "SELECT " . $field->db_field_name . "_fid FROM #__os_cck_content_entity_".$field->fk_eid." WHERE fk_eiid=".$this->eiid;
            $this->_db->setQuery($query);
            $image_fid = $this->_db->loadResult();

            $query = "DELETE FROM #__os_cck_files WHERE fid='{$image_fid}'";
            $this->_db->setQuery($query);
            try {
                $this->_db->execute();
            } catch (RuntimeException $e) {
                echo $e->getMessage();
            }
            if(isset($value[0]) && file_exists(JPATH_SITE . $value[0]->data)){
              // var_dump($value); exit;
              unlink(JPATH_SITE . $value[0]->data); 
            }
            // var_dump($image_fid);exit;
          }
          if($value[0]->fid != 0 ){
            $file->load($value[0]->fid);
            if($file->fid == null){
              $file->delete(null, $value[0]->fid);
            }else{
              $file->delete();  
            }
            
            
          }


        }
      }

//       print_r($this->eiid);
//       exit;
      $query = "SELECT fid_child FROM  #__os_cck_child_parent_connect as cpc "
              . "LEFT JOIN #__os_cck_entity_instance as ei ON ei.eiid = cpc.fid_child "
              . "LEFT JOIN #__os_cck_layout as l ON l.lid = ei.fk_lid "
              . "WHERE cpc.fid_parent = $this->eiid AND cpc.media_type = 'instance' AND l.type='review_instance'";
      $this->_db->setQuery($query);
      $reviews = $this->_db->loadColumn();
      
//      var_dump($reviews); exit;
      foreach($reviews as $review_id){
          $review = new os_cckEntityInstance($this->_db);
          $review->load($review_id);
          $review->delete();
      }

      $query = " DELETE FROM  #__os_cck_child_parent_connect ".
        " WHERE media_type = 'instance' and " . 
        " ( fid_child = '" . $this->eiid . "' or fid_parent = '" . $this->eiid . "' ) ";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }


      $query = "DELETE FROM #__os_cck_content_entity_{$this->fk_eid} WHERE fk_eiid='{$this->eiid}'";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }
//      $this->_db->execute();
//      echo $this->_db->getErrorMsg();

      $query = "DELETE FROM #__os_cck_entity_instance WHERE eiid={$this->eiid}";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }
//      $this->_db->execute();
//      echo $this->_db->getErrorMsg();

      $query = "DELETE FROM #__os_cck_video_source WHERE  fk_eiid={$this->eiid}";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }
//      $this->_db->execute();
//      echo $this->_db->getErrorMsg();

      $query = "DELETE FROM #__os_cck_track_source WHERE  fk_eiid={$this->eiid}";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }
//      $this->_db->execute();
//      echo $this->_db->getErrorMsg();

      $query = "DELETE FROM #__os_cck_audio_source WHERE  fk_eiid={$this->eiid}";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }
//      $this->_db->execute();
//      echo $this->_db->getErrorMsg();
      
      //bch
      $query = "DELETE FROM #__os_cck_child_parent_connect WHERE fid_child = {$this->eiid}";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }

      $query = "DELETE FROM #__os_cck_child_parent_connect WHERE fid_parent = {$this->eiid} AND media_type LIKE'e-p-ch-%'";
      // echo $query; exit;
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }

      $query = "DELETE FROM #__os_cck_content_instances_price WHERE  fk_eiid={$this->eiid}";
      $this->_db->setQuery($query);
      try {
          $this->_db->execute();
      } catch (RuntimeException $e) {
          echo $e->getMessage();
      }
//      $this->_db->execute();
//      echo $this->_db->getErrorMsg();
      //bch

      return true;
  }

  function _is_filed_exist($field_name)
  {
      foreach ($this->getProperties() as $name => $value) {
          if ($name == $field_name) {
              return true;
          }
      }
      return false;
  }

  function _getFieldType($fieldName)
  {

      $query = 'SELECT f.field_type FROM #__os_cck_content_entity_field_instance as fi,  #__os_cck_content_entity_field as f ' .
          ' where fi.field_name = f.field_name and fi.entity_name = "' . $this->fk_eid . '" ' .
          ' and f.fieldName = "' . $fieldName . '"';
      $this->_db->setQuery($query);
      $tmp = (version_compare(JVERSION, "3.0.0", "lt")) ? $this->_db->loadResultArray() : $this->_db->loadColumn();
      if (count($tmp) == 0) {
          
          $app->enqueueMessage('Bad set field type in _build_table_filed_type - field type unknow.', 'warning');
          return false;
      }

      return $tmp->field_type;
  }

  function getFieldDetails($fieldName){
      //check exist fields with this name
      if (!$this->_is_filed_exist($fieldName)) {
          
          $app->enqueueMessage('The fields' . $fieldName . ' not exist for this entity.', 'warning');
          return false;
      }

      $query = "select * FROM #__os_cck_content_entity_field_instance " .
          " where  fieldName = '" . $fieldName . "' and entity_name = '" . $this->entity_name . "' ";
      $this->_db->setQuery($query);
      $os_cck_content_entity_field_instance = (version_compare(JVERSION, "3.0.0", "lt")) ? $this->_db->loadResultArray() : $this->_db->loadColumn();
      if (count($os_cck_content_entity_field_instance) == 0) {
          
          $app->enqueueMessage('The fields' . $fieldName . ' not defined for this entity .', 'warning');
          return false;
      }

      $query = 'SELECT f.* FROM #__os_cck_content_entity_field_instance as fi,  #__os_cck_content_entity_field as f ' .
          ' where fi.field_name = f.field_name and fi.entity_name = "' . $this->fk_eid . '" ' .
          ' and f.fieldName = "' . $fieldName . '"';
      $this->_db->setQuery($query);
      $os_cck_content_entity_field = (version_compare(JVERSION, "3.0.0", "lt")) ? $this->_db->loadResultArray() : $this->_db->loadColumn();
      if (count($os_cck_content_entity_field) == 0) {
          
          $app->enqueueMessage('The fields' . $fieldName . ' not defined for this entity .', 'warning');
          return false;
      }

      $os_cck_content_entity_field["global_settings"] = unserialize($os_cck_content_entity_field["global_settings"]);
      $os_cck_content_entity_field["db_columns"] = unserialize($os_cck_content_entity_field["db_columns"]);
      $os_cck_content_entity_field_instance["widget_settings"] =
          unserialize($os_cck_content_entity_field_instance["widget_settings"]);
      $os_cck_content_entity_field_instance["display_settings"] =
          unserialize($os_cck_content_entity_field_instance["display_settings"]);

      $tmp['os_cck_content_entity_field_instance'] = $os_cck_content_entity_field_instance;
      $tmp['os_cck_content_entity_field'] = $os_cck_content_entity_field;

      return $tmp;
  }

  function getAllLends($exclusion=""){

  	$this->_db->setQuery("SELECT id FROM #__os_cck_rent \n".
  						"WHERE fk_eiid='$this->eiid' " . $exclusion . " ORDER BY id");
  	if(version_compare(JVERSION, '3.0', 'lt')) {
  	  $tmp = $this->_db->loadResultArray();
  	} else {
  	  $tmp = $this->_db->loadColumn();
  	}

  	$retVal = array();
  	for($i = 0, $j = count($tmp); $i < $j; $i++ ){
  		$help = new mosCCK_rent($this->_db);
  		$help->load(intval($tmp[$i]));
  		$retVal[$i] = $help;
  	}
  	return $retVal;
  }

  function saveTracks($eiid, $src, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel,$fk_fid=0) {    
    $location = 'components/com_os_cck/files/track/'.$src;
    // var_dump($eiid); exit;
    if ($src != "" && !strstr($src, "http")) {
      $query = "INSERT INTO #__os_cck_track_source (fk_eiid,src,kind,scrlang,label,fk_fid,fk_video_id)".
                "\n VALUE ($eiid,
                          '" . $location . "',
                          '" . $uploadTrackKind . "',
                          '" . $uploadTrackScrlang . "',
                          '" . $uploadTrackLabel . "', $fk_fid, 0)";
    }else{
      $query ="INSERT INTO #__os_cck_track_source (fk_eiid,src,kind,scrlang,label,fk_fid,fk_video_id)".
              "\n VALUE ($eiid,
                        '" . $src."',
                        '" . $uploadTrackKind . "',
                        '" . $uploadTrackScrlang . "',
                        '" . $uploadTrackLabel . "', $fk_fid, 0 )";
    }
    // echo $query; exit;
    $this->_db->setQuery($query);
    $this->_db->execute();
  }


  function saveAudios($src, $eiid, $type, $fid) {


    $location = 'components/com_os_cck/files/audio/'.$src;

    if ($src != "" && strstr($src, "http")) {

      $query = "INSERT INTO #__os_cck_audio_source(fk_eiid,src,type,fk_fid)". 
               " VALUE($eiid,".$this->_db->quote($src) . ",'" . $type."', '".$fid."')";
    }else{

      $db = new os_cckDb();
      $query ="INSERT INTO #__os_cck_audio_source(fk_eiid,src,type,fk_fid)". 
              " VALUE($eiid," . $this->_db->quote($location) . ",'" . $type."', '".$fid."')";
    }

    $this->_db->setQuery($query);
    $this->_db->execute();
  }



  function saveVideos($src, $eiid, $type, $fid) {
      
    $location = 'components/com_os_cck/files/video/'.$src;
    
    if ($src != "" && strstr($src, "http")) {
      $query = "INSERT INTO #__os_cck_video_source( fk_eiid, src, type, fk_fid)".
          "\n VALUE($eiid," . $this->_db->quote($src) . ", '" . $type . "', '" . $fid . "')";
    }else{
      $query = "INSERT INTO #__os_cck_video_source( fk_eiid,src,type, fk_fid)".
                "\n VALUE($eiid,".$this->_db->quote($location).",'".$type."', '".$fid."')";
    }
    
    $this->_db->setQuery($query);
    $this->_db->execute();

  }



  function saveYouTubeCode($youtube_code, $eiid, $fid) {

    $this->_db->setQuery("SELECT id FROM #__os_cck_video_source 
                          WHERE youtube != '' 
                          AND fk_eiid = $eiid AND fk_fid = $fid");
    $this->_db->execute();
    $youtubeId = $this->_db->LoadResult();
    if ($youtube_code != '' && !empty($youtubeId)) {
      $query = "UPDATE #__os_cck_video_source".
                "\n SET youtube = '" . $youtube_code . "', ".
                "\n fk_fid = $fid".
                "\n WHERE id = $youtubeId";
    } else {
      $query = "INSERT INTO #__os_cck_video_source (fk_eiid,youtube,fk_fid)". 
                "\n VALUE($eiid,'" . $youtube_code . "', '" . $fid . "')";
    }
    $this->_db->setQuery($query);
    $this->_db->execute();
  }


  function checkMimeType($ext) {
    $this->_db->setQuery("SELECT mime_type FROM #__os_cck_mime_types WHERE mime_ext=".$this->_db->quote($ext));
    $type = $this->_db->loadResult();
    if(!$type)
      $type = 'unknown';
    return $type;
  }


  function filter($value) {
    $value = str_replace(array("/", "|", "\\", "?", ":", ";", "*", "#", "%", "$", "+", "=", ";", " "), "_", $value);
    return $value;
  }


  function guid() {
    if (function_exists('com_create_guid')) {
      return com_create_guid();
    } else {
      mt_srand((double)microtime() * 10000); //optional for php 4.2.0 and up.
      $charid = strtoupper(md5(uniqid(rand(), true)));
      $hyphen = chr(45); // "-"
      $uuid = //chr(123)// "{"
      substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
      //.chr(125);// "}"
      return $uuid;
    }
  }  


  function deleteTracks($eiid) {
    $this->_db->setQuery("SELECT id FROM #__os_cck_track_source where fk_eiid = $eiid;");
    $tdiles_id = $this->_db->loadColumn();
    $deleteTr_id = array();
    foreach($tdiles_id as $key => $value) {
      if (isset($_POST['track_option_del' . $value])) {
        array_push($deleteTr_id, protectInjectionWithoutQuote('track_option_del' . $value, '', 'post'));
        // array_push($deleteTr_id, $input->get('track_option_del' . $value, ''));
      }
    }
    if ($deleteTr_id) {
      $del_tid = implode(',', $deleteTr_id);
      $sql = "SELECT src FROM #__os_cck_track_source WHERE id IN (" .$del_tid . ")";
      $this->_db->setQuery($sql);
      $tracks = $this->_db->loadColumn();
      if ($tracks) {
        foreach($tracks as $name) {
          if (substr($name, 0, 4) != "http") unlink(JPATH_SITE . $name);
        }
      }
      $sql = "DELETE FROM #__os_cck_track_source WHERE (id IN (" . $del_tid . ")) 
              AND (fk_eiid = $eiid)";
      $this->_db->setQuery($sql);
      $this->_db->execute();
    }
  }

  function deleteAudios($eiid, $removeaudio = 0) {
    $this->_db->setQuery("SELECT id FROM #__os_cck_audio_source where fk_eiid = $eiid;");
    $adiles_id = $this->_db->loadColumn();
    $deleteAud_id = array();
    if ($removeaudio) {
      $deleteAud_id = $adiles_id;
    } else {
      foreach($adiles_id as $key => $value) {
        if (isset($_POST['audio_option_del' . $value])) {
          array_push($deleteAud_id, protectInjectionWithoutQuote('audio_option_del' . $value, '', 'post'));
            // array_push($deleteAud_id, $input->get('audio_option_del' . $value, ''));
        }
      }
    }
    if (isset($deleteAud_id['0']) && $deleteAud_id['0']) {
      $del_id = "";
      $sql = "SELECT src FROM #__os_cck_audio_source WHERE id IN (";
      foreach($deleteAud_id as $aid_id) $del_id.= $aid_id . ",";
      $sql.= $del_id . "0)";
      $this->_db->setQuery($sql);
      $audios = $this->_db->loadColumn();
      if ($audios) {
        foreach($audios as $name) {
          if (substr($name, 0, 4) != "http") unlink(JPATH_SITE . '/' . $name);
        }
      }
      $sql = "DELETE FROM #__os_cck_audio_source WHERE (id IN (" . $del_id . "0)) and (fk_eiid=$eiid)";
      $this->_db->setQuery($sql);
      $this->_db->execute();
    }
  }

    function deleteVideos($eiid) {
        global $input;

        $this->_db->setQuery("SELECT id, fk_fid FROM #__os_cck_video_source where fk_eiid = $eiid;");
        $vdiles_id = $this->_db->loadObjectList();
        $deleteVid_id = array();

        foreach($vdiles_id as $key => $value) {
            //prepere for delete normal video
            if (isset($_POST[$value->fk_fid.'_video_option_del' . $value->id])) {
                array_push($deleteVid_id, protectInjectionWithoutQuote($value->fk_fid.'_video_option_del' . $value->id, '', 'post'));
                // array_push($deleteVid_id, $input->get($value->fk_fid.'_video_option_del' . $value->id, ''));
            }

            //delete youtube video
            if (isset($_POST['youtube_option_del' . $value->id] )) {
                $y_t_id = intval( protectInjectionWithoutQuote('youtube_option_del' . $value->id, '', 'post') );
                $sql = "DELETE FROM #__os_cck_video_source ".
                  " WHERE id = $y_t_id AND fk_eiid=$eiid ";
                $this->_db->setQuery($sql);
                $this->_db->execute();
            }
        }

        if ($deleteVid_id) {
            $del_id = implode(',', $deleteVid_id);
            $sql = "SELECT src FROM #__os_cck_video_source WHERE id IN (". $del_id . ")";
            $this->_db->setQuery($sql);
            $videos = $this->_db->loadColumn();
            if ($videos) {
                foreach($videos as $name) {

                    if (substr($name, 0, 4) != "http" && file_exists(JPATH_SITE . '/' . $name))
                        unlink(JPATH_SITE . '/' . $name);
                }
            }
            $sql = "DELETE FROM #__os_cck_video_source 
              WHERE (id IN (" . $del_id . ")) 
              AND (fk_eiid=$eiid)";
            $this->_db->setQuery($sql);
            $this->_db->execute();
        }
        // $this->_db->setQuery("SELECT id FROM #__os_cck_video_source where fk_eiid = $eiid AND youtube IS NOT NULL;");
        // $youtubeid = $this->_db->loadResult();
        // if (!empty($youtubeid)) {
        //     if (isset($_POST['youtube_option_del' . $youtubeid])) {
        //         $y_t_id = intval(mosGetParam($_REQUEST, 'youtube_option_del' . $youtubeid, ''));
        //         $sql = "DELETE FROM #__os_cck_video_source 
        //         WHERE id = $y_t_id 
        //         AND fk_eiid=$eiid";
        //         $this->_db->setQuery($sql);
        //         $this->_db->execute();
        //     }
        // }
    }

  //accept ONLY rent requests  
  function accept(){
    global $my, $os_cck_configuration, $entityFieldLists, $app;
    if ($this->eiid == null) {
      return "Method called on a non instant object";
    }


    //$my = JFactory::getUser();
    //$this->check($my->id);

    //create new lend dataset
    

//    var_dump($this); exit;
    // $child_instance = new os_cckEntityInstance($this->_db);
    // $child_instance->load($this->child_id);

    //   $query = "SELECT * FROM #__os_cck_orders order by fk_request_id";
    //   $this->_db->setQuery($query);
    //   $order = $this->_db->loadObjectList();
    // echo ":9999999999999999991:"; 
    // print_r($order); exit;


    $fields_list = $entityFieldLists[$this->fk_eid];
    
    $assoc_instance = unserialize($this->associate_instances);

    if(empty($assoc_instance)){
        $assoc_instance[] = $this->eiid; 
    }
    
    foreach($assoc_instance as $eiid){
        $rent = new mosCCK_rent($this->_db);
        $rent->fk_userid = $this->fk_userid;
        $query = "SELECT name, email FROM #__users WHERE id=$this->fk_userid";
        $this->_db->setQuery($query);
        $user = $this->_db->loadObjectList();
        if($user){
          $rent->user_name = $user[0]->name;
          $rent->user_email = $user[0]->email;
        }
        $rent->request_id = $this->eiid;
        $layout = new os_cckLayout($this->_db);
        $layout->load($this->fk_lid);
        $fields_from_params = unserialize($layout->params);

        foreach ($fields_list as $value) {
          if($value->field_type == 'datetime_popup'){
              if($fields_from_params['fields'][$value->db_field_name."_field_type"] == "rent_from"){
                  $rent_from = $this->getFieldValue($value);
              }

              if($fields_from_params['fields'][$value->db_field_name."_field_type"] == "rent_to"){
                  $rent_to = $this->getFieldValue($value);
              }
          }
        }

        $rent->rent_from = $rent_from[0]->data; // date("Y-m-d H:i:s");
        $rent->rent_until = $rent_to[0]->data;

        //find item for which we do rent request
        $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child = ". $eiid. " ";
        $this->_db->setQuery($query);
        $rent_items_eiids = $this->_db->loadColumn();

        //lend check start
        $rent->fk_eiid = $rent_items_eiids[0];
        $rent->checked_out_time = date('Y-m-d H:m:s');
        $query = "SELECT * FROM #__os_cck_rent WHERE fk_eiid = " . $rent->fk_eiid .
            " AND rent_return IS NULL ";
        $this->_db->setQuery($query);
        $lendTerm = $this->_db->loadObjectList();

        $lend_from = $rent->rent_from;
        $lend_until = $rent->rent_until;

        if (isset($lendTerm[0])) {
          for ($e = 0, $m = count($lendTerm); $e < $m; $e++) {
              $returnMessage = checkRentCCK($lendTerm[$e]->rent_from, $lendTerm[$e]->rent_until, $lend_from, $lend_until);
            //rent check
              if(!$app->isClient('site') && $returnMessage !== NULL){
                return $returnMessage;
              }
              if($returnMessage !== NULL){
                  echo "<script> alert('" . $returnMessage . " '); window.history.go(-1); </script>\n";
                exit ();
              }
          }
        }
        
        //if end(end lend check)
        if (!$rent->store()) {
          return $rent->getError();
        }
        
        
    }
//    var_dump($this->eiid); exit;
//    $query = "UPDATE #__os_cck_entity_instance SET published='0' WHERE eiid = ".$this->eiid;
//    $this->_db->setQuery($query);
//    try {
//        $this->_db->execute();
//    } catch (Exception $ex) {
//        echo $ex->getMessage(); exit;
//    }

    //here also send email for rent request  
    if (!$this->publishInstance(0)) {
      return $this->getError();
    }

    return null;
  }


  // for rent and for buy requests
  function decline(){
    if ($this->eiid == null) {
      return "Method called on a non instant object";
    }

    //here also send email for buy/rent request  
    if (!$this->publishInstance(1)) {
      return $this->getError();
    }

      $query = "SELECT * FROM #__os_cck_orders WHERE fk_request_id = ".$this->eiid."";
      $this->_db->setQuery($query);
      $order = $this->_db->loadObjectList();
      
      if(!empty($order)){
          foreach ($order as $o){
              
              $query = "DELETE FROM #__os_cck_orders_details WHERE fk_order_id=$o->id";
              $this->_db->setQuery($query);
              $this->_db->execute();

              $query = "DELETE FROM #__os_cck_orders WHERE id=$o->id";
              $this->_db->setQuery($query);
              $this->_db->execute();
              
              $query = "DELETE FROM #__os_cck_orders_price WHERE fk_order_id=$o->id";
              $this->_db->setQuery($query);
              $this->_db->execute();

          }
      }
    if (!$this->delete()) {
      return $this->getError();
    }
    return null;
  }
  
  function getInstanciesListLang($lang){
      $query = "SELECT eiid, title FROM #__os_cck_entity_instance WHERE language='$lang' AND fk_eid='$this->fk_eid'";
      $this->_db->setQuery($query);
      $result = $this->_db->loadObjectList();
      return $result;
  }
  
  function saveInstance(){
    global $db, $user,$task, $Itemid, $app, $os_cck_state, $entityFieldLists, $input;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }

    $session = JFactory::getSession();
    $post = $_POST;

//    var_dump($post['eiid']);
    if(isset($post['eiid'])){
      unset($post['eiid']);
        $is_new = false;
    } else{
        $is_new = true;
      
    }
    
    // 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;
    //   }
    // }

    $is_site = cck_is_site();

    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    
    if($is_site){
      $menu = new JTableMenu($db->_db);
      $menu->load($Itemid);
      $params = new JRegistry;
      if($menu->params){
        $params->loadString($menu->params);
      }
    }
    $lay_type = $input->get('lay_type');
    
    $query = "SELECT c.title,c.lid,c.params,c.fk_eid ,c.mail, ch.layout_html, c.type FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n LEFT JOIN #__os_cck_layout_html AS ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid = ".$lay_type . " limit 1 ";
// echo $query; exit;
    try {
        $db->setQuery($query);
        $layout = $db->loadObjectList();
    }catch (Exception $e){
        // echo ':saveInstance 1111111111111111';
        echo $query;
        exit;
    }

//           echo '2222222222222'; exit; 
    $layout_params = unserialize($layout[0]->params);
    // echo '2222222222222222'; exit;
    $instance = $this;
    $data = $post;
    
    $select_list = array();
    $assoc_instancies_list = array();
    foreach ($data as $key => $value) {
       if(stripos($key,'fi_text_select_list_') !== false){
        $select_id = str_ireplace('fi_text_select_list_', '', $key);
          $select_list[] = $instance->getField($select_id);
       }
       
       if(stripos($key,'instanse_assoc_') !== false){
           $lang = str_replace('instanse_assoc_', '', $key);
           $assoc_instancies_list[$lang] = $value;
           if($lang == $data['language']){
               $assoc_instancies_list[$lang] = $post['id'];
           }
       }
    }

    $assoc_instancies_list_serialize = serialize($assoc_instancies_list);

    $data['fields_data'] = array();

    foreach ($post as $key => $var) {
      if (strpos($key, 'fi_') === 0){
        $key = str_replace('fi_', '', $key);
        $data['fields_data'][$key] = $var;
      }else{
        continue;
      }
    }
    foreach ($_FILES as $key => $var) {
      if (strpos($key, 'fi_') === 0){
        $key = str_replace('fi_', '', $key);
        $data['fields_data'][$key] = $var;
      }else{
        continue;
      }
    }
    if($is_site){
      if(isset($data['g-recaptcha-response']) || isset($data['plg_captcha_recaptcha_os_action'])){
          $config = JFactory::getConfig();
          $captha_type = $config->get('captcha', '');
          $captcha = JCaptcha::getInstance($captha_type, array('namespace' => $data['recaptcha_namespace']));
          if($captcha){
              $get_answer = protectInjectionWithoutQuote('g-recaptcha-response', "");
              if($get_answer == ''){
                $get_answer = protectInjectionWithoutQuote('plg_captcha_recaptcha_os_action', "");
              }
              
              if(!$get_answer ) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }

              $answer = $captcha->checkAnswer($get_answer);
              //$answer = $captcha->checkAnswer('captcha_keystring_rent_request');
              if(!$answer) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }
          }
          // echo '1111111111111111';
      }
    }

    $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
    $paypal_currency = cck_getCurrency($os_cck_configuration);
    $instance->instance_currency = $paypal_currency[0]['sign'];
    
    $instance->instance_price = 0;
    
    $total_price=0;
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $price_fields = array();

    if(isset($data['price_fields'])){
        foreach ($data['price_fields'] as $price_field){
            
            $ordering = protectInjectionWithoutQuote($price_field.'_ordering', array(), 'ARRAY');
  //            var_dump($ordering);
            $min_price = 0;
            foreach ($ordering as $key => $val){
                
                //var_dump($data[$price_field . '_price_type']); exit;
  //                if(is_array($val)) continue;
                if(stripos($price_field, 'pricefield_number_') !== false){
                    $price_field_type = 'pricefield_number';
                }elseif(stripos($price_field, 'pricefield_select_list_') !== false){
                    $price_field_type = 'pricefield_select_list';
                }elseif(stripos($price_field, 'pricefield_radio_buttons_') !== false){
                    $price_field_type = 'pricefield_radio_buttons';
                }
                $price_class = new stdClass;
                $price_class->fid = '';
                //$price_class->price_type = '';
                $price_class->price_name = '';
                $price_class->price_value = '';
                $price_class->quantity = '';
                $price_class->ordering = '';
                if(isset($data[$price_field . '_fid'])){
                    $price_class->fid = $data[$price_field . '_fid'];
                }
  //                if(isset($data[$price_field . '_price_type'])){
  //                    $price_class->price_type = $data[$price_field . '_price_type'];
  //                }else{
  //                    $price_class->price_type = 'base_price';
  //                }
                    
                if(isset($data['fields_data'][$price_field . '_' . $key])){
                    $price_class->price_value = $data['fields_data'][$price_field . '_' . $key];
                }
                if(isset($data['fields_data'][$price_field . '_price_name_' . $key])){
                    $price_class->price_name = $data['fields_data'][$price_field . '_price_name_' . $key];
                }else{
                    $price_class->price_name = $price_class->price_value;
                }
                if(isset($data['fields_data'][$price_field . '_quantity_' . $key])){
                    $price_class->quantity = $data['fields_data'][$price_field . '_quantity_' . $key];
                }
                
                $price_class->ordering = $key;
                
                $price_fields[] = $price_class;
                
                $field = new os_cckEntityField($db->_db);
              $field->load($price_class->fid);

              $layout = new os_cckLayout($db->_db);
              $layout->load($data['lay_type']);
              $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($calculate_type == 'base_price'){
                  if($price_class->price_value == '') $price_class->price_value = 0;
                  if($price_field_type == 'pricefield_number'){
                    $instance->instance_price = $price_class->price_value;
                  }else{
                      if($key == 0){
                          $min_price = $price_class->price_value;
                      }else{
                          if($price_class->price_value < $min_price){
                              $min_price = $price_class->price_value;
                          }
                      }
                      if(count($ordering) > $key){
                          $instance->instance_price += $min_price;
                      }
  //                      var_dump($price_class->price_value);
                  }
                  //$instance->quantity = $price_class->quantity;
              }
              if($instance->instance_price == ''){
                  $instance->instance_price = 0;
              }
              
            }
        }
    }
// var_dump($post); exit;
    foreach ($post as $key => $var) {
      if (strpos($key, 'child_field_') === 0){ 
          $data['child_entity_fields'][str_replace('child_field_', '', $key)] = $var;
                  
      }
    }

    if (isset($post['id']) && $post['id'] != 0 && $post['id'] != '') {
      $instance->load($post['id']);
      $data['changed'] = date("Y-m-d H:i:s");
    } else {
      $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".intval(protectInjectionWithoutQuote('lay_type'));
      $db->setQuery($query);
      $data['fk_eid'] = $db->loadResult();
      $data['created'] = date("Y-m-d H:i:s");
      $data['changed'] = date("Y-m-d H:i:s");
      $data['last_review'] = get_curent_site_time();
    }
    
    $data['title'] = protectInjectionWithoutQuote('title','');
    $data['asset_id'] = 0;
    if(!isset($post['categories'])){
      $data['categories'] = array();
    }

    //check instance owner_users_id, if so User not exist, set by Current logined user 
    $fk_userid = protectInjectionWithoutQuote('fk_userid','');
    $temp_owner_user = JFactory::getUser($fk_userid);
    if( !isset($fk_userid) || empty($fk_userid) || $fk_userid == 0 
      || !isset($temp_owner_user) || !isset($temp_owner_user->id) ) $data['fk_userid'] = $user->id;

    $data['fk_lid'] = protectInjectionWithoutQuote('lay_type','');
    
    if($is_site){
      $access_publish = (isset($layout_params['views']['access_publish'])) ? $layout_params['views']['access_publish'] : array();
      if(checkAccess_cck($access_publish, $user->groups, $instance->fk_eid, 'instancies'))
      {

          if(isset($layout_params['views']['layout_publish_on_add'])){
              if(isСorrectMaxItemsLimit($instance->fk_eid)){
                  $data['published'] = 1;
              }else{
                  $data['published'] = 0;
              }
          }else{
            $data['published'] = 0;
          }
      }else{
          $data['published'] = 0;
      }

      if(checkAccess_cck($layout_params['views']['access_approved'], $user->groups, $instance->fk_eid, 'instancies'))
      {
          if(isset($layout_params['views']['layout_approve_on_add'])){
            $data['approved'] = 1;
          }else{
            $data['approved'] = 0;
          }
          
      }else{
            $data['approved'] = 0;
      }
    }else{
      $data['published'] = 1;
      $data['approved'] = 1;
    }

    $data['checked_out'] = 0;
    $data['checked_out_time'] = date("Y-m-d H:i:s");
    $data['teid'] = 0;
    $instance->fields_data = '';
    $instance->categories = '';

    if (!$instance->bind($data)) {
      echo "<script> alert('Entity with this name alredy exist'); window.history.go(-1); </script>\n";
      exit ();
    }
  

    $title = '';
    foreach($entityFieldLists[$instance->fk_eid] as $old_field){
        $params = new JRegistry;
        $params->loadString($old_field->params);
//        var_dump($params);
        if($params->get('title_field', '') == 'yes' && isset($data['fi_'.$old_field->db_field_name])){
            $title = $data['fi_'.$old_field->db_field_name];
        }
    }
    $entitty = new os_cckEntity($this->_db);
    $entitty->load($instance->fk_eid);
    $instance->title = $title;
    $instance->_entity_name = $entitty->name;
    $instance->associate_instances = $assoc_instancies_list_serialize;
    $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;
    $layout = new os_cckLayout($db->_db);
    $layout->load($instance->fk_lid);
    $layout_params = unserialize($layout->params);
    $bootstrap_version = $session->get( 'bootstrap','2');
    $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
    $instance->_field_list = $entitty->getFieldList($layout->layout_html);
    $instance->_field_list = array_merge($instance->_field_list, $select_list);
    $instance->notreaded = 0;
    $instance->featured_clicks = (!isset($data['featured_clicks']) || $data['featured_clicks'] === '')?-1:$data['featured_clicks'];
    $instance->featured_shows = (!isset($data['featured_shows']) || $data['featured_shows'] === '')?-1:$data['featured_shows'];
    
    $instance->access = isset($data['access']) ? ',' . implode(',', $data['access']) . ',' : ',1,';
    
    
    $instance->_price_fields = $price_fields;
    $instance->_child_entity_fields = (isset($data['child_entity_fields'])) ? $data['child_entity_fields'] : array();
    $instance->fk_userid = ($data['fk_userid'] === '')?JFactory::getUser()->id:$data['fk_userid'];
    
    $instance->_layout_params = $layout_params['fields'];
    $instance->fk_lid = $layout->lid;
    $bootstrap_version = $session->get( 'bootstrap','2');

    $instance->check(true);

    //if date field apply data_transform_cck
    foreach ($instance->_field_list as $field) {
      if($field->field_type == 'datetime_popup'){
        $date_format = $layout_params['fields']['datetime_popup_'.$field->fid.'_input_format'];
        $time_format = $layout_params['fields']['datetime_popup_'.$field->fid.'_input_time_format'];
        $format = $date_format.' '.$time_format;
        $date = $instance->fields_data['datetime_popup_'.$field->fid];
        $instance->fields_data['datetime_popup_'.$field->fid] = data_transform_cck($date, $format);
        
      }elseif ($field->field_type == 'text_textfield' || $field->field_type == 'text_textarea') {
          if(isset($layout_params['fields'][$field->db_field_name . '_cut_tags'])
                  && $layout_params['fields'][$field->db_field_name . '_cut_tags'] == 1){
                    $instance->fields_data[$field->db_field_name] = strip_tags($instance->fields_data[$field->db_field_name]);
              
                  }
      }
    }

    
    if (!$instance->require_check()) {
      echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
      exit ();
    }

   $instance->store();
    
    foreach ($assoc_instancies_list as $inst){
        $query = "UPDATE #__os_cck_entity_instance SET associate_instances='$assoc_instancies_list_serialize' WHERE eiid='$inst'";
        $db->setQuery($query);
        $db->execute();
    }

    $layout_html = urldecode($layout->layout_html);

    $layout_mail = new os_cckLayout($db->_db);
    $layout_mail->load($instance->fk_lid);

     
    //old code - where we can have ONE mail field in layout
    if(!isset($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 this Add_Instance layout!!!"), 'warning');
    }      

    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ){
      $mail_data = array();
      $mail_data['mail'] = unserialize($layout_mail->mail);
      $fields_for_mail = getInstanceFieldsData( $instance->eiid);
      $mail_data['request_instance_fields_data'] = $fields_for_mail ;
      $mail_data['mail_fields'] = $layout_params['mail_fields'] ;
      if( $is_new ) $mail_data['mail_event'] = "create" ;
      if(!$is_new ) $mail_data['mail_event'] = "change" ;

      $parent_fields_data = array();
      $price_fields_assoc = array();
      if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
          && isset($parent_instance_id) && $parent_instance_id != 0 ){

          $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

          //run after correct $parentIdsArr defined
          $parent_fields_data = getParentsFieldsData( $coupon_id, $parentIdsArr, $price_fields_assoc );
          
      } 
      //in add_instance $parent_fields_data - empty
      $mail_data['parent_instances_fields_data'] = $parent_fields_data ;
      $parentIdsArr = array();
      cckSendMailEvent($mail_data, $parentIdsArr, $instance );


      //if published yet one email send
      if($instance->published ) {
        $mail_data['mail_event'] = "published" ;
        cckSendMailEvent($mail_data, $parentIdsArr, $instance );
      }
      //if approved yet one email send
      if($instance->approved ) {
        $mail_data['mail_event'] = "approved" ;
        cckSendMailEvent($mail_data, $parentIdsArr, $instance );
      }
    }


  }
  
  function getInstanceManager($option, $avaibleUpdate, $item_type = 'add_instance',$entity_list_menu = array() ){
      global $jConf, $app, $entities_type, $entityFieldLists ;

        $db = new os_cckDb();
        $user_checked_out_categories = " UPDATE #__os_cck_entity_instance SET checked_out=0, checked_out_time='0000-00-00 00:00:00'
        WHERE checked_out_time > 0 AND ( TIME_TO_SEC('" . date('Y-m-d H:i:s') . "') - TIME_TO_SEC(checked_out_time) ) >= 7200;";
        $db->setQuery($user_checked_out_categories);
        $db->execute();
        // $doc->addScript(JURI::root()."components/com_os_cck/assets/bootstrap/js/bootstrapCCK.js");
        JHtml::_('bootstrap.modal');
        $session = JFactory::getSession();

        if($avaibleUpdate){
            $message = cck_lang_text('COM_OS_CCK_NEW_VERSION_AVALIABLE');
            $app->enqueueMessage($message);
        }

        // $session = JFactory::getSession();
        // $session->destroy();

        // SORTING parameters start
        $session = JFactory::getSession();

        $sort_string = '';

        $item_sort_param = mosGetParam($_GET, 'sort', 'jei.eiid');

        if (is_array($sort_arr = $session->get('eq_itemsort', ''))) {

          if(protectInjectionWithoutQuote('sorting_direction','')){
            if(protectInjectionWithoutQuote('sorting_direction')=="ASC"){
              $sort_arr['sorting_direction'] = "DESC";
            }else{
              $sort_arr['sorting_direction'] = "ASC";
            }
          }elseif($session->get('sorting_direction','')){ 
            $sort_arr['sorting_direction'] = $session->get('sorting_direction');
          }else{
            $sort_arr['sorting_direction']="DESC";
          }

          if(protectInjectionWithoutQuote('sort','')){
              $sort_arr['field'] = protectInjectionWithoutQuote('sort','');
              $item_sort_param = protectInjectionWithoutQuote('sort','');
          }elseif(isset($sort_arr['field']) && $sort_arr['field'] != ''){

              if(stripos($sort_arr['field'], 'category') === false && $sort_arr['field'] != 'c.title' && $sort_arr['field'] != 'cc.title'){

                $item_sort_param = $sort_arr['field'];
              }else{
                $sort_arr['field'] = $item_sort_param = 'cc.title';
              }
              //$sort_arr['field'] = $session->get('field','');

          }else{
              $sort_arr['field'] = $item_sort_param ='jei.eiid';
          }

    //      if ($item_sort_param == $sort_arr['field']) {
    //          
    //      }
    //      if ($item_sort_param == $sort_arr['field']) {
    //      } else {
    //        $sort_arr['field'] = $item_sort_param;
    //      }

          if($item_sort_param == 'inst_entity'){
            $sort_string = ', jei.fk_eid' . " " . $sort_arr['sorting_direction'];
          }elseif($item_sort_param == 'inst_id'){
            $sort_string = ', jei.eiid' . " " . $sort_arr['sorting_direction'];
          }elseif($item_sort_param == "jei.eiid"){
            $sort_string = ', ' . $item_sort_param . " " . $sort_arr['sorting_direction'];
          }elseif($item_sort_param == "cc.title"){
            $sort_string = ', ' . $item_sort_param . " " . $sort_arr['sorting_direction'];
          }

        } else { 

          $sort_arr = array();
          if(protectInjectionWithoutQuote('sorting_direction','')){
            $sort_arr['sorting_direction'] = protectInjectionWithoutQuote('sorting_direction');
          }elseif($session->get('sorting_direction','')){ 
            $sort_arr['sorting_direction'] = protectInjectionWithoutQuote('sorting_direction');
          }else{
            $sort_arr['sorting_direction']="DESC";
          }

          if($item_sort_param == 'inst_entity'){
            $sort_string = ', jei.fk_eid'. " " . $sort_arr['sorting_direction'];
          }elseif($item_sort_param == 'inst_id'. " " . $sort_arr['sorting_direction']){
            $sort_string = ', jei.eiid'. " " . $sort_arr['sorting_direction'];
          }elseif($item_sort_param == "jei.eiid"){
            $sort_string = ', ' . $item_sort_param. " " . $sort_arr['sorting_direction'];
          }elseif($item_sort_param == "cc.title"){
            $sort_string = ', ' . $item_sort_param . " " . $sort_arr['sorting_direction'];
          }
          $sort_arr['field'] = $item_sort_param;
        }
        // var_dump($sort_arr);
        $session->set('eq_itemsort', $sort_arr);

        //maybe it is search below
        $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
        $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
        $catid = $app->getUserStateFromRequest("catid{$option}", 'catid', '');
        $pub = $app->getUserStateFromRequest("pub{$option}", 'pub', '');
        $approved = $app->getUserStateFromRequest("appr{$option}", 'appr', '');
        $userid = $app->getUserStateFromRequest("userid{$option}", 'userid', '');
        $search = trim($app->getUserStateFromRequest("search{$option}", 'search', ''));

        $lang = $app->getUserStateFromRequest("cck_language{$option}", 'cck_language', '*');

        $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
        $entities = array();
        $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES'));
        if( !empty($entity_list_menu) ) {
          $entity_list_str = implode(',',$entity_list_menu);
          $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity where eid IN ({$entity_list_str}) ORDER BY name ";
        } else {
          $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity  ORDER BY name ";
        }
        $db->setQuery($query);
        $ent = $db->loadObjectList("value");
        if( count($ent) > 1 ){
          $entities = array_merge($entities, (array)$ent) ;
        } else{
          //$entities = $entities;
          //set $entity_id == "" - when we haven 1 entity, and yet one - old was war selected we removed, 
          //for clear old values from $entity_list filter and from $where array
          $entity_id = "";
        }
        $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 
          'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);
        // $entity_list = OrdaSoft\os_lib\os_libHtmlInput::genericlist($entities, 'entity_id', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);


        $where = $where2 = array();
        $catwhere = "";
        if ($entity_id != '' && isset($ent[$entity_id])) {
            array_push($where, "jei.fk_eid ='{$entity_id}'");
        } else if ( !empty($entity_list_menu) ) {
          $entity_list_str = implode(',',$entity_list_menu);
          array_push($where, "jei.fk_eid in ({$entity_list_str})");
        }

        if ($approved == "appr") {
          array_push($where, "jei.approved = 1");
        } else if ($approved == "not_appr") {
          array_push($where, "jei.approved = 0");
        }

        if ($pub == "pub") {
          array_push($where, "jei.published = 1");
        } else if ($pub == "not_pub") {
          array_push($where, "jei.published = 0");
        }

        if($userid != -1 && $userid != 0 && $userid != ''){
          array_push($where, "jei.fk_userid = " . $userid);
        }


        //************* begin add for sub category  *************
        $categories[] = os_libHtmlInputs::option('-1', cck_lang_text('COM_OS_CCK_LABEL_SELECT_ALL_CATEGORIES'),'value','text');
        $options = $categories;
        $id = 0;
        $fromSearch=0;
        $list = CCK_CAT_Utils::categoryArray('com_os_cck',$fromSearch);
        $cat = new os_cckCategory($db->_db);
        $cat->load($id);

        $this_treename = '';
        foreach ($list as $item) {
          if ($this_treename) {
              if ($item->cid != $cat->cid && strpos($item->title, $this_treename) === false) {
                  $options[] = os_libHtmlInputs::option($item->cid, $item->title,'value','text');
              }
          } else {
              if ($item->cid != $cat->cid) {
                  $options[] = os_libHtmlInputs::option($item->cid, $item->title,'value','text');
              } else {
                  $this_treename = "$item->title/";
              }
          }
        }

        $clist = os_libHtmlInputs::genericlist($options, 'catid', 
          'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); 


        if ($catid > 0  && isset($list[$catid])) {
          array_push($where, "c.fk_cid='$catid'");
        }

        if ($lang != '*') {
          array_push($where, "jei.language='$lang'");
        }

        array_push($where, "cl.type = '$item_type'");

        //pagination?*
        $selectstring = "SELECT count(DISTINCT jei.eiid) " .
          "\nFROM #__os_cck_entity_instance AS jei" .
          "\nLEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
          "\nLEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
          "\nLEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";

        if($search || $sort_arr['field']){
            $select_enteties = "SELECT eid FROM #__os_cck_entity";
            $db->setQuery($select_enteties);
            $entityEaaray = $db->loadColumn();
            foreach(array_unique($entityEaaray) as $key => $value){
                if($entities_type[$value] == 'joomla_user') continue;

                $entity = new os_cckEntity($db->_db);
                $entity->load($value);

                $extra_fields_list = $entity->getFieldList();

                if(empty($extra_fields_list)) continue;
                foreach($extra_fields_list as $Fieldvalue){
                  if($Fieldvalue->show_in_instance_menu){
                    $fieldNames[$value]['ent_name'] = $entity->eid;
                    $fieldNames[$value]['field_type'] = $Fieldvalue->field_type;
                    $fieldNames[$value]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
                  }
                }
              }

    //      $fieldNames = $session->get('field_names');
    //      $tempfieldNames = $fieldNames;
          if(!empty($fieldNames)){
              $i = 0;
              foreach ($fieldNames as $value){
                if($i > 50) continue;
                foreach ($value['fields'] as $name) {
                  if($value['field_type'] == 'categoryfield' && $name == $sort_arr['field']){
                    $sort_string = ', cc.title'. " " . $sort_arr['sorting_direction'];
                    continue;
                  }
                  array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
                }

                $selectstring .= "\n LEFT JOIN #__os_cck_content_entity_".$value['ent_name'].
                  " ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
                $i++;
              }
          }else{
              $sort_string = '';
          }
          array_push($where2, "jei.eiid LIKE '%$search%' ");
        }

        $selectstring .=  "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
          "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
          "\n LEFT JOIN #__users AS u ON u.id = jei.checked_out " .
          (count($where) ? "\n WHERE " . implode(' AND ', $where) : "");

        if($search){
          $conditions_connect = count($where) ? 'AND' : 'WHERE';
          $selectstring .=  (count($where2) ? "\n".$conditions_connect." (" . implode(' OR ', $where2).')' : "");
        }
        $db->setQuery($selectstring);
        try {
            $total = $db->loadResult();
        } catch (RuntimeException $e) {
            echo $e->getMessage();
        }

        //echo $db->getErrorMsg();
        $limit = intval($limit);

        // $pageNav = new JPagination($total, $limitstart, $limit);
        $pageNav = new os_libPagination($total, $limitstart, $limit);

        $selectstring = "SELECT jei.*, cl.title as lay_title, cl.type as lay_type, cl.params as lay_params, " .
          "\n GROUP_CONCAT(DISTINCT cc.title SEPARATOR ', ') AS category, ce.name AS entity, " .
          "\n l.id as rentid, l.rent_from as rent_from, l.rent_return as rent_return,l.rent_until as rent_until," .
          "\n u.name AS editor, jei.language as lang " .
          "\n FROM #__os_cck_entity_instance AS jei" .
          "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
          "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
          "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";

          if($search || $sort_arr['field']){
            // $fieldNames 
            // if($sort_arr['field']){

            // }
            // $fieldNames = $session->get('field_names');

            if(!empty($fieldNames)){
                $i = 0;  
                foreach ($fieldNames as $value) {
                  $i++;
                  if($i > 50) continue;
                  // var_dump($i);
                  foreach ($value['fields'] as $name) {

                    if($value['field_type'] == 'categoryfield' && $name == $sort_arr['field']){
                      $sort_string = ', cc.title'. " " . $sort_arr['sorting_direction'];
                      continue;
                    }
                    // var_dump(!isset($sort_string));
                    if((!isset($sort_string) || $sort_string == '') && (isset($item_sort_param) && !empty($item_sort_param))){

                      if($item_sort_param == $name){
                        $sort_string = ', #__os_cck_content_entity_'.$value['ent_name'].'.'.$name." ".$sort_arr['sorting_direction'];
                      }
                    }
                    array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
                  }
                  $selectstring .= "\nLEFT JOIN #__os_cck_content_entity_".$value['ent_name']." ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";

                }
            }else{
                $sort_string = '';
            }
            array_push($where2, "jei.eiid LIKE '%$search%' ");
          }

        $selectstring .= "\nLEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
          "\nLEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
          "\nLEFT JOIN #__users AS u ON u.id = jei.checked_out " .
          (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

        if($search){
          $conditions_connect = count($where) ? 'AND' : 'WHERE';
          $selectstring .=  (count($where2) ? "\n".$conditions_connect." (" . implode(' OR ', $where2).')' : "");
        }
        // var_dump($sort_string);
        $selectstring .= "\n GROUP BY jei.eiid " .
          "\n ORDER BY jei.notreaded desc $sort_string " .
          "\n LIMIT $pageNav->limitstart,$pageNav->limit;";
        $db->setQuery($selectstring);
        try {
            $rows = $db->loadObjectList();
        }catch(RuntimeException $e) {
          echo $selectstring;
            echo $e->getMessage();
            return false;
        }
    //    if ($db->getErrorNum()) {
    //      echo $db->stderr();
    //      return false;
    //    }


    //prepere for show fields: selected for show in InstancesManager
    $show_fields = $entityEaaray = $layoutArray = $fieldNames = array();
    if(count($rows)>0){
          $date = strtotime(JFactory::getDate()->toSql());
          foreach ($rows as $row) {
            $check = strtotime($row->checked_out_time);
            $remain = 7200 - ($date - $check);
            if (($remain <= 0) && ($row->checked_out != 0)) {
                $db->setQuery("UPDATE #__os_cck_entity_instance SET checked_out=0,checked_out_time=0");
                $db->execute();
                $row->checked_out = 0;
                $row->checked_out_time = 0;
            }
            if($row->lay_type != ''){  
              $lay_params = unserialize($row->lay_params);
              $entityEaaray[] = $row->fk_eid;
              $layoutArray[] = $row->fk_lid;
            }
          }

          $entityEaaray = array_unique($entityEaaray);
          $layoutArray = array_unique($layoutArray);
          $uniqFieldsArray = array(); //need for add fields only 1 time
          foreach($entityEaaray as $key => $value){
            $entity = new os_cckEntity($db->_db);
            $entity->load($value);
            $extra_fields_list = $entity->getFieldList();
            foreach($layoutArray as $key2 => $value2){
              $layout = new os_cckLayout($db->_db);
              $layout->load($layoutArray[$key2]);
              $bootstrap_version = $session->get( 'bootstrap','2');
              $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
              $layout_params = unserialize($layout->params);
              foreach($extra_fields_list as $Fieldvalue){
                if($Fieldvalue->show_in_instance_menu && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
                  if( isset($uniqFieldsArray[$Fieldvalue->fid] ) ) continue; //need for add fields only 1 time
                  $uniqFieldsArray[$Fieldvalue->fid] = $Fieldvalue->fid ;
                  // $fieldNames[$key]['ent_name'] = $entity->eid;
                  // $fieldNames[$key]['field_type'] = $Fieldvalue->field_type;
                  // $fieldNames[$key]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
                  $show_fields[$value][]= $Fieldvalue;
                }
              }
            }
          }
          ksort($show_fields);
        }
        // $show_fields = array_unique($show_fields); 
      

        if (version_compare(JVERSION, "3.7.0", "ge")) {
            $install_lang = JLanguageHelper::getKnownLanguages();
        }else{
            $install_lang = JLanguage::getKnownLanguages();
        }

        $lang_list = array();
        $lang_opt[] = os_libHtmlInputs::option('*',cck_lang_text('COM_OS_CCK_OPTION_ALL_LANGUAGES'));
        foreach($install_lang as $key => $item){
            $lang_opt[] = os_libHtmlInputs::option($key,$item['name']);
        }
        $lang_list = os_libHtmlInputs::genericlist($lang_opt, 'cck_language', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $lang); //new nik edit

        $pubmenu[] = os_libHtmlInputs::option('0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
        $pubmenu[] = os_libHtmlInputs::option('not_pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_PUBLIC'),'value','text');
        $pubmenu[] = os_libHtmlInputs::option('pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_PUBLIC'),'value','text');
        $publist = os_libHtmlInputs::genericlist($pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);

        $approvedmenu[] = os_libHtmlInputs::option('0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
        $approvedmenu[] = os_libHtmlInputs::option('not_appr', cck_lang_text('COM_OS_CCK_LABEL_UNAPPROVED'),'value','text');
        $approvedmenu[] = os_libHtmlInputs::option('appr', cck_lang_text('COM_OS_CCK_LABEL_APPROVED'),'value','text');
        $approvedlist = os_libHtmlInputs::genericlist($approvedmenu, 'appr', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $approved);

    //    SELECT DISTINCT fk_userid FROM shop_os_cck_entity_instance as ei INNER JOIN `shop_users` as us ON ei.fk_userid = us.id
        $select = "SELECT DISTINCT fk_userid FROM #__os_cck_entity_instance as ei "
                . " INNER JOIN `#__users` as us ON ei.fk_userid = us.id";
        $db->setQuery($select);
        $users = $db->loadObjectList();

        $userOpt = array();
        $userOpt[] = os_libHtmlInputs::option('', 'All Users','value','text');

        foreach ($users as $user => $value) {
            if($value->fk_userid == 0) $value->fk_userid = cck_lang_text("COM_OS_CCK_LABEL_ALL_OWNERS");
            $userOpt[] = os_libHtmlInputs::option($value->fk_userid, @JFactory::getUser($value->fk_userid)->name,'value','text');
        }

        $userslist = os_libHtmlInputs::genericlist($userOpt, 'userid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $userid);
        
        $return = array();
        $return['pageNav'] = $pageNav;
        $return['rows'] = $rows;
        $return['show_fields'] = $show_fields;
        $return['entity_list'] = $entity_list;
        $return['lang_list'] = $lang_list;
        $return['sort_arr'] = $sort_arr;
        $return['clist'] = $clist;
        $return['publist'] = $publist;
        $return['search'] = $search;
        $return['approvedlist'] = $approvedlist;
        $return['userslist'] = $userslist;
        
        return $return;
  }
  
  function getParentInstance() {
      $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child=$this->eiid AND media_type='instance'";
      $this->_db->setQuery($query);
      $parent_eiid = $this->_db->loadResult();

      return $parent_eiid;
  }
  
  function publishInstance($publish){
      global $user, $entityFieldLists;
      
      $query = "UPDATE #__os_cck_entity_instance SET published='$publish'"
                    . "\n WHERE eiid=$this->eiid AND (checked_out=0 OR (checked_out='$user->id'))";
      $this->_db->setQuery($query);
      $this->_db->execute();
      
      $layout_mail = new os_cckLayout($this->_db);
      $layout_mail->load($this->fk_lid);
      $layout_params = unserialize($layout_mail->params);
      $layout_html = urldecode($layout_mail->getLayoutHtml('3'));
      // $mail = unserialize($layout->mail);
      // $fields_for_mail = array();
      
      
      if( $layout_mail->type != 'add_instance'){
          //for $layout_mail->type == 'review_instance', buy_request_instance, rent_request_instance
          $parent_instance_id = $this->getParentInstance();
      }
      

      if( strpos($layout_html,"{|f-cck_mail_") ){
          $mail_data = array();
          $orderId = 0 ;
          $mail_data['mail'] = unserialize($layout_mail->mail);
          //orderid - may exist for $layout_mail->type == 'buy_request_instance' || 'rent_request_instance', so find it
          $fields_for_mail = getInstanceFieldsData( $this->eiid, $orderId);
          $mail_data['request_instance_fields_data'] = $fields_for_mail ;
          $mail_data['mail_fields'] = $layout_params['mail_fields'] ;
          if( intval($orderId) != 0 ) $mail_data['order_id'] = $orderId ; 

          if( ($layout_mail->type == 'buy_request_instance' || $layout_mail->type == 'rent_request_instance') && $publish == 0 )
              $mail_data['mail_event'] = "accept" ;
          if( ($layout_mail->type == 'buy_request_instance' || $layout_mail->type == 'rent_request_instance') && $publish == 1 )
              $mail_data['mail_event'] = "decline" ;


          if( ($layout_mail->type == 'review_instance' || $layout_mail->type == 'add_instance') && $publish == 0 )
              $mail_data['mail_event'] = "unpublish" ;
          if( ($layout_mail->type == 'review_instance' || $layout_mail->type == 'add_instance') && $publish == 1 )
              $mail_data['mail_event'] = "publish" ;


          $parent_fields_data = array();
          $parentIdsArr = array();
          $price_fields_assoc = array();
          if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
              && (isset($parent_instance_id) && $parent_instance_id != 0) || intval($orderId) != 0  ){
            //for $layout_mail->type == 'review_instance', buy_request_instance, rent_request_instance
            

            if( isset($parent_instance_id) && $parent_instance_id != 0 ) 
                $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc, $orderId );
            $mail_data['parent_instances_fields_data'] = $parent_fields_data ;

            cckSendMailEvent($mail_data, $parentIdsArr, $this );
              
          } else{
            //for $layout_mail->type == 'add_instance'
            $mail_data['parent_instances_fields_data'] = $parent_fields_data ;

            cckSendMailEvent($mail_data, $parentIdsArr, $this );
          }
      }

      return true ;

  }
  
  function approvInstance($aprove){
      global $user, $entityFieldLists;
      $query = "UPDATE #__os_cck_entity_instance SET approved='$aprove'"
                    . "\n WHERE eiid=$this->eiid AND (checked_out=0 OR (checked_out='$user->id'))";
      $this->_db->setQuery($query);
      $this->_db->execute();
      
      $layout_mail = new os_cckLayout($this->_db);
      $layout_mail->load($this->fk_lid);
      $layout_params = unserialize($layout_mail->params);
      $layout_html = urldecode($layout_mail->getLayoutHtml('3'));
      // $mail = unserialize($layout_mail->mail);

      if( $layout_mail->type != 'add_instance'){
        //for $layout_mail->type == 'review_instance
        $parent_instance_id = $this->getParentInstance();
      }
      

      if( strpos($layout_html,"{|f-cck_mail_") ){
          $mail_data = array();
          $mail_data['mail'] = unserialize($layout_mail->mail);
          $fields_for_mail = getInstanceFieldsData( $this->eiid);
          $mail_data['request_instance_fields_data'] = $fields_for_mail ;
          $mail_data['mail_fields'] = $layout_params['mail_fields'] ;
          
          if( ($layout_mail->type == 'review_instance' || $layout_mail->type == 'add_instance') && $aprove == 0 )
              $mail_data['mail_event'] = "unapproved" ;

          if( ($layout_mail->type == 'review_instance' || $layout_mail->type == 'add_instance') && $aprove == 1 )
              $mail_data['mail_event'] = "approved" ;

          $parent_fields_data = array();
          $parentIdsArr = array();
          $price_fields_assoc = array();
          if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
              && isset($parent_instance_id) && $parent_instance_id != 0 ){

            //for $layout_mail->type == 'review_instance'
            $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc );
            $mail_data['parent_instances_fields_data'] = $parent_fields_data ;

            cckSendMailEvent($mail_data, $parentIdsArr, $this );
              
          } else{
            //for $layout_mail->type == 'add_instance'
            $mail_data['parent_instances_fields_data'] = $parent_fields_data ;

            cckSendMailEvent($mail_data, $parentIdsArr, $this );
          }
      }
    
      
  }

}


