Index: /extensions/ColorStat/admin/cstat_config.tpl
===================================================================
--- /extensions/ColorStat/admin/cstat_config.tpl	(revision 6175)
+++ /extensions/ColorStat/admin/cstat_config.tpl	(revision 6176)
@@ -25,4 +25,26 @@
 <script type="text/javascript">
 
+  function displayConfig(tabsheet)
+  {
+    switch(tabsheet)
+    {
+      case 'database':
+        $('#iDisplayConfigDatabase').css('display', 'block');
+        $('#iDisplayConfigStatSearch').css('display', 'none');
+        $('#iDisplayConfigDisplay').css('display', 'none');
+        break;
+      case 'statsearch':
+        $('#iDisplayConfigDatabase').css('display', 'none');
+        $('#iDisplayConfigStatSearch').css('display', 'block');
+        $('#iDisplayConfigDisplay').css('display', 'none');
+        break;
+      case 'display':
+        $('#iDisplayConfigDatabase').css('display', 'none');
+        $('#iDisplayConfigStatSearch').css('display', 'none');
+        $('#iDisplayConfigDisplay').css('display', 'block');
+        break;
+    }
+
+  }
 
   function init()
@@ -38,4 +60,5 @@
       });
     $("#icstat_stat_minPct_slider a").addClass('gcBgInput');
+    displayConfig('database');
   }
 
@@ -48,5 +71,5 @@
 {/literal}
 
-
+{$configTabsheet}
 
 <h2>{'cstat_config_plugin'|@translate}</h2>
@@ -54,37 +77,41 @@
 <form id="iConfig" method="post" action="" class="general">
 
-  <fieldset>
-    <legend>{'cstat_stat_and_search'|@translate}</legend>
+  <div id='iDisplayConfigDatabase' style='display:none;'>
 
-    <table class="formtable">
-      <tr>
-        <td colspan="2">{'cstat_percent_min_significant'|@translate}</td>
-      </tr>
-      <tr>
-        <td>
-          <input type="hidden" name="f_stat_minPct" id="icstat_stat_minPct" value="{$datas.minPct}">
-          <div id="icstat_stat_minPct_slider" class="gcBgInput gcBorderInput"></div>
-        </td>
-        <td width="90px">
-          <div id="icstat_stat_minPct_display"></div>
-        </td>
-      </tr>
-    </table>
+  </div>
 
-  </fieldset>
+  <div id='iDisplayConfigStatSearch'  style='display:none;'>
+    <fieldset>
+      <legend>{'cstat_stat_and_search'|@translate}</legend>
 
+      <table class="formtable">
+        <tr>
+          <td colspan="2">{'cstat_percent_min_significant'|@translate}</td>
+        </tr>
+        <tr>
+          <td>
+            <input type="hidden" name="f_stat_minPct" id="icstat_stat_minPct" value="{$datas.minPct}">
+            <div id="icstat_stat_minPct_slider" class="gcBgInput gcBorderInput"></div>
+          </td>
+          <td width="90px">
+            <div id="icstat_stat_minPct_display"></div>
+          </td>
+        </tr>
+      </table>
+    </fieldset>
+  </div>
 
-  <fieldset>
-    <legend>{'cstat_gallery_integration'|@translate}</legend>
+  <div id='iDisplayConfigDisplay'  style='display:none;'>
+    <fieldset>
+      <legend>{'cstat_gallery_integration'|@translate}</legend>
 
-    <label>
-      <input type="checkbox" id='idisplay_gallery_showColorsCBox' onclick="$('#idisplay_gallery_showColors').val(($('#idisplay_gallery_showColorsCBox').get(0).checked=='on')?'y':'n');"  {if $datas.showColors=='y'}checked{/if} >
-      {'cstat_display_colors_on_image'|@translate}
-      <input type="hidden" id='idisplay_gallery_showColors' name='f_display_gallery_showColors' value='{$datas.showColors}'>
-    </label>
+      <label>
+        <input type="checkbox" id='idisplay_gallery_showColorsCBox' onclick="$('#idisplay_gallery_showColors').val(($('#idisplay_gallery_showColorsCBox').get(0).checked=='on')?'y':'n');"  {if $datas.showColors=='y'}checked{/if} >
+        {'cstat_display_colors_on_image'|@translate}
+        <input type="hidden" id='idisplay_gallery_showColors' name='f_display_gallery_showColors' value='{$datas.showColors}'>
+      </label>
 
-  </fieldset>
-
-
+    </fieldset>
+  </div>
 
   <input type="submit" value="{'cstat_apply'|@translate}" name="submit_save_config" style="margin-left:1em;" >
Index: /extensions/ColorStat/admin/cstat_search.tpl
===================================================================
--- /extensions/ColorStat/admin/cstat_search.tpl	(revision 6175)
+++ /extensions/ColorStat/admin/cstat_search.tpl	(revision 6176)
@@ -1,284 +1,4 @@
-{known_script id="jquery.ui" src=$ROOT_URL|@cat:"themes/default/js/ui/packed/ui.core.packed.js"}
-{known_script id="jquery.ui.dialog" src=$ROOT_URL|@cat:"themes/default/js/ui/packed/ui.dialog.packed.js"}
-{known_script id="jquery.tipTip" src=$ROOT_URL|@cat:"themes/default/js/plugins/jquery.tipTip.minified.js"}
-
-{known_script id="gpc.pagesNavigator" src=$ROOT_URL|@cat:"plugins/GrumPluginClasses/js/pagesNavigator.js"}
-
-
-{literal}
-<script type="text/javascript">
-var cb=null;
-
-  interfaceManager = function(optionsToSet)
-  {
-    var pn=null;
-    var requestNumber=0;
-
-    options =
-      {
-        requestCriterionsVisible:'',
-        requestCriterionsHidden:'',
-        requestResult:'',
-        requestResultContent:'',
-        requestResultNfo:'',
-        requestResultPagesNavigator:'',
-        requestResultRequestNumber:0,
-        onPageChange:null,
-        numberPerPage:30,
-      };
-
-    /**
-     *
-     */
-    this.doAction = function(fct)
-    {
-      switch(fct)
-      {
-        case 'queryResult':
-          /* function 'queryResult' : when query is executed, prepare the interface
-           */
-          if(arguments.length==3)
-          {
-            displayQueryResult(arguments[1], arguments[2]);
-          }
-          break;
-        case 'queryPage':
-          /* function 'queryPage' : display returned page
-           */
-          if(arguments.length==3)
-          {
-            displayQueryPage(arguments[1], arguments[2]);
-          }
-          break;
-        case 'show':
-          /* function 'show' : show/hide the query/result
-           */
-          if(arguments.length==2)
-          {
-            show(arguments[1]);
-          }
-          break;
-        case 'setOptions':
-          /* function 'setOptions' : allows to set options after the object was
-           *                         created
-           */
-          if(arguments.length==2)
-          {
-            setOptions(arguments[1]);
-          }
-          break;
-      }
-    }
-
-    /**
-     * returns the current request number
-     */
-    this.getRequestNumber = function ()
-    {
-      return(requestNumber);
-    }
-
-    /**
-     * returns the number of items per page
-     */
-    this.getNumberPerPage = function ()
-    {
-      return(options.numberPerPage);
-    }
-
-    /**
-     * this function show/hide the different panels
-     *  'buildQuery'  : hide the result panel and display the panel to build query
-     *  'resultQuery' : hide the panel to build query and display the result panel
-     */
-    var show = function(mode)
-    {
-      switch(mode)
-      {
-        case 'buildQuery':
-          $('.'+options.requestCriterionsVisible).css('display', 'block');
-          $('.'+options.requestCriterionsHidden).css('display', 'none');
-          $('.'+options.requestResult).css('display', 'none');
-          break;
-        case 'resultQuery':
-          $('#iResultQueryContent').html("<br><img src='./plugins/GrumPluginClasses/icons/processing.gif'>");
-          $('.'+options.requestCriterionsVisible).css('display', 'none');
-          $('.'+options.requestCriterionsHidden).css('display', 'block');
-          $('.'+options.requestResult).css('display', 'block');
-          break;
-      }
-    }
-
-    /**
-     * this function display the number of items found and prepare the page
-     * navigator
-     *
-     * @param String nfo : 2 information separated with a semi-colon ';'
-     *                      requestNumber;numberOfItems
-     */
-    var displayQueryResult = function (isSuccess, nfo)
-    {
-      if(isSuccess)
-      {
-        nfo=nfo.split(';');
-
-        requestNumber=nfo[0];
-        $('#iResultQueryNfo').html(nfo[1]);
-        pn.doAction('setOptions', { numberItem:nfo[1], defaultPage:1 } );
-        show('resultQuery');
-      }
-      else
-      {
-        //$('#'+options.requestResultContent).html("");
-        show('buildQuery');
-        alert('Something is wrong on the server-side !');
-      }
-    }
-
-
-    /**
-     * this function display the number of items found and prepare the page
-     * navigator
-     *
-     * @param String nfo : 2 information separated with a semi-colon ';'
-     *                      requestNumber;numberOfItems
-     */
-    var displayQueryPage = function (isSuccess, nfo)
-    {
-      if(isSuccess)
-      {
-        $('#iResultQueryContent').html(nfo);
-      }
-      else
-      {
-        alert('Something is wrong on the server-side !');
-      }
-    }
-
-
-    /**
-     *
-     * @param Object optionsToSet : set the given options
-     */
-    var setOptions = function(optionsToSet)
-    {
-      if(typeof optionsToSet=='object')
-      {
-        options = jQuery.extend(options, optionsToSet);
-      }
-    }
-
-    /**
-     * initialize the object
-     */
-    var init = function (optionsToSet)
-    {
-      setOptions(optionsToSet);
-
-      pn = new pagesNavigator(options.requestResultPagesNavigator,
-        {
-          itemPerPage:options.numberPerPage,
-          displayNumPage:9,
-          classActive:'pnActive{/literal}{$datas.themeName}{literal}',
-          classInactive:'pnInactive{/literal}{$datas.themeName}{literal}',
-          onPageChange: function (page)
-            {
-              if(options.onPageChange!=null && jQuery.isFunction(options.onPageChange))
-              {
-                options.onPageChange(requestNumber, page, options.numberPerPage);
-              }
-            },
-        }
-      );
-
-      requestNumber=options.requestResultRequestNumber;
-    }
-
-    init(optionsToSet);
-  }
-
-
-  function init()
-  {
-    im = new interfaceManager(
-      {
-        requestCriterionsVisible:'cRequestCriterions',
-        requestCriterionsHidden:'cModifyRequest',
-        requestResult:'cResultQuery',
-        requestResultContent:'iResultQueryContent',
-        requestResultNfo:'iResultQueryNfo',
-        requestResultPagesNavigator:'iPagesNavigator',
-      }
-    );
-
-    requestBuilderOptions.imgEditUrl='{/literal}{$ROOT_URL}{$themeconf.admin_icon_dir}{literal}/edit_s.png';
-    requestBuilderOptions.imgDeleteUrl='{/literal}{$ROOT_URL}{$themeconf.admin_icon_dir}{literal}/delete.png';
-    requestBuilderOptions.classGroup='gcBorderInput gcTextInput';
-    requestBuilderOptions.classItem='gcBgInput gcTextInput';
-    requestBuilderOptions.classOperator='cbOperator cbOperatorBg{/literal}{$datas.themeName}{literal} gcLinkHover';
-    requestBuilderOptions.onRequestSuccess = function (msg) { im.doAction('queryResult', true, msg); cb.doAction('getPage', im.getRequestNumber(), 1, im.getNumberPerPage()); };
-    requestBuilderOptions.onRequestError = function (msg) { im.doAction('queryResult', false, msg); };
-    requestBuilderOptions.onGetPageSuccess = function (msg) { im.doAction('queryPage', true, msg); };
-    requestBuilderOptions.onGetPageError = function (msg) { im.doAction('queryPage', false, msg); };
-
-    cb = new criteriaBuilder('iListColorsChoosen', requestBuilderOptions);
-
-    im.doAction('setOptions',
-      { onPageChange:
-          function (requestNumber, page, numberPerPage)
-          {
-            $('#iResultQueryContent').html("<br><img src='./plugins/GrumPluginClasses/icons/processing.gif'>");
-            cb.doAction('getPage', requestNumber, page, numberPerPage);
-          }
-      }
-    );
-
-  }
-
-
-
-</script>
-{/literal}
-
-{$datas.dialogBox}
 
 <h2>{'cstat_search_by_color'|@translate}</h2>
 
