From ba0460a40b4d0347c20a0b089432aae585fbf79d Mon Sep 17 00:00:00 2001
From: Alex ORLUC <alex.orluc@maarch.org>
Date: Thu, 9 Mar 2017 19:35:34 +0100
Subject: [PATCH] FEAT #5286 evo drap and drop avis circuit

---
 modules/avis/class/avis_controler.php         |   46 +-
 .../avis/class/avis_controler_Abstract.php    | 1047 +++------------
 modules/avis/css/module.css                   |  121 ++
 modules/avis/js/functions.js                  | 1162 +++++------------
 modules/avis/lang/en.php                      |    2 +
 modules/avis/lang/fr.php                      |    7 +-
 modules/avis/load_listmodel_avis_users.php    |   44 +
 modules/avis/saveAvisModel.php                |  105 +-
 modules/avis/send_to_avis.php                 |  392 +++---
 modules/avis/updateAvisWF.php                 |   55 +
 10 files changed, 985 insertions(+), 1996 deletions(-)
 create mode 100644 modules/avis/load_listmodel_avis_users.php
 create mode 100644 modules/avis/updateAvisWF.php

diff --git a/modules/avis/class/avis_controler.php b/modules/avis/class/avis_controler.php
index 889e91da384..845d24c4b46 100755
--- a/modules/avis/class/avis_controler.php
+++ b/modules/avis/class/avis_controler.php
@@ -1,41 +1,19 @@
 <?php
-/*
-*   Copyright 2013-2016 Maarch
-*
-*   This file is part of Maarch Framework.
-*
-*   Maarch Framework is free software: you can redistribute it and/or modify
-*   it under the terms of the GNU General Public License as published by
-*   the Free Software Foundation, either version 3 of the License, or
-*   (at your option) any later version.
-*
-*   Maarch Framework is distributed in the hope that it will be useful,
-*   but WITHOUT ANY WARRANTY; without even the implied warranty of
-*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-*   GNU General Public License for more details.
-*
-*   You should have received a copy of the GNU General Public License
-*   along with Maarch Framework.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-/**
-* @brief  Contains the controler of the note Object
-*
-*
-* @file
-* @author Alex Orluc <dev@maarch.org>
-* @date $date$
-* @version $Revision$
-* @ingroup notes
-*/
+/* 
+ * Copyright Maarch since 2008 under licence GPLv3.
+ * See LICENCE.txt file at the root folder for more details.
+ * This file is part of Maarch software.
+ * 
+ */
 
+/* 
+ * @brief avis_controler
+ * @author dev@maarch.org
+ * @ingroup avis
+ * 
+ */
 require_once 'modules/avis/class/avis_controler_Abstract.php';
 
