<?php
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  18/03/11, 11:05
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class cfg_34
  @brief Gestion Des configuration product extra fields
*/

define('FILENAME_CFG_34',"gparentID=120&gID=34&");
error_reporting(E_ALL);
Class cfg_34{

  const FILENAME = FILENAME_CONFIGURATION;
  /**
    @var array
  */
  public static $selected_labels;
  /**
    @var array
  */
  public static $list;
  /**
    @var array
  */
  public static $lang;
  /**
    @var int value id selected
  */
  public static $eid;
  /**
    @var integer
  */
  public static $double_check;
  /**
    @var object
  */
  public static $pInfo;
  /**
    @var object
  */
  public static $cInfo;

  /**
  */
  function __construct(){

    $this->code=__CLASS__;

    global $messageStack, $language,$oscss;

    $oscss->pile_file_lang(DIR_FS_ADMIN.DIR_WS_LANGUAGES.$language.'/modules/configuration/'.$this->code.'.txt');

    //! detail item in ajax
    if(!defined('AJAXSTATMENTDETAIL')) define('AJAXSTATMENTDETAIL', 'mod=page');

    self::$eid=(isset($_GET['eid']) ? $_GET['eid'] : '');
  }


  /**
    Action en remplacement des action par defaut
  */
  public function draw_action(){
    global $action,$messageStack,$language_id;

  $confirm = (isset($_GET['confirm']) ? $_GET['confirm'] : '');
  $languages = tep_get_languages();
  $confirmation_needed = false;

    $messages = array();
    $error = false;
    switch ($action) {
      case 'insert': // validate form

	try{
	  if (!isset($_POST['status'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_ACTIVATE_NOW);
	  $status = ($_POST['status'] == '0') ? 0 : 1;
	  $order = (isset($_POST['sort_order'])) ? tep_db_prepare_input($_POST['sort_order']) : 0;
	  $epf_admin = (isset($_POST['epf_admin'])) ? tep_db_prepare_input($_POST['epf_admin']) : 0;
	  $epf_special_mod = (isset($_POST['epf_special_mod'])) ? tep_db_prepare_input($_POST['epf_special_mod']) : '';

	  if (!isset($_POST['search'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_SEARCH);
	  $search = ($_POST['search'] == '0') ? 0 : 1;

	  if (!isset($_POST['listing'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_LISTING);
	  $listing = ($_POST['listing'] == '0') ? 0 : 1;

	  if (!isset($_POST['meta'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_META);
	  $meta = ($_POST['meta'] == '0') ? 0 : 1;

	  if (!isset($_POST['value_list'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_VALUE_LIST);
	  $value_list = ($_POST['value_list'] == '0') ? 0 : 1;

	  if (!isset($_POST['size'])) throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_SIZE);
	  $size = ($_POST['size'] == '0') ? 0 : (int)$_POST['size'];

          if ($value_list === 0) { // size required only if not using value list
            if (!isset($_POST['size'])) throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_SIZE);
              $size = tep_db_prepare_input($_POST['size']);
              if (!is_numeric($size) || ($size < 1) || ($size > 255)) throw new Exception(ERROR_ENTRY_REQUIRED . ERROR_OUTOFRANGE);
          }
          if ($value_list == 1) {
            $size = 64;
            if (!isset($_POST['chain']))throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_SHOW_PARENTS);
	    $chain = ($_POST['chain'] == '0') ? 0 : 1;
            if (!isset($_POST['restrict'])) throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_RESTRICTS);
	    $restrict = ($_POST['restrict'] == '0') ? 0 : 1;
          } else { // parent chain and restrict listing are never active if not using value list
            $chain = 0;
            $restrict = 0;
          }

          $labels = array();
          $active = false;
	  if (!isset($_POST['epf_active_for_language'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_ACTIVE );
	  $lactive = ($_POST['epf_active_for_language'] == '0') ? 0 : 1;

          for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
            $lbl = (isset($_POST['label_' . $languages[$i]['id']])) ? tep_db_prepare_input($_POST['label_' . $languages[$i]['id']]) : '';
            if ($lactive && !tep_not_null($lbl))  throw new Exception(ERROR_LABEL, $languages[$i]['name'] );
            if ($lactive) $active = true;
            $labels[$languages[$i]['id']] = array('active' => $lactive, 'label' => $lbl);
          }
          if (!$active) throw new Exception(ERROR_ACTIVE);

	  $epf_key= (isset($_POST['epf_key'])) ? tep_db_prepare_input($_POST['epf_key']) : md5($_POST['label_'.$language_id]);
	}
	catch(Exception $e){
	  $messageStack->add($e->getMessage(), 'error');
	  $error=true;
	}

	$this->field=$data_array = array('epf_order' => (int)$order,
			  'epf_status' => $status,
			  'epf_uses_value_list' => $value_list,
			  'epf_advanced_search' => $search,
			  'epf_show_in_listing' => $listing,
			  'epf_size' => $size,
			  'epf_use_as_meta_keyword' => $meta,
			  'epf_use_to_restrict_listings' => $restrict,
			  'epf_show_parent_chain' => $chain,
			  'epf_key' => $epf_key,
			  'epf_admin' => $epf_admin,
			  'epf_special_mod' => $epf_special_mod);

          if ($error) {  // if error return to entry form
            $action = 'new';
	    for ($i=0, $n=sizeof($languages); $i<$n; $i++){
	      $this->epf_label=$labels;
	    }
          } else { // otherwise create field

            $resobj=tep_db_perform(TABLE_PRODUCTS_EXTRA_FIELDS, $data_array);
            self::$eid = tep_db_insert_id($resobj);
            $field = 'extra_value' . ($value_list ? '_id' : '') . self::$eid;
            tep_db_query('alter table ' . TABLE_PRODUCTS_DESCRIPTION . ' add ' . $field . ($value_list ? ' int unsigned not null default 0' : ' varchar(' . (int)$size . ') default null'));
            foreach ($labels as $lid => $value) {
              $label_array = array('epf_id' => self::$eid,
                                   'languages_id' => $lid,
                                   'epf_label' => ($value['active'] ? $value['label'] : ''),
				   'epf_active_for_language' => $value['active']);
              tep_db_perform(TABLE_PRODUCTS_EXTRA_FIELDS_LABELS, $label_array);
            }
            tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','eid','confirm'),false).'eid=' . self::$eid));
          }
      break;

      case 'update': // validate form
	$query = tep_db_query("select epf_size, epf_uses_value_list from " . TABLE_PRODUCTS_EXTRA_FIELDS . " where epf_id = " . (int)self::$eid);
	$field_info = tep_db_fetch_array($query); // retrieve original field information

	try{
	  if (!isset($_POST['status'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_ACTIVATE_NOW);
	  $status = ($_POST['status'] == '0') ? 0 : 1;
	  $order = (isset($_POST['sort_order'])) ? tep_db_prepare_input($_POST['sort_order']) : 0;
	  $epf_admin = (isset($_POST['epf_admin'])) ? tep_db_prepare_input($_POST['epf_admin']) : 0;
	  $epf_special_mod = (isset($_POST['epf_special_mod'])) ? tep_db_prepare_input($_POST['epf_special_mod']) : '';

	  if (!isset($_POST['search'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_SEARCH);
	  $search = ($_POST['search'] == '0') ? 0 : 1;

	  if (!isset($_POST['listing'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_LISTING);
	  $listing = ($_POST['listing'] == '0') ? 0 : 1;

	  if (!isset($_POST['meta'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_META);
	  $meta = ($_POST['meta'] == '0') ? 0 : 1;

	  if (!isset($_POST['size'])) throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_SIZE);
	  $size = ($_POST['size'] == '0') ? 0 : (int)$_POST['size'];

	  $uses_list = $field_info['epf_uses_value_list'];
	  if ($uses_list === 0) { // size required only if not using value list
	    if (!isset($_POST['size'])) throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_SIZE);
	      $size = tep_db_prepare_input($_POST['size']);
	      if (!is_numeric($size) || ($size < 1) || ($size > 255)) throw new Exception(ERROR_ENTRY_REQUIRED . ERROR_OUTOFRANGE);
	  }
	  if ($uses_list == 1) {
	    $size = 64;
	    if (!isset($_POST['chain']))throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_SHOW_PARENTS);
	    $chain = ($_POST['chain'] == '0') ? 0 : 1;
	    if (!isset($_POST['restrict'])) throw new Exception(ERROR_ENTRY_REQUIRED . TEXT_RESTRICTS);
	    $restrict = ($_POST['restrict'] == '0') ? 0 : 1;
	  } else { // parent chain and restrict listing are never active if not using value list
	    $chain = 0;
	    $restrict = 0;
	  }

	  if (!isset($_POST['epf_active_for_language'])) throw new Exception(ERROR_ENTRY_REQUIRED . ENTRY_ACTIVE );
	  $lactive = ($_POST['epf_active_for_language'] == '0') ? 0 : 1;

	  $labels = array();
	  $active = false;
	  for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
	    $lbl = (isset($_POST['label_' . $languages[$i]['id']])) ? tep_db_prepare_input($_POST['label_' . $languages[$i]['id']]) : '';
	    if ($lactive && !tep_not_null($lbl))  throw new Exception(ERROR_LABEL, $languages[$i]['name'] );

	    if ($lactive) $active = true;
	    $labels[$languages[$i]['id']] = array('active' => $lactive, 'label' => $lbl);
	  }
	  // if no active languages
	  $epf_key= (isset($_POST['epf_key'])) ? tep_db_prepare_input($_POST['epf_key']) : md5($_POST['label_'.$language_id]);
	}
	catch(Exception $e){
	  $messageStack->add($e->getMessage(), 'error');
	  $error=true;
	}

	if ($error) {  // if error return to entry form
	  $action = 'edit';
	} else { // otherwise update field
	  $field = 'extra_value' . ($uses_list ? '_id' : '') . (int)self::$eid;
	  if (($size < $field_info['epf_size'])) {
	    $check_query = tep_db_query("select count(products_id) as total, max(length(" . $field . ")) as maxlen from " . TABLE_PRODUCTS_DESCRIPTION . " where length(" . $field . ") > " . (int)$size);
	    $check = tep_db_fetch_array($check_query);
	    if ($check['total'] > 1) { // check to see if reducing size will truncate data
	      $confirmation_needed = true;
	      $messageStack->add(WARNING_TRUNCATE, $check['total'].$check['maxlen'],'error');
	    }
	  }
	  $label_query = tep_db_query("select * from " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " where epf_id=" . (int)self::$eid);
	  while ($label_info = tep_db_fetch_array($label_query)) {
// print_r($label_info);
	    if ($label_info['epf_active_for_language'] > $labels[$label_info['languages_id']]['active']) { // if language being deactivated
	      $check_query = tep_db_query("select count(products_id) as total from " . TABLE_PRODUCTS_DESCRIPTION . " where language_id = " . (int)$label_info['languages_id'] . " and " . ($uses_list ? $field . " > 0" : "length(" . $field . ") > 0"));
	      $check = tep_db_fetch_array($check_query);
	      if ($check['total'] > 0) { // check to see if language is used
		$confirmation_needed = true;
		$messageStack->add(WARNING_LANGUAGE_IN_USE, $check['total']. $lang[$label_info['languages_id']]['name'],'error');
	      }
	    }
	  }

	  if ((!$confirmation_needed) || ($confirm == 'yes')) { // if confirmation not needed or changes have been confirmed
	    $data_array = array('epf_order' => (int)$order,
				'epf_status' => $status,
				'epf_advanced_search' => $search,
				'epf_show_in_listing' => $listing,
				'epf_size' => $size,
				'epf_use_as_meta_keyword' => $meta,
				'epf_use_to_restrict_listings' => $restrict,
				'epf_show_parent_chain' => $chain,
				'epf_key' => $epf_key,
				'epf_admin' => $epf_admin,
				'epf_special_mod' => $epf_special_mod);
	    tep_db_perform(TABLE_PRODUCTS_EXTRA_FIELDS, $data_array, 'update', 'epf_id = ' . (int)self::$eid);
	    if (($uses_list == 0) && ($field_info['epf_size'] != $size)) { // if text field size has changed
	      tep_db_query('alter table ' . TABLE_PRODUCTS_DESCRIPTION . '  change ' . $field . ' ' . $field . ' varchar(' . (int)$size . ') default null');
	    }
	    foreach ($labels as $lid => $value) {
	      $label_array = array('epf_label' => $value['label'], 'epf_active_for_language' => $value['active']);
	      tep_db_perform(TABLE_PRODUCTS_EXTRA_FIELDS_LABELS, $label_array, 'update', '(epf_id = ' . (int)self::$eid . ') and (languages_id = ' . (int)$lid . ')');
	    }

	    tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','eid','confirm'),false). 'eid=' . self::$eid));

	  } else { // request confirmation
	    $action = 'edit';
	  }
	}
      break;
      case 'delete':
        if ($confirm == 'yes') {
          if (isset($_GET['used']) && ($_GET['used'] > 0)) {
            self::$double_check = 'yes';
          } else {
//             $query = tep_db_query("select epf_uses_value_list from " . TABLE_PRODUCTS_EXTRA_FIELDS . " where epf_id = " . (int)self::$eid);
//             $field_info = tep_db_fetch_array($query); // retrieve field type
// 	    if(tep_db_num_rows($query) >0) {
// 	      $field = 'extra_value' . ($field_info['epf_uses_value_list'] ? '_id' : '') . (int)self::$eid;
// 	      tep_db_query('alter table ' . TABLE_PRODUCTS_DESCRIPTION . ' drop ' . $field);
// 	    }
	    tep_db_query('delete from ' . TABLE_PRODUCTS_EXTRA_FIELDS . ' where epf_id = ' . (int)self::$eid);
	    tep_db_query('delete from ' . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . ' where epf_id = ' . (int)self::$eid);
	    tep_db_query('delete from ' . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . ' where epf_id = ' . (int)self::$eid);
	    tep_db_query('delete from ' . TABLE_PRODUCTS_TO_PRODUCTS_EXTRA_FIELDS . ' where products_extra_fields_id = ' . (int)self::$eid);
	    tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','confirm','eid'),false)));
          }
        } else {
          self::$double_check = 'no';
        }
        break;
      case 'setflag':
	if(isset($_GET['flag']) ){
	  if (!is_numeric($_GET['flag']) || (($_GET['flag'] != 0) && ($_GET['flag'] != 1))) break; // skip if flag not properly set
	  tep_db_query('update ' . TABLE_PRODUCTS_EXTRA_FIELDS . ' set epf_status = ' . (int)$_GET['flag'] . ' where epf_id = ' . (int)self::$eid);
	}elseif(isset($_GET['flag_admin']) ){
	  if (!is_numeric($_GET['flag_admin']) || (($_GET['flag_admin'] != 0) && ($_GET['flag_admin'] != 1))) break; // skip if flag not properly set
	  tep_db_query('update ' . TABLE_PRODUCTS_EXTRA_FIELDS . ' set epf_admin = ' . (int)$_GET['flag_admin'] . ' where epf_id = ' . (int)self::$eid);
	}
	tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','flag_spe','flag_admin','flag'),false)));
      break;




      case 'value_update':
	$languages = tep_get_languages();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++){
	  $data_array = array('sort_order' => (int)(isset($_POST['sort_order'][$languages[$i]['id']]) ? tep_db_prepare_input($_POST['sort_order'][$languages[$i]['id']]) : 0),
                              'epf_value' => (isset($_POST['value'][$languages[$i]['id']]) ? tep_db_prepare_input($_POST['value'][$languages[$i]['id']]) : 0),
			      'languages_id'=> $languages[$i]['id']);
	}

	tep_db_perform(TABLE_PRODUCTS_EXTRA_FIELDS_VALUES, $data_array, 'update',"value_id = '" . (int)$_GET['vid']."' and epf_id='".self::$eid."' ");
	tep_redirect(tep_href_link(FILENAME_CONFIGURATION, FILENAME_CFG_34 . 'eid=' . self::$eid.'&action=value_listing'));
      break;
      case 'value_insert':

	$languages = tep_get_languages();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++){
	  $data_array = array('sort_order' => (int)(isset($_POST['sort_order'][$languages[$i]['id']]) ? tep_db_prepare_input($_POST['sort_order'][$languages[$i]['id']]) : 0),
                              'epf_value' => (isset($_POST['value'][$languages[$i]['id']]) ? tep_db_prepare_input($_POST['value'][$languages[$i]['id']]) : 0),
			      'languages_id'=> $languages[$i]['id'],
			      'epf_id' => (int)self::$eid,
			      'parent_id' => (int)0,
			      );
	}

	tep_db_perform(TABLE_PRODUCTS_EXTRA_FIELDS_VALUES, $data_array);

	tep_redirect(tep_href_link(FILENAME_CONFIGURATION, FILENAME_CFG_34 . 'eid=' . self::$eid.'&action=value_listing'));
      break;
      case 'value_delete':
        if ($confirm == 'yes') {
          if (isset($_GET['used']) && ($_GET['used'] > 0)) {
            $double_check = 'yes';
          } else {
            $children = tep_list_epf_children($vid);
            $field = 'extra_value_id' . (int)$eid;
            $query = tep_db_query("update " . TABLE_PRODUCTS_DESCRIPTION . " set " . $field . " = 0 where language_id = " . (int)$lid . " and " . $field . " in (" . (int)$vid . $children . ")");
            tep_db_query('delete from ' . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . ' where value_id in (' . (int)$vid . $children . ")");
            tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','vid','list_id','parent'),false).  'list_id=' . $list_id));
          }
        } else {
          $double_check = 'no';
        }
      break;

      case 'value_edit':

	$list_id = (isset($_GET['list_id']) ? $_GET['list_id'] : '_');
	list($eid, $lid) = explode('_', $list_id);
	$vid = (isset($_GET['vid']) ? $_GET['vid'] : '');
	$confirm = (isset($_GET['confirm']) ? $_GET['confirm'] : '');

//         $check_query = tep_db_query("select count(products_id) as total from " . TABLE_PRODUCTS_DESCRIPTION . " where extra_value_id" . (int)$eid . " = " . (int)$vid);
//         $check = tep_db_fetch_array($check_query);
//         if ($check['total'] > 0)  $messageStack->add(WARNING_VALUE_USED. $check['total'],'error');
      break;
      default:

    }
  }

  /**
    @brief load db value
  */
  public function load_db_values(){
    global $action,$languages_id,$messageStack;

    switch($action){


      case 'value_listing':
	/**
	  Delete d'un label
	  @author oscim <mail oscim@oscss.org> <www http://www.oscim.fr>
	*/
	      global $list, $languages,$action ;

	  $eid=self::$eid;
	  $lid=$languages;

	    $query = tep_db_fetch_array(tep_db_query($sql="select epf_label from " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " where epf_id = " . (int)$eid . " and languages_id = " . (int)$lid));
	  //   var_dump($query) ;
	    $current_label = $query['epf_label'];
	    if ($current_label == '') { // if invalid label get first matching label and use that information
	      $query = tep_db_fetch_array(tep_db_query("select l.epf_label, l.languages_id, l.epf_id from " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " l join " . TABLE_PRODUCTS_EXTRA_FIELDS . " e where e.epf_id = l.epf_id and l.epf_active_for_language and e.epf_uses_value_list order by e.epf_order"));
	      $current_label = $query['epf_label'];
	      $eid = $query['epf_id'];
	      $lid = $query['languages_id'];
	      $list_id = $eid . '_' . $lid;
	      $_GET['list_id'] = $list_id; // set so dropdown list of fields will match value list chosen
	    }


	  $list[] = $this->build_value_list($eid, $lid);
		$selected = array();
	  //   var_dump($list) ;
	  //   }
	return $list;
      break;
      case 'value_new':
	$list_id = (isset($_GET['list_id']) ? $_GET['list_id'] : '_');
	list($eid, $lid) = explode('_', $list_id);
	$vid = (isset($_GET['vid']) ? $_GET['vid'] : '');
	$confirm = (isset($_GET['confirm']) ? $_GET['confirm'] : '');
	$parent_id = (isset($_GET['parent']) ? $_GET['parent'] : 0);
      break;

      case 'value_edit':

	$sql = tep_db_query($sql_="select * from " . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . " where epf_id = " . self::$eid. " and  value_id = " . (int)$_GET['vid'] . " order by sort_order, epf_value");

	while ($v = tep_db_fetch_array($sql)) {
	  $res[$v['languages_id']] =$v;
	}

	$languages = tep_get_languages();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++){
	  $list[$languages[$i]['id']] = $res[$languages[$i]['id']] ;
	}
	return $list;
      break;

      case 'edit':
        $query = tep_db_query("select * from " . TABLE_PRODUCTS_EXTRA_FIELDS . " where epf_id = " . (int)self::$eid);
        $this->field = tep_db_fetch_array($query);
        $label_query = tep_db_query("select * from " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " where epf_id = " . (int)self::$eid);
	$this->field['epf_active_for_language']=0;
        $epf_label = array();
        while ($label = tep_db_fetch_array($label_query)) {
          $this->epf_label[$label['languages_id']] = $label;
	  $this->field['epf_active_for_language'] =$label['epf_active_for_language'];
        }
      break;
      case 'new':
        $this->field=array('epf_status'=>''
			  ,'epf_order'=>''
			  ,'epf_advanced_search'=>''
			  ,'epf_show_in_listing'=>''
			  ,'epf_use_as_meta_keyword'=>''
			  ,'epf_show_parent_chain'=>''
			  ,'epf_use_to_restrict_listings'=>''
			  ,'epf_size'=>''
			  ,'epf_key'=>''
			  ,'epf_admin'=>''
			  ,'epf_special_mod'=>''
			  ,'epf_uses_value_list'=>'0'
			  );
	$languages = tep_get_languages();

	for ($i=0, $n=sizeof($languages); $i<$n; $i++){
	    $this->epf_label[$languages[$i]['id']]['epf_label'] ='';
	    $this->field['epf_active_for_language']=false;
	}
      break;
      default:
	$languages = tep_get_languages();
	self::$lang = array();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++) { // build array accessed directly by language id
	  self::$lang[$languages[$i]['id']] = array ('name' => $languages[$i]['name'],
					      'code' => $languages[$i]['code'],
					      'image' => $languages[$i]['image'],
					      'directory' => $languages[$i]['directory']);
	}

	$field_query = tep_db_query("select * from " . TABLE_PRODUCTS_EXTRA_FIELDS . " order by epf_order,epf_admin, epf_special_mod ");
	$selected_labels = array();
	$list=array();
	while ($epf = tep_db_fetch_array($field_query)) {
	  $class= ($epf['epf_id'] == self::$eid)? "Selected" : '';
	  if ($epf['epf_id'] == self::$eid)$selected=$epf;
	  $list[]=new objectInfo($epf);
	}
	return $list;
    }

  }

  /**
    @fn load_for_delete()
    @brief call value for form confim delete
  */
  private static function load_for_delete(){
    global  $languages,$action;
    $query = tep_db_query("select epf_uses_value_list as uses_list from " . TABLE_PRODUCTS_EXTRA_FIELDS . " where epf_id = " . (int)self::$eid);
    $field_info = tep_db_fetch_array($query);

    self::$pInfo=new objectInfo($field_info);

    $field = 'extra_value' . ($field_info['uses_list'] ? '_id' : '') . (int)self::$eid;
    $used = 0;
    for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
      $label_query = tep_db_query("select * from " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " where epf_id = " . (int)self::$eid . " and languages_id = " . (int)$languages[$i]['id']. " and epf_active_for_language='1' ");
      if(tep_db_num_rows($label_query) >0){
	$label = tep_db_fetch_array($label_query);
	$check_query = tep_db_query("select count(products_id) as total from " . TABLE_PRODUCTS_DESCRIPTION . " where language_id = " . (int)$languages[$i]['id'] . " and " . ($field_info['uses_list'] ? $field . " > 0" : "length(" . $field . ") > 0"));
	$check = tep_db_fetch_array($check_query);
	$used += $check['total']; // total how many descriptions use this field
	echo '<p>' . sprintf(TEXT_FIELD_DATA, $languages[$i]['name'], $label['epf_label'], $check['total']) . "</p>\n";
      }
    }
    self::$pInfo->used=$used;
  }

  /**
    Appelé dans le header de page
  */
  public static function draw_header(){
    echo '<script type="text/javascript"><!--'."\n".
    '$(function() {'."\n".
    " $('#tabs').tabs().find('.ui-tabs-nav').sortable({axis:'x'});"."\n".
    " $('.tabs_lang').tabs().find('.ui-tabs-nav').sortable({axis:'x'});"."\n".
    '});'."\n".
  '// --></script>'."\n";
  }

  /**
    Contenu central
  */
  public function draw(){
    global $action,$gparentID,$current_theme, $languages_id;

    switch($action){
      case 'value_listing':
	self::$list= $this->load_db_values();

	return tep_get_include_contents(__CLASS__.'.value.listing');
      break;
      case 'value_new':
      case 'value_edit':

	self::$cInfo=$this->load_db_values();

	return tep_get_include_contents(__CLASS__.'.value.edit');
      break;

      case 'new':
      case 'edit':

	global $list, $languages,$action;
	$this->load_db_values();

	self::$cInfo=$this->field;
	self::$pInfo =  $this->epf_label;
	return tep_get_include_contents(__CLASS__.'.label.edit');
      break;

      case 'delete':
	self::load_for_delete();
	return tep_get_include_contents(__CLASS__.'.delete');
      break;

      default:
	self::$list=$this->load_db_values();
	self::$selected_labels=array();
	$languages = tep_get_languages();
	return tep_get_include_contents(__CLASS__.'.listing');
    }


  }
  /* Private function class */



  /**
    @brief get_item_action($item)
    @brief content col action
    @param $item arrau , detail ligne
  */
  public static function get_item_action($item){
    global $action;
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  '' ,
		  (($item->epf_uses_value_list)? sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,FILENAME_CFG_34.'&eid=' . $item->epf_id . '&amp;action=' . 'value_listing' ) ,'' ) :'').
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,FILENAME_CFG_34.'&eid=' . $item->epf_id . '&amp;action=edit') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME, FILENAME_CFG_34.'&eid=' . $item->epf_id . '&amp;action=delete') ,'' )
		);
  }

  /**
    @brief get_item_action($item)
    @brief content col action
    @param $item arrau , detail ligne
  */
  public static function get_item_value_action($item){
global $action;
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  '' ,
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,FILENAME_CFG_34.'&eid=' . $item['epf_id'] . '&vid=' . $item['value_id'] . '&amp;action=value_edit') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME, FILENAME_CFG_34.'&eid=' . $item['epf_id'] . '&vid=' . $item['value_id'] . '&amp;action=value_delete') ,'' )
		);
  }




  /**
    Colonne droite list labels
  */
  public static  function draw_right_colum($selected=''){
    if(empty($selected))  return;
    $heading = array();
    $contents = array();
    $admin_language = '1';

    if (!empty(self::$eid)) {
      $heading[] = array('text' => TABLE_HEADING_ID . ' ' . self::$eid);
      foreach (self::$selected_labels as $label) {
	$heading[] = array('text' => self::$lang[$label['languages_id']]['name'] . ': ' . $label['epf_label']);
	if ($label['languages_id'] == $languages_id) $admin_language = $languages_id;
      }
      $contents[] = array('align' => 'center', 'text' => '<a class="button" href="' . tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','flag','eid')) . 'eid=' . self::$eid . '&action=edit') . '">' .  IMAGE_EDIT . '</a> <a class="button" href="' . tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','flag','eid')) .'eid=' . self::$eid . '&action=delete') . '">' .  IMAGE_DELETE . '</a>');
      if ($selected->epf_uses_value_list) {
	$contents[] = array('align' => 'center', 'text' => tep_draw_form('edit_values', FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','flag','list_id')) . 'action=value_listing&list_id=' . $selected->epf_id . '_' . $admin_language) . tep_draw_input_field('edit_values','edit_values', BUTTON_EDIT_VALUES, 'alt="' . BUTTON_EDIT_VALUES . '"', false, 'submit',' class="button"') . '</form>');
      }
      $contents[] = array('text' => TABLE_HEADING_STATUS . ': ' . ($selected->epf_status ? TEXT_ENABLED : TEXT_DISABLED));
      $contents[] = array('text' => ENTRY_UNIQ_KEY . $selected->epf_key);
      $contents[] = array('text' => ENTRY_USE_ADMIN . $selected->epf_admin);
      $contents[] = array('text' => ENTRY_SPECIFIQUE_MODULE . $selected->epf_special_mod);
      $contents[] = array('text' => ENTRY_ORDER . $selected->epf_order);
      $contents[] = array('text' => TEXT_SIZE . $selected->epf_size);
      $contents[] = array('text' => TEXT_SEARCHABLE . ($selected->epf_advanced_search ? TEXT_YES : TEXT_NO));
      $contents[] = array('text' => ENTRY_LISTING . ($selected->epf_show_in_listing ? TEXT_YES : TEXT_NO));
      $contents[] = array('text' => TEXT_META . ($selected->epf_use_as_meta_keyword ? TEXT_YES : TEXT_NO));
      $contents[] = array('text' => ENTRY_VALUE_LIST . ($selected->epf_uses_value_list ? TEXT_YES : TEXT_NO));
      $contents[] = array('text' => TEXT_RESTRICTS . ($selected->epf_uses_value_list ? ($selected->epf_use_to_restrict_listings ? TEXT_YES : TEXT_NO) : TEXT_NOT_APPLY));
      $contents[] = array('text' => TEXT_SHOW_PARENTS . ($selected->epf_uses_value_list ? ($selected->epf_show_parent_chain ? TEXT_YES : TEXT_NO) : TEXT_NOT_APPLY));
    }
      ?>
      <div class="box_right">
      <?php
	if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
	  $box = new box;
	  echo $box->infoBox($heading, $contents);
	}
      ?>
      </div>
    <?php
  }


  /** SPECIFIQUE */

  /**
    @author oscim <mail oscim@oscss.org> <www http://www.oscim.fr>
  */
  private function build_value_list($epf_id, $lang_id, $value_array = '', $parent_id = 0) {
    if (!is_array($value_array)) $value_array = array();
    $sql = tep_db_query($sql_="select * from " . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . " where epf_id = " . (int)$epf_id . " and languages_id = " . (int)$lang_id . " and parent_id = " . (int)$parent_id . " order by sort_order, epf_value");
// echo $sql_;
    while ($v = tep_db_fetch_array($sql)) {
      $value_array[] = $v;
      $value_array = $this->build_value_list($epf_id, $lang_id, $value_array, $v['value_id']);
    }
    return $value_array;
  }

}


?>