-<form>
-  <fieldset>
-    <legend>{'cstat_search_criterion'|@translate}</legend>
-
-    <div id='iRequestCriterions' class='cRequestCriterions'>
-      <div style='width:100%;min-height:250px;margin-bottom:8px;'>
-        <ul id='iListColorsChoosen'>
-        </ul>
-      </div>
-
-      <div class='gcBgInput cbButtons'>{literal}<a onclick="colorBox.show({cBuilder:cb});">{/literal}{'cstat_add_colors'|@translate}</a></div>
-      <div class='gcBgInput cbButtons'>{literal}<a onclick="cb.doAction('clear');">{/literal}{'cstat_clear_colors'|@translate}</a></div>
-    </div>
-    <div class='cModifyRequest' style='display:none;'>
-      <div class='gcBgInput cbButtons'>{literal}<a onclick="im.doAction('show', 'buildQuery');">{/literal}{'cstat_do_modify_request'|@translate}</a></div>
-    </div>
-
-  </fieldset>
-
-  <input type="button" class='cRequestCriterions' style="margin-left:1em;" onclick="cb.doAction('send');" value="{'cstat_search'|@translate}">
-</form>
-
-  <fieldset id='iResultQuery' style='display:none;' class='cResultQuery'>
-    <legend>{'cstat_result_query'|@translate}</legend>
-
-    <div id='iResultQueryContent' style='width:100%;min-height:250px;max-height:450px;overflow:auto;margin-bottom:8px;'></div>
-
-    <div class='gcBgInput gcTextInput'>
-      <div id='iPagesNavigator' style='float:right;'></div>
-      <div style='text-align:left;padding:4px;'>{'cstat_number_of_item_found'|@translate}&nbsp;:&nbsp;<span id='iResultQueryNfo'></span></div>
-    </div>
-
-  </fieldset>
-
-
-<script type="text/javascript">
- init();
-</script>
+{$cstat_search_page}
Index: /extensions/ColorStat/cstat.css
===================================================================
--- /extensions/ColorStat/cstat.css	(revision 6175)
+++ /extensions/ColorStat/cstat.css	(revision 6176)
@@ -41,63 +41,4 @@
 }
 