-/**
-* @brief  Controler of the avis Object
-*
-* @ingroup avis
-*/
 class avis_controler extends avis_controler_Abstract
 {
     // custom
diff --git a/modules/avis/class/avis_controler_Abstract.php b/modules/avis/class/avis_controler_Abstract.php
index 6d7dd1d08ac..c0e73a7a4a2 100755
--- a/modules/avis/class/avis_controler_Abstract.php
+++ b/modules/avis/class/avis_controler_Abstract.php
@@ -1,939 +1,316 @@
 <?php
-/*
-*   Copyright 2013-2016 Maarch
-*
-*   This file is part of Maarch Framework.
-*
-*   Maarch Framework is free software: you can redistribute it and/or modify
-*   it under the terms of the GNU General Public License as published by
-*   the Free Software Foundation, either version 3 of the License, or
-*   (at your option) any later version.
-*
-*   Maarch Framework is distributed in the hope that it will be useful,
-*   but WITHOUT ANY WARRANTY; without even the implied warranty of
-*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-*   GNU General Public License for more details.
-*
-*   You should have received a copy of the GNU General Public License
-*   along with Maarch Framework.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-/**
-* @brief  Contains the controler of the note Object
-*
-*
-* @file
-* @author Alex Orluc <dev@maarch.org>
-* @date $date$
-* @version $Revision$
-* @ingroup avis
-*/
-
-/**
-* @brief  Controler of the note Object
-*
-* @ingroup notes
-*/
+/* 
+ * Copyright Maarch since 2008 under licence GPLv3.
+ * See LICENCE.txt file at the root folder for more details.
+ * This file is part of Maarch software.
+ * 
+ */
+
+/* 
+ * @brief avis_controler_Abstract
+ * @author dev@maarch.org
+ * @ingroup avis
+ * 
+ */
 abstract class avis_controler_Abstract
 {
+
     public function getAvis($resId)
     {
         //define avis limit date
         $db = new Database();
-        
+
         $query = "SELECT notes.user_id,notes.note_text,recommendation_limit_date FROM notes,mlb_coll_ext WHERE identifier = ? AND note_text LIKE '[POUR AVIS]%' AND notes.identifier=mlb_coll_ext.res_id";
-                
+
         $stmt = $db->query($query, array($resId));
 
         $avis = $stmt->fetchObject();
 
         return $avis;
-              
     }
+
     #####################################
     ## send avis
     #####################################
-    public function processAvis($resId, $recommendation_limit_date='')
+
+    public function processAvis($resId, $recommendation_limit_date = '')
     {
         //define avis limit date
         $db = new Database();
-        
-        if($recommendation_limit_date <> ''){
-        
+
+        if ($recommendation_limit_date <> '') {
+
             $query = "UPDATE mlb_coll_ext SET recommendation_limit_date = ? where res_id = ?";
-            $stmt = $db->query($query, array($recommendation_limit_date,$resId));
+            $stmt = $db->query($query, array($recommendation_limit_date, $resId));
         }
 
-        $query = "UPDATE res_letterbox SET modification_date = CURRENT_DATE where res_id = ?";        
+        $query = "UPDATE res_letterbox SET modification_date = CURRENT_DATE where res_id = ?";
         $stmt = $db->query($query, array($resId));
-              
     }
 
-    public function getList($res_id, $coll_id, $bool_modif=false, $typeList, $isAvisStep = false, $fromDetail = ""){
-        require_once 'modules/entities/class/class_manage_listdiff.php';
-        $core_tools =new core_tools();
-
-        $id_tab="tab_avisSetWorkflow";
-        $id_form="form_avisSetWorkflow";
-        
-        if ($fromDetail == "Y" && !$core_tools->test_service('config_avis_workflow_in_detail', 'avis', false)) {
-            $bool_modif = false;
-        }else if($fromDetail == "" && !$core_tools->test_service('config_avis_workflow', 'avis', false)){
-            $bool_modif = false;
-        }
-        $circuitAvis = $this->getWorkflow($res_id, $coll_id, $typeList);
-
-        $model = new diffusion_list();
-        $modelListDiff = $model->get_listmodel('AVIS_CIRCUIT',$_SESSION['destination_entity']);
-
-        // LOAD MODEL if exist
-        if(empty($circuitAvis['avis']['users']) && !empty($modelListDiff)){
-            $circuitAvis = $modelListDiff;
-        }
-
-        $str = "";
-
-        if (!isset($circuitAvis['avis']['users']) && $fromDetail == "Y" && !isset($circuitAvis['lastAvis']['users']) && (!$core_tools->test_service('config_avis_workflow_in_detail', 'avis', false))){
-            $str .= "<div class='error' id='divErrorAvis' name='divErrorAvis' onclick='this.hide();'>" . _EMPTY_USER_LIST . "</div>";
-            $str .= "<div><strong><em>" . _EMPTY_AVIS_WORKFLOW . "</em></strong></div>";
-        }else if(!isset($circuitAvis['avis']['users']) && $fromDetail == "" && !isset($circuitAvis['lastAvis']['users']) && (!$core_tools->test_service('config_avis_workflow', 'avis', false))){
-            $str .= "<div class='error' id='divErrorAvis' name='divErrorAvis' onclick='this.hide();'>" . _EMPTY_USER_LIST . "</div>";
-            $str .= "<div><strong><em>" . _EMPTY_AVIS_WORKFLOW . "</em></strong></div>";
-
-        }else {
-            $diff_list = new diffusion_list();
-            $listModels = $diff_list->select_listmodels($typeList);
-
-            //$listModels = $modelListDiff;
-
-            $str .= '<div align="center">';
-        
-            $str .= '<div class="error" id="divErrorAvis" onclick="this.hide();"></div>';
-            $str .= '<div class="info" id="divInfoAvis" onclick="this.hide();"></div>';
-
-            if (!empty($listModels) && $bool_modif && !$isAvisStep){
-                $str .= '<select name="modelList" id="modelList" onchange="load_listmodel_avis(this.options[this.selectedIndex], \''.$typeList.'\', \''.$id_tab.'\');">';
-                $str .= '<option value="">Sélectionnez un modèle</option>';
-                foreach($listModels as $lm){
-                    $str .= '<option value="'.$lm['object_id'].'">'.$lm['title'].'</option>';
-                }
-                $str .= '</select>';
-            }
-
-            $str .= '<table class="listing spec detailtabricatordebug" style="width:100%;" cellspacing="0" border="0" id="'.$id_tab.'">';
-            $str .= '<thead><tr>';
-            $str .= '<th style="width:40%;" align="left" valign="bottom"><span>Avis</span></th>';
-            if ($bool_modif){
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:45%;" align="left" valign="bottom"><span>Consigne</span></th>';
-                $str .= '<th style="width:0;display:none" align="left" valign="bottom"></th>';
-                $str .= '<th style="width:0;display:none" align="center" valign="bottom"></th>';
-            }
-            else {
-                $str .= '<th style="width:55%;" align="left" valign="bottom"><span>Consigne</span></th>';
-                $str .= '<th style="width:10%;" align="left" valign="bottom"><span>Etat</span></th>';
-            }
-            $str .= '</tr></thead>';
-            $str .= '<tbody>';
-            $color = "";
-        
-            if ($typeList == 'AVIS_CIRCUIT'){
-                if (!isset($circuitAvis['avis']['users']) && !isset($circuitAvis['lastAvis']['users'])){
-                    $j=0;
-                    $str .= '<tr class="col" id="lineAvisWorkflow_'.$j.'">';
-                    $str .= '<td>';
-                    $str .= '<span id="avis_rank_' . $j . '"><span class="nbResZero" style="font-weight:bold;opacity:0.5;">1</span> </span>';
-                    if ($bool_modif){
-                        $str .= '<select id="avis_'.$j.'" name="avis_'.$j.'" >';
-                        $str .= '<option value="" >Sélectionnez un utilisateur</option>';
-
-                        $tab_userentities = $this->getEntityAvis();
-
-                        /** Order by parent entity **/
-                        foreach ($tab_userentities as $key => $value) {
-                            $str .= '<optgroup label="'.$tab_userentities[$key]['entity_id'].'">';
-                            $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                            foreach($tab_users as $user){
-                                if($tab_userentities[$key]['entity_id'] == $user['entity_id']){
-                                    $str .= '<option value="'.$user['id'].'" >'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                }
-                                
-                            }
-                            $str .= '</optgroup>';
-                        }
-                        /*$tab_usergroups = $this->getGroupAvis();
-                        foreach ($tab_usergroups as $key => $value) {
-                            $str .= '<optgroup label="'.$tab_usergroups[$key]['group_desc'].'">';
-                            $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                            foreach($tab_users as $user){
-                                $str .= '<option value="'.$user['id'].'" >'.$user['lastname'].', '.$user['firstname'].'</option>';
-                            }
-                        }
-                        $str .= '</optgroup>';*/
-                        $str .= '</select>';
-                    }
-                    $str .= '<span id="lastavis_' . $j . '"> ';
-                    //$str .= '<i title="'._LAST_AVIS.'" style="color : #fdd16c" class="fa fa-certificate fa-lg fa-fw"></i>';
-                    $str .= '</span></td>';
-                    $str .= '<td><a href="javascript://" id="avis_down_'.$j.'" name="avis_down_'.$j.'" style="visibility:hidden;" onclick="deplacerLigneAvis(0,1,\''.$id_tab.'\')" ><i class="fa fa-arrow-down fa-2x" title="'.DOWN_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><a href="javascript://" id="avis_up_'.$j.'" name="avis_up_'.$j.'" style="visibility:hidden;" ><i class="fa fa-arrow-up fa-2x" title="'.UP_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><a href="javascript://" onclick="delRowAvis(this.parentNode.parentNode.rowIndex,\''.$id_tab.'\')" id="avis_suppr_'.$j.'" name="avis_suppr_'.$j.'" style="visibility:hidden;" ><i class="fa fa-user-times fa-2x" title="'.DEL_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><a href="javascript://" style="visibility:visible;"  id="avis_add_'.$j.'" name="avis_add_'.$j.'" onclick="addRowAvis(\''.$id_tab.'\')" ><i class="fa fa-user-plus fa-2x" title="'.ADD_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><input type="text" id="avis_consigne_'.$j.'" name="avis_consigne_'.$j.'" onmouseover="setTitle(this);" style="width:95%;"/></td>';
-                    $str .= '<td style="display:none"><input type="hidden" id="avis_date_'.$j.'" name="avis_date_'.$j.'"/></td>';
-
-                    $str .= '<td style="display:none"><input type="checkbox" id="avis_isSign_'.$j.'" name="avis_isSign_'.$j.'" style="visibility:hidden;" /></td>';
-                    $str .= '<td><i class="fa fa-plus fa-lg" title="Nouvel utilisateur ajouté"></i></td>';
-                    $str .= '</tr>';
-                }
-                else{
-                    //var_dump($myPosAvis);
-                    $isAvisStep = true;
-                    if ($isAvisStep)
-                        $myPosAvis = $this->myPosAvis($res_id, $coll_id, $typeList);
-                    if (isset($circuitAvis['avis']['users'])){
-                        foreach($circuitAvis['avis']['users'] as $seq=>$step){
-                            if($color == ' class="col"') {
-                                $color = '';
-                            } else {
-                                $color = ' class="col"';
-                            }
-
-                            if (($isAvisStep && !is_null($myPosAvis) && $myPosAvis >= $seq || $step['process_date'] != '') && $circuitAvis['avis']['users'][$seq]['user_id'] == $_SESSION['user']['UserId'])
-                                    $title = ' Vous ne pouvez pas modifier votre propre étape ';
-                                else
-                                    $title = '';
-
-                            $str .= '<tr ' . $color . ' title="'.$title.'">';
-
-                            if ($bool_modif){
-                                $str .= '<td>';
-                                $tab_users = $this->getUsersAvis();
-
-                                if ($isAvisStep && !is_null($myPosAvis) && $myPosAvis >= $seq || $step['process_date'] != '' /*&& $circuitAvis['avis']['users'][$seq]['user_id'] == $_SESSION['user']['UserId']*/)
-                                    $disabled = ' disabled ';
-                                else
-                                    $disabled = '';
-                                $str .= '<span id="avis_rank_' . $seq . '"><span class="nbResZero" style="font-weight:bold;opacity:0.5;">'. ($seq + 1) . '</span> </span>';
-                                $str .= '<select id="avis_'.$seq.'" name="avis_'.$seq.'" '.$disabled.'>';
-                                $str .= '<option value="" >Sélectionnez un utilisateur</option>';
-        
-
-                                /** Order by parent entity **/
-                                $tab_userentities = $this->getEntityAvis();
-                                foreach ($tab_userentities as $key => $value) {
-                                    $str .= '<optgroup label="'.$tab_userentities[$key]['entity_id'].'">';
-                                    $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                    foreach($tab_users as $user){
-                                        if($tab_userentities[$key]['entity_id'] == $user['entity_id']){
-                                            $selected = " ";
-                                            if ($user['id'] == $step['user_id'])
-                                                $selected = " selected";
-                                            $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                        }
-                                        
-                                    }
-                                    $str .= '</optgroup>';
-                                }
-                                /*$tab_usergroups = $this->getGroupAvis();
-                                foreach ($tab_usergroups as $key => $value) {
-                                    $str .= '<optgroup label="'.$tab_usergroups[$key]['group_desc'].'">';
-                                    $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                    foreach($tab_users as $user){
-                                        $selected = " ";
-                                        if ($user['id'] == $step['user_id'])
-                                            $selected = " selected";
-                                        $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-
-                                    }
-                                    $str .= '</optgroup>';
-                                }*/
-                                $str .= '</select>';
-
-                                $str .= "<span id=\"lastAvis_" . $seq . "\">";
-                                if (empty($circuitAvis['lastAvis']['users']) && $seq == count ($circuitAvis['avis']['users'])-1)
-                                    $str .= " <i title=\""._LAST_AVIS."\" style=\"color : #fdd16c;visibility:hidden;\" class=\"fa fa-certificate fa-lg fa-fw\"></i>";
-                                $str .= "</span></td>";
-                                $up = ' style="visibility:visible"';
-                                $displayCB = ' style="visibility:hidden"';
-                                $checkCB = '';
-                                if ($isAvisStep && !is_null($myPosAvis) && $myPosAvis >= $seq || $step['process_date'] != '')
-                                    $down = ' style="visibility:hidden"';
-                                else
-                                    $down = ' style="visibility:visible"';
-                                if ($isAvisStep && !is_null($myPosAvis) && $myPosAvis >= $seq || $step['process_date'] != '' || count($circuitAvis['avis']['users']) == '1')
-                                    $del = ' style="visibility:hidden"';
-                                else
-                                    $del = ' style="visibility:visible"';
-                                if (empty($circuitAvis['lastAvis']['users']) && $seq == count ($circuitAvis['avis']['users'])-1){
-                                    $add = ' style="visibility:visible"';
-                                    $down = ' style="visibility:hidden"';
-                                    $displayCB = ' style="visibility:hidden"';
-                                    $checkCB = ' checked';
-                                }
-                                else{
-                                    $add = ' style="visibility:hidden"';
-                                }
-                                if ($isAvisStep && $myPosAvis >= $seq || $step['process_date'] != '')
-                                    $displayCB = ' style="visibility:hidden"';
-
-                                if ($seq == 0 || ($isAvisStep && $myPosAvis >= $seq) || $circuitAvis['avis']['users'][$seq-1]['process_date'] != ''){
-                                    $up = ' style="visibility:hidden"';
-                                }
-                                $str .= '<td><a href="javascript://"  '.$down.' id="avis_down_'.$seq.'" name="avis_down_'.$seq.'" onclick="deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2,\''.$id_tab.'\')" ><i class="fa fa-arrow-down fa-2x" title="'.DOWN_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td><a href="javascript://"   '.$up.' id="avis_up_'.$seq.'" name="avis_up_'.$seq.'" onclick="deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1,\''.$id_tab.'\')" ><i class="fa fa-arrow-up fa-2x" title="'.UP_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td id="allez"><a href="javascript://" onclick="delRowAvis(this.parentNode.parentNode.rowIndex,\''.$id_tab.'\')" id="suppr_'.$seq.'" name="suppr_'.$seq.'" '.$del.' ><i class="fa fa-user-times fa-2x" title="'.DEL_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td><a href="javascript://" '.$add.'  id="avis_add_'.$seq.'" name="avis_add_'.$seq.'" onclick="addRowAvis(\''.$id_tab.'\')" ><i class="fa fa-user-plus fa-2x" title="'.ADD_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td><input type="text" id="avis_consigne_'.$seq.'" name="avis_consigne_'.$seq.'" value="'.$step['process_comment'].'" onmouseover="setTitle(this);" style="width:95%;" '.$disabled.'/></td>';
-                                $str .= '<td style="display:none"><input type="hidden" value="'.$step['process_date'].'" id="avis_date_'.$seq.'" name="avis_date_'.$seq.'"/></td>';
-
-
-                                $str .= '<td style="display:none"><input type="checkbox" id="avis_isSign_'.$seq.'" name="avis_isSign_'.$seq.'" '.$displayCB.' '.$checkCB.'/></td>';
-                                if ($step['process_date'] != '')
-                                    $str .= '<td><i class="fa fa-check fa-2x" title="'._AVIS_SENT.'"></i></td>';
-                                else
-                                    $str .= '<td><i class="fa fa-hourglass-half fa-lg" title="'._WAITING_FOR_AVIS.'"></i></td>';
-
-                            }
-                            else{
-                                $str .= '<td><span><strong>' . ($seq + 1) . ' </strong></span>'.$step['firstname'].' '.$step['lastname'];
-                                $str .= '</td>';
-                                $str .= '<td>'.$step['process_comment'].'</td>';
-                                if ($step['process_date'] != '')
-                                    $str .= '<td><i class="fa fa-check fa-2x" title="'._AVIS_SENT.'"></i></td>';
-                                else
-                                    $str .= '<td><i class="fa fa-hourglass-half fa-lg" title="'._WAITING_FOR_AVIS.'"></i></td>';
-                                // else $str .= '<td></td>';
-                            }
-                            $str .= '</tr>';
-                        }
-                    }
-                    //ajout signataire
-
-                    if (!empty($circuitAvis['lastAvis']['users'])){
-                        $seq = count ($circuitAvis['avis']['users']);
-                        if($color == ' class="col"') {
-                            $color = '';
-                        } else {
-                            $color = ' class="col"';
-                        }
-
-                        $str .= '<tr ' . $color . '>';
-                        if ($bool_modif){
-                            if ($isAvisStep && $myPosAvis >= $seq)
-                                $disabled = ' disabled ';
-                            else
-                                $disabled = '';
-
-                            $str .= '<td>';
-                            $tab_users = $this->getUsersAvis();
-                            $str .= '<span id="rank_' . $seq . '"><strong>'. ($seq + 1) . ' </strong></span>';
-                            $str .= '<select id="avis_'.$seq.'" name="avis_'.$seq.'" '.$disabled.'>';
-                            $str .= '<option value="" >Sélectionnez un utilisateur</option>';
-                            
-                            /** Order by parent entity **/
-                            $tab_userentities = $this->getEntityAvis();
-                            foreach ($tab_userentities as $key => $value) {
-                                $str .= '<optgroup label="'.$tab_userentities[$key]['entity_id'].'">';
-                                $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                foreach($tab_users as $user){
-                                    if($tab_userentities[$key]['entity_id'] == $user['entity_id']){
-                                        $selected = " ";
-                                        if ($user['id'] == $circuitAvis['lastAvis']['users'][0]['user_id'])
-                                            $selected = " selected";
-                                        $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                    }
-                                    
-                                }
-                                $str .= '</optgroup>';
-                            }
-                            /*$tab_usergroups = $this->getGroupAvis();
-                            foreach ($tab_usergroups as $key => $value) {
-                                $str .= '<optgroup label="'.$tab_usergroups[$key]['group_desc'].'">';
-                                $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                foreach($tab_users as $user){
-                                    $selected = " ";
-                                    if ($user['id'] == $circuitAvis['lastAvis']['users'][0]['user_id'])
-                                        $selected = " selected";
-                                    $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                }
-                                $str .= '</optgroup>';
-                            }*/
-                            $str .= '</select>';
-
-                            $str .= '<span id="lastAvis_' . $seq . '"> <i title="Signataire" style="color : #fdd16c;visibility:hidden;" class="fa fa-certificate fa-lg fa-fw"></i></span></td>';
-                            if ($isAvisStep && ($myPosAvis+1 == $seq || $myPosAvis == $seq))
-                                $up = ' style="visibility:hidden"';
-                            else
-                                $up = ' style="visibility:visible"';
-                            $down = ' style="visibility:hidden"';
-
-                            // if ($isAvisStep && $myPosAvis == $seq) $add = ' style="visibility:hidden"';
-                            // else $add = ' style="visibility:visible"';
-                            $add = ' style="visibility:visible"';
-
-                            if ($isAvisStep && $myPosAvis == $seq)
-                                $del = ' style="visibility:hidden"';
-                            else
-                                $del = ' style="visibility:visible"';
-
-                            if (count ($circuitAvis['avis']['users']) == 0){
-                                $up     = 'style="visibility:hidden"';
-                                $del    = 'style="visibility:hidden"';
-                            }
-                            $displayCB = ' style="visibility:hidden"';
-                            if ($isAvisStep && $myPosAvis == $seq)
-                                $displayCB = ' style="visibility:hidden"';
-
-                            $str .= '<td><a href="javascript://"  '.$down.' id="avis_down_'.$seq.'" name="avis_down_'.$seq.'" onclick="deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2,\''.$id_tab.'\')" ><i class="fa fa-arrow-down fa-2x" title="'.DOWN_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><a href="javascript://"   '.$up.' id="avis_up_'.$seq.'" name="avis_up_'.$seq.'" onclick="deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1,\''.$id_tab.'\')" ><i class="fa fa-arrow-up fa-2x" title="'.UP_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><a href="javascript://" onclick="delRowAvis(this.parentNode.parentNode.rowIndex,\''.$id_tab.'\')" id="avis_suppr_'.$seq.'" name="avis_suppr_'.$seq.'" '.$del.' ><i class="fa fa-user-times fa-2x" title="'.DEL_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><a href="javascript://" '.$add.'  id="avis_add_'.$seq.'" name="avis_add_'.$seq.'" onclick="addRowAvis(\''.$id_tab.'\')" ><i class="fa fa-user-plus fa-2x" title="'.ADD_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><input type="text" id="avis_consigne_'.$seq.'" name="avis_consigne_'.$seq.'" value="'.$circuitAvis['lastAvis']['users'][0]['process_comment'].'" onmouseover="setTitle(this);" style="width:95%;" '.$disabled.'/></td>';
-                            $str .= '<td style="display:none"><input type="hidden" id="avis_date_'.$seq.'" name="avis_date_'.$seq.'" value="'.$circuitAvis['lastAvis']['users'][0]['process_date'].'" /></td>';
-
-                            $str .= '<td style="display:none"><input type="checkbox" id="avis_isSign_'.$seq.'" name="avis_isSign_'.$seq.'" '.$displayCB.' checked/></td>';
-                        } else {
-                            $str .= '<td><span><strong>' . ($seq + 1) . ' </strong></span>' . $circuitAvis['lastAvis']['users'][0]['firstname'].' '.$circuitAvis['lastAvis']['users'][0]['lastname'];
-                            $str .= ' <i title="'._LAST_AVIS.'" style="color : #fdd16c;visibility:hidden;" class="fa fa-certificate fa-lg fa-fw"></i></td>';
-                            $str .= '<td>'.$circuitAvis['lastAvis']['users'][0]['process_comment'].'</td>'; 
-                            if ($circuitAvis['lastAvis']['users'][0]['process_date'] != '')
-                                $str .= '<td><i class="fa fa-check fa-2x" title="'._SIGNED.'"></i></td>';
-                            else
-                                $str .= '<td><i class="fa fa-hourglass-half fa-lg" title="'._WAITING_FOR_SIGN.'"></i></td>';
-                                
-                        }
-                        $str .= '</tr>';
-                    }
-                }
-            }
-        
-            $str .= '</tbody>';
-            $str .= '</table>';
-            if ($bool_modif){
-                $str .= '<input type="button" name="send" id="send" value="Sauvegarder" class="button" ';
+    public function getList($res_id, $coll_id, $bool_modif = false, $typeList, $isAvisStep = false, $fromDetail = "")
+    {
 
-                    if ($fromDetail == "Y") {
-                        $str .= 'onclick="saveAvisWorkflow(\''.$res_id.'\', \''.$coll_id.'\', \''.$id_tab.'\', \'Y\');" /> ';
-                    } else {
-                        $str .= 'onclick="saveAvisWorkflow(\''.$res_id.'\', \''.$coll_id.'\', \''.$id_tab.'\', \'N\');" /> ';
+        $circuit = $this->getWorkflow($res_id, $coll_id, $typeList);
+
+        $str .= '<div class="error" id="divErrorAvis" onclick="this.hide();"></div>';
+        $str .= '<div class="info" id="divInfoAvis" onclick="this.hide();"></div>';
+
+        //AVIS USER LIST
+        if ($bool_modif == true) {
+            $str .= '<select data-placeholder="' . _ADD_AVIS_ROLE . '" id="avisUserList" onchange="addAvisUser();">';
+            $str .= '<option value="" ></option>';
+
+            $tab_userentities = $this->getEntityAvis();
+            /** Order by parent entity * */
+            foreach ($tab_userentities as $key => $value) {
+                $str .= '<optgroup label="' . $tab_userentities[$key]['entity_id'] . '">';
+                $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
+                foreach ($tab_users as $user) {
+                    if ($tab_userentities[$key]['entity_id'] == $user['entity_id']) {
+                        $selected = " ";
+                        if ($user['id'] == $step['user_id'])
+                            $selected = " selected";
+                        $str .= '<option value="' . $user['id'] . '" ' . $selected . '>' . $user['lastname'] . ' ' . $user['firstname'] . '</option>';
                     }
-
-                if ($fromDetail == "Y") {
-                    $str .= '<input type="button" name="reset" id="reset" value="Reinitialiser" class="button" ';
-
-                    $str .= 'onclick="if(confirm(\'Voulez-vous réinitialiser le circuit ?\')){resetAvisWorkflow(\''.$res_id.'\', \''.$coll_id.'\', \''.$id_tab.'\', \'Y\');}" /> ';
                 }
-
-                    $str .= '<input type="button" name="save" id="save" value="Enregistrer comme modèle" class="button" onclick="$(\'modalSaveAvisModel\').style.display = \'block\';" />';
-                    $str .= '<div id="modalSaveAvisModel" >';
-                    $str .= '<h3>Sauvegarder le circuit de avis</h3>';
-                    $str .= '<input type="hidden" value="'.$typeList . '_' . strtoupper(base_convert(date('U'), 10, 36)).'" name="objectId_inputAvis" id="objectId_inputAvis"/><br/>';
-                    $str .= '<label for="titleModel">Titre</label> ';
-                    $str .= '<input type="text" name="titleModelAvis" id="titleModelAvis"/><br/>';
-                    $str .= '<input type="button" name="saveModelAvis" id="saveModelAvis" value="'._VALIDATE.'" class="button" onclick="saveAvisModel(\''.$id_tab.'\');" /> ';
-                    $str .= '<input type="button" name="cancelModelAvis" id="cancelModelAvis" value="'._CANCEL.'" class="button" onclick="$(\'modalSaveAvisModel\').style.display = \'none\';" />';
-                    $str .= '</div>';
+                $str .= '</optgroup>';
             }
-            $str .= '</div>';
-        }
-        return $str;
-    }
-
-    public function getListPopup($res_id, $coll_id, $bool_modif=false, $typeList, $isAvisStep = false, $fromDetail = ""){
-        require_once 'modules/entities/class/class_manage_listdiff.php';
-        $core_tools =new core_tools();
-
-        $id_tab="tab_avisSetWorkflowPopup";
-        $id_form="form_avisSetWorkflowPopup";
-        
-                
-        $circuitAvis = $this->getWorkflow($res_id, $coll_id, $typeList);
+            $str .= '</select>';
+            $str .= '<script>';
+            $str .= 'new Chosen($(\'avisUserList\'),{width: "250px", disable_search_threshold: 10});';
+            $str .= '</script>';
 
-        $model = new diffusion_list();
-        $modelListDiff = $model->get_listmodel('AVIS_CIRCUIT',$_SESSION['destination_entity']);
-
-        // LOAD MODEL if exist
-        if(empty($circuitAvis['avis']['users']) && !empty($modelListDiff)){
-            $circuitAvis = $modelListDiff;
-        }
-
-
-        $str = "";
-        if (!isset($circuitAvis['avis']['users']) && !isset($circuitAvis['lastAvis']['users']) && !$core_tools->test_service('config_avisPopup_workflow_in_detail', 'avis', false) && $fromDetail == "Y"){
-            $str .= "<div class='error' id='divErrorAvisPopup' name='divErrorAvisPopup' onclick='this.hide();'>" . _EMPTY_USER_LIST . "</div>";
-            $str .= "<div><strong><em>" . _EMPTY_AVIS_WORKFLOW . "</em></strong></div>";
-        }
-        else {
             require_once("modules/entities/class/class_manage_listdiff.php");
             $diff_list = new diffusion_list();
             $listModels = $diff_list->select_listmodels($typeList);
 
-            $str .= '<div align="center">';
-        
-            $str .= '<div class="error" id="divErrorAvisPopup" onclick="this.hide();"></div>';
-            $str .= '<div class="info" id="divInfoAvisPopup" onclick="this.hide();"></div>';
+            $str .= ' <select data-placeholder="Ajouter des personnes à partir d\'un modèle" name="modelList" id="modelList" onchange="loadAvisModelUsers();">';
+            $str .= '<option value=""></option>';
+            foreach ($listModels as $lm) {
 
-            if (!empty($listModels) && $bool_modif && !$isAvisStep){
-                $str .= '<select name="modelListPopup" id="modelListPopup" onchange="load_listmodel_avisPopup(this.options[this.selectedIndex], \''.$typeList.'\', \''.$id_tab.'\');">';
-                $str .= '<option value="">Sélectionnez un modèle</option>';
-                foreach($listModels as $lm){
-                    $str .= '<option value="'.$lm['object_id'].'">'.$lm['title'].'</option>';
-                }
-                $str .= '</select>';
-            }
-
-            $str .= '<table class="listing spec detailtabricatordebug" style="width:100%;" cellspacing="0" border="0" id="'.$id_tab.'">';
-            $str .= '<thead><tr>';
-            $str .= '<th style="width:40%;" align="left" valign="bottom"><span>Avis</span></th>';
-            if ($bool_modif){
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:5%;"></th>';
-                $str .= '<th style="width:45%;" align="left" valign="bottom"><span>Consigne</span></th>';
-                $str .= '<th style="width:0;display:none" align="left" valign="bottom"></th>';
-                $str .= '<th style="width:0;display:none" align="center" valign="bottom"></th>';
+                $str .= '<option value="' . $lm['object_id'] . '">' . $lm['title'] . '</option>';
             }
-            else {
-                $str .= '<th style="width:55%;" align="left" valign="bottom"><span>Consigne</span></th>';
-                $str .= '<th style="width:10%;" align="left" valign="bottom"><span>Etat</span></th>';
-            }
-            $str .= '</tr></thead>';
-            $str .= '<tbody>';
-            $color = "";
-        
-            if ($typeList == 'AVIS_CIRCUIT'){
-                if (!isset($circuitAvis['avis']['users']) && !isset($circuitAvis['lastAvis']['users'])){
-                    $j=0;
-                    $str .= '<tr class="col" id="lineAvisWorkflowPopup_'.$j.'">';
-                    $str .= '<td>';
-                    $str .= '<span id="avisPopup_rankPopup_' . $j . '"> <span class="nbResZero" style="font-weight:bold;opacity:0.5;">'. ($seq + 1) . '</span> </span>';
-                    if ($bool_modif){
-                        $str .= '<select style="width:150px;" id="avisPopup_'.$j.'" name="avisPopup_'.$j.'" >';
-                        $str .= '<option value="" >Sélectionnez un utilisateur</option>';
-                        
-                        /** Order by parent entity **/
-                        $tab_userentities = $this->getEntityAvis();
-                        foreach ($tab_userentities as $key => $value) {
-                            $str .= '<optgroup label="'.$tab_userentities[$key]['entity_id'].'">';
-                            $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                            foreach($tab_users as $user){
-                                if($tab_userentities[$key]['entity_id'] == $user['entity_id']){
-                                    $str .= '<option value="'.$user['id'].'" >'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                }
-                                
-                            }
-                            $str .= '</optgroup>';
-                        }
-                        /*$tab_usergroups = $this->getGroupAvis();
-                        foreach ($tab_usergroups as $key => $value) {
-                            $str .= '<optgroup label="'.$tab_usergroups[$key]['group_desc'].'">';
-                            $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                            foreach($tab_users as $user){
-                                $str .= '<option value="'.$user['id'].'" >'.$user['lastname'].', '.$user['firstname'].'</option>';
-                            }
-                        }
-                        $str .= '</optgroup>';*/
-                        $str .= '</select>';
-                    }
-                    $str .= '<span id="lastavisPopup_' . $j . '"> <i title="'._LAST_AVIS.'" style="color : #fdd16c;visibility:hidden;" class="fa fa-certificate fa-lg fa-fw"></i></span></td>';
-                    $str .= '<td><a href="javascript://" id="avisPopup_down_'.$j.'" name="avisPopup_down_'.$j.'" style="visibility:hidden;" onclick="deplacerLigneAvisPopup(0,1,\''.$id_tab.'\')" ><i class="fa fa-arrow-down fa-2x" title="'.DOWN_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><a href="javascript://" id="avisPopup_up_'.$j.'" name="avisPopup_up_'.$j.'" style="visibility:hidden;" ><i class="fa fa-arrow-up fa-2x" title="'.UP_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><a href="javascript://" onclick="delRowAvisPopup(this.parentNode.parentNode.rowIndex,\''.$id_tab.'\')" id="avisPopup_suppr_'.$j.'" name="avisPopup_suppr_'.$j.'" style="visibility:hidden;" ><i class="fa fa-user-times fa-2x" title="'.DEL_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><a href="javascript://" style="visibility:visible;"  id="avisPopup_add_'.$j.'" name="avisPopup_add_'.$j.'" onclick="addRowAvisPopup(\''.$id_tab.'\')" ><i class="fa fa-user-plus fa-2x" title="'.ADD_USER_WORKFLOW.'"></i></a></td>';
-                    $str .= '<td><input type="text" id="avisPopup_consigne_'.$j.'" name="avisPopup_consigne_'.$j.'" onmouseover="setTitle(this);" style="width:95%;"/></td>';
-                    $str .= '<td style="display:none"><input type="hidden" id="avisPopup_date_'.$j.'" name="avisPopup_date_'.$j.'"/></td>';
-
-                    $str .= '<td style="display:none"><input type="checkbox" id="avisPopup_isSign_'.$j.'" name="avisPopup_isSign_'.$j.'" style="visibility:hidden;" /></td>';
-                    $str .= '<td><i class="fa fa-plus fa-lg" title="Nouvel utilisateur ajouté"></i></td>';
-                    $str .= '</tr>';
-                }
-                else{
-                    if ($isAvisStep)
-                        $myPosAvis = $this->myPosAvis($res_id, $coll_id, $typeList);
-                    if (isset($circuitAvis['avis']['users'])){
-                        foreach($circuitAvis['avis']['users'] as $seq=>$step){
-                            if($color == ' class="col"') {
-                                $color = '';
-                            } else {
-                                $color = ' class="col"';
-                            }
-
-                            $str .= '<tr ' . $color . '>';
-
-                            if ($bool_modif){
-                                $str .= '<td>';
-                                $tab_users = $this->getUsersAvis();
-
-                                if ($isAvisStep && $myPosAvis >= $seq || $step['process_date'] != '')
-                                    $disabled = ' disabled ';
-                                else
-                                    $disabled = '';
-                                $str .= '<span id="avisPopup_rankPopup_' . $seq . '"><span class="nbResZero" style="font-weight:bold;opacity:0.5;">'. ($seq + 1) . '</span> </span>';
-                                $str .= '<select style="width:150px;" id="avisPopup_'.$seq.'" name="avisPopup_'.$seq.'" '.$disabled.'>';
-                                $str .= '<option value="" >Sélectionnez un utilisateur</option>';
-                                
-                                /** Order by parent entity **/
-                                $tab_userentities = $this->getEntityAvis();
-                                foreach ($tab_userentities as $key => $value) {
-                                    $str .= '<optgroup label="'.$tab_userentities[$key]['entity_id'].'">';
-                                    $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                    foreach($tab_users as $user){
-                                        if($tab_userentities[$key]['entity_id'] == $user['entity_id']){
-                                            $selected = " ";
-                                            if ($user['id'] == $step['user_id']){
-                                                $selected = " selected";
-                                            }
-                                            $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                        }
-                                        
-                                    }
-                                    $str .= '</optgroup>';
-                                }
-                                /*$tab_usergroups = $this->getGroupAvis();
-                                foreach ($tab_usergroups as $key => $value) {
-                                    $str .= '<optgroup label="'.$tab_usergroups[$key]['group_desc'].'">';
-                                    $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                    foreach($tab_users as $user){
-                                        $selected = " ";
-                                        if ($user['id'] == $step['user_id']){
-                                            $selected = " selected";
-                                        }
-                                        $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-
-                                    }
-                                    $str .= '</optgroup>';
-                                }*/
-                                $str .= '</select>';
-
-                                $str .= "<span id=\"lastAvisPopup_" . $seq . "\">";
-                                if (empty($circuitAvis['lastAvis']['users']) && $seq == count ($circuitAvis['avis']['users'])-1)
-                                    $str .= " <i title=\""._LAST_AVIS."\" style=\"color : #fdd16c;visibility:hidden;\" class=\"fa fa-certificate fa-lg fa-fw\"></i>";
-                                $str .= "</span></td>";
-                                $up = ' style="visibility:visible"';
-                                $displayCB = ' style="visibility:hidden"';
-                                $checkCB = '';
-                                if ($isAvisStep && $myPosAvis >= $seq || $step['process_date'] != '')
-                                    $down = ' style="visibility:hidden"';
-                                else
-                                    $down = ' style="visibility:visible"';
-                                if ($isAvisStep && $myPosAvis >= $seq || $step['process_date'] != '' || count($circuitAvis['avis']['users']) == '1')
-                                    $del = ' style="visibility:hidden"';
-                                else
-                                    $del = ' style="visibility:visible"';
-                                if (empty($circuitAvis['lastAvis']['users']) && $seq == count ($circuitAvis['avis']['users'])-1){
-                                    $add = ' style="visibility:visible"';
-                                    $down = ' style="visibility:hidden"';
-                                    $displayCB = ' style="visibility:hidden"';
-                                    $checkCB = ' checked';
-                                }
-                                else{
-                                    $add = ' style="visibility:hidden"';
-                                }
-                                if ($isAvisStep && $myPosAvis >= $seq || $step['process_date'] != '')
-                                    $displayCB = ' style="visibility:hidden"';
-
-                                if ($seq == 0 || ($isAvisStep && $myPosAvis+1 >= $seq) || $circuitAvis['avis']['users'][$seq-1]['process_date'] != ''){
-                                    $up = ' style="visibility:hidden"';
-                                }
-                                $str .= '<td><a href="javascript://"  '.$down.' id="avisPopup_down_'.$seq.'" name="avisPopup_down_'.$seq.'" onclick="deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2,\''.$id_tab.'\')" ><i class="fa fa-arrow-down fa-2x" title="'.DOWN_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td><a href="javascript://"   '.$up.' id="avisPopup_up_'.$seq.'" name="avisPopup_up_'.$seq.'" onclick="deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1,\''.$id_tab.'\')" ><i class="fa fa-arrow-up fa-2x" title="'.UP_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td id="allez"><a href="javascript://" onclick="delRowAvisPopup(this.parentNode.parentNode.rowIndex,\''.$id_tab.'\')" id="suppr_'.$seq.'" name="suppr_'.$seq.'" '.$del.' ><i class="fa fa-user-times fa-2x" title="'.DEL_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td><a href="javascript://" '.$add.'  id="avisPopup_add_'.$seq.'" name="avisPopup_add_'.$seq.'" onclick="addRowAvisPopup(\''.$id_tab.'\')" ><i class="fa fa-user-plus fa-2x" title="'.ADD_USER_WORKFLOW.'"></i></a></td>';
-                                $str .= '<td><input type="text" id="avisPopup_consigne_'.$seq.'" name="avisPopup_consigne_'.$seq.'" value="'.$step['process_comment'].'" onmouseover="setTitle(this);" style="width:95%;" '.$disabled.'/></td>';
-                                $str .= '<td style="display:none"><input type="hidden" value="'.$step['process_date'].'" id="avisPopup_date_'.$seq.'" name="avisPopup_date_'.$seq.'"/></td>';
+            $str .= '</select>';
 
+            $str .= '<script>';
+            $str .= 'new Chosen($(\'modelList\'),{width: "250px;", disable_search_threshold: 10});';
+            $str .= '</script>';
+            $str .= '<br/><br/>';
+        }
 
-                                $str .= '<td style="display:none"><input type="checkbox" id="avisPopup_isSign_'.$seq.'" name="avisPopup_isSign_'.$seq.'" '.$displayCB.' '.$checkCB.'/></td>';
-                                if ($step['process_date'] != '')
-                                    $str .= '<td><i class="fa fa-check fa-2x" title="'._AVIS_SENT.'"></i></td>';
-                                else
-                                    $str .= '<td><i class="fa fa-hourglass-half fa-lg" title="'._WAITING_FOR_AVIS.'"></i></td>';
+        $str .= '<div id="avis_content">';
+        //AVIS USER IN DOCUMENT
+        $i = 1;
+        $lastUserAvis = true;
 
+        if (count($circuit['avis']['users']) == 0) {
+            $str .= '<div id="emptyAvis"><strong><em>' . _EMPTY_AVIS_WORKFLOW . '</em></strong></div>';
+        } else {
+            $str .= '<div id="emptyAvis" style="display:none;"><strong><em>' . _EMPTY_AVIS_WORKFLOW . '</em></strong></div>';
+            if (count($circuit['avis']['users']) > 0) {
+                foreach ($circuit['avis']['users'] as $it => $info_userAvis) {
+                    if (empty($info_userAvis['process_date'])) {
+                        if ($lastUserAvis == true && $isAvisStep == true) {
+                            $vised = ' currentAvis';
+                            $modif = 'false';
+                            $disabled = '';
+                            $link_vis = 'arrow-right ';
+                            $del_vis = '<div class="delete_avis"></div>';
+                            if ($info_userAvis['user_id'] <> $_SESSION['user']['UserId']) {
+                                $info_vised = '<p style="color:red;">Vous être en train de viser à la place de ' . $info_userAvis['firstname'] . ' ' . $info_userAvis['lastname'] . '!</p>';
+                            } else {
+                                $info_vised = 'Vous êtes l\'actuel viseur';
                             }
-                            else{
-                                $str .= '<td><span><strong>' . ($seq + 1) . ' </strong></span>'.$step['firstname'].' '.$step['lastname'];
-                                $str .= '</td>';
-                                $str .= '<td>'.$step['process_comment'].'</td>';
-                                if ($step['process_date'] != '')
-                                    $str .= '<td><i class="fa fa-check fa-2x" title="'._AVIS_SENT.'"></i></td>';
-                                else
-                                    $str .= '<td><i class="fa fa-hourglass-half fa-lg" title="'._WAITING_FOR_AVIS.'"></i></td>';
-                                // else $str .= '<td></td>';
-                            }
-                            $str .= '</tr>';
-                        }
-                    }
-                    //ajout signataire
-
-                    if (!empty($circuitAvis['lastAvis']['users'])){
-                        $seq = count ($circuitAvis['avis']['users']);
-                        if($color == ' class="col"') {
-                            $color = '';
                         } else {
-                            $color = ' class="col"';
-                        }
-
-                        $str .= '<tr ' . $color . '>';
-                        if ($bool_modif){
-                            if ($isAvisStep && $myPosAvis >= $seq)
-                                $disabled = ' disabled ';
-                            else
+                            $vised = '';
+                            if ($bool_modif == true) {
+                                $modif = 'true';
+                                $del_vis = '<i class="fa fa-trash" aria-hidden="true" onclick="delAvisUser(this.parentElement.parentElement);" title="' . _DELETE . '"></i>';
                                 $disabled = '';
-
-                            $str .= '<td>';
-                            $tab_users = $this->getUsersAvis();
-                            $str .= '<span id="rank_' . $seq . '"><strong>'. ($seq + 1) . ' </strong></span>';
-                            $str .= '<select id="avisPopup_'.$seq.'" name="avisPopup_'.$seq.'" '.$disabled.'>';
-                            $str .= '<option value="" >Sélectionnez un utilisateur</option>';
-                            
-                            /** Order by parent entity **/
-                            $tab_userentities = $this->getEntityAvis();
-                            foreach ($tab_userentities as $key => $value) {
-                                $str .= '<optgroup label="'.$tab_userentities[$key]['entity_id'].'">';
-                                $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                foreach($tab_users as $user){
-                                    if($tab_userentities[$key]['entity_id'] == $user['entity_id']){
-                                        $selected = " ";
-                                        if ($user['id'] == $circuitAvis['lastAvis']['users'][0]['user_id'])
-                                            $selected = " selected";
-                                        $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                    }
-                                    
-                                }
-                                $str .= '</optgroup>';
+                            } else {
+                                $modif = 'false';
+                                $del_vis = '';
+                                $disabled = ' disabled="disabled"';
                             }
-                            /*$tab_usergroups = $this->getGroupAvis();
-                            foreach ($tab_usergroups as $key => $value) {
-                                $str .= '<optgroup label="'.$tab_usergroups[$key]['group_desc'].'">';
-                                $tab_users = $this->getUsersAvis($tab_usergroups[$key]['group_id']);
-                                foreach($tab_users as $user){
-                                    $selected = " ";
-                                    if ($user['id'] == $circuitAvis['lastAvis']['users'][0]['user_id'])
-                                        $selected = " selected";
-                                    $str .= '<option value="'.$user['id'].'" '.$selected.'>'.$user['lastname'].', '.$user['firstname'].'</option>';
-                                }
-                                $str .= '</optgroup>';
-                            }*/
-                            $str .= '</select>';
-
-                            $str .= '<span id="lastAvisPopup_' . $seq . '"> <i title="Signataire" style="color : #fdd16c;visibility:hidden;" class="fa fa-certificate fa-lg fa-fw"></i></span></td>';
-                            if ($isAvisStep && ($myPosAvis+1 == $seq || $myPosAvis == $seq))
-                                $up = ' style="visibility:hidden"';
-                            else
-                                $up = ' style="visibility:visible"';
-                            $down = ' style="visibility:hidden"';
 
-                            // if ($isAvisStep && $myPosAvis == $seq) $add = ' style="visibility:hidden"';
-                            // else $add = ' style="visibility:visible"';
-                            $add = ' style="visibility:visible"';
 
-                            if ($isAvisStep && $myPosAvis == $seq)
-                                $del = ' style="visibility:hidden"';
-                            else
-                                $del = ' style="visibility:visible"';
+                            $info_vised = '';
+                            $link_vis = 'hourglass';
+                        }
 
-                            if (count ($circuitAvis['avis']['users']) == 0){
-                                $up     = 'style="visibility:hidden"';
-                                $del    = 'style="visibility:hidden"';
-                            }
-                            $displayCB = ' style="visibility:hidden"';
-                            if ($isAvisStep && $myPosAvis == $seq)
-                                $displayCB = ' style="visibility:hidden"';
 
-                            $str .= '<td><a href="javascript://"  '.$down.' id="avisPopup_down_'.$seq.'" name="avisPopup_down_'.$seq.'" onclick="deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2,\''.$id_tab.'\')" ><i class="fa fa-arrow-down fa-2x" title="'.DOWN_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><a href="javascript://"   '.$up.' id="avisPopup_up_'.$seq.'" name="avisPopup_up_'.$seq.'" onclick="deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1,\''.$id_tab.'\')" ><i class="fa fa-arrow-up fa-2x" title="'.UP_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><a href="javascript://" onclick="delRowAvisPopup(this.parentNode.parentNode.rowIndex,\''.$id_tab.'\')" id="avisPopup_suppr_'.$seq.'" name="avisPopup_suppr_'.$seq.'" '.$del.' ><i class="fa fa-user-times fa-2x" title="'.DEL_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><a href="javascript://" '.$add.'  id="avisPopup_add_'.$seq.'" name="avisPopup_add_'.$seq.'" onclick="addRowAvisPopup(\''.$id_tab.'\')" ><i class="fa fa-user-plus fa-2x" title="'.ADD_USER_WORKFLOW.'"></i></a></td>';
-                            $str .= '<td><input type="text" id="avisPopup_consigne_'.$seq.'" name="avisPopup_consigne_'.$seq.'" value="'.$circuitAvis['lastAvis']['users'][0]['process_comment'].'" onmouseover="setTitle(this);" style="width:95%;" '.$disabled.'/></td>';
-                            $str .= '<td style="display:none"><input type="hidden" id="avisPopup_date_'.$seq.'" name="avisPopup_date_'.$seq.'" value="'.$circuitAvis['lastAvis']['users'][0]['process_date'].'" /></td>';
 
-                            $str .= '<td style="display:none"><input type="checkbox" id="avisPopup_isSign_'.$seq.'" name="avisPopup_isSign_'.$seq.'" '.$displayCB.' checked/></td>';
-                        } else {
-                            $str .= '<td><span><strong>' . ($seq + 1) . ' </strong></span>' . $circuitAvis['lastAvis']['users'][0]['firstname'].' '.$circuitAvis['lastAvis']['users'][0]['lastname'];
-                            $str .= ' <i title="'._LAST_AVIS.'" style="color : #fdd16c;visibility:hidden;" class="fa fa-certificate fa-lg fa-fw"></i></td>';
-                            $str .= '<td>'.$circuitAvis['lastAvis']['users'][0]['process_comment'].'</td>'; 
-                            if ($circuitAvis['lastAvis']['users'][0]['process_date'] != '')
-                                $str .= '<td><i class="fa fa-check fa-2x" title="'._SIGNED.'"></i></td>';
-                            else
-                                $str .= '<td><i class="fa fa-hourglass-half fa-lg" title="'._WAITING_FOR_SIGN.'"></i></td>';
-                                
-                        }
-                        $str .= '</tr>';
+                        $lastUserAvis = false;
+                    } else {
+                        $lastUserAvis = true;
+                        $modif = 'false';
+                        $vised = ' vised';
+                        $link_vis = 'check';
+                        $disabled = ' disabled="disabled"';
+                        $info_vised = '<br/><sub>avis donné le : ' . functions::format_date_db($info_userAvis['process_date'], '', '', true) . '</sub>';
+                        $del_vis = '';
                     }
+                    //AVIS USER LINE CIRCUIT
+                    $str .= '<div class="droptarget' . $vised . '" id="avis_' . $i . '" draggable="' . $modif . '">';
+                    $str .= '<span class="avisUserStatus">';
+                    $str .= '<i class="fa fa-' . $link_vis . '" aria-hidden="true"></i>';
+                    $str .= '</span>';
+                    $str .= '<span class="avisUserInfo">';
+                    $str .= '<i class="fa fa-user fa-2x" aria-hidden="true"></i> ' . $info_userAvis['lastname'] . ' ' . $info_userAvis['firstname'] . ' <sup class="nbRes">' . $info_userAvis['entity_id'] . '</sup>' . $info_vised;
+                    $str .= '</span>';
+                    $str .= '<span class="avisUserConsigne">';
+                    $str .= '<input class="userId" type="hidden" value="' . $info_userAvis['user_id'] . '"/><input class="avisDate" type="hidden" value="' . $info_userAvis['process_date'] . '"/><input' . $disabled . ' class="consigne" type="text" value="' . $info_userAvis['process_comment'] . '"/>';
+                    $str .= '</span>';
+                    $str .= '<span class="avisUserAction">';
+                    $str .= $del_vis;
+                    $str .= '</span>';
+                    $str .= '<span id="dropZone">';
+                    $str .= '<i class="fa fa-exchange fa-2x fa-rotate-90" aria-hidden="true"></i>';
+                    $str .= '</span>';
+                    $str .= '</div>';
+
+                    $i++;
                 }
             }
-        
-            $str .= '</tbody>';
-            $str .= '</table>';
-            if ($bool_modif){
+        }
 
-                    $str .= '<input type="button" name="save" id="save" value="Enregistrer comme modèle" class="button" onclick="$(\'modalSaveAvisModelPopup\').style.display = \'block\';" />';
-                    $str .= '<div id="modalSaveAvisModelPopup" >';
-                    $str .= '<h3>Sauvegarder le circuit de avis</h3>';
-                    $str .= '<input type="hidden" value="'.$typeList . '_' . strtoupper(base_convert(date('U'), 10, 36)).'" name="objectId_inputAvisPopup" id="objectId_inputAvisPopup"/><br/>';
-                    $str .= '<label for="titleModel">Titre</label> ';
-                    $str .= '<input type="text" name="titleModelAvisPopup" id="titleModelAvisPopup"/><br/>';
-                    $str .= '<input type="button" name="saveModelAvis" id="saveModelAvis" value="'._VALIDATE.'" class="button" onclick="saveAvisModelPopup(\''.$id_tab.'\');" /> ';
-                    $str .= '<input type="button" name="cancelModelAvis" id="cancelModelAvis" value="'._CANCEL.'" class="button" onclick="$(\'modalSaveAvisModelPopup\').style.display = \'none\';" />';
-                    $str .= '</div>';
-            }
+        $str .= '</div>';
+
+        if ($bool_modif == true) {
+            //SAVE AVIS CIRCUIT
+            $str .= '<input type="button" name="send" id="send" value="' . _SAVE_CHANGES . '" class="button" ';
+            $str .= 'onclick="updateAvisWorkflow(' . $res_id . ');" /> ';
+
+            //SAVE AS MODEL
+            $str .= '<input type="button" name="save" id="save" value="Enregistrer comme modèle" class="button" onclick="$(\'modalSaveAvisModel\').style.display = \'block\';" />';
+            $str .= '<div id="modalSaveAvisModel" >';
+            $str .= '<h3>' . _SAVE_POSITION . ' ' . _AVIS_WORKFLOW . '</h3><br/>';
+            $str .= '<label for="titleModel">' . _TITLE . '</label> ';
+            $str .= '<input type="text" name="titleModel" id="titleModel"/><br/>';
+            $str .= '<input type="button" name="saveModel" id="saveModel" value="' . _VALIDATE . '" class="button" onclick="saveAvisWorkflowAsModel();" /> ';
+            $str .= '<input type="button" name="cancelModel" id="cancelModel" value="' . _CANCEL . '" class="button" onclick="$(\'modalSaveAvisModel\').style.display = \'none\';" />';
             $str .= '</div>';
         }
+        $str .= '<script>initDragNDropAvis();</script>';
         return $str;
     }
 
-    public function getWorkflow($res_id, $coll_id, $typeList){
+    public function getWorkflow($res_id, $coll_id, $typeList)
+    {
         require_once('modules/entities/class/class_manage_listdiff.php');
         $listdiff = new diffusion_list();
         $roles = $listdiff->list_difflist_roles();
         $circuitAvis = $listdiff->get_listinstance($res_id, false, $coll_id, $typeList);
-        if (isset($circuitAvis['copy'])) unset($circuitAvis['copy']);
+        if (isset($circuitAvis['copy']))
+            unset($circuitAvis['copy']);
         return $circuitAvis;
     }
 
-    public function getEntityAvis(){
+    public function getEntityAvis()
+    {
         $db = new Database();
-        
+
         $stmt = $db->query("SELECT distinct(entities.entity_id) from users, usergroup_content, users_entities,entities WHERE users_entities.user_id = users.user_id and 
             users_entities.primary_entity = 'Y' and users.user_id = usergroup_content.user_id AND entities.entity_id = users_entities.entity_id AND group_id IN 
             (SELECT group_id FROM usergroups_services WHERE service_id = ?)  
             order by entities.entity_id", array('avis_documents'));
-        
+
         $tab_userentities = array();
-        
-        
-        while($res = $stmt->fetchObject()){
-            array_push($tab_userentities,array('entity_id'=>$res->entity_id));
+
+
+        while ($res = $stmt->fetchObject()) {
+            array_push($tab_userentities, array('entity_id' => $res->entity_id));
         }
         //print_r($tab_userentities);
         return $tab_userentities;
     }
 
-    public function getGroupAvis(){
+    public function getGroupAvis()
+    {
         $db = new Database();
-        
+
         $stmt = $db->query("SELECT DISTINCT(usergroup_content.group_id),group_desc from usergroups, usergroup_content WHERE usergroups.group_id = usergroup_content.group_id AND usergroup_content.group_id IN (SELECT group_id FROM usergroups_services WHERE service_id = ?)", array('avis_documents'));
-        
+
         $tab_usergroup = array();
-        
-        
-        while($res = $stmt->fetchObject()){
-            array_push($tab_usergroup,array('group_id'=>$res->group_id,'group_desc'=>$res->group_desc));
+
+
+        while ($res = $stmt->fetchObject()) {
+            array_push($tab_usergroup, array('group_id' => $res->group_id, 'group_desc' => $res->group_desc));
         }
         //print_r($tab_usergroup);
         return $tab_usergroup;
     }
 
-    public function getUsersAvis($group_id = null){
+    public function getUsersAvis($group_id = null)
+    {
         $db = new Database();
-        
-        if($group_id <> null){
+
+        if ($group_id <> null) {
             $stmt = $db->query("SELECT users.user_id, users.firstname, users.lastname, usergroup_content.group_id,entities.entity_id from users, usergroup_content, users_entities,entities WHERE users_entities.user_id = users.user_id and 
                 users_entities.primary_entity = 'Y' and users.user_id = usergroup_content.user_id AND entities.entity_id = users_entities.entity_id AND group_id IN 
-                (SELECT group_id FROM usergroups_services WHERE service_id = ? AND group_id = ?)  order by users.lastname", array('avis_documents',$group_id));
-        }else{
+                (SELECT group_id FROM usergroups_services WHERE service_id = ? AND group_id = ?)  order by users.lastname", array('avis_documents', $group_id));
+        } else {
             $stmt = $db->query("SELECT users.user_id, users.firstname, users.lastname, usergroup_content.group_id,entities.entity_id from users, usergroup_content, users_entities,entities WHERE users_entities.user_id = users.user_id and 
                 users_entities.primary_entity = 'Y' and users.user_id = usergroup_content.user_id AND entities.entity_id = users_entities.entity_id AND group_id IN 
                 (SELECT group_id FROM usergroups_services WHERE service_id = ?)  
                 order by users.lastname", array('avis_documents'));
         }
-        
+
         $tab_users = array();
-        
-        
-        while($res = $stmt->fetchObject()){
-            array_push($tab_users,array('id'=>$res->user_id, 'firstname'=>$res->firstname,'lastname'=>$res->lastname,'group_id'=>$res->group_id,'entity_id'=>$res->entity_id));
+
+
+        while ($res = $stmt->fetchObject()) {
+            array_push($tab_users, array('id' => $res->user_id, 'firstname' => $res->firstname, 'lastname' => $res->lastname, 'group_id' => $res->group_id, 'entity_id' => $res->entity_id));
         }
         return $tab_users;
     }
 
-    public function myPosAvis($res_id, $coll_id, $listDiffType){
+    public function myPosAvis($res_id, $coll_id, $listDiffType)
+    {
         $db = new Database();
         $stmt = $db->query("SELECT sequence, item_mode from listinstance WHERE res_id= ? and coll_id = ? and difflist_type = ? and item_id = ? and  process_date ISNULL ORDER BY listinstance_id ASC LIMIT 1", array($res_id, $coll_id, $listDiffType, $_SESSION['user']['UserId']));
         $res = $stmt->fetchObject();
-        /*if ($res->item_mode == 'sign'){
-            return $this->nbVisa($res_id, $coll_id);
-        }*/
+        /* if ($res->item_mode == 'sign'){
+          return $this->nbAvis($res_id, $coll_id);
+          } */
         return $res->sequence;
     }
 
-    protected function getWorkflowsNumberByTitle($title){
-        $db = new Database();
-        $stmt = $db->query("SELECT * FROM listmodels WHERE title = ?", array($title));
-        return $stmt->rowCount();
-    }
-
-    public function isWorkflowTitleFree($title){
-        $nb = $this->getWorkflowsNumberByTitle($title);
-        if ($nb == 0)
-            return true;
-        else
-            return false;
-    }
-
-    public function saveModelWorkflow($id_list, $workflow, $typeList, $title){
+    public function saveModelWorkflow($id_list, $workflow, $typeList, $title)
+    {
         require_once('modules/entities/class/class_manage_listdiff.php');
         $diff_list = new diffusion_list();
 
-        
+
         $diff_list->save_listmodel(
-            $workflow, 
-            $typeList,
-            $id_list,
-            $title
-        );    
+                $workflow, $typeList, $id_list, $title
+        );
     }
 
-    public function saveWorkflow($res_id, $coll_id, $workflow, $typeList){
+    public function saveWorkflow($res_id, $coll_id, $workflow, $typeList)
+    {
         require_once('modules/entities/class/class_manage_listdiff.php');
         $diff_list = new diffusion_list();
-        
-        $diff_list->save_listinstance(
-            $workflow, 
-            $typeList,
-            $coll_id, 
-            $res_id, 
-            $_SESSION['user']['UserId'],
-            $_SESSION['user']['primaryentity']['id']
-        ); 
-        
-    }
-
-    public function setStatusAvis($res_id, $coll_id){
-        $curr_avis_wf = $this->getWorkflow($res_id, $coll_id, 'AVIS_CIRCUIT');
-
-        $db = new Database();
-        $stmt = $db->query("SELECT sequence, item_mode from listinstance WHERE res_id= ? and coll_id = ? and difflist_type = ? and process_date ISNULL ORDER BY listinstance_id ASC LIMIT 1", array($res_id, $coll_id, 'AVIS_CIRCUIT'));
-        $resListDiffAvis = $stmt->fetchObject();
-
-        // If there is only one step in the avis workflow, we set status to EVISA
-        if (count($curr_avis_wf['avis']) == 0){
-            $mailStatus = 'NEW';
-        } else {
-            $mailStatus = 'EAVIS';
-        }
-
-        $db->query("UPDATE res_letterbox SET status = ? WHERE res_id = ? ", array($mailStatus, $res_id));
 
+        $diff_list->save_listinstance(
+                $workflow, $typeList, $coll_id, $res_id, $_SESSION['user']['UserId'], $_SESSION['user']['primaryentity']['id']
+        );
     }
 
-    public function getCurrentStepAvis($res_id, $coll_id, $listDiffType){
+    public function getCurrentStepAvis($res_id, $coll_id, $listDiffType)
+    {
         $db = new Database();
-        if($listDiffType == 'entity_id'){
+        if ($listDiffType == 'entity_id') {
             $order = 'DESC';
-        }else{
+        } else {
             $order = 'ASC';
         }
-        $stmt = $db->query("SELECT sequence, item_mode from listinstance WHERE res_id= ? and coll_id = ? and difflist_type = ? and process_date ISNULL ORDER BY listinstance_id ".$order." LIMIT 1", array($res_id, $coll_id, $listDiffType));
+        $stmt = $db->query("SELECT sequence, item_mode from listinstance WHERE res_id= ? and coll_id = ? and difflist_type = ? and process_date ISNULL ORDER BY listinstance_id " . $order . " LIMIT 1", array($res_id, $coll_id, $listDiffType));
         $res = $stmt->fetchObject();
-        /*if ($res->item_mode == 'avis'){
-            return $this->nbAvis($res_id, $coll_id);
-        }*/
+        /* if ($res->item_mode == 'avis'){
+          return $this->nbAvis($res_id, $coll_id);
+          } */
         return $res->sequence;
     }
 
@@ -942,10 +319,9 @@ abstract class avis_controler_Abstract
         $stepDetails = array();
         $db = new Database();
         $stmt = $db->query("SELECT * "
-            . "from listinstance WHERE res_id= ? and coll_id = ? "
-            . "and difflist_type = ? and sequence = ? "
-            . "ORDER BY listinstance_id ASC LIMIT 1", 
-            array($res_id, $coll_id, $listDiffType, $sequence));
+                . "from listinstance WHERE res_id= ? and coll_id = ? "
+                . "and difflist_type = ? and sequence = ? "
+                . "ORDER BY listinstance_id ASC LIMIT 1", array($res_id, $coll_id, $listDiffType, $sequence));
         $res = $stmt->fetchObject();
         $stepDetails['listinstance_id'] = $res->listinstance_id;
         $stepDetails['coll_id'] = $res->coll_id;
@@ -962,19 +338,21 @@ abstract class avis_controler_Abstract
         $stepDetails['difflist_type'] = $res->difflist_type;
         $stepDetails['process_date'] = $res->process_date;
         $stepDetails['process_comment'] = $res->process_comment;
-        
+
         return $stepDetails;
     }
 
-    public function nbAvis($res_id, $coll_id){
+    public function nbAvis($res_id, $coll_id)
+    {
         $db = new Database();
         $stmt = $db->query("SELECT listinstance_id from listinstance WHERE res_id= ? and coll_id = ? and item_mode = ? and difflist_type = 'AVIS_CIRCUIT'", array($res_id, $coll_id, 'avis'));
         return $stmt->rowCount();
     }
 
-        #####################################
+    #####################################
     ## add note on a resource
     #####################################
+
     public function UpdateNoteAvis($resId, $collId, $noteContent)
     {
         $status = 'ok';
@@ -1006,23 +384,20 @@ abstract class avis_controler_Abstract
                 $status = 'ko';
                 $error .= 'resId not exists';
             } else {
-                $query =
-                    "UPDATE " . NOTES_TABLE
-                    . " SET note_text = ?"
-                    . ", date_note = CURRENT_TIMESTAMP"
-                    . " WHERE identifier = ?"
-                    . " AND note_text LIKE '[POUR AVIS]%'"
-                    . " AND coll_id = ?";
+                $query = "UPDATE " . NOTES_TABLE
+                        . " SET note_text = ?"
+                        . ", date_note = CURRENT_TIMESTAMP"
+                        . " WHERE identifier = ?"
+                        . " AND note_text LIKE '[POUR AVIS]%'"
+                        . " AND coll_id = ?";
 
                 $stmt = $db->query($query, array($noteContent, $resId, $collId));
 
                 $hist = new history();
                 $hist->add(
-                    $view, $resId, 'UP', 'resup', _AVIS_UPDATED
-                    . _ON_DOC_NUM . $resId . ' ' . _BY . ' '.$_SESSION['user']['UserId'],
-                    $_SESSION['config']['databasetype'], 'notes'
+                        $view, $resId, 'UP', 'resup', _AVIS_UPDATED
+                        . _ON_DOC_NUM . $resId . ' ' . _BY . ' ' . $_SESSION['user']['UserId'], $_SESSION['config']['databasetype'], 'notes'
                 );
-
             }
         }
         $returnArray = array(
@@ -1032,5 +407,5 @@ abstract class avis_controler_Abstract
         );
         return $returnArray;
     }
-    
+
 }
diff --git a/modules/avis/css/module.css b/modules/avis/css/module.css
index 6c185f75126..33aa472e4e1 100755
--- a/modules/avis/css/module.css
+++ b/modules/avis/css/module.css
@@ -24,4 +24,125 @@
 	left: 40%;
 	top: 10%;
 	text-align: center;
+}
+
+[draggable=true]{
+    cursor: move;
+}
+[draggable=true]:hover{
+    box-shadow:0 0 5px green; /* CSS3 */
+}
+[draggable=false]:hover{
+    cursor: not-allowed;
+}
+#avis_content{
+  display: block;
+  width: 100%;
+}
+.droptarget{
+	position: relative;
+    background-color: #93D1E4;
+    display: table;
+    margin: 10px;
+    padding: 10px;
+    text-align: left;
+    width: 95%;
+    cursor: default;
+    border: dashed 2px #93D1E4
+}
+
+.droptarget_arrow {
+    border: none;
+    display:table-cell;
+}
+
+.vised{
+  opacity: 0.5;
+  color: green;
+  border: solid 2px green;
+}
+
+.droptarget input{
+    width : 100%;
+}
+
+#avisUserList{
+    width:45%;
+    float:left;
+}
+
+.droptarget.currentVis{
+    color : #009DC5;
+    border: solid 2px #009DC5;
+}
+
+.avisUserInfo,.avisUserStatus,.avisUserConsigne,.avisUserAction{
+	display: table-cell;
+	vertical-align: middle;
+}
+
+.avisUserStatus{
+	width: 5%;
+	opacity: 0.5;
+}
+.vised .avisUserStatus{
+	opacity: 1;
+}
+.avisUserInfo{
+	width: 45%;
+	font-weight: bold;
+}
+
+.avisUserInfo .nbRes{
+	background-color: grey;
+	font-weight: normal;
+}
+
+.avisUserInfo sub{
+	font-weight: normal;
+}
+
+.droptarget:hover.vised #dropZone{
+	visibility: hidden;
+}
+.droptarget:hover #dropZone{
+	visibility: visible;
+}
+
+.dropArea{
+    border: dashed 3px white;
+    width: 60%;
+    margin:auto;
+    opacity: 0.5;
+    padding: 5px;
+    
+}
+
+.dropArea::after{
+    font-weight: bolder;
+}
+
+#dropZone,#dropZone:active{
+	width: 5%;
+	opacity: 0.5;
+	visibility: hidden;
+	text-align: right;
+	margin: 5px;
+}
+#dropZone:hover{
+	cursor: grab;
+}
+#dropZone:active{
+	cursor: grabbing;
+}
+.avisUserConsigne{
+	width: 40%;
+}
+.avisUserAction{
+	color : red;
+	text-align: right;
+	width: 5%;
+}
+.avisUserAction i{
+	cursor: pointer;
 }
\ No newline at end of file
diff --git a/modules/avis/js/functions.js b/modules/avis/js/functions.js
index dc383ce5358..86fb6083e0e 100755
--- a/modules/avis/js/functions.js
+++ b/modules/avis/js/functions.js
@@ -1,858 +1,278 @@
-function addRowAvis(id_tableau)
-{
-
-	var tableau = document.getElementById(id_tableau);	
-	var ligne = tableau.insertRow(-1);//on a ajouté une ligne
-	var position = ligne.rowIndex;
-
-	if (position%2 == 1) ligne.className = "col";
-
-	/*var colonne1 = ligne.insertCell(0);//on a une ajouté une cellule
-	colonne1.innerHTML += position;//on y met la position
-	*/
-	var id_Cons = "avis_0";
-	var last_select = tableau.rows.length-3;
-	
-	//var listeDeroulante = document.getElementById(id_Cons);
-	var listeDeroulante = document.getElementById('avis_'+last_select);
-	var colonne2 = ligne.insertCell(0);//on ajoute la seconde cellule
-	var listOptions = "";
-
-	listOptions=listeDeroulante.innerHTML;
-
-	colonne2.innerHTML += "<span id='avis_rank_" + position + "'></span><select>"+listOptions+"</select><span id='lastAvis_" + position + "'></span>";
-	//colonne2.innerHTML += "</select>";
-
-	var colonne3 = ligne.insertCell(1);
-	colonne3.innerHTML += "<a href=\"javascript://\"  id=\"avis_down_"+position+"\" name=\"avis_down_"+position+"\" onclick=\"deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2, '"+id_tableau+"')\" style=\"visibility:hidden;\" ><i class=\"fa fa-arrow-down fa-2x\" title=\"Déplacer l'utilisateur vers le bas\"></i></a>";
-
-	var colonne4 = ligne.insertCell(2);
-	colonne4.innerHTML += "<a href=\"javascript://\" id=\"avis_up_"+position+"\" name=\"avis_up_"+position+"\" onclick=\"deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1, '"+id_tableau+"')\" style=\"visibility:visible;\" ><i class=\"fa fa-arrow-up fa-2x\" title=\"Déplacer l'utilisateur vers le haut\"></i></a>";
-
-	var colonne5 = ligne.insertCell(3);
-	colonne5.innerHTML += "<a href=\"javascript://\" onclick=\"delRowAvis(this.parentNode.parentNode.rowIndex, '"+id_tableau+"')\" id=\"avis_suppr_"+position+"\" name=\"avis_suppr_"+position+"\" style=\"visibility:visible;\" ><i class=\"fa fa-user-times fa-2x\" title=\"Retirer l'utilisateur du circuit\"></i></a>";
-	
-	var colonne6 = ligne.insertCell(4);
-	colonne6.innerHTML += "<a href=\"javascript://\" id=\"avis_add_"+position+"\" name=\"avis_add_"+position+"\" onclick=\"addRowAvis('"+id_tableau+"')\"style=\"visibility:visible;\" ><i class=\"fa fa-user-plus fa-2x\" title=\"Ajouter un utilisateur dans le circuit\"></i></a>";
-	
-	var colonne7 = ligne.insertCell(5);
-	colonne7.innerHTML += "<input type=\"text\" id=\"avis_consigne_"+position+"\" name=\"avis_consigne_"+position+"\" value=\""+document.getElementById('avis_consigne_'+last_select).value+"\" style=\"width:95%;\"/>";
-	
-	var colonne8 = ligne.insertCell(6);
-	colonne8.style.display = 'none';
-	colonne8.innerHTML += "<input type=\"hidden\" id=\"avis_date_"+position+"\" name=\"avis_date_"+position+"\"/>";
-	
-	var colonne9 = ligne.insertCell(7);
-	colonne9.style.display = 'none';
-	colonne9.innerHTML += "<input type=\"checkbox\" id=\"avis_isSign_"+position+"\" name=\"avis_isSign_"+position+"\"/>";
-
-	var colonne10 = ligne.insertCell(8);
-	//colonne10.style.display = 'none';
-	colonne10.innerHTML += '<i class="fa fa-plus fa-lg" title="Nouvel utilisateur ajouté"></i>';
-
-	//document.getElementById('avis_consigne_'+last_select).value = "";
-
-	refreshIconesAvis(id_tableau);
-}
-
-function addRowAvisPopup(id_tableau)
-{
-
-    var tableau = document.getElementById(id_tableau);  
-    var ligne = tableau.insertRow(-1);//on a ajouté une ligne
-    var position = ligne.rowIndex;
-
-    if (position%2 == 1) ligne.className = "col";
-
-    /*var colonne1 = ligne.insertCell(0);//on a une ajouté une cellule
-    colonne1.innerHTML += position;//on y met la position
-    */
-    var id_Cons = "avisPopup_0";
-	var last_select = tableau.rows.length-3;
-	
-	//var listeDeroulante = document.getElementById(id_Cons);
-	var listeDeroulante = document.getElementById('avisPopup_'+last_select);
-	var colonne2 = ligne.insertCell(0);//on ajoute la seconde cellule
-	var listOptions = "";
-    
-    listOptions=listeDeroulante.innerHTML;
-
-    colonne2.innerHTML += "<span id='avisPopup_rank_" + position + "'></span><select style='width:150px;' >"+listOptions+"</select><span id='lastAvisPopup_" + position + "'></span>";
-    //colonne2.innerHTML += "</select>";
-
-    var colonne3 = ligne.insertCell(1);
-    colonne3.innerHTML += "<a href=\"javascript://\"  id=\"avisPopup_down_"+position+"\" name=\"avisPopup_down_"+position+"\" onclick=\"deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2, '"+id_tableau+"')\" style=\"visibility:hidden;\" ><i class=\"fa fa-arrow-down fa-2x\" title=\"Déplacer l'utilisateur vers le bas\"></i></a>";
-
-    var colonne4 = ligne.insertCell(2);
-    colonne4.innerHTML += "<a href=\"javascript://\" id=\"avisPopup_up_"+position+"\" name=\"avisPopup_up_"+position+"\" onclick=\"deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1, '"+id_tableau+"')\" style=\"visibility:visible;\" ><i class=\"fa fa-arrow-up fa-2x\" title=\"Déplacer l'utilisateur vers le haut\"></i></a>";
-
-    var colonne5 = ligne.insertCell(3);
-    colonne5.innerHTML += "<a href=\"javascript://\" onclick=\"delRowAvisPopup(this.parentNode.parentNode.rowIndex, '"+id_tableau+"')\" id=\"avisPopup_suppr_"+position+"\" name=\"avisPopup_suppr_"+position+"\" style=\"visibility:visible;\" ><i class=\"fa fa-user-times fa-2x\" title=\"Retirer l'utilisateur du circuit\"></i></a>";
-    
-    var colonne6 = ligne.insertCell(4);
-    colonne6.innerHTML += "<a href=\"javascript://\" id=\"avisPopup_add_"+position+"\" name=\"avisPopup_add_"+position+"\" onclick=\"addRowAvisPopup('"+id_tableau+"')\"style=\"visibility:visible;\" ><i class=\"fa fa-user-plus fa-2x\" title=\"Ajouter un utilisateur dans le circuit\"></i></a>";
-    
-    var colonne7 = ligne.insertCell(5);
-    colonne7.innerHTML += "<input type=\"text\" id=\"avisPopup_consigne_"+position+"\" name=\"avisPopup_consigne_"+position+"\" value=\""+document.getElementById('avisPopup_consigne_'+last_select).value+"\" style=\"width:95%;\"/>";
-    
-    var colonne8 = ligne.insertCell(6);
-    colonne8.style.display = 'none';
-    colonne8.innerHTML += "<input type=\"hidden\" id=\"avisPopup_date_"+position+"\" name=\"avisPopup_date_"+position+"\"/>";
-    
-    var colonne9 = ligne.insertCell(7);
-    colonne9.style.display = 'none';
-    colonne9.innerHTML += "<input type=\"checkbox\" id=\"avisPopup_isSign_"+position+"\" name=\"avisPopup_isSign_"+position+"\"/>";
-    
-    var colonne10 = ligne.insertCell(8);
-	//colonne10.style.display = 'none';
-	colonne10.innerHTML += '<i class="fa fa-plus fa-lg" title="Nouvel utilisateur ajouté"></i>';
-
-	//document.getElementById('avisPopup_consigne_'+last_select).value = "";
-
-    refreshIconesAvisPopup(id_tableau);
-}
-
-function refreshIconesAvis(id_tableau){
-	var tableau = document.getElementById(id_tableau);
-	
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur = arrayLignes.length;//on peut donc appliquer la propriété length
-	var i=1; //on définit un incrémenteur qui représentera la clé
-
-
-	while(i<longueur)
-	{
-		var disabledLine = false;
-		//Maj de la couleur de ligne
-		if(i % 2 == 0)
-		{
-			arrayLignes[i].className = "";
-		}
-		else
-		{
-			arrayLignes[i].className = "col";
-		}
-		
-		var num = i-1;
-		
-		if (arrayLignes[i].cells[0].childNodes[1].disabled == true)
-			disabledLine = true;
-		//MAJ id et name
-		//arrayLignes[i].cells[0].innerHTML = i;
-		arrayLignes[i].cells[0].childNodes[0].id = "avis_rank_" + num;
-		arrayLignes[i].cells[0].childNodes[1].name = "avis_"+num;
-		arrayLignes[i].cells[0].childNodes[1].id="avis_"+num;
-		arrayLignes[i].cells[0].childNodes[2].id = "lastAvis_" + num;
-		arrayLignes[i].cells[1].childNodes[0].name = "avis_down_"+num;
-		arrayLignes[i].cells[1].childNodes[0].id="avis_down_"+num;
-		document.getElementById("avis_down_"+num).setAttribute('onclick','deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2, \''+id_tableau+'\');');
-				
-		arrayLignes[i].cells[2].childNodes[0].name = "avis_up_"+num;	arrayLignes[i].cells[2].childNodes[0].id="avis_up_"+num;
-		document.getElementById("avis_up_"+num).setAttribute('onclick','deplacerLigneAvis(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1, \''+id_tableau+'\');');
-		
-		arrayLignes[i].cells[3].childNodes[0].name = "avis_suppr_"+num;	arrayLignes[i].cells[3].childNodes[0].id="avis_suppr_"+num;
-		arrayLignes[i].cells[4].childNodes[0].name = "avis_add_"+num;	arrayLignes[i].cells[4].childNodes[0].id="avis_add_"+num;
-		arrayLignes[i].cells[5].childNodes[0].name = "avis_consigne_"+num;	arrayLignes[i].cells[5].childNodes[0].id="avis_consigne_"+num;
-		arrayLignes[i].cells[6].childNodes[0].name = "avis_date_"+num;	arrayLignes[i].cells[6].childNodes[0].id="avis_date_"+num;
-		arrayLignes[i].cells[7].childNodes[0].name = "avis_isSign_"+num;	arrayLignes[i].cells[7].childNodes[0].id="avis_isSign_"+num;
-
-		document.getElementById("avis_rank_" + num).innerHTML = "<span class='nbResZero' style='font-weight:bold;opacity:0.5;'>"+i+"</span> ";
-	
-		if(longueur > 2){
-			document.getElementById("avis_add_0").style.visibility="hidden";
-			document.getElementById("avis_suppr_"+num).style.visibility="visible";
-
-		}else{
-			document.getElementById("avis_add_0").style.visibility="visible";
-			document.getElementById("avis_suppr_"+num).style.visibility="hidden";
-
-		}
-		if (i > 1){
-			document.getElementById("avis_up_"+num).style.visibility="visible";
-		}else{
-			document.getElementById("avis_up_"+num).style.visibility="hidden";
-		}
-		
-		if (i != longueur-1){
-			document.getElementById("avis_add_"+num).style.visibility="hidden";
-
-			document.getElementById("avis_isSign_"+num).style.visibility="hidden";
-			document.getElementById("avis_isSign_"+num).checked=false;
-			document.getElementById("lastAvis_" + num).innerHTML = "";
-
-			document.getElementById("avis_down_"+num).style.visibility="visible";
-		}
-		else {
-			document.getElementById("avis_add_"+num).style.visibility="visible";
-			document.getElementById("avis_isSign_"+num).style.visibility="hidden";
-			document.getElementById("avis_isSign_"+num).checked=true;
-			//document.getElementById("lastAvis_" + num).innerHTML = " <i title='Conseiller décideur' style='color : #fdd16c' class='fa fa-certificate fa-lg fa-fw'></i>";
-
-			document.getElementById("avis_down_"+num).style.visibility="hidden";
-
-		}
-		
-		/* Ajout des conditions pour les lignes disabled */
-		if (disabledLine){
-			document.getElementById("avis_suppr_"+num).style.visibility="hidden";
-			document.getElementById("avis_down_"+num).style.visibility="hidden";
-			document.getElementById("avis_up_"+num).style.visibility="hidden";
-			document.getElementById("avis_isSign_"+num).style.visibility="hidden";
-		}
-		if (num > 0) {
-			if (arrayLignes[i-1].cells[0].childNodes[1].disabled == true)
-				document.getElementById("avis_up_"+num).style.visibility="hidden";
-		}
-		/*************************************************/
-		i++;
-	}
-}
-
-function refreshIconesAvisPopup(id_tableau){
-    var tableau = document.getElementById(id_tableau);
-    
-    var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-    var longueur = arrayLignes.length;//on peut donc appliquer la propriété length
-    var i=1; //on définit un incrémenteur qui représentera la clé
-
-
-    while(i<longueur)
-    {
-        var disabledLine = false;
-        //Maj de la couleur de ligne
-        if(i % 2 == 0)
-        {
-            arrayLignes[i].className = "";
+function addAvisUser(users) {
+    if (!users) {
+        nb_avis = $j(".droptarget").length;
+        next_avis = nb_avis + 1;
+        if (nb_avis == 0) {
+            $j("#emptyAvis").hide();
         }
-        else
-        {
-            arrayLignes[i].className = "col";
+        $j("#avis_content").append('<div class="droptarget" id="avis_' + next_avis + '" draggable="true">'
+                + '<span class="avisUserStatus">'
+                + '<i class="fa fa-hourglass" aria-hidden="true"></i>'
+                + '</span>'
+                + '<span class="avisUserInfo">'
+                + '<i class="fa fa-user fa-2x" aria-hidden="true"></i> ' + $j("select#avisUserList option:selected").text() + ' <sup class="nbRes">' + $j("select#avisUserList option:selected").parent().get(0).label + '</sup>'
+                + '<input class="userId" type="hidden" value="' + $j("select#avisUserList option:selected").val() + '"/><input class="avisDate" type="hidden" value=""/>'
+                + '</span>'
+                + '<span class="avisUserConsigne">'
+                + '<input type="text" class="consigne" value=""/>'
+                + '</span>'
+                + '<span class="avisUserAction">'
+                + '<i class="fa fa-trash" aria-hidden="true" onclick="delAvisUser(this.parentElement.parentElement);"></i>'
+                + '</span>'
+                + '<span id="dropZone">'
+                + '<i class="fa fa-exchange fa-2x fa-rotate-90" aria-hidden="true"></i>'
+                + '</span>'
+                + '</div>');
+
+        //prototype
+        document.getElementById("avisUserList").selectedIndex = 0;
+        Event.fire($("avisUserList"), "chosen:updated");
+    } else {
+        nb_avis = $j(".droptarget").length;
+        next_avis = nb_avis + 1;
+        if (nb_avis == 0) {
+            $j("#emptyAvis").hide();
         }
-        
-        var num = i-1;
-        
-        if (arrayLignes[i].cells[0].childNodes[1].disabled == true)
-            disabledLine = true;
-        //MAJ id et name
-        //arrayLignes[i].cells[0].innerHTML = i;
-        arrayLignes[i].cells[0].childNodes[0].id = "avisPopup_rank_" + num;
-        arrayLignes[i].cells[0].childNodes[1].name = "avisPopup_"+num;
-        arrayLignes[i].cells[0].childNodes[1].id="avisPopup_"+num;
-        arrayLignes[i].cells[0].childNodes[2].id = "lastAvisPopup_" + num;
-        arrayLignes[i].cells[1].childNodes[0].name = "avisPopup_down_"+num;
-        arrayLignes[i].cells[1].childNodes[0].id="avisPopup_down_"+num;
-        document.getElementById("avisPopup_down_"+num).setAttribute('onclick','deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex+2, \''+id_tableau+'\');');
-                
-        arrayLignes[i].cells[2].childNodes[0].name = "avisPopup_up_"+num;    arrayLignes[i].cells[2].childNodes[0].id="avisPopup_up_"+num;
-        document.getElementById("avisPopup_up_"+num).setAttribute('onclick','deplacerLigneAvisPopup(this.parentNode.parentNode.rowIndex, this.parentNode.parentNode.rowIndex-1, \''+id_tableau+'\');');
-        
-        arrayLignes[i].cells[3].childNodes[0].name = "avisPopup_suppr_"+num; arrayLignes[i].cells[3].childNodes[0].id="avisPopup_suppr_"+num;
-        arrayLignes[i].cells[4].childNodes[0].name = "avisPopup_add_"+num;   arrayLignes[i].cells[4].childNodes[0].id="avisPopup_add_"+num;
-        arrayLignes[i].cells[5].childNodes[0].name = "avisPopup_consigne_"+num;  arrayLignes[i].cells[5].childNodes[0].id="avisPopup_consigne_"+num;
-        arrayLignes[i].cells[6].childNodes[0].name = "avisPopup_date_"+num;  arrayLignes[i].cells[6].childNodes[0].id="avisPopup_date_"+num;
-        arrayLignes[i].cells[7].childNodes[0].name = "avisPopup_isSign_"+num;    arrayLignes[i].cells[7].childNodes[0].id="avisPopup_isSign_"+num;
-
-        document.getElementById("avisPopup_rank_" + num).innerHTML = "<span class='nbResZero' style='font-weight:bold;opacity:0.5;'>" + i + "</span> ";
-    
-        if(longueur > 2){
-            document.getElementById("avisPopup_add_0").style.visibility="hidden";
-            document.getElementById("avisPopup_suppr_"+num).style.visibility="visible";
-
-        }else{
-            document.getElementById("avisPopup_add_0").style.visibility="visible";
-            document.getElementById("avisPopup_suppr_"+num).style.visibility="hidden";
+        $j("#avis_content").append('<div class="droptarget" id="avis_' + next_avis + '" draggable="true">'
+                + '<span class="avisUserStatus">'
+                + '<i class="fa fa-hourglass" aria-hidden="true"></i>'
+                + '</span>'
+                + '<span class="avisUserInfo">'
+                + '<i class="fa fa-user fa-2x" aria-hidden="true"></i> ' + users.lastname + ' ' + users.firstname + ' <sup class="nbRes">' + users.entity_id + '</sup>'
+                + '<input class="userId" type="hidden" value="' + users.user_id + '"/><input class="avisDate" type="hidden" value=""/>'
+                + '</span>'
+                + '<span class="avisUserConsigne">'
+                + '<input type="text" class="consigne" value="' + users.process_comment + '"/>'
+                + '</span>'
+                + '<span class="avisUserAction">'
+                + '<i class="fa fa-trash" aria-hidden="true" onclick="delAvisUser(this.parentElement.parentElement);"></i>'
+                + '</span>'
+                + '<span id="dropZone">'
+                + '<i class="fa fa-exchange fa-2x fa-rotate-90" aria-hidden="true"></i>'
+                + '</span>'
+                + '</div>');
 
-        }
-        if (i > 1){
-            document.getElementById("avisPopup_up_"+num).style.visibility="visible";
-        }else{
-            document.getElementById("avisPopup_up_"+num).style.visibility="hidden";
-        }
-        
-        if (i != longueur-1){
-            document.getElementById("avisPopup_add_"+num).style.visibility="hidden";
-
-            document.getElementById("avisPopup_isSign_"+num).style.visibility="hidden";
-            document.getElementById("avisPopup_isSign_"+num).checked=false;
-            document.getElementById("lastAvisPopup_" + num).innerHTML = "";
+    }
+}
+function delAvisUser(target) {
+    console.log(target);
+    var id = '#' + target.id;
 
-            document.getElementById("avisPopup_down_"+num).style.visibility="visible";
-        }
-        else {
-            document.getElementById("avisPopup_add_"+num).style.visibility="visible";
-            document.getElementById("avisPopup_isSign_"+num).style.visibility="hidden";
-            document.getElementById("avisPopup_isSign_"+num).checked=true;
-            //document.getElementById("lastAvisPopup_" + num).innerHTML = " <i title='Conseiller décideur' style='color : #fdd16c' class='fa fa-certificate fa-lg fa-fw'></i>";
+    if ($j(".droptarget").length == 1) {
+        $j("#emptyAvis").show();
+    }
+    $j(id).remove();
 
-            document.getElementById("avisPopup_down_"+num).style.visibility="hidden";
+    resetPosAvis();
 
-        }
-        
-        /* Ajout des conditions pour les lignes disabled */
-        if (disabledLine){
-            document.getElementById("avisPopup_suppr_"+num).style.visibility="hidden";
-            document.getElementById("avisPopup_down_"+num).style.visibility="hidden";
-            document.getElementById("avisPopup_up_"+num).style.visibility="hidden";
-            document.getElementById("avisPopup_isSign_"+num).style.visibility="hidden";
-        }
-        if (num > 0) {
-            if (arrayLignes[i-1].cells[0].childNodes[0].disabled == true)
-                document.getElementById("avisPopup_up_"+num).style.visibility="hidden";
-        }
-        /*************************************************/
-        i++;
-    }
 }
-
-function delRowAvis(num, id_tableau){
-	document.getElementById(id_tableau).deleteRow(num);
-	
-	refreshIconesAvis(id_tableau);
+function resetPosAvis() {
+    $i = 1;
+    $j(".droptarget").each(function () {
+        this.id = 'avis_' + $i;
+        $i++;
+    });
 }
+function updateAvisWorkflow(resId) {
+    var $i = 0;
+    var userList = [];
+    if ($j(".droptarget").length) {
+        $j(".droptarget").each(function () {
+            //console.log('viseur : '+$j("#"+this.id+" .userdId").val());
+            userId = $j("#" + this.id).find(".userId").val();
+            userConsigne = $j("#" + this.id).find(".consigne").val();
+            userAvisDate = $j("#" + this.id).find(".avisDate").val();
+            userPos = $i;
+            userList.push({userId: userId, userPos: userPos, userConsigne: userConsigne, userAvisDate: userAvisDate});
+            $i++;
+        });
+    }
+    $j.ajax({
+        url: 'index.php?display=true&module=avis&page=updateAvisWF',
+        type: 'POST',
+        dataType: 'JSON',
+        data: {
+            resId: resId,
+            userList: JSON.stringify(userList)
+        },
+        success: function (response) {
+            if (response.status == 0) {
+                $('divInfoAvis').innerHTML = 'Mise à jour du circuit effectuée';
+                $('divInfoAvis').style.display = 'table-cell';
+                Element.hide.delay(5, 'divInfoAvis');
+                eval(response.exec_js);
+            } else if (response.status != 1) {
+                alert(response.error_txt)
+            }
+        },
+        error: function (error) {
+            alert(error);
+        }
 
-function delRowAvisPopup(num, id_tableau){
-	document.getElementById(id_tableau).deleteRow(num);
-	
-	refreshIconesAvisPopup(id_tableau);
+    });
 }
+function saveAvisWorkflowAsModel() {
+    var $i = 0;
+    var userList = [];
+    var title = $j("#titleModel").val();
+
+    if ($j(".droptarget").length) {
+        $j(".droptarget").each(function () {
+            //console.log('viseur : '+$j("#"+this.id+" .userdId").val());
+            userId = $j("#" + this.id).find(".userId").val();
+            userConsigne = $j("#" + this.id).find(".consigne").val();
+            userAvisDate = $j("#" + this.id).find(".avisDate").val();
+            userPos = $i;
+            userList.push({userId: userId, userPos: userPos, userConsigne: userConsigne, userAvisDate: userAvisDate});
+            $i++;
+        });
+        $j.ajax({
+            url: 'index.php?display=true&module=avis&page=saveAvisModel',
+            type: 'POST',
+            dataType: 'JSON',
+            data: {
+                title: title,
+                userList: JSON.stringify(userList)
+            },
+            success: function (response) {
+                if (response.status == 0) {
+                    $('divInfoAvis').innerHTML = 'Modèle enregistré';
+                    $('divInfoAvis').style.display = 'table-cell';
+                    Element.hide.delay(5, 'divInfoAvis');
+                    $j('#modalSaveAvisModel').hide();
+                    eval(response.exec_js);
+                } else {
+                    alert(response.error_txt)
+                }
+            },
+            error: function (error) {
+                alert(error);
+            }
+
+        });
+
+    } else {
+        alert('Aucun utilisateur dans le circuit !');
+    }
 
-function deplacerLigneAvis(source, cible, id_tableau)
-{
-
-	var tableau = document.getElementById(id_tableau);
-	//on initialise nos variables
-	var ligne = tableau.rows[source];//on copie la ligne
-	var nouvelle = tableau.insertRow(cible);//on insère la nouvelle ligne
-	var cellules = ligne.cells;
-
-	//on boucle pour pouvoir agir sur chaque cellule
-	for(var i=0; i<cellules.length; i++)
-	{
-		nouvelle.insertCell(-1).innerHTML += cellules[i].innerHTML;//on copie chaque cellule de l'ancienne à la nouvelle ligne
-		/*if (i == 6 && cellules[i].childNodes[0].value != ""){
-			nouvelle.cells[5].childNodes[0].value = cellules[i].childNodes[0].value;
-		}*/
-		if (i == 0){
-			nouvelle.cells[0].childNodes[1].selectedIndex = cellules[i].childNodes[1].selectedIndex;
-		}
-
-		if(i == 5){
-			nouvelle.cells[5].childNodes[0].value = cellules[i].childNodes[0].value;
-			//console.log(cellules[i].childNodes[0].value);
-		}
-		
-		/*if (i > 6)
-			nouvelle.cells[i].style.display = 'none';*/
-		if (i == 7 || i == 6){
-			nouvelle.cells[i].style.display = 'none';
-		}
-	}
-
-	//on supprimer l'ancienne ligne
-	tableau.deleteRow(ligne.rowIndex);//on met ligne.rowIndex et non pas source car le numéro d'index a pu changer
-	refreshIconesAvis(id_tableau);
 }
+function loadAvisModelUsers() {
+
+    var objectId = $j("select#modelList option:selected").val();
+    var objectType = 'AVIS_CIRCUIT';
+    $j.ajax({
+        url: 'index.php?display=true&module=avis&page=load_listmodel_avis_users',
+        type: 'POST',
+        dataType: 'JSON',
+        data: {
+            objectType: objectType,
+            objectId: objectId
+        },
+        success: function (response) {
+            if (response.status == 0) {
+
+                var userList = response.result;
+                if (userList) {
+                    userList.each(function (user, key) {
+                        addAvisUser(user);
+                    });
+                }
+
+
+            } else {
+                alert(response.error_txt);
+            }
+        },
+        error: function (error) {
+            alert(error);
+        }
+
+    });
 
-function deplacerLigneAvisPopup(source, cible, id_tableau)
-{
-
-    var tableau = document.getElementById(id_tableau);
-	//on initialise nos variables
-	var ligne = tableau.rows[source];//on copie la ligne
-	var nouvelle = tableau.insertRow(cible);//on insère la nouvelle ligne
-	var cellules = ligne.cells;
-
-	//on boucle pour pouvoir agir sur chaque cellule
-	for(var i=0; i<cellules.length; i++)
-	{
-		nouvelle.insertCell(-1).innerHTML += cellules[i].innerHTML;//on copie chaque cellule de l'ancienne à la nouvelle ligne
-		/*if (i == 6 && cellules[i].childNodes[0].value != ""){
-			nouvelle.cells[5].childNodes[0].value = cellules[i].childNodes[0].value;
-		}
-		if (i == 0){
-			nouvelle.cells[0].childNodes[1].selectedIndex = cellules[i].childNodes[1].selectedIndex;
-		}
-		if (i > 6)
-			nouvelle.cells[i].style.display = 'none';*/
-		if (i == 7 || i == 6){
-			nouvelle.cells[i].style.display = 'none';
-		}
-	}
-
-	//on supprimer l'ancienne ligne
-	tableau.deleteRow(ligne.rowIndex);//on met ligne.rowIndex et non pas source car le numéro d'index a pu changer
-	refreshIconesAvisPopup(id_tableau);
+    //prototype
+    document.getElementById("modelList").selectedIndex = 0;
+    Event.fire($("modelList"), "chosen:updated");
 }
 
-function saveAvisModelPopup(id_tableau) {
-	var tableau 		= document.getElementById(id_tableau);
-	var title 			= $('titleModelAvisPopup').value;
-	var id_list			= $('objectId_inputAvisPopup').value;
-
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur 		= arrayLignes.length;//on peut donc appliquer la propriété length
-
-	var conseillers = "";
-	var consignes 	= "";
-	var cons_empty 	= false;
-
-	var i = 1;
-	while(i < longueur)
-	{
-		var num = i - 1;
-		if (document.getElementById("avisPopup_"+num).value == "" )
-			cons_empty = true;
-		conseillers	+= document.getElementById("avisPopup_"+num).value + "#";
-		consignes		+= document.getElementById("avisPopup_consigne_"+num).value + "#";
-		
-		i++;
-	}
-
-	if (cons_empty){
-		triggerFlashMsg('divErrorAvis', 'Sélectionner au moins un utilisateur');
-	} else if (title == "") {
-		triggerFlashMsg('divErrorAvis', 'Titre manquant');
-	} else {
-		new Ajax.Request("index.php?display=true&module=avis&page=getAvisModelByTitle",
-			{
-
-				method: 'GET',
-				dataType:	'JSON',
-				parameters: {
-					title: title
-				},
-				onSuccess: function (responseValue) {
-					var response = JSON.parse(responseValue.responseText);
-					if (response.isWorkflowTitleFree) {
-
-						new Ajax.Request("index.php?display=true&module=avis&page=saveAvisModel",
-							{
-								method:'POST',
-								parameters: {
-									title 			: title,
-									id_list 		: id_list,
-									consignes 	: consignes,
-									conseillers	: conseillers
-								},
-								onSuccess: function(responseValue){
-									var response = JSON.parse(responseValue.responseText);
-									if (response.status == 1){
-										triggerFlashMsg('divInfoAvis', 'Modèle sauvegardé');
-										$('modalSaveAvisModelPopup').style.display = 'none';
-									}
-								}
-							});
-
-					} else {
-						triggerFlashMsg('divErrorAvis', 'Titre déjà utilisé pour un modèle');
-					}
-				}
-			});
-	}
+function initDragNDropAvis() {
+    document.getElementById("avis_content").addEventListener("dragstart", function (event) {
+        $j(".droptarget").css("border", "dashed 2px #93D1E4");
+        // The dataTransfer.setData() method sets the data type and the value of the dragged data
+        event.dataTransfer.setData("Text", event.target.id);
 
-}
+        // Output some text when starting to drag the p element
+        //document.getElementById("demo").innerHTML = "Started to drag the p element.";
 
-function saveAvisModel(id_tableau) {
-	var tableau 		= document.getElementById(id_tableau);
-	var title 			= $('titleModelAvis').value;
-	var id_list			= $('objectId_inputAvis').value;
-
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur 		= arrayLignes.length;//on peut donc appliquer la propriété length
-
-	var conseillers = "";
-	var consignes 	= "";
-	var cons_empty 	= false;
-
-	var i = 1;
-	while(i < longueur)
-	{
-
-		var num = i - 1;
-		if (document.getElementById("avis_"+num).value == "" )
-			cons_empty = true;
-		conseillers	+= document.getElementById("avis_"+num).value + "#";
-		consignes		+= document.getElementById("avis_consigne_"+num).value + "#";
-		
-		i++;
-	}
-
-
-	if (cons_empty){
-		triggerFlashMsg('divErrorAvis', 'Sélectionner au moins un utilisateur');
-	} else if (title == "") {
-		triggerFlashMsg('divErrorAvis', 'Titre manquant');
-	} else {
-		new Ajax.Request("index.php?display=true&module=avis&page=getAvisModelByTitle",
-			{
-
-				method: 'GET',
-				dataType:	'JSON',
-				parameters: {
-					title: title
-				},
-				onSuccess: function (responseValue) {
-					var response = JSON.parse(responseValue.responseText);
-					if (response.isWorkflowTitleFree) {
-
-						new Ajax.Request("index.php?display=true&module=avis&page=saveAvisModel",
-							{
-								method:'POST',
-								parameters: {
-									title 			: title,
-									id_list 		: id_list,
-									consignes 	: consignes,
-									conseillers	: conseillers
-								},
-								onSuccess: function(responseValue){
-									var response = JSON.parse(responseValue.responseText);
-									if (response.status == 1){
-										triggerFlashMsg('divInfoAvis', 'Modèle sauvegardé');
-										$('modalSaveAvisModel').style.display = 'none';
-									}
-								}
-							});
-
-					} else {
-						triggerFlashMsg('divErrorAvis', 'Titre déjà utilisé pour un modèle');
-					}
-				}
-			});
-	}
+        // Change the opacity of the draggable element
+        event.target.style.opacity = "0.4";
+    });
 
-}
+    // While dragging the p element, change the color of the output text
+    document.getElementById("avis_content").addEventListener("drag", function (event) {
+        //document.getElementById("demo").style.color = "red";
+    });
 
-function load_listmodel_avis(selectedOption, objectType, diff_list_id, save_auto) {
-	if (save_auto == undefined || save_auto == '') {
-		save_auto = false;
-	}
-	var div_id = diff_list_id || 'tab_avisSetWorkflow';
-	
-	var objectId = selectedOption.value || selectedOption;
-	
-	var diff_list_div = $(div_id);
-	new Ajax.Request("index.php?display=true&module=avis&page=load_listmodel_avis",
-		{
-			method:'post',
-			parameters: {
-				objectType	: objectType,
-				objectId		: objectId
-			},
-			onSuccess: function(answer){
-				eval("response = "+answer.responseText);
-				if(response.status == 0 ) {
-					diff_list_div.innerHTML = response.div_content;
-					if (save_auto){
-						var res_id = $('values').value;
-						var coll_id = $('coll_id').value;
-						saveAvisWorkflow(res_id, coll_id, diff_list_id);
-					}
-				} else if (response.status != 1 ){
-					diff_list_div.innerHTML = '';
-					try{
-						$('frm_error').innerHTML = response.error_txt;
-					} catch(e){}
-				}
-			}
-		}
-	);
-}
+    // Output some text when finished dragging the p element and reset the opacity
+    document.getElementById("avis_content").addEventListener("dragend", function (event) {
+        //document.getElementById("demo").innerHTML = "Finished dragging the p element.";
+        $j(".droptarget").css("border", "dashed 2px #93D1E4");
+        event.target.style.opacity = "1";
+    });
 
-function load_listmodel_avisPopup(selectedOption, objectType, diff_list_id, save_auto) {
-	if (save_auto == undefined || save_auto == '') {
-		save_auto = false;
-	}
-	var div_id = diff_list_id || 'tab_avisSetWorkflow';
-	
-	var objectId = selectedOption.value || selectedOption;
-	
-	var diff_list_div = $(div_id);
-	new Ajax.Request("index.php?display=true&module=avis&page=load_listmodel_avis_popup",
-		{
-			method:'post',
-			parameters: {
-				objectType	: objectType,
-				objectId		: objectId
-			},
-			onSuccess: function(answer){
-				eval("response = "+answer.responseText);
-				if(response.status == 0 ) {
-					diff_list_div.innerHTML = response.div_content;
-					if (save_auto){
-						var res_id = $('values').value;
-						var coll_id = $('coll_id').value;
-						saveAvisWorkflowPopup(res_id, coll_id, diff_list_id);
-					}
-				} else if (response.status != 1 ){
-					diff_list_div.innerHTML = '';
-					try{
-						$('frm_error').innerHTML = response.error_txt;
-					} catch(e){}
-				}
-			}
-		}
-	);
-}
 
-function saveAvisWorkflow(res_id, coll_id, id_tableau, fromDetail){
-	var tableau = document.getElementById(id_tableau);
-	
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur = arrayLignes.length;//on peut donc appliquer la propriété length
-	var i=1; //on définit un incrémenteur qui représentera la clé
-	
-	var conseillers = "";
-	var consignes = "";
-	var dates = "";
-	var isSign = "";
-	
-	var cons_empty = false;
-
-	var detail = "";
-
-	if (fromDetail == undefined || fromDetail == "N" ) {
-		detail = "N";
-	} else if (fromDetail == "Y") {
-		detail = "Y";
-	}
-
-	while(i<longueur)
-	{
-		
-		var num = i-1;
-		if (document.getElementById("avis_"+num).value == "" ) cons_empty = true;
-		conseillers += document.getElementById("avis_"+num).value + "#";
-		consignes += document.getElementById("avis_consigne_"+num).value + "#";
-		dates += document.getElementById("avis_date_"+num).value + "#";
-		if (document.getElementById("avis_isSign_"+num).checked == true) isSign += "1#";
-		else isSign += "0#";
-		
-		
-		i++;
-	}
-
-	new Ajax.Request("index.php?display=true&module=avis&page=saveAvisWF",
-	{
-		
-			method:'post',
-			parameters: { 
-				res_id : res_id,
-				coll_id : coll_id,
-				conseillers : conseillers,
-				consignes : consignes,
-				dates : dates,
-				list_sign : isSign,
-				fromDetail : detail,
-				cons_empty : cons_empty
-			},
-			onSuccess: function(answer){
-				eval("response = "+answer.responseText);
-				if (response.status == 1) {
-                                    $('divInfoAvis').innerHTML = 'Mise à jour du circuit effectuée';
-                                    $('divInfoAvis').style.display = 'table-cell';
-                                    Element.hide.delay(5, 'divInfoAvis');
-                                    eval(response.exec_js);
-				} else if (response.status == 2){
-					$('divErrorAvis').innerHTML = 'Sélectionner au moins un utilisateur';
-					$('divErrorAvis').style.display = 'table-cell';
-					Element.hide.delay(5, 'divErrorAvis');
-				}
-
-			}
-	});
-}
+    /* Events fired on the drop target */
 
-function saveAvisWorkflowPopup(res_id, coll_id, id_tableau, fromDetail){
-	var tableau = document.getElementById(id_tableau);
-	
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur = arrayLignes.length;//on peut donc appliquer la propriété length
-	var i=1; //on définit un incrémenteur qui représentera la clé
-	
-	var conseillers = "";
-	var consignes = "";
-	var dates = "";
-	var isSign = "";
-	
-	var cons_empty = false;
-
-	var detail = "";
-
-	if (fromDetail == undefined || fromDetail == "N" ) {
-		detail = "N";
-	} else if (fromDetail == "Y") {
-		detail = "Y";
-	}
-
-	while(i<longueur)
-	{
-		
-		var num = i-1;
-		if (document.getElementById("avisPopup_"+num).value == "" ) cons_empty = true;
-		conseillers += document.getElementById("avisPopup_"+num).value + "#";
-		consignes += document.getElementById("avisPopup_consigne_"+num).value + "#";
-		dates += document.getElementById("avisPopup_date_"+num).value + "#";
-		if (document.getElementById("avisPopup_isSign_"+num).checked == true) isSign += "1#";
-		else isSign += "0#";
-		
-		
-		i++;
-	}
-
-	/*if (cons_empty){
-		$('divErrorAvis').innerHTML = 'Sélectionner au moins un utilisateur';
-		$('divErrorAvis').style.display = 'table-cell';
-		Element.hide.delay(5, 'divErrorAvis');
-	}
-	else*/
-	new Ajax.Request("index.php?display=true&module=avis&page=saveAvisWF",
-	{
-		
-			method:'post',
-			parameters: { 
-				res_id : res_id,
-				coll_id : coll_id,
-				conseillers : conseillers,
-				consignes : consignes,
-				dates : dates,
-				list_sign : isSign,
-				fromDetail : detail,
-				cons_empty : cons_empty
-			},
-			onSuccess: function(answer){
-				eval("response = "+answer.responseText);
-				if (response.status == 1) {
-					$('divInfoAvis').innerHTML = 'Mise à jour du circuit effectuée';
-                    $('divInfoAvis').style.display = 'table-cell';
-                    Element.hide.delay(5, 'divInfoAvis');
-				} else if (response.status == 2){
-					$('divErrorAvis').innerHTML = 'Sélectionner au moins un utilisateur';
-					$('divErrorAvis').style.display = 'table-cell';
-					Element.hide.delay(5, 'divErrorAvis');
-				}
-
-			}
-	});
-}
+    // When the draggable p element enters the droptarget, change the DIVS's border style
+    document.getElementById("avis_content").addEventListener("dragenter", function (event) {
+        if (event.target.className == "droptarget") {
+            event.target.style.border = "dashed 2px green";
+        }
+    });
 
-function resetAvisWorkflow(res_id, coll_id, id_tableau, fromDetail){
-	var tableau = document.getElementById(id_tableau);
-	
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur = arrayLignes.length;//on peut donc appliquer la propriété length
-	var i=1; //on définit un incrémenteur qui représentera la clé
-	
-	var conseillers = "";
-	var consignes = "";
-	var dates = "";
-	var isSign = "";
-	
-	var cons_empty = false;
-
-	var detail = "";
-
-	if (fromDetail == undefined || fromDetail == "N" ) {
-		detail = "N";
-	} else if (fromDetail == "Y") {
-		detail = "Y";
-	}
-
-	while(i<longueur)
-	{
-		
-		var num = i-1;
-		if (document.getElementById("avis_"+num).value == "" ) cons_empty = true;
-		conseillers += document.getElementById("avis_"+num).value + "#";
-		consignes += document.getElementById("avis_consigne_"+num).value + "#";
-		dates += document.getElementById("avis_date_"+num).value + "#";
-		if (document.getElementById("avis_isSign_"+num).checked == true) isSign += "1#";
-		else isSign += "0#";
-		
-		
-		i++;
-	}
-
-	new Ajax.Request("index.php?display=true&module=avis&page=resetAvisWF",
-	{
-		
-			method:'post',
-			parameters: { 
-				res_id : res_id,
-				coll_id : coll_id,
-				conseillers : conseillers,
-				consignes : consignes,
-				dates : dates,
-				list_sign : isSign,
-				fromDetail : detail,
-				cons_empty : cons_empty
-			},
-			onSuccess: function(answer){
-				eval("response = "+answer.responseText);
-                    location.reload(); 
-				}
-
-
-	});
-}
+    // By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element
+    document.getElementById("avis_content").addEventListener("dragover", function (event) {
+        event.preventDefault();
+    });
 
-function resetAvisWorkflowPopup(res_id, coll_id, id_tableau, fromDetail){
-	var tableau = document.getElementById(id_tableau);
-	
-	var arrayLignes = tableau.rows; //l'array est stocké dans une variable
-	var longueur = arrayLignes.length;//on peut donc appliquer la propriété length
-	var i=1; //on définit un incrémenteur qui représentera la clé
-	
-	var conseillers = "";
-	var consignes = "";
-	var dates = "";
-	var isSign = "";
-	
-	var cons_empty = false;
-
-	var detail = "";
-
-	if (fromDetail == undefined || fromDetail == "N" ) {
-		detail = "N";
-	} else if (fromDetail == "Y") {
-		detail = "Y";
-	}
-
-	while(i<longueur)
-	{
-		
-		var num = i-1;
-		if (document.getElementById("avisPopup_"+num).value == "" ) cons_empty = true;
-		conseillers += document.getElementById("avisPopup_"+num).value + "#";
-		consignes += document.getElementById("avisPopup_consigne_"+num).value + "#";
-		dates += document.getElementById("avisPopup_date_"+num).value + "#";
-		if (document.getElementById("avisPopup_isSign_"+num).checked == true) isSign += "1#";
-		else isSign += "0#";
-		
-		
-		i++;
-	}
-
-	new Ajax.Request("index.php?display=true&module=avis&page=resetAvisWF",
-	{
-		
-			method:'post',
-			parameters: { 
-				res_id : res_id,
-				coll_id : coll_id,
-				conseillers : conseillers,
-				consignes : consignes,
-				dates : dates,
-				list_sign : isSign,
-				fromDetail : detail,
-				cons_empty : cons_empty
-			},
-			onSuccess: function(answer){
-				eval("response = "+answer.responseText);
-                    location.reload(); 
-				}
-
-
-	});
+    // When the draggable p element leaves the droptarget, reset the DIVS's border style
+    document.getElementById("avis_content").addEventListener("dragleave", function (event) {
+        if (event.target.className == "droptarget") {
+            event.target.style.border = "dashed 2px #ccc";
+        }
+    });
+
+    /* On drop - Prevent the browser default handling of the data (default is open as link on drop)
+     Reset the color of the output text and DIV's border color
+     Get the dragged data with the dataTransfer.getData() method
+     The dragged data is the id of the dragged element ("drag1")
+     Append the dragged element into the drop element
+     */
+    document.getElementById("avis_content").addEventListener("drop", function (event) {
+        event.preventDefault();
+        if (event.target.className == "droptarget") {
+            /*event.target.style.border = "";
+             var data = event.dataTransfer.getData("Text");
+             var oldContent = event.target.innerHTML;
+             var draggedConsigne = $j('#'+data+' .consigne').val();
+             var replaceConsigne = $j('#'+event.target.id+' .consigne').val();
+             event.target.innerHTML = document.getElementById(data).innerHTML;
+             $j('#'+event.target.id+' .consigne').val(draggedConsigne);
+             document.getElementById(data).innerHTML = oldContent;
+             $j('#'+data+' .consigne').val(replaceConsigne);*/
+            var data = event.dataTransfer.getData("Text");
+            var target = event.target.id;
+            posData = data.split("_");
+            posTarget = target.split("_");
+            if (posData[1] > posTarget[1]) {
+                $j('#' + target).before($j('#' + data));
+            } else {
+                $j('#' + target).after($j('#' + data));
+            }
+            resetPosAvis();
+
+
+        }
+    });
 }
 
 function checkRealDateAvis() {
@@ -860,62 +280,62 @@ function checkRealDateAvis() {
     var docDate;
     var processLimitDate;
     var avisLimitDate;
-    
-    var nowDate = new Date ();
+
+    var nowDate = new Date();
     var date3 = new Date();
-    
+
     var current_date = Date.now();
-    
 
 
-   /* if($('doc_date')) {
-        docDate = $('doc_date').value;
-		var date2 = new Date();
-		date2.setFullYear(docDate.substr(6,4));
-		date2.setMonth(docDate.substr(3,2));
-		date2.setDate(docDate.substr(0,2));
-		date2.setHours(0);
-		date2.setMinutes(0);
-		var d2_docDate=date2.getTime();
-    } */
 
-    if($('process_limit_date')) {
+    /* if($('doc_date')) {
+     docDate = $('doc_date').value;
+     var date2 = new Date();
+     date2.setFullYear(docDate.substr(6,4));
+     date2.setMonth(docDate.substr(3,2));
+     date2.setDate(docDate.substr(0,2));
+     date2.setHours(0);
+     date2.setMinutes(0);
+     var d2_docDate=date2.getTime();
+     } */
+
+    if ($('process_limit_date')) {
         processLimitDate = $('process_limit_date').value;
-		var date4 = new Date();
-		date4.setFullYear(processLimitDate.substr(6,4));
-		date4.setMonth(processLimitDate.substr(3,2)-1);
-		date4.setDate(processLimitDate.substr(0,2));
-		date4.setHours(0);
-		date4.setMinutes(0);
-                date4.setSeconds(0);
-		var d4_processLimitDate=date4.getTime();
+        var date4 = new Date();
+        date4.setFullYear(processLimitDate.substr(6, 4));
+        date4.setMonth(processLimitDate.substr(3, 2) - 1);
+        date4.setDate(processLimitDate.substr(0, 2));
+        date4.setHours(0);
+        date4.setMinutes(0);
+        date4.setSeconds(0);
+        var d4_processLimitDate = date4.getTime();
     }
 
 
-    if($('recommendation_limit_date')) {
+    if ($('recommendation_limit_date')) {
         avisLimitDate = $('recommendation_limit_date_tr').value;
-		var date5 = new Date();
-		date5.setFullYear(avisLimitDate.substr(6,4));
-		date5.setMonth(avisLimitDate.substr(3,2)-1);
-		date5.setDate(avisLimitDate.substr(0,2));
-		date5.setHours(0);
-		date5.setMinutes(0);
-		date5.setSeconds(0);
-		var d5_avisLimitDate;
-		var d5_avisLimitDate=date5.getTime();
-	 }
-
-    if(d4_processLimitDate != "" && avisLimitDate != "" && (d5_avisLimitDate > d4_processLimitDate && d4_processLimitDate > current_date)) {          
+        var date5 = new Date();
+        date5.setFullYear(avisLimitDate.substr(6, 4));
+        date5.setMonth(avisLimitDate.substr(3, 2) - 1);
+        date5.setDate(avisLimitDate.substr(0, 2));
+        date5.setHours(0);
+        date5.setMinutes(0);
+        date5.setSeconds(0);
+        var d5_avisLimitDate;
+        var d5_avisLimitDate = date5.getTime();
+    }
+
+    if (d4_processLimitDate != "" && avisLimitDate != "" && (d5_avisLimitDate > d4_processLimitDate && d4_processLimitDate > current_date)) {
         alert("La date limite d'avis doit être antérieure à la date limite du courrier ");
         $('recommendation_limit_date').value = "";
         $('recommendation_limit_date_tr').value = "";
 
     }
-	
-    if (current_date > d5_avisLimitDate && avisLimitDate != "") {        
-	alert("La date d'avis doit être supérieure à la date du jour ");
+
+    if (current_date > d5_avisLimitDate && avisLimitDate != "") {
+        alert("La date d'avis doit être supérieure à la date du jour ");
         $('recommendation_limit_date').value = "";
         $('recommendation_limit_date_tr').value = "";
-        
+
     }
 }
diff --git a/modules/avis/lang/en.php b/modules/avis/lang/en.php
index 81dddc70e8a..8bd833244b0 100755
--- a/modules/avis/lang/en.php
+++ b/modules/avis/lang/en.php
@@ -71,3 +71,5 @@ if (!defined("_EMPTY_AVIS_WORKFLOW"))
 if (!defined("_AVIS_SENT"))
     define("_AVIS_SENT", "Notice given");
 
+if (!defined("_ADD_AVIS_ROLE"))
+    define("_ADD_AVIS_ROLE", "Add a user for recommendation");
diff --git a/modules/avis/lang/fr.php b/modules/avis/lang/fr.php
index 7639e8a7b70..bb966cad741 100755
--- a/modules/avis/lang/fr.php
+++ b/modules/avis/lang/fr.php
@@ -66,7 +66,7 @@ if (!defined("_PROCEED_WORKFLOW_AVIS_SIMPLE"))
     define("_PROCEED_WORKFLOW_AVIS_SIMPLE", "Émettre un avis (parallèle)");
 
 if (!defined("_EMPTY_AVIS_WORKFLOW"))
-    define("_EMPTY_AVIS_WORKFLOW", "Le circuit d'avis est vide");
+    define("_EMPTY_AVIS_WORKFLOW", "Aucun circuit d'avis paramétré");
 
 if (!defined("_AVIS_SENT"))
     define("_AVIS_SENT", "Avis donné");
@@ -93,4 +93,7 @@ if (!defined("_VALIDATE_BY"))
     define("_VALIDATE_BY", "Validé par");
 
 if (!defined("_AVIS_ROLE_UNAVAILABLE"))
-    define("_AVIS_ROLE_UNAVAILABLE", "Le rôle \"pour avis\" n'est pas disponible dans la liste de diffusion");
\ No newline at end of file
+    define("_AVIS_ROLE_UNAVAILABLE", "Le rôle \"pour avis\" n'est pas disponible dans la liste de diffusion");
+
+if (!defined("_ADD_AVIS_ROLE"))
+    define("_ADD_AVIS_ROLE", "Ajouter un conseiller");
\ No newline at end of file
diff --git a/modules/avis/load_listmodel_avis_users.php b/modules/avis/load_listmodel_avis_users.php
new file mode 100644
index 00000000000..2e998683a46
--- /dev/null
+++ b/modules/avis/load_listmodel_avis_users.php
@@ -0,0 +1,44 @@
+<?php
+
+/*
+ * Copyright Maarch since 2008 under licence GPLv3.
+ * See LICENCE.txt file at the root folder for more details.
+ * This file is part of Maarch software.
+ * 
+ */
+
+/*
+ * @brief load_listmodel_avis_users
+ * @author dev@maarch.org
+ * @ingroup avis
+ * 
+ */
+require_once 'modules/entities/class/class_manage_listdiff.php';
+require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
+        . "class" . DIRECTORY_SEPARATOR
+        . "avis_controler.php";
+
+
+$db = new Database();
+$core = new core_tools();
+$core->load_lang();
+$diffList = new diffusion_list();
+
+$objectType = $_REQUEST['objectType'];
+$objectId = $_REQUEST['objectId'];
+$origin = 'avis';
+
+// Get listmodel_parameters
+$contentListModel = $diffList->get_listmodel($objectType, $objectId);
+
+if (!$contentListModel['avis']['users']) {
+    $contentListModel['avis']['users'] = array();
+}
+
+$userList = $contentListModel['avis']['users'];
+
+$userList = json_encode($userList);
+
+
+echo "{\"status\" : 0, \"result\" :" . $userList . "}";
+exit();
diff --git a/modules/avis/saveAvisModel.php b/modules/avis/saveAvisModel.php
index 2e8f504a7fd..4afc1b889b7 100755
--- a/modules/avis/saveAvisModel.php
+++ b/modules/avis/saveAvisModel.php
@@ -1,67 +1,50 @@
 <?php
-	/*
-	*   Copyright 2008-2015 Maarch and Document Image Solutions
-	*
-	*   This file is part of Maarch Framework.
-	*
-	*   Maarch Framework is free software: you can redistribute it and/or modify
-	*   it under the terms of the GNU General Public License as published by
-	*   the Free Software Foundation, either version 3 of the License, or
-	*   (at your option) any later version.
-	*
-	*   Maarch Framework is distributed in the hope that it will be useful,
-	*   but WITHOUT ANY WARRANTY; without even the implied warranty of
-	*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	*   GNU General Public License for more details.
-	*
-	*   You should have received a copy of the GNU General Public License
-	*   along with Maarch Framework.  If not, see <http://www.gnu.org/licenses/>.
-	*/
 
-	/**
-	* @brief   Save the avis diffusion list
-	*
-	* Save the avis diffusion list
-	*
-	* @file
-	* @author Nicolas Couture <couture@docimsol.com>
-	* @date $date$
-	* @version $Revision$
-	* @ingroup apps
-	*/
-	require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
-			. "class" . DIRECTORY_SEPARATOR
-			. "avis_controler.php";
-			
-			
-	$id_list = $_REQUEST['id_list'];
-	$title = $_REQUEST['title'];
-	$conseillers = explode('#',$_REQUEST['conseillers']);
-	$consignes = explode('#',$_REQUEST['consignes']);
+/*
+ * Copyright Maarch since 2008 under licence GPLv3.
+ * See LICENCE.txt file at the root folder for more details.
+ * This file is part of Maarch software.
+ * 
+ */
 
-	$avis = new avis_controler();
-	
-	$_SESSION['avis_wf']['diff_list']['avis']['users'] = array();
-	
-	for ($i = 0; $i < count($conseillers) - 1; $i++){
-		if ($list_sign[$i] == 0){
-			array_push(
-				$_SESSION['avis_wf']['diff_list']['avis']['users'], 
-				array(
-				'user_id' => $conseillers[$i], 
-				'process_comment' => $consignes[$i], 
-				'viewed' => 0,
-				'visible' => 'Y',
-				'difflist_type' => 'AVIS_CIRCUIT'
-				)
-			);
-		}
-	}
-		
-	$avis->saveModelWorkflow($id_list, $_SESSION['avis_wf']['diff_list'], 'AVIS_CIRCUIT', $title);
+/*
+ * @brief saveAvisModel
+ * @author dev@maarch.org
+ * @ingroup avis
+ * 
+ */
+require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
+        . "class" . DIRECTORY_SEPARATOR
+        . "avis_controler.php";
 
-	$response = ['status' => 1];
 
-	echo json_encode($response);
-	exit();
+$title = $_REQUEST['title'];
+$id_list = 'AVIS_CIRCUIT_' . strtoupper(base_convert(date('U'), 10, 36));
+
+
+$userList = json_decode($_REQUEST['userList']);
+
+$avis = new avis_controler();
+$_SESSION['avis_wf']['diff_list']['avis']['users'] = array();
+$_SESSION['avis_wf']['diff_list']['sign']['users'] = array();
+
+$i = 0;
+foreach ($userList as $user) {
+
+    array_push(
+            $_SESSION['avis_wf']['diff_list']['avis']['users'], array(
+        'user_id' => $user->userId,
+        'process_comment' => $user->userConsigne,
+        'process_date' => $user->userAvisDate,
+        'viewed' => 0,
+        'visible' => 'Y',
+        'difflist_type' => 'AVIS_CIRCUIT'
+            )
+    );
+}
+$avis->saveModelWorkflow($id_list, $_SESSION['avis_wf']['diff_list'], 'AVIS_CIRCUIT', $title);
+
+echo "{\"status\" : 0}";
+
+exit();
 ?>
\ No newline at end of file
diff --git a/modules/avis/send_to_avis.php b/modules/avis/send_to_avis.php
index 4ce31ab6e70..fbc1235357b 100755
--- a/modules/avis/send_to_avis.php
+++ b/modules/avis/send_to_avis.php
@@ -1,27 +1,42 @@
 <?php
+
+/*
+ * Copyright Maarch since 2008 under licence GPLv3.
+ * See LICENCE.txt file at the root folder for more details.
+ * This file is part of Maarch software.
+ * 
+ */
+
+/*
+ * @brief send_to_avis
+ * @author dev@maarch.org
+ * @ingroup avis
+ * 
+ */
+
 $confirm = false;
 $etapes = array('form');
-$frm_width='650px';
+$frm_width = '650px';
 $frm_height = 'auto';
 require("modules/entities/entities_tables.php");
 require_once("modules/entities/class/EntityControler.php");
-require_once('modules/entities/class/class_manage_entities.php');;
+require_once('modules/entities/class/class_manage_entities.php');
 require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
-			. "class" . DIRECTORY_SEPARATOR
-			. "avis_controler.php";
+        . "class" . DIRECTORY_SEPARATOR
+        . "avis_controler.php";
 
- function get_form_txt($values, $path_manage_action,  $id_action, $table, $module, $coll_id, $mode )
- {
+function get_form_txt($values, $path_manage_action, $id_action, $table, $module, $coll_id, $mode)
+{
     require_once('apps/' . $_SESSION['config']['app_id'] . '/class/class_chrono.php');
     $cr7 = new chrono();
 
     require_once 'apps/maarch_entreprise/definition_mail_categories.php';
-    
- 	$res_id=$values[0];
+
+    $res_id = $values[0];
 
     $data = get_general_data($coll_id, $res_id, 'minimal');
     //print_r($data);
- 	$avis = new avis_controler();
+    $avis = new avis_controler();
     $ent = new entity();
     $entity_ctrl = new EntityControler();
     $services = array();
@@ -29,35 +44,33 @@ require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
     $db = new Database();
     $labelAction = '';
     if ($id_action <> '') {
-        $stmt = $db->query("select label_action from actions where id = ?",array($id_action));
+        $stmt = $db->query("select label_action from actions where id = ?", array($id_action));
         $resAction = $stmt->fetchObject();
         $labelAction = functions::show_string($resAction->label_action);
     }
-    
 
-    $frm_str = '<div id="frm_error_'.$id_action.'" class="error"></div>';
+
+    $frm_str = '<div id="frm_error_' . $id_action . '" class="error"></div>';
     if ($labelAction <> '') {
         $frm_str .= '<h2 class="title">' . $labelAction . ' ' . _NUM;
     } else {
-        $frm_str .= '<h2 class="title">'._REDIRECT_MAIL.' '._NUM;
+        $frm_str .= '<h2 class="title">' . _REDIRECT_MAIL . ' ' . _NUM;
     }
     $values_str = '';
-    if(empty($_SESSION['stockCheckbox'])){
-    for($i=0; $i < count($values);$i++)
-        {
-            $values_str .= $values[$i].', ';
+    if (empty($_SESSION['stockCheckbox'])) {
+        for ($i = 0; $i < count($values); $i++) {
+            $values_str .= $values[$i] . ', ';
         }
-    }else{ 
+    } else {
 
-    for($i=0; $i < count($_SESSION['stockCheckbox']);$i++)
-        {
-            $values_str .= $_SESSION['stockCheckbox'][$i].', ';
+        for ($i = 0; $i < count($_SESSION['stockCheckbox']); $i++) {
+            $values_str .= $_SESSION['stockCheckbox'][$i] . ', ';
         }
     }
     $values_str = preg_replace('/, $/', '', $values_str);
-    if(_ID_TO_DISPLAY == 'res_id'){
+    if (_ID_TO_DISPLAY == 'res_id') {
         $frm_str .= $values_str;
-    } else if (_ID_TO_DISPLAY == 'chrono_number'){
+    } else if (_ID_TO_DISPLAY == 'chrono_number') {
         $chrono_number = $cr7->get_chrono_number($values_str, 'res_view_letterbox');
         $frm_str .= $chrono_number;
     }
@@ -66,166 +79,166 @@ require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
     $templatesControler = new templates_controler();
     $templates = array();
 
-      
-        $EntitiesIdExclusion = array();
-        $entities = $entity_ctrl->getAllEntities();
-        $countEntities = count($entities);
-        //var_dump($entities);
-        for ($cptAllEnt = 0;$cptAllEnt<$countEntities;$cptAllEnt++) {
-            if (!is_integer(array_search($entities[$cptAllEnt]->__get('entity_id'), $servicesCompare))) {
-                array_push($EntitiesIdExclusion, $entities[$cptAllEnt]->__get('entity_id'));
-            }
+
+    $EntitiesIdExclusion = array();
+    $entities = $entity_ctrl->getAllEntities();
+    $countEntities = count($entities);
+    //var_dump($entities);
+    for ($cptAllEnt = 0; $cptAllEnt < $countEntities; $cptAllEnt++) {
+        if (!is_integer(array_search($entities[$cptAllEnt]->__get('entity_id'), $servicesCompare))) {
+            array_push($EntitiesIdExclusion, $entities[$cptAllEnt]->__get('entity_id'));
         }
-        
-        $allEntitiesTree= array();
-        $allEntitiesTree = $ent->getShortEntityTreeAdvanced(
+    }
+
+    $allEntitiesTree = array();
+    $allEntitiesTree = $ent->getShortEntityTreeAdvanced(
             $allEntitiesTree, 'all', '', $EntitiesIdExclusion, 'all'
-        );
-        if ($destination <> '') {
-            $templates = $templatesControler->getAllTemplatesForProcess($destination);
-        } else {
-            $templates = $templatesControler->getAllTemplatesForSelect();
-        } 
-        $frm_str .='<b>'._RECOMMENDATION_LIMIT_DATE.':</b><br/>';
-        $frm_str .= '<input name="recommendation_limit_date_tr" type="text" '
+    );
+    if ($destination <> '') {
+        $templates = $templatesControler->getAllTemplatesForProcess($destination);
+    } else {
+        $templates = $templatesControler->getAllTemplatesForSelect();
+    }
+    $frm_str .='<b>' . _RECOMMENDATION_LIMIT_DATE . ':</b><br/>';
+    $frm_str .= '<input name="recommendation_limit_date_tr" type="text" '
             . 'id="recommendation_limit_date_tr" value="" placeholder="JJ-MM-AAAA" onfocus="checkRealDateAvis();" onChange="checkRealDateAvis();"  onclick="clear_error(\'frm_error_'
             . $actionId . '\');showCalender(this);"  onblur="document.getElementById(\'recommendation_limit_date\').value=document.getElementById(\'recommendation_limit_date_tr\').value;"/>';
-        $frm_str .='<br/>';
-        $frm_str .='<br/><b>'._RECOMMENDATION_NOTE.':</b><br/>';
-        $frm_str .= '<select name="templateNotes" id="templateNotes" style="width:98%;margin-bottom: 10px;background-color: White;border: 1px solid #999;color: #666;text-align: left;" '
-                    . 'onchange="addTemplateToNote($(\'templateNotes\').value, \''
-                    . $_SESSION['config']['businessappurl'] . 'index.php?display=true'
-                    . '&module=templates&page=templates_ajax_content_for_notes\');document.getElementById(\'notes\').focus();">';
-        $frm_str .= '<option value="">' . _SELECT_NOTE_TEMPLATE . '</option>';
-            for ($i=0;$i<count($templates);$i++) {
-                if ($templates[$i]['TYPE'] == 'TXT' && ($templates[$i]['TARGET'] == 'notes' || $templates[$i]['TARGET'] == '')) {
-                    $frm_str .= '<option value="';
-                    $frm_str .= $templates[$i]['ID'];
-                    $frm_str .= '">';
-                    $frm_str .= $templates[$i]['LABEL'];
-                }
-                $frm_str .= '</option>';
-            }
-        $frm_str .= '</select><br />';
-
-        $frm_str .= '<textarea style="width:98%;height:60px;resize:none;" name="notes"  id="notes" onblur="document.getElementById(\'note_content_to_users\').value=document.getElementById(\'notes\').value.replace(/[\n]/gi, \'##\' );"></textarea>';
-        //var_dump($allEntitiesTree);
-        $frm_str .= '<hr />';
-        $frm_str .= '<div class="error" id="divError" name="divError"></div>';
-                $frm_str .= '<div style="text-align:center;">';
-                $frm_str .= $avis->getListPopup($res_id, $coll_id, true,'AVIS_CIRCUIT');
-      
-                $frm_str .='</div>';
-        $frm_str .='<div id="form2" style="border:none;">';
-        $frm_str .= '<form name="frm_redirect_dep" id="frm_redirect_dep" method="post" class="forms" action="#">';
-        $frm_str .= '<input type="hidden" name="chosen_action" id="chosen_action" value="end_action" />';
-        $frm_str .= '<input type="hidden" name="note_content_to_users" id="note_content_to_users" />';
-        $frm_str .= '<input type="hidden" name="recommendation_limit_date" id="recommendation_limit_date" />';
-        $frm_str .= '<input type="hidden" name="doc_date" id="doc_date" value ="'.$data['doc_date'].'"/>';
-        $frm_str .= '<input type="hidden" name="process_limit_date" id="process_limit_date" value ="'.$data['process_limit_date'].'" />';
-            $frm_str .='</form>';
-        $frm_str .='</div>';
+    $frm_str .='<br/>';
+    $frm_str .='<br/><b>' . _RECOMMENDATION_NOTE . ':</b><br/>';
+    $frm_str .= '<select name="templateNotes" id="templateNotes" style="width:98%;margin-bottom: 10px;background-color: White;border: 1px solid #999;color: #666;text-align: left;" '
+            . 'onchange="addTemplateToNote($(\'templateNotes\').value, \''
+            . $_SESSION['config']['businessappurl'] . 'index.php?display=true'
+            . '&module=templates&page=templates_ajax_content_for_notes\');document.getElementById(\'notes\').focus();">';
+    $frm_str .= '<option value="">' . _SELECT_NOTE_TEMPLATE . '</option>';
+    for ($i = 0; $i < count($templates); $i++) {
+        if ($templates[$i]['TYPE'] == 'TXT' && ($templates[$i]['TARGET'] == 'notes' || $templates[$i]['TARGET'] == '')) {
+            $frm_str .= '<option value="';
+            $frm_str .= $templates[$i]['ID'];
+            $frm_str .= '">';
+            $frm_str .= $templates[$i]['LABEL'];
+        }
+        $frm_str .= '</option>';
+    }
+    $frm_str .= '</select><br />';
+
+    $frm_str .= '<textarea style="width:98%;height:60px;resize:none;" name="notes"  id="notes" onblur="document.getElementById(\'note_content_to_users\').value=document.getElementById(\'notes\').value.replace(/[\n]/gi, \'##\' );"></textarea>';
+    //var_dump($allEntitiesTree);
+    $frm_str .= '<hr />';
+    $frm_str .= '<div class="error" id="divError" name="divError"></div>';
+    $frm_str .= '<div style="text-align:center;">';
+    $frm_str .= $avis->getList($res_id, $coll_id, true, 'AVIS_CIRCUIT');
+
+    $frm_str .='</div>';
+    $frm_str .='<div id="form2" style="border:none;">';
+    $frm_str .= '<form name="frm_redirect_dep" id="frm_redirect_dep" method="post" class="forms" action="#">';
+    $frm_str .= '<input type="hidden" name="chosen_action" id="chosen_action" value="end_action" />';
+    $frm_str .= '<input type="hidden" name="note_content_to_users" id="note_content_to_users" />';
+    $frm_str .= '<input type="hidden" name="recommendation_limit_date" id="recommendation_limit_date" />';
+    $frm_str .= '<input type="hidden" name="doc_date" id="doc_date" value ="' . $data['doc_date'] . '"/>';
+    $frm_str .= '<input type="hidden" name="process_limit_date" id="process_limit_date" value ="' . $data['process_limit_date'] . '" />';
+    $frm_str .='</form>';
+    $frm_str .='</div>';
     $frm_str .='<hr />';
 
     $frm_str .='<div align="center">';
-        $frm_str .=' <input type="button" name="redirect_dep" value="'._VALIDATE.'" id="redirect_dep" class="button" onclick="saveAvisWorkflowPopup(\''.$res_id.'\', \''.$coll_id.'\', \'tab_avisSetWorkflowPopup\', \'N\');valid_action_form( \'frm_redirect_dep\', \''.$path_manage_action.'\', \''. $id_action.'\', \''.$values_str.'\', \''.$table.'\', \''.$module.'\', \''.$coll_id.'\', \''.$mode.'\');" />';
-        $frm_str .=' <input type="button" name="cancel" id="cancel" class="button"  value="'._CANCEL.'" onclick="pile_actions.action_pop();actions_status.action_pop();destroyModal(\'modal_'.$id_action.'\');"/>';
+    $frm_str .=' <input type="button" name="redirect_dep" value="' . _VALIDATE . '" id="redirect_dep" class="button" onclick="updateAvisWorkflow(' . $res_id . ');valid_action_form( \'frm_redirect_dep\', \'' . $path_manage_action . '\', \'' . $id_action . '\', \'' . $values_str . '\', \'' . $table . '\', \'' . $module . '\', \'' . $coll_id . '\', \'' . $mode . '\');" />';
+    $frm_str .=' <input type="button" name="cancel" id="cancel" class="button"  value="' . _CANCEL . '" onclick="pile_actions.action_pop();actions_status.action_pop();destroyModal(\'modal_' . $id_action . '\');"/>';
     $frm_str .='</div>';
     return addslashes($frm_str);
- }
+}
 
- function check_form($form_id,$values)
- {
-	 //var_dump($values);
+function check_form($form_id, $values)
+{
+    //var_dump($values);
     $recommendation_limit_date = get_value_fields($values, 'recommendation_limit_date');
     $note_content_to_users = get_value_fields($values, 'note_content_to_users');
-    
-    if($recommendation_limit_date == null || $recommendation_limit_date == ''){
-        $_SESSION['action_error'] = _RECOMMENDATION_LIMIT_DATE. " " . _MANDATORY;
+
+    if ($recommendation_limit_date == null || $recommendation_limit_date == '') {
+        $_SESSION['action_error'] = _RECOMMENDATION_LIMIT_DATE . " " . _MANDATORY;
         return false;
     } else if ($note_content_to_users == null || $note_content_to_users == '') {
-		$_SESSION['action_error'] = _NOTE. " " . _MANDATORY;
-		return false;
-	}
-    
+        $_SESSION['action_error'] = _NOTE . " " . _MANDATORY;
+        return false;
+    }
+
 
     $avis = new avis_controler();
-	$curr_avis_wf = $avis->getWorkflow($_SESSION['doc_id'], $_SESSION['current_basket']['coll_id'], 'AVIS_CIRCUIT');
-
-	if (count($curr_avis_wf['avis']) == 0){
-		$_SESSION['action_error'] = _AVIS_WORKFLOW. " " . _MANDATORY;
-		return false;
-	}
-    /*if($form_id == 'frm_redirect_dep') {
-        $dep = get_value_fields($values, 'department');
-        if($dep == '') {
-            $_SESSION['action_error'] = _MUST_CHOOSE_DEP;
-            return false;
-        } else if (empty($_SESSION['redirect']['diff_list']['dest']['users'][0])
-                || ! isset($_SESSION['redirect']['diff_list']['dest']['users'][0])
-            ) {
-                $_SESSION['action_error'] = _DEST
-                    . " " . _MANDATORY;
-                return false;
-        } else {
-            return true;
-        }
-    } else if($form_id == 'frm_redirect_user') {
-        $user = get_value_fields($values, 'user');
-        if($user == '')
-        {
-            $_SESSION['action_error'] = _MUST_CHOOSE_USER;
-            return false;
-        }
-        else
-        {
-            return true;
-        }
-    } else {
-        $_SESSION['action_error'] = _FORM_ERROR;
+    $curr_avis_wf = $avis->getWorkflow($_SESSION['doc_id'], $_SESSION['current_basket']['coll_id'], 'AVIS_CIRCUIT');
+
+    if (count($curr_avis_wf['avis']) == 0) {
+        $_SESSION['action_error'] = _AVIS_WORKFLOW . " " . _MANDATORY;
         return false;
-    }*/
+    }
+    /* if($form_id == 'frm_redirect_dep') {
+      $dep = get_value_fields($values, 'department');
+      if($dep == '') {
+      $_SESSION['action_error'] = _MUST_CHOOSE_DEP;
+      return false;
+      } else if (empty($_SESSION['redirect']['diff_list']['dest']['users'][0])
+      || ! isset($_SESSION['redirect']['diff_list']['dest']['users'][0])
+      ) {
+      $_SESSION['action_error'] = _DEST
+      . " " . _MANDATORY;
+      return false;
+      } else {
+      return true;
+      }
+      } else if($form_id == 'frm_redirect_user') {
+      $user = get_value_fields($values, 'user');
+      if($user == '')
+      {
+      $_SESSION['action_error'] = _MUST_CHOOSE_USER;
+      return false;
+      }
+      else
+      {
+      return true;
+      }
+      } else {
+      $_SESSION['action_error'] = _FORM_ERROR;
+      return false;
+      } */
     return true;
- }
+}
 
-function manage_form($arr_id, $history, $id_action, $label_action, $status, $coll_id, $table, $values_form )
+function manage_form($arr_id, $history, $id_action, $label_action, $status, $coll_id, $table, $values_form)
 {
     /*
-        Redirect to dep:
-        $values_form = array (size=3)
-          0 => 
-            array (size=2)
-              'ID' => string 'chosen_action' (length=13)
-              'VALUE' => string 'end_action' (length=10)
-          1 => 
-            array (size=2)
-              'ID' => string 'department' (length=10)
-              'VALUE' => string 'DGA' (length=3)
-          2 => 
-            array (size=2)
-              'ID' => string 'redirect_dep' (length=12)
-              'VALUE' => string 'Rediriger' (length=9)
-        
-        Redirect to user:
-        $values_form = array (size=3)
-          0 => 
-            array (size=2)
-              'ID' => string 'chosen_action' (length=13)
-              'VALUE' => string 'end_action' (length=10)
-          1 => 
-            array (size=2)
-              'ID' => string 'user' (length=4)
-              'VALUE' => string 'aackermann' (length=10)
-          2 => 
-            array (size=2)
-              'ID' => string 'redirect_user' (length=13)
-              'VALUE' => string 'Rediriger' (length=9)
-    
-    */
-    
-    if(empty($values_form) || count($arr_id) < 1) 
+      Redirect to dep:
+      $values_form = array (size=3)
+      0 =>
+      array (size=2)
+      'ID' => string 'chosen_action' (length=13)
+      'VALUE' => string 'end_action' (length=10)
+      1 =>
+      array (size=2)
+      'ID' => string 'department' (length=10)
+      'VALUE' => string 'DGA' (length=3)
+      2 =>
+      array (size=2)
+      'ID' => string 'redirect_dep' (length=12)
+      'VALUE' => string 'Rediriger' (length=9)
+
+      Redirect to user:
+      $values_form = array (size=3)
+      0 =>
+      array (size=2)
+      'ID' => string 'chosen_action' (length=13)
+      'VALUE' => string 'end_action' (length=10)
+      1 =>
+      array (size=2)
+      'ID' => string 'user' (length=4)
+      'VALUE' => string 'aackermann' (length=10)
+      2 =>
+      array (size=2)
+      'ID' => string 'redirect_user' (length=13)
+      'VALUE' => string 'Rediriger' (length=9)
+
+     */
+
+    if (empty($values_form) || count($arr_id) < 1)
         return false;
-    
+
     $res_id = $arr_id[0];
     require_once('modules/entities/class/class_manage_listdiff.php');
     require_once('modules/notes/class/notes_controler.php');
@@ -234,63 +247,58 @@ function manage_form($arr_id, $history, $id_action, $label_action, $status, $col
 
 
     $db = new Database();
-    
+
     $formValues = array();
-    for($i=0; $i<count($values_form); $i++) {
+    for ($i = 0; $i < count($values_form); $i++) {
         $formValue = $values_form[$i];
         $id = $formValue['ID'];
         $value = $formValue['VALUE'];
         $formValues[$id] = $value;
     }
-    
-        
-        # save note
-        if($formValues['note_content_to_users'] != ''){
-            //Add notes
-            $userIdTypist = $_SESSION['user']['UserId'];
-            $content_note = $formValues['note_content_to_users'];
-            $content_note = str_replace("##", "\n", $content_note);
-            $content_note = str_replace(";", ".", $content_note);
-            $content_note = str_replace("--", "-", $content_note);
-            $content_note = $content_note;
-            $content_note = '[' . _TO_AVIS . '] ' . $content_note;
-            $note->addNote($res_id, $coll_id, $content_note);
-            
-        }
-         
+
+
+    # save note
+    if ($formValues['note_content_to_users'] != '') {
+        //Add notes
+        $userIdTypist = $_SESSION['user']['UserId'];
+        $content_note = $formValues['note_content_to_users'];
+        $content_note = str_replace("##", "\n", $content_note);
+        $content_note = str_replace(";", ".", $content_note);
+        $content_note = str_replace("--", "-", $content_note);
+        $content_note = $content_note;
+        $content_note = '[' . _TO_AVIS . '] ' . $content_note;
+        $note->addNote($res_id, $coll_id, $content_note);
+    }
+
     return array('result' => implode('#', $arr_id), 'history_msg' => $message);
 }
 
 function manage_unlock($arr_id, $history, $id_action, $label_action, $status, $coll_id, $table)
 {
     $db = new Database();
-    for($i=0; $i<count($arr_id );$i++)
-    {
-        $req = $db->query("update ".$table. " set video_user = '', video_time = 0 where res_id = ?",array($arr_id[$i]));
+    for ($i = 0; $i < count($arr_id); $i++) {
+        $req = $db->query("update " . $table . " set video_user = '', video_time = 0 where res_id = ?", array($arr_id[$i]));
 
-        if(!$req)
-        {
+        if (!$req) {
             $_SESSION['action_error'] = _SQL_ERROR;
             return false;
         }
     }
     return true;
- }
+}
 
- /**
+/**
  * Get the value of a given field in the values returned by the form
  *
  * @param $values Array Values of the form to check
  * @param $field String the field
  * @return String the value, false if the field is not found
- **/
+ * */
 function get_value_fields($values, $field)
 {
-    for($i=0; $i<count($values);$i++)
-    {
-        if($values[$i]['ID'] == $field)
-        {
-            return  $values[$i]['VALUE'];
+    for ($i = 0; $i < count($values); $i++) {
+        if ($values[$i]['ID'] == $field) {
+            return $values[$i]['VALUE'];
         }
     }
     return false;
diff --git a/modules/avis/updateAvisWF.php b/modules/avis/updateAvisWF.php
new file mode 100644
index 00000000000..5eb31170948
--- /dev/null
+++ b/modules/avis/updateAvisWF.php
@@ -0,0 +1,55 @@
+<?php
+
+/*
+ * Copyright Maarch since 2008 under licence GPLv3.
+ * See LICENCE.txt file at the root folder for more details.
+ * This file is part of Maarch software.
+ * 
+ */
+
+/*
+ * @brief updateAvisWF
+ * @author dev@maarch.org
+ * @ingroup avis
+ * 
+ */
+require_once "modules" . DIRECTORY_SEPARATOR . "avis" . DIRECTORY_SEPARATOR
+        . "class" . DIRECTORY_SEPARATOR
+        . "avis_controler.php";
+
+
+$res_id = $_REQUEST['resId'];
+$coll_id = 'letterbox_coll';
+
+$userList = json_decode($_REQUEST['userList']);
+
+$avis = new avis_controler();
+$_SESSION['avis_wf']['diff_list']['avis']['users'] = array();
+
+$i = 0;
+if ($userList) {
+    foreach ($userList as $user) {
+
+        array_push(
+                $_SESSION['avis_wf']['diff_list']['avis']['users'], array(
+            'user_id' => $user->userId,
+            'process_comment' => $user->userConsigne,
+            'process_date' => $user->userAvisDate,
+            'viewed' => 0,
+            'visible' => 'Y',
+            'difflist_type' => 'AVIS_CIRCUIT'
+                )
+        );
+    }
+}
+
+$avis->saveWorkflow($res_id, $coll_id, $_SESSION['avis_wf']['diff_list'], 'AVIS_CIRCUIT');
+
+//LOAD TOOLBAR BADGE
+$toolbarBagde_script = $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=avis&page=load_toolbar_avis&origin=parent&resId=' . $res_id . '&collId=' . $coll_id;
+$js = 'loadToolbarBadge(\'avis_tab\',\'' . $toolbarBagde_script . '\');';
+
+
+echo "{\"status\" : 0, \"exec_js\" : \"" . $js . "\"}";
+exit();
+?>
\ No newline at end of file
-- 
GitLab