-
-#iListColorsChoosen { padding:0px; }
-
-#iListColorsChoosen ul li, #dragHelper ul li {
-  clear:both;
-  min-height:32px;
-  list-style-image:none;
-  list-style-position:outside;
-  list-style-type:none;
-  margin:4px;
-  padding:0px;
-}
-
-#iListColorsChoosen ul { padding:0px; }
-
-
-.cbGroup { border-width:1px; border-style:solid; padding:0px; margin:2px; min-height:30px; list-style:none; }
-.cbItem {   padding:2px; margin:8px; min-height:34px; list-style:none; }
-
-#iListColorsChoosen ul li.cbItem, #dragHelper ul li.cbItem { padding:2px; }
-
-.cbItemButtons { padding:2px; }
-.cbItem img { cursor: pointer; }
-
-.cbSortHandle { cursor:move; }
-
-div.cbOperator {
- cursor:pointer;
- padding:4px;
- text-align:left;
- font-weight:bold;
-}
-
-div.cbOperatorBgroma {
- background:#333333;
-}
-
-div.cbOperatorBgclear {
- background:#dbe8f3;
-}
-
-.cbButtons {
-  float:left;
-  margin:2px;
-  padding:8px;
-}
-
-.helper {
- border:2px dashed #777777;
-}
-
-.cPnActive, .cPnDisabled, .cPnInactive { margin:2px; padding:2px;  min-width:20px; text-align:center; }
-.pnInactiveclear, .pnInactiveroma { cursor:pointer; }
-.pnInactiveclear:hover { background:#F1F1F1; }
-.pnActiveclear { background:#F1F1F1; font-weight:bold; }
-.pnInactiveroma:hover { background:#999999; color:#444444; }
-.pnActiveroma { background:#999999; color:#444444; font-weight:bold; }
-#iPagesNavigator ul { margin:0px; }
-
 .color1px { border-spacing:1px; }
 .color0px { border-spacing:0px; }
Index: /extensions/ColorStat/cstat_aip.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_aip.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_aip.class.inc.php	(revision 6176)
@@ -221,14 +221,15 @@
                 dirname($this->getFileLocation()).'/admin/cstat_stat.tpl');
 
-    $colorTable=$this->getColorTableWithStat();
+    $colorTable=CStat_functions::getColorTableWithStat();
 
 
     $datas=Array(
       //'themeconf' => Array('name' => $template->get_themeconf('name')),
-      'colorTable' => $this->htmlColorTable(
+      'colorTable' => CStat_functions::htmlColorTable(
                         $colorTable,
                         ($this->config['analyze_colorTable']=='small')?19:10,
                         "",
-                        "color0px"
+                        "color0px",
+                        "<br>"
                       ),
       'urlRequest' => $this->getAdminLink(),
@@ -250,10 +251,5 @@
                 dirname($this->getFileLocation()).'/admin/cstat_search.tpl');
 
-    $datas=Array(
-      'dialogBox' => $this->dialogBoxColor(),
-      'themeName' => $template->get_themeconf('name'),
-    );
-
-    $template->assign('datas', $datas);
+    $template->assign('cstat_search_page', GPCRequestBuilder::displaySearchPage());
 
     $template->assign_var_from_handle('CSTAT_BODY_PAGE', 'body_page');
@@ -297,4 +293,16 @@
   {
     global $template, $lang;
+
+    $configTabs=new GPCTabSheet('configTabsheet', $this->tabsheet->get_titlename(), 'tabsheet2 gcBorder', 'itab2');
+    $configTabs->add('database',
+                      l10n('cstat_database'),
+                      '', true, "displayConfig('database');");
+    $configTabs->add('statsearch',
+                      l10n('cstat_stat_and_search'),
+                      '', false, "displayConfig('statsearch');");
+    $configTabs->add('display',
+                      l10n('cstat_gallery_integration'),
+                      '', false, "displayConfig('display');");
+    $configTabs->assign();
 
     $template->set_filename('body_page',
@@ -390,48 +398,4 @@
 
 
-  protected function getGeneralStats()
-  {
-    $returned=Array(
-      'nbImages' => 0,
-      'totalTime' => 0,
-      'pixelsAnalyzedMax' => 0,
-      'pixelsAnalyzedMin' => 0,
-      'pixelsAnalyzedAvg' => 0,
-      'pixelsAnalyzedSum' => 0,
-      'totalPixels' => 0,
-      'ppsMax' => 0,
-      'ppsMin' => 0,
-      'ppsAvg' => 0,
-      'qualityMax' => 0,
-      'qualityMin' => 0,
-      'qualityAvg' => 0,
-    );
-    $sql="SELECT COUNT(image_id) AS nbImages,
-                 SUM(time) AS totalTime,
-                 MAX(analyzed_pixels) AS pixelsAnalyzedMax,
-                 MIN(analyzed_pixels) AS pixelsAnalyzedMin,
-                 AVG(analyzed_pixels) AS pixelsAnalyzedAvg,
-                 SUM(analyzed_pixels) AS pixelsAnalyzedSum,
-                 SUM(num_pixels) AS totalPixels,
-                 MAX(pps) AS ppsMax,
-                 MIN(pps) AS ppsMin,
-                 AVG(pps) AS ppsAvg,
-                 MAX(quality) AS qualityMax,
-                 MIN(quality) AS qualityMin,
-                 AVG(quality) AS qualityAvg
-          FROM ".$this->tables['images']."
-          WHERE analyzed='y';";
-    $result=pwg_query($sql);
-    if($result)
-    {
-      while($row=pwg_db_fetch_assoc($result))
-      {
-        $returned=$row;
-      }
-    }
-    return($returned);
-  }
-
-
   /**
    * make consolidation for the color_table :
@@ -626,6 +590,6 @@
       {
         $colorTable=ColorStat::getColorTable(
-          $this->colorTableSize[$this->config['analyze_colorTable']][0],
-          $this->colorTableSize[$this->config['analyze_colorTable']][1]
+          CStat_root::$colorTableSize[$this->config['analyze_colorTable']][0],
+          CStat_root::$colorTableSize[$this->config['analyze_colorTable']][1]
         );
 
@@ -688,5 +652,5 @@
                   dirname($this->getFileLocation()).'/admin/cstat_stat_show_iListColors.tpl');
 
-    $generalStats=$this->getGeneralStats();
+    $generalStats=CStat_functions::getGeneralStats();
 
     $sql="SELECT color_id, num_images, num_pixels
Index: /extensions/ColorStat/cstat_aip_install.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_aip_install.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_aip_install.class.inc.php	(revision 6176)
@@ -126,12 +126,12 @@
                 dirname($this->getFileLocation()).'/admin/cstat_install_page.tpl');
 
-    $smallColorTable=ColorStat::getColorTable($this->colorTableSize['small'][0],$this->colorTableSize['small'][1]);
-    $largeColorTable=ColorStat::getColorTable($this->colorTableSize['large'][0],$this->colorTableSize['large'][1]);
-    $template->assign('smallTableColor', $this->htmlColorTable($smallColorTable, 19, '', 'color0px'));
-    $template->assign('largeTableColor', $this->htmlColorTable($largeColorTable, 10, '', 'color0px'));
+    $smallColorTable=ColorStat::getColorTable(CStat_root::$colorTableSize['small'][0],CStat_root::$colorTableSize['small'][1]);
+    $largeColorTable=ColorStat::getColorTable(CStat_root::$colorTableSize['large'][0],CStat_root::$colorTableSize['large'][1]);
+    $template->assign('smallTableColor', CStat_functions::htmlColorTable($smallColorTable, 19, '', 'color0px'));
+    $template->assign('largeTableColor', CStat_functions::htmlColorTable($largeColorTable, 10, '', 'color0px'));
 
     $template->assign(
       'smallColorList1',
-      $this->htmlColorList(
+      CStat_functions::htmlColorList(
         ColorStat::getFileColors(dirname($this->getFileLocation()).'/image/sample1.png', $smallColorTable, Array('quality' => 8, 'numColors' => 16)),
         16, 18, '', 'colorListSample color0px'
@@ -142,5 +142,5 @@
     $template->assign(
       'largeColorList1',
-      $this->htmlColorList(
+      CStat_functions::htmlColorList(
         ColorStat::getFileColors(dirname($this->getFileLocation()).'/image/sample1.png', $largeColorTable, Array('quality' => 8, 'numColors' => 16)),
         16, 18, '', 'colorListSample color0px'
@@ -151,5 +151,5 @@
     $template->assign(
       'smallColorList2',
-      $this->htmlColorList(
+      CStat_functions::htmlColorList(
         ColorStat::getFileColors(dirname($this->getFileLocation()).'/image/sample2.png', $smallColorTable, Array('quality' => 8, 'numColors' => 16)),
         16, 18, '', 'colorListSample color0px'
@@ -160,5 +160,5 @@
     $template->assign(
       'largeColorList2',
-      $this->htmlColorList(
+      CStat_functions::htmlColorList(
         ColorStat::getFileColors(dirname($this->getFileLocation()).'/image/sample2.png', $largeColorTable, Array('quality' => 8, 'numColors' => 16)),
         16, 18, '', 'colorListSample color0px'
@@ -205,16 +205,19 @@
     $this->saveConfig();
 
-    $colorTable=ColorStat::getColorTable($this->colorTableSize[$tableSize][0],$this->colorTableSize[$tableSize][1]);
-
-    foreach($colorTable as $key => $val)
+    $colorTable=ColorStat::getColorTable(CStat_root::$colorTableSize[$tableSize][0],CStat_root::$colorTableSize[$tableSize][1]);
+
+    foreach($colorTable as $key => $hue)
     {
-      foreach($val as $key2 => $val2)
+      foreach($hue as $key2 => $saturation)
       {
-        $hsv=$val2->get();
-        $sql.=(($sql=="")?"":", ")."('".$val2->getRGB()->getHexString()."',
-               '".$hsv['H']."',
-               '".$hsv['S']."',
-               '".$hsv['V']."',
-               0, 0)";
+        foreach($saturation as $key3=>$value)
+        {
+          $hsv=$value->get();
+          $sql.=(($sql=="")?"":", ")."('".$value->getRGB()->getHexString()."',
+                 '".$hsv['H']."',
+                 '".$hsv['S']."',
+                 '".$hsv['V']."',
+                 0, 0)";
+        }
       }
     }
Index: /extensions/ColorStat/cstat_colorstat.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_colorstat.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_colorstat.class.inc.php	(revision 6176)
@@ -46,5 +46,18 @@
   --------------------------------------------------------------------------- */
 
-  if(!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
+if(!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
+
+/**
+ * if DEBUG_MODE is set to true, the getFileColors function save a jpg file of
+ * the 'viewed' image :
+ *  - resampled file
+ *  - color from the color table
+ *
+ * use it only for debug, or if you are curious about what the function really
+ * see
+ */
+define('DEBUG_MODE', false);
+
+
 
 /**
@@ -59,4 +72,12 @@
   }
 
+  /**
+   * set the R,G and B values
+   *
+   * @param Byte $R : the red value, between [0..255]
+   * @param Byte $G : the green value, between [0..255]
+   * @param Byte $B : the blue value, between [0..255]
+   * @return Array('R'=>$R, 'G'=>$G, 'B'=>$B)
+   */
   public function set($R, $G, $B)
   {
@@ -67,4 +88,10 @@
   }
 
+  /**
+   * set RGB values from an Integer (0xFFFFFF : white value)
+   *
+   * @param Integer $value : the RGB value
+   * @return Array('R'=>$R, 'G'=>$G, 'B'=>$B)
+   */
   public function setInt($value)
   {
@@ -76,4 +103,12 @@
   }
 
+  /**
+   * returns the current RGB values as array
+   *
+   * @param Boolean $floatValue : if set to true, values are returned as float
+   *                              values between [0..1] otherwise values are
+   *                              returned as integer between [0..255]
+   * @return Array('R'=>$R, 'G'=>$G, 'B'=>$B)
+   */
   public function get($floatValue=false)
   {
@@ -94,4 +129,10 @@
   }
 
+
+  /**
+   * returns the current RGB values as hex string  ('FFFFFF' : white)
+   *
+   * @return String
+   */
   public function getHexString()
   {
@@ -99,4 +140,9 @@
   }
 
+  /**
+   * returns the current RGB values as integer  (0xFFFFFF : white)
+   *
+   * @return Integer
+   */
   public function getInt()
   {
@@ -104,4 +150,10 @@
   }
 
+
+  /**
+   * returns the current RGB values as a HSV object
+   *
+   * @return HSV
+   */
   public function getHSV()
   {
@@ -109,4 +161,9 @@
   }
 
+  /**
+   * set the RGB values from a HSV ojbect
+   *
+   * @param HSV $hsv : a HSV object
+   */
   public function setHSV(HSV $hsv)
   {
@@ -118,4 +175,11 @@
   }
 
+  /**
+   * set the RGB property
+   *
+   * @param String $property : 'R', 'G', 'B'
+   * @param Integer $value : value between [0..255]
+   * @return Integer : value of the property
+   */
   private function setProperty($property, $value)
   {
@@ -143,4 +207,12 @@
   }
 
+  /**
+   * set the H, S and V values
+   *
+   * @param Integer $H : the hue value, between [0..360]
+   * @param Byte $S    : the saturation value, between [0..100]
+   * @param Byte $V    : the value value, between [0..100]
+   * @return Array('H'=>$H, 'S'=>$S, 'V'=>$V)
+   */
   public function set($H, $S, $V)
   {
@@ -151,4 +223,9 @@
   }
 
+  /**
+   * returns the current HSV values as array
+   *
+   * @return Array('H'=>$H, 'S'=>$S, 'V'=>$V)
+   */
   public function get()
   {
@@ -156,4 +233,9 @@
   }
 
+  /**
+   * returns the current HSV values as a RGB object
+   *
+   * @return RGB
+   */
   public function getRGB()
   {
@@ -161,4 +243,11 @@
   }
 
+
+
+  /**
+   * set the HSV values from a RGB ojbect
+   *
+   * @param RGB $rgb : a RGB object
+   */
   public function setRGB(RGB $rgb)
   {
@@ -170,4 +259,11 @@
   }
 
+  /**
+   * set the HSV property
+   *
+   * @param String $property : 'H', 'S', 'V'
+   * @param Integer $value : value between [0..255]
+   * @return Integer : value of the property
+   */
   private function setProperty($property, $value)
   {
@@ -203,4 +299,9 @@
 
   /**
+   * returns colors of an image file
+   *
+   * return :
+   *
+   *
    *
    * @param String $fileName : the name of picture to scan
@@ -212,5 +313,8 @@
    *                          if 'maxTime' and 'pps' are greater than zero, the
    *                          quality parameter is computed automatically
-   * @return Array : an array of HSV objects
+   * @return : -1 if file doesn't exist
+   *           -2 if file is not a PNG, a JPEG or a GIF file
+   *           -3 if a fatal error occurs
+   *            array of HSV objects if everthing is Ok
    */
   static function getFileColors($fileName, $colorTable, $options=array())
@@ -229,112 +333,145 @@
       $time=microtime(true);
 
-      if(preg_match('/.*\.gif$/i', $fileName))
+      try
       {
-        $image = imagecreatefromgif($fileName);
+        if(preg_match('/.*\.gif$/i', $fileName))
+        {
+          $image = imagecreatefromgif($fileName);
+        }
+        elseif(preg_match('/.*\.(jpg|jpeg)$/i', $fileName))
+        {
+          $image = imagecreatefromjpeg($fileName);
+        }
+        elseif(preg_match('/.*\.png$/i', $fileName))
+        {
+          $image = imagecreatefrompng($fileName);
+        }
+        else
+        {
+          return(-2);
+        }
+
+
+        $imageWidth=imagesx($image);
+        $imageHeight=imagesy($image);
+
+        if($options['pps']>0 && $options['maxTime']>0)
+        {
+          $quality=round(sqrt($imageWidth*$imageHeight/($options['pps']*$options['maxTime'])), 0);
+        }
+        else
+        {
+          $quality=$options['quality'];
+        }
+
+        $imageWorkWidth=round($imageWidth/$quality,0);
+        $imageWorkHeight=round($imageHeight/$quality,0);
+        $imageWork=imagecreatetruecolor($imageWorkWidth,$imageWorkHeight);
+        imagecopyresampled($imageWork, $image, 0, 0, 0, 0, $imageWorkWidth, $imageWorkHeight, $imageWidth, $imageHeight);
+        //imagecopyresized($imageWork, $image, 0, 0, 0, 0, $imageWorkWidth, $imageWorkHeight, $imageWidth, $imageHeight);
+        imagedestroy($image);
+
+        $returned=Array();
+
+        $i=0;
+        for($px=0;$px<$imageWorkWidth;$px++)
+        {
+          for($py=0;$py<$imageWorkHeight;$py++)
+          {
+            $i++;
+            $value=imagecolorat($imageWork, $px, $py);
+
+            $rgb=self::IntToRGB($value);
+            //echo sprintf("%06x", $value)." => ".$rgb->getHexString();
+
+
+            //echo " ($i) ".$color->getHexString()."<br>";
+
+            if(DEBUG_MODE)
+            {
+              $color=self::getColorFromTable($rgb->getHSV(), $colorTable);
+              $newRGB=$color->get();
+              $col=imagecolorallocate($imageWork, $newRGB['R'], $newRGB['G'], $newRGB['B']);
+              imagesetpixel($imageWork, $px, $py, $col);
+              imagecolordeallocate($imageWork, $col);
+              $color=$color->getHexString();
+              unset($newRGB);
+            }
+            else
+            {
+              $color=self::getColorFromTable($rgb->getHSV(), $colorTable)->getHexString();
+            }
+
+
+            if(array_key_exists($color, $returned))
+            {
+              $returned[$color]['num']++;
+            }
+            else
+            {
+              $returned[$color]=Array(
+                'hsv' => $rgb->getHSV()->get(),
+                'num' => 1,
+                'pct' => 0,
+              );
+            }
+            unset($rgb);
+          }
+        }
+
+
+        if(DEBUG_MODE)
+        {
+          $fName="q".$quality."_c".$options['numColors']."_nb".count($returned)."_".$fileName.".png";
+          imagepng($imageWork, $fName);
+        }
+
+
+        imagedestroy($imageWork);
+        uasort($returned, Array('ColorStat', 'sortTones'));
+
+        if($options['numColors']>0)
+        {
+          foreach($returned as $key=>$val)
+          {
+            $returnedColors[$key]=$val;
+            $options['numColors']--;
+            if($options['numColors']<=0) break;
+          }
+        }
+        else
+        {
+          $returnedColors=$returned;
+        }
+
+        self::$fileColorsStat=Array(
+          'pixels'   => $imageWidth*$imageHeight,
+          'analyzed' => $i,
+          'time'     => microtime(true)-$time,
+          'colors'   => count($returned),
+          'pps'      => $i/(microtime(true)-$time),
+          'quality'  => $quality,
+        );
+
+        if(DEBUG_MODE)
+        {
+          self::$fileColorsStat['fileName']=$fName;
+        }
+
+        unset($returned);
+
+        foreach($returnedColors as $key => $val)
+        {
+          $returnedColors[$key]['pct']=round(100*$val['num']/self::$fileColorsStat['analyzed'],2);
+        }
+
+        return($returnedColors);
       }
-      elseif(preg_match('/.*\.(jpg|jpeg)$/i', $fileName))
+      catch (Exception $e)
       {
-        $image = imagecreatefromjpeg($fileName);
+        echo "ERROR!<br>".print_r($e, true);
+        return(-3);
       }
-      elseif(preg_match('/.*\.png$/i', $fileName))
-      {
-        $image = imagecreatefrompng($fileName);
-      }
-      else
-      {
-        return(-2);
-      }
-
-      $imageWidth=imagesx($image);
-      $imageHeight=imagesy($image);
-
-      if($options['pps']>0 && $options['maxTime']>0)
-      {
-        $quality=round(sqrt($imageWidth*$imageHeight/($options['pps']*$options['maxTime'])), 0);
-      }
-      else
-      {
-        $quality=$options['quality'];
-      }
-
-      $imageWorkWidth=round($imageWidth/$quality,0);
-      $imageWorkHeight=round($imageHeight/$quality,0);
-      $imageWork=imagecreatetruecolor($imageWorkWidth,$imageWorkHeight);
-      imagecopyresampled($imageWork, $image, 0, 0, 0, 0, $imageWorkWidth, $imageWorkHeight, $imageWidth, $imageHeight);
-      //imagecopyresized($imageWork, $image, 0, 0, 0, 0, $imageWorkWidth, $imageWorkHeight, $imageWidth, $imageHeight);
-      imagedestroy($image);
-
-      $returned=Array();
-
-      $i=0;
-      for($px=0;$px<$imageWorkWidth;$px++)
-      {
-        for($py=0;$py<$imageWorkHeight;$py++)
-        {
-          $i++;
-          $value=imagecolorat($imageWork, $px, $py);
-
-          $rgb=self::IntToRGB($value);
-          //echo sprintf("%06x", $value)." => ".$rgb->getHexString();
-
-          $color=self::getColorFromTable($rgb->getHSV(), $colorTable)->getHexString();
-          //echo " ($i) $color<br>";
-
-          if(array_key_exists($color, $returned))
-          {
-            $returned[$color]['num']=$returned[$color]['num']+1;
-          }
-          else
-          {
-            $returned[$color]=Array(
-              'hsv' => $rgb->getHSV()->get(),
-              'num' => 1,
-              'pct' => 0,
-            );
-          }
-          unset($rgb);
-        }
-      }
-
-      /*
-      $fName="q".$quality."_c".$options['numColors']."_".$fileName.".png";
-      imagepng($imageWork, $fName);
-      */
-
-      imagedestroy($imageWork);
-      uasort($returned, Array('ColorStat', 'sortTones'));
-
-      if($options['numColors']>0)
-      {
-        foreach($returned as $key=>$val)
-        {
-          $returnedColors[$key]=$val;
-          $options['numColors']--;
-          if($options['numColors']<=0) break;
-        }
-      }
-      else
-      {
-        $returnedColors=$returned;
-      }
-
-      self::$fileColorsStat=Array(
-        'pixels'   => $imageWidth*$imageHeight,
-        'analyzed' => $i,
-        'time'     => microtime(true)-$time,
-        'colors'   => count($returned),
-        'pps'      => $i/(microtime(true)-$time),
-        'quality'  => $quality,
-        //'fileName' => $fName,
-      );
-
-      unset($returned);
-
-      foreach($returnedColors as $key => $val)
-      {
-        $returnedColors[$key]['pct']=round(100*$val['num']/self::$fileColorsStat['analyzed'],2);
-      }
-
-      return($returnedColors);
+
     }
     else
@@ -432,19 +569,10 @@
   /**
    * return a color table
-   *  $table = Array(
-   *              Array(),
-   *              Array(),
-   *              ...
-   *              Array(),
-   *              Array(),
-   *           )
-   *  $table[n]    => Array of all colors for a given hue value
-   *  $table[n][m] => HSV object or a color string RRGGBB
-   *
+   *  $table[h][s][v] => HSV object or string 'RRGGBB'
    *
    * @param Int $huePrec : degree of precision for hue [1..360]
    * @param Float $prec    : precision step for saturation & value [1..100]
    * @param String $returnedType : 'HSV'   => return a HSV object
-   *                               'color' => return a color string RRGGBB
+   *                               'color' => return a color string 'RRGGBB'
    * @return Array : the color table
    */
@@ -452,90 +580,33 @@
   {
     $returned=Array();
-    for($hue=0;$hue<=360;$hue+=$huePrec)
+    for($hue=0;$hue<360;$hue+=$huePrec)
     {
       $hueValues=Array();
 
-      $saturation=100;
-      for($value=0;$value<100;$value=$value+=$prec)
+      for($saturation=0;$saturation<=100;$saturation+=$prec)
       {
-        $hsv=new HSV($hue, $saturation, $value);
-        if($returnedType=='HSV')
-        {
-          $hueValues[]=$hsv;
-        }
-        else
-        {
-          $hueValues[]=$hsv->getRGB()->getHexString();
-        }
-        unset($hsv);
+        $saturationValues=Array();
+
+        for($value=0;$value<=100;$value+=$prec)
+        {
+          $hsv=new HSV($hue, $saturation, $value);
+          if($returnedType=='HSV')
+          {
+            $saturationValues[$value]=$hsv;
+          }
+          else
+          {
+            $saturationValues[$value]=$hsv->getRGB()->getHexString();
+          }
+          unset($hsv);
+        }
+
+        $hueValues[$saturation]=$saturationValues;
+        unset($saturationValues);
       }
-
-      $value=100;
-      for($saturation=100;$saturation>=0;$saturation-=$prec)
-      {
-        $hsv=new HSV($hue, $saturation, $value);
-        if($returnedType=='HSV')
-        {
-          $hueValues[]=$hsv;
-        }
-        else
-        {
-          $hueValues[]=$hsv->getRGB()->getHexString();
-        }
-        unset($hsv);
-      }
-
-
-      for($tmp=$prec;$tmp<=100;$tmp+=$prec)
-      {
-        $hsv=new HSV($hue, $tmp, 100-$tmp);
-        if($returnedType=='HSV')
-        {
-          $hueValues[]=$hsv;
-        }
-        else
-        {
-          $hueValues[]=$hsv->getRGB()->getHexString();
-        }
-        unset($hsv);
-      }
-      for($tmp=$prec;$tmp<=100;$tmp+=$prec)
-      {
-        $hsv=new HSV($hue, $tmp, $tmp);
-        if($returnedType=='HSV')
-        {
-          $hueValues[]=$hsv;
-        }
-        else
-        {
-          $hueValues[]=$hsv->getRGB()->getHexString();
-        }
-        unset($hsv);
-      }
-
-      $returned[]=$hueValues;
+      $returned[$hue]=$hueValues;
       unset($hueValues);
     }
 
-    $hue=0;
-    $saturation=0;
-    $hueValues=Array();
-    //$prec=1/(count($returned[0])-2);
-    for($value=0;$value<=100;$value+=$prec/4)
-    {
-      $hsv=new HSV($hue, $saturation, round($value,0));
-      if($returnedType=='HSV')
-      {
-        $hueValues[]=$hsv;
-      }
-      else
-      {
-        $hueValues[]=$hsv->getRGB()->getHexString();
-      }
-      unset($hsv);
-    }
-
-    $returned[]=$hueValues;
-    unset($hueValues);
 
     return($returned);
@@ -621,78 +692,40 @@
   }
 
-  static public function getColorFromTable(HSV $hsvObject, $colorTable)
-  {
-    $hue=360/(count($colorTable)-2);
-    $step=count($colorTable[0]);
-//echo "*hue:$hue<br>";
-//echo "*step:$step<br>";
-
+  /**
+   * for the given color, return the nearest color of the color table
+   *
+   * @param HSV $hsvObject    : the color, as HSV object
+   * @param Array $colorTable : the colorTable
+   * @param String $mode      : 'HSV' or 'RGB' to define the returned object
+   * @return HSV or RGB       : the color
+   */
+  static public function getColorFromTable(HSV $hsvObject, $colorTable, $mode='RGB')
+  {
     $hsv=$hsvObject->get();
-
+//echo "*H:".$hsv['H']." ";
+//echo "*S:".$hsv['S']." ";
+//echo "*V:".$hsv['V']."<br>";
+
+    $hue=360/count($colorTable);
     $hueNumber=round($hsv['H']/$hue,0);
-//echo "*hueNumber:$hueNumber<br>";
-
-//echo "*H:".$hsv['H']."<br>";
-//echo "*S:".$hsv['S']."<br>";
+    $step=100/(count($colorTable[0])-1);
+//echo "*H_Step:$hue<br>";
+//echo "*SV_Step:$step<br>";
+
+    $hsv['S']=round((100/$step)*$hsv['S']/100,0)*$step;
+    $hsv['V']=round((100/$step)*$hsv['V']/100,0)*$step;
+    $hsv['H']=($hueNumber*$hue)%360;
+//echo "*H:".$hsv['H']." ";
+//echo "*S:".$hsv['S']." ";
 //echo "*V:".$hsv['V']."<br>";
 
-    if($hsv['V']==0)
-    {
-//echo "-black-<br>";
-      // black
-      return(new RGB(0,0,0));
-    }
-    elseif($hsv['S']==0 && $hsv['V']==100)
-    {
-//echo "-white-<br>";
-      // white
-      return(new RGB(255,255,255));
-    }
-    elseif($hsv['S']==0 && $hsv['V']<100 && $hsv['V']>0)
-    {
-//echo "-grey-<br>";
-      // grey
-      $stepNumber=round($hsv['V']*($step-1)/100,0);
-      return($colorTable[count($colorTable)-1][$stepNumber]->getRGB());
-    }
-    elseif($hsv['S']==100 && $hsv['V']<100 && $hsv['V']>0)
-    {
-//echo "-value-<br>";
-      //color 'value'
-      $stepNumber=round($hsv['V']*$step/400,0);
-      return($colorTable[$hueNumber][$stepNumber]->getRGB());
-    }
-    elseif($hsv['V']==100 && $hsv['S']<100 && $hsv['S']>0)
-    {
-//echo "-saturation-<br>";
-      //color 'saturation'
-      $stepNumber=round(($step/4)+(100-$hsv['S'])*($step/400),0);
-      return($colorTable[$hueNumber][$stepNumber]->getRGB());
-    }
-    elseif($hsv['V']==100 && $hsv['S']==100)
-    {
-//echo "-pure-<br>";
-      //color 'pure'
-      $stepNumber=$step/4;
-      return($colorTable[$hueNumber][$stepNumber]->getRGB());
-    }
-    elseif(
-      ($hsv['V']<100 && $hsv['V']>50 && $hsv['S']<50 && $hsv['S']>0) ||
-      ($hsv['S']<100 && $hsv['S']>50 && $hsv['V']<50 && $hsv['V']>0))
-    {
-//echo "-desaturated 1-<br>";
-      //color 'desaturated'
-      $stepNumber=($step/2)+(100-$hsv['V'])*$step/400;
-      return($colorTable[$hueNumber][$stepNumber]->getRGB());
-    }
-    elseif($hsv['V']<100 && $hsv['V']>0 && $hsv['S']<100 && $hsv['S']>0)
-    {
-//echo "-desaturated 2-<br>";
-      //color 'desaturated'
-      $stepNumber=($step*0.75)+$hsv['V']*$step/400;
-      return($colorTable[$hueNumber][$stepNumber]->getRGB());
-    }
-//echo "-none-<br>";
-    return(new RGB(0,0,0));
+    if($mode=='RGB')
+    {
+      return($colorTable[$hsv['H']][$hsv['S']][$hsv['V']]->getRGB());
+    }
+    else
+    {
+      return($colorTable[$hsv['H']][$hsv['S']][$hsv['V']]);
+    }
   }
 
Index: /extensions/ColorStat/cstat_install.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_install.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_install.class.inc.php	(revision 6176)
@@ -125,5 +125,5 @@
                       quality=0;");
       pwg_query("INSERT INTO ".$this->tables['images']."
-                  SELECT id, 'n', 0, 0, 0, 0, 0, 0, ''
+                  SELECT id, 'n', 0, 0, 0, 0, 0, 0, '', ''
                     FROM ".IMAGES_TABLE."
                     WHERE id NOT IN (SELECT image_id FROM ".$this->tables['images'].")");
Index: /extensions/ColorStat/cstat_pip.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_pip.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_pip.class.inc.php	(revision 6176)
@@ -68,5 +68,5 @@
     global $page, $template;
 
-    $colors=$this->getImageColors($page['image_id']);
+    $colors=CStat_functions::getImageColors($page['image_id']);
 
 
@@ -85,5 +85,5 @@
         'TITLE' => l10n('cstat_colors'),
         'lines' => Array(
-          l10n('cstat_colors_on_image') => $this->htmlColorList($tmp, 8, 25, "", "color1px", "/"),
+          l10n('cstat_colors_on_image') => CStat_functions::htmlColorList($tmp, 8, 25, "", "color1px", "/"),
         )
       );
Index: /extensions/ColorStat/cstat_rb_callback.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_rb_callback.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_rb_callback.class.inc.php	(revision 6176)
@@ -15,4 +15,5 @@
   if(!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
 
+  //include_once('')
   include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCRequestBuilder.class.inc.php');
 
@@ -119,7 +120,4 @@
    * return HTML code for a given colors list
    *
-   * ==> this is the same function than the CStat_root::htmlColorList() function
-   *     make a copy here only top optimize performance (don't load the
-   *     CStat_root file for one function)
    *
    * @param Array $colors : list of colors
@@ -163,4 +161,51 @@
   }
 
+
+  /**
+   * this function is called by the request builder to make the search page, and
+   * must return the HTML & JS code of the dialogbox used to select criterion
+   *
+   * Notes :
+   *  - the dialogbox is a JS object with a public method 'show'
+   *  - when the method show is called, one parameter is given by the request
+   *    builder ; the parameter is an object defined as this :
+   *      {
+   *        cBuilder: an instance of the criteriaBuilder object used in the page,
+   *        eventOK : a callback function, called when the OK button is pushed
+   *        id:
+   *      }
+   *
+   *
+   *
+   *
+   * @param String $mode : can take 'admin' or 'public' values, allowing to
+   *                       return different interface if needed
+   * @return String : HTML formatted value
+   */
+  static public function getInterfaceContent($mode='admin')
+  {
+    return(CStat_functions::dialogBoxColor());
+  }
+
+  /**
+   * this function returns the label displayed in the criterion menu
+   *
+   * @return String : label displayed in the criterions menu
+   */
+  static public function getInterfaceLabel()
+  {
+    return(l10n('cstat_add_colors'));
+  }
+
+  /**
+   * this function returns the name of the dialog box class
+   *
+   * @return String : name of the dialogbox class
+   */
+  static public function getInterfaceDBClass()
+  {
+    return('dialogChooseColorBox');
+  }
+
 }
 
Index: /extensions/ColorStat/cstat_root.class.inc.php
===================================================================
--- /extensions/ColorStat/cstat_root.class.inc.php	(revision 6175)
+++ /extensions/ColorStat/cstat_root.class.inc.php	(revision 6176)
@@ -24,15 +24,19 @@
   class CStat_root extends CommonPlugin
   {
+    static public $pluginName='ColorStat';
+    static public $pluginNameFile='cstat';
+    static public $pluginTables=array('images', 'color_table', 'images_colors');
+    static public $colorTableSize=Array('small' => Array(30,20), 'large' => Array(10,10));
+
     protected $css;   //the css object
-    protected $colorTableSize=Array('small' => Array(30,20), 'large' => Array(10,10));
 
     public function __construct($prefixeTable, $filelocation)
     {
-      $this->setPluginName('ColorStat');
-      $this->setPluginNameFiles("cstat");
+      $this->setPluginName(self::$pluginName);
+      $this->setPluginNameFiles(self::$pluginNameFile);
       parent::__construct($prefixeTable, $filelocation);
       $this->section_name=$this->getPluginNameFiles();
 
-      $this->setTablesList(array('images', 'color_table', 'images_colors'));
+      $this->setTablesList(self::$pluginTables);
 
 
@@ -67,5 +71,5 @@
       $this->config=array(
         'newInstall' => 'n',
-        'analyze_maxTime' => 0.1,
+        'analyze_maxTime' => 1,
         'analyze_colorTable' => 'small',
         'analyze_pps' => 0,
@@ -73,6 +77,84 @@
         'display_gallery_showColors' => 'n',
         'display_stat_orderType' => 'img',
-        'stat_minPct' => 3.5,
-      );
+        'stat_minPct' => 1.5,
+      );
+    }
+
+    /* ---------------------------------------------------------------------------
+      ajax functions
+    --------------------------------------------------------------------------- */
+
+
+  } //class
+
+
+  class CStat_functions
+  {
+    static private $tables = Array();
+    static private $config = Array();
+
+    /**
+     * initialise the class
+     *
+     * @param String $prefixeTable : the piwigo prefixe used on tables name
+     * @param String $pluginNameFile : the plugin name used for tables name
+     */
+    static public function init($prefixeTable)
+    {
+      GPCCore::loadConfig(CStat_root::$pluginNameFile, self::$config);
+      $list=CStat_root::$pluginTables;
+
+      for($i=0;$i<count($list);$i++)
+      {
+        self::$tables[$list[$i]]=$prefixeTable.CStat_root::$pluginNameFile.'_'.$list[$i];
+      }
+    }
+
+    /**
+     * return a color table with stat on color
+     *
+     * @return Array : a color table with statistics on colors
+     */
+    static public function getColorTableWithStat()
+    {
+      $generalStats=self::getGeneralStats();
+
+      $colors=Array();
+      $sql="SELECT color_id, num_images, num_pixels
+            FROM ".self::$tables['color_table']."
+            WHERE num_images > 0
+            ORDER BY color_id ";
+      $result=pwg_query($sql);
+      if($result)
+      {
+        while($row=pwg_db_fetch_assoc($result))
+        {
+          $colors[$row['color_id']]=Array('num_images' => $row['num_images'], 'num_pixels' => $row['num_pixels']);
+        }
+      }
+
+      $colorTable=ColorStat::getColorTable(
+       CStat_root::$colorTableSize[self::$config['analyze_colorTable']][0],
+       CStat_root::$colorTableSize[self::$config['analyze_colorTable']][1]
+      );
+
+      foreach($colorTable as $key=>$hue)
+      {
+        foreach($hue as $key2=>$saturation)
+        {
+          foreach($saturation as $key3=>$value)
+          {
+            $rgb=$value->getRGB()->getHexString();
+            $colorTable[$key][$key2][$key3]=Array(
+              'color' => $rgb,
+              'pct'   => '', //(array_key_exists($rgb, $colors))?sprintf("%.2f", round(100*$colors[$rgb]['num_pixels']/$generalStats['pixelsAnalyzedSum'],2)):"",
+              'num'   => (array_key_exists($rgb, $colors))?$colors[$rgb]['num_images']:"",
+            );
+          }
+        }
+      }
+
+      unset($colors);
+      return($colorTable);
     }
 
@@ -86,79 +168,89 @@
      * @return String : HTML code
      */
-    public function htmlColorTable($colorTable, $size=5, $id="", $class="")
+    static public function htmlColorTable($colorTable, $size=5, $id="", $class="", $br='<br>')
     {
       global $template;
 
       $template->set_filename('color_table_page',
-                    dirname($this->getFileLocation()).'/templates/cstat_color_table.tpl');
-
+                    dirname(__FILE__).'/templates/cstat_color_table.tpl');
+
+      switch(count($colorTable))
+      {
+        case 12;
+          $break=4;
+          $size=10;
+          break;
+        case 15;
+          $break=5;
+          $size=10;
+          break;
+        case 18;
+          $break=6;
+          $size=5;
+          break;
+        case 20;
+          $break=5;
+          $size=10;
+          break;
+        case 24;
+          $break=6;
+          $size=5;
+          break;
+        case 30;
+          $break=6;
+          $size=5;
+          break;
+        case 36;
+          $break=6;
+          $size=5;
+          break;
+        case 45;
+          $break=9;
+          $size=3;
+          break;
+      }
+
+      $colors=Array();
       $nbHue=count($colorTable);
       $nbStep=count($colorTable[0]);
-      $colors=Array();
-      for($step=0;$step<$nbStep;$step++)
-      {
-        $row=Array();
-        for($hue=0;$hue<$nbHue;$hue++)
-        {
-
-          if($colorTable[$hue][$step] instanceof HSV)
+      $col=0;
+      $row=0;
+      foreach($colorTable as $key => $hue)
+      {
+        $lrow=0;
+        foreach($hue as $key2 => $saturation)
+        {
+          $lcol=0;
+          foreach($saturation as $key3 => $value)
           {
-            $row[]=Array('color' => $colorTable[$hue][$step]->getRGB()->getHexString(), 'pct' => "", 'num' => "");
+            //if(!($col!=0 and $hsv['V']==0) and !($row!=0 and $hsv['S']==0))
+            $trow=$lcol+$col*$nbStep;
+            $tcol=$lrow+$row*$nbStep;
+
+            if($colorTable[$key][$key2][$key3] instanceof HSV)
+            {
+              $colors[$tcol][$trow]=Array('color' => $colorTable[$key][$key2][$key3]->getRGB()->getHexString(), 'pct' => "", 'num' => "");
+            }
+            elseif(is_array($colorTable[$key][$key2][$key3]))
+            {
+              $colors[$tcol][$trow]=Array(
+                'color' => (array_key_exists('color', $colorTable[$key][$key2][$key3]))?$colorTable[$key][$key2][$key3]['color']:"",
+                'pct' => (array_key_exists('pct', $colorTable[$key][$key2][$key3]))?$colorTable[$key][$key2][$key3]['pct']:"",
+                'num' => (array_key_exists('num', $colorTable[$key][$key2][$key3]))?$colorTable[$key][$key2][$key3]['num']:"",
+              );
+            }
+            else
+            {
+              $colors[$tcol][$trow]=Array('color' => $colorTable[$key][$key2][$key3], 'pct' => "", 'num' => "");
+            }
+            $lcol++;
           }
-          elseif(is_array($colorTable[$hue][$step]))
-          {
-            $row[]=Array(
-              'color' => (array_key_exists('color', $colorTable[$hue][$step]))?$colorTable[$hue][$step]['color']:"",
-              'pct' => (array_key_exists('pct', $colorTable[$hue][$step]))?$colorTable[$hue][$step]['pct']:"",
-              'num' => (array_key_exists('num', $colorTable[$hue][$step]))?$colorTable[$hue][$step]['num']:"",
-            );
-          }
-          else
-          {
-            $row[]=Array('color' => $colorTable[$hue][$step], 'pct' => "", 'num' => "");
-          }
-        }
-        $colors[]=$row;
-        unset($row);
-      }
-
-      $data=array(
-        'colorTable' => $colors,
-        'size' => $size,
-        'id' => $id,
-        'class' => $class
-      );
-
-      $template->assign('data', $data);
-      unset($data);
-
-      return($template->parse('color_table_page', true));
-    }
-
-    /**
-     * return HTML code for a given colors list
-     *
-     * @param Array $colors : list of colors
-     * @param Int $size     : size for colorbox in the HTML table
-     * @return String : HTML code
-     */
-    public function htmlColorList($colorList, $split=8, $size=5, $id="", $class="", $br='<br>')
-    {
-      global $template;
-
-      $template->set_filename('color_table_page',
-                    dirname($this->getFileLocation()).'/templates/cstat_color_table.tpl');
-
-      $colors=Array();
-
-      $row=0;
-      $num=0;
-      foreach($colorList as $key => $val)
-      {
-        $colors[$row][]=Array('color' => $key, 'pct' => $val['pct'], 'num' => "");
-        $num++;
-        if($num==$split)
-        {
-          $num=0;
+          $lrow++;
+        }
+
+        $col++;
+        if($col==$break)
+        {
+          $col=0;
           $row++;
         }
@@ -180,4 +272,47 @@
 
     /**
+     * return HTML code for a given colors list
+     *
+     * @param Array $colors : list of colors
+     * @param Int $size     : size for colorbox in the HTML table
+     * @return String : HTML code
+     */
+    static public function htmlColorList($colorList, $split=8, $size=5, $id="", $class="", $br='<br>')
+    {
+      global $template;
+
+      $template->set_filename('color_table_page',
+                    dirname(__FILE__).'/templates/cstat_color_table.tpl');
+
+      $colors=Array();
+
+      $row=0;
+      $num=0;
+      foreach($colorList as $key => $val)
+      {
+        $colors[$row][]=Array('color' => $key, 'pct' => $val['pct'], 'num' => "");
+        $num++;
+        if($num==$split)
+        {
+          $num=0;
+          $row++;
+        }
+      }
+
+      $data=array(
+        'colorTable' => $colors,
+        'size' => $size,
+        'id' => $id,
+        'class' => $class,
+        'br' => $br,
+      );
+
+      $template->assign('data', $data);
+      unset($data);
+
+      return($template->parse('color_table_page', true));
+    }
+
+    /**
      * returns an array of colors & colors percent of an image
      *
@@ -185,5 +320,5 @@
      * @return Array('colors' => Array(), 'colors_pct' => Array())
      */
-    public function getImageColors($imageId)
+    static public function getImageColors($imageId)
     {
       $returned=Array(
@@ -193,5 +328,5 @@
 
       $sql="SELECT colors, colors_pct
-            FROM ".$this->tables['images']."
+            FROM ".self::$tables['images']."
             WHERE image_id='".$imageId."'";
       $result=pwg_query($sql);
@@ -208,22 +343,21 @@
 
 
-
     /**
      *  return all HTML&JS code necessary to display a dialogbox to choose
      *  colors
      */
-    protected function dialogBoxColor()
+    static public function dialogBoxColor()
     {
       global $template;
 
       $template->set_filename('colors_choose',
-                    dirname($this->getFileLocation()).'/templates/cstat_dialog_colors_choose.tpl');
-
-      $colorTable=$this->getColorTableWithStat();
+                    dirname(__FILE__).'/templates/cstat_dialog_colors_choose.tpl');
+
+      $colorTable=CStat_functions::getColorTableWithStat();
 
       $datas=Array(
-        'colorTable' => $this->htmlColorTable(
+        'colorTable' => CStat_functions::htmlColorTable(
                           $colorTable,
-                          ($this->config['analyze_colorTable']=='small')?16:8,
+                          (self::$config['analyze_colorTable']=='small')?16:8,
                           "",
                           "color0px"
@@ -240,17 +374,49 @@
 
     /**
-     * return a color table with stat on color
-     *
-     * @return Array : a color table with statistics on colors
-     */
-    protected function getColorTableWithStat()
-    {
-      $generalStats=$this->getGeneralStats();
-
-      $colors=Array();
-      $sql="SELECT color_id, num_images, num_pixels
-            FROM ".$this->tables['color_table']."
-            WHERE num_images > 0
-            ORDER BY color_id ";
+     * returns general stats on the analyzed colors process
+     *
+     * @return Array : array with keys
+     *                  'nbImages',  'timeMax',  'timeMin', 'timeSum',
+     *                  'pixelsAnalyzedMax', 'pixelsAnalyzedMin',
+     *                  'pixelsAnalyzedAvg', 'pixelsAnalyzedSum', 'totalPixels',
+     *                  'ppsMax', 'ppsMin', 'ppsAvg', 'qualityMax',
+     *                  'qualityMin', 'qualityAvg'
+     */
+    static public function getGeneralStats()
+    {
+      $returned=Array(
+        'nbImages' => 0,
+        'timeMax' => 0,
+        'timeMin' => 0,
+        'timeSum' => 0,
+        'pixelsAnalyzedMax' => 0,
+        'pixelsAnalyzedMin' => 0,
+        'pixelsAnalyzedAvg' => 0,
+        'pixelsAnalyzedSum' => 0,
+        'totalPixels' => 0,
+        'ppsMax' => 0,
+        'ppsMin' => 0,
+        'ppsAvg' => 0,
+        'qualityMax' => 0,
+        'qualityMin' => 0,
+        'qualityAvg' => 0,
+      );
+      $sql="SELECT COUNT(image_id) AS nbImages,
+                   MAX(time) AS timeMax,
+                   MIN(time) AS timeMin,
+                   SUM(time) AS timeSum,
+                   MAX(analyzed_pixels) AS pixelsAnalyzedMax,
+                   MIN(analyzed_pixels) AS pixelsAnalyzedMin,
+                   AVG(analyzed_pixels) AS pixelsAnalyzedAvg,
+                   SUM(analyzed_pixels) AS pixelsAnalyzedSum,
+                   SUM(num_pixels) AS totalPixels,
+                   MAX(pps) AS ppsMax,
+                   MIN(pps) AS ppsMin,
+                   AVG(pps) AS ppsAvg,
+                   MAX(quality) AS qualityMax,
+                   MIN(quality) AS qualityMin,
+                   AVG(quality) AS qualityAvg
+            FROM ".self::$tables['images']."
+            WHERE analyzed='y';";
       $result=pwg_query($sql);
       if($result)
@@ -258,39 +424,11 @@
         while($row=pwg_db_fetch_assoc($result))
         {
-          $colors[$row['color_id']]=Array('num_images' => $row['num_images'], 'num_pixels' => $row['num_pixels']);
-        }
-      }
-
-      $colorTable=ColorStat::getColorTable(
-        $this->colorTableSize[$this->config['analyze_colorTable']][0],
-        $this->colorTableSize[$this->config['analyze_colorTable']][1]
-      );
-      foreach($colorTable as $key=>$val)
-      {
-        foreach($val as $key2=>$val2)
-        {
-          $rgb=$val2->getRGB()->getHexString();
-          $colorTable[$key][$key2]=Array(
-            'color' => $rgb,
-            'pct'   => '', //(array_key_exists($rgb, $colors))?sprintf("%.2f", round(100*$colors[$rgb]['num_pixels']/$generalStats['pixelsAnalyzedSum'],2)):"",
-            'num'   => (array_key_exists($rgb, $colors))?$colors[$rgb]['num_images']:"",
-          );
-        }
-      }
-
-      unset($colors);
-      return($colorTable);
-    }
-
-
-
-
-
-    /* ---------------------------------------------------------------------------
-      ajax functions
-    --------------------------------------------------------------------------- */
-
-
-  } //class
+          $returned=$row;
+        }
+      }
+      return($returned);
+    }
+
+  } //CStat_functions
 
 ?>
Index: /extensions/ColorStat/language/fr_FR/plugin.lang.php
===================================================================
--- /extensions/ColorStat/language/fr_FR/plugin.lang.php	(revision 6175)
+++ /extensions/ColorStat/language/fr_FR/plugin.lang.php	(revision 6176)
@@ -23,5 +23,5 @@
 Travailler sur une gamme réduite de couleurs augmente la probabilité de référencer des teintes minoritaires. Ceci a pour avantage de permettre d'effectuer des recherches sur des gammes de couleurs plus larges.
 
-En contrepartie, la variation des nuances étant plus réduite, la pertinence des résultats lors de la recherche sur une couleur particulière peut s'avérer peu probante.";
+En contrepartie, la variation des nuances étant plus réduite, la pertinence des résultats lors de la recherche sur une couleur peut s'avérer étonnante, notamment sur les images peu saturées.";
 $lang['cstat_help_large_color_table'] = "
 Travailler sur une gamme élargie de couleurs permet de disposer d'un nombre accru de nuances pour une teinte donnée. Ceci a pour avantage de permettre d'affiner les recherches sur une gamme de couleurs plus précise et augmenter ainsi la pertinence des résultats.
@@ -79,9 +79,5 @@
 $lang['cstat_color_already_choosen']='La couleur est déjà sélectionnée dans la liste';
 $lang['cstat_add_colors']='Ajouter une sélection de couleurs';
-$lang['cstat_clear_colors']='Réinitialiser les critères';
-$lang['cstat_do_modify_request']='Modifier la recherche';
-$lang['cstat_search_criterion'] = 'Critères de recherche';
-$lang['cstat_number_of_item_found']='Nombre d\'images trouvées';
-$lang['cstat_result_query']='Résultat de la recherche';
+
 
 $lang['cstat_config']='Configuration';
Index: /extensions/ColorStat/main.inc.php
===================================================================
--- /extensions/ColorStat/main.inc.php	(revision 6175)
+++ /extensions/ColorStat/main.inc.php	(revision 6176)
@@ -78,4 +78,5 @@
   //CStat admin interface loaded and active only if in admin page
   include_once("cstat_aim.class.inc.php");
+  CStat_functions::init($prefixeTable);
   $obj=new CStat_AIM($prefixeTable, __FILE__);
   $obj->initEvents();
Index: /extensions/ColorStat/templates/cstat_color_table.tpl
===================================================================
--- /extensions/ColorStat/templates/cstat_color_table.tpl	(revision 6175)
+++ /extensions/ColorStat/templates/cstat_color_table.tpl	(revision 6176)
@@ -4,5 +4,5 @@
     {foreach from=$row item=col}
     <td id="cellColor_{$col.color}" style="width:{$data.size}px;height:{$data.size}px;background-color:#{$col.color};{if $col.num!=''}cursor:pointer;{/if}" class="tiptip {if $col.num!=''}csSelectable{/if}"
-        title="{'cstat_color'|@translate}&nbsp;#{$col.color}{if $col.num!=''}&nbsp;:&nbsp;{$col.num}&nbsp;{'cstat_images'|@translate}{/if}{if $col.pct!=''} {$data.br} {'cstat_surface'|@translate}&nbsp;{$col.pct}%{/if}">
+        title="<table><tr style='vertical-align:middle;'><td><div style='display:inline-block;width:18px;height:18px;background-color:#{$col.color};'></div></td><td style='display:inline-block;'>{'cstat_color'|@translate}&nbsp;#{$col.color}{if $col.num!=''}&nbsp;:&nbsp;{$col.num}&nbsp;{'cstat_images'|@translate}{/if}{if $col.pct!=''} {$data.br} {'cstat_surface'|@translate}&nbsp;{$col.pct}%{/if}</td></tr></table>">
     </td>
     {/foreach}
Index: /extensions/ColorStat/templates/cstat_dialog_colors_choose.tpl
===================================================================
--- /extensions/ColorStat/templates/cstat_dialog_colors_choose.tpl	(revision 6175)
+++ /extensions/ColorStat/templates/cstat_dialog_colors_choose.tpl	(revision 6176)
@@ -300,5 +300,5 @@
 {/literal}
 
-<div id="iDialogColorChoose">
+<div id="iDialogColorChoose" style='display:none;'>
   <table style="padding-top:8px;">
     <tr>
@@ -320,5 +320,3 @@
 </div>
 
-<script type="text/javascript">
- var colorBox=new dialogChooseColorBox();
-</script>
+
