From 6ba78394dfdd29e073e3e04db5ca7422bb33eed1 Mon Sep 17 00:00:00 2001
From: Alex Orluc <alex.orluc@maarch.org>
Date: Tue, 20 Mar 2018 19:47:08 +0100
Subject: [PATCH] FEAT #6844 merge from 17_06_project_develop

---
 .../indexing_searching/file_iframe.php        |  297 +-
 modules/attachments/ajaxDelAttachment.php     |   44 +
 modules/attachments/attachments_content.php   | 3151 +++++++----------
 modules/attachments/choose_attachment.php     |  274 +-
 .../class/attachments_controler_Abstract.php  |  185 +-
 modules/attachments/css/module.css            |    2 +-
 modules/attachments/del_attachment.php        |  145 +-
 modules/attachments/get_chrono_attachment.php |  137 +-
 modules/attachments/js/functions.js           |  637 ++--
 modules/attachments/lang/en.php               |    5 +
 modules/attachments/lang/fr.php               |    5 +
 .../attachments/saveTransmissionContact.php   |   61 +-
 .../attachments/xml/IVS/validation_rules.xml  |    4 +-
 .../content_management/applet_controller.php  |   17 +-
 .../applet_modal_launcher.php                 |   55 +-
 .../content_management/checkEditingDoc.php    |    5 +-
 .../class_content_manager_tools_Abstract.php  |    3 +-
 modules/content_management/js/functions.js    |  109 +-
 .../retrieve_new_attachment_from_cm.php       |   10 +-
 .../save_attachment_from_cm.php               |  126 +-
 modules/templates/js/functions.js             |   41 +-
 modules/templates/templates_management.php    |   18 +-
 22 files changed, 2631 insertions(+), 2700 deletions(-)
 create mode 100644 modules/attachments/ajaxDelAttachment.php

diff --git a/apps/maarch_entreprise/indexing_searching/file_iframe.php b/apps/maarch_entreprise/indexing_searching/file_iframe.php
index 36f3d8567ed..3f21512df33 100755
--- a/apps/maarch_entreprise/indexing_searching/file_iframe.php
+++ b/apps/maarch_entreprise/indexing_searching/file_iframe.php
@@ -38,139 +38,224 @@ require_once 'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id']
     .'class_indexing_searching_app.php';
 $is = new indexing_searching_app();
 
-$extension = explode('.', $_SESSION['upfile']['name']);
-$count_level = count($extension) - 1;
-$the_ext = $extension[$count_level];
-$_SESSION['upfile']['format'] = $the_ext;
-
-$extList = $is->filetypes_showed_indexation();
-
-if (isset($_SESSION['upfile']['format'])) {
-    $showFile = $is->show_index_frame($_SESSION['upfile']['format']);
-    $ext = strtolower($_SESSION['upfile']['format']);
-} else {
-    $showFile = false;
-    $ext = '';
-}
-
-if ($_SESSION['origin'] == 'scan') {
-    if (file_exists(
-        $_SESSION['config']['tmppath'].'tmp_file_'
-        .$_SESSION['upfile']['md5'].'.'.$ext
-    )
-    ) {
+//REFACTORING
+if (isset($_GET['num'])) {
+    $num = $_GET['num'];
+    if (!empty($_SESSION['upfile'][$num]['fileNamePdfOnTmp'])) {
+        $mimeType = $is->get_mime_type('pdf');
         header('Pragma: public');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Cache-Control: public');
         header('Content-Description: File Transfer');
-        header('Content-Type: '.$_SESSION['upfile']['mime']);
-        header(
+        header('Content-Type: '.$mimeType);
+        header('Content-Disposition: inline; filename='.basename('maarch').'.pdf');
+        header('Content-Transfer-Encoding: binary');
+        if (file_exists($_SESSION['config']['tmppath'].$_SESSION['upfile'][$num]['fileNamePdfOnTmp'])) {
+            $loc = $_SESSION['config']['tmppath'].$_SESSION['upfile'][$num]['fileNamePdfOnTmp'];
+            readfile($loc);
+        }
+        exit();
+    } elseif (isset($_SESSION['upfile'][$num]['mime'])
+        && !empty($_SESSION['upfile'][$num]['mime'])
+        && isset($_SESSION['upfile'][$num]['format'])
+        && !empty($_SESSION['upfile'][$num]['format'])
+        && $_SESSION['upfile'][$num]['error'] != 1
+    ) {
+        $extension = explode('.', $_SESSION['upfile'][$num]['name']);
+        $count_level = count($extension) - 1;
+        $the_ext = $extension[$count_level];
+        $_SESSION['upfile'][$num]['format'] = $the_ext;
+
+        $extList = $is->filetypes_showed_indexation();
+
+        if (isset($_SESSION['upfile'][$num]['format'])) {
+            $showFile = $is->show_index_frame($_SESSION['upfile'][$num]['format']);
+            $ext = strtolower($_SESSION['upfile'][$num]['format']);
+        } else {
+            $showFile = false;
+            $ext = '';
+        }
+        if ($showFile) {
+            $mimeType = $is->get_mime_type($_SESSION['upfile'][$num]['format']);
+            //print_r($_SESSION['upfile']);exit;
+            header('Pragma: public');
+            header('Expires: 0');
+            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+            header('Cache-Control: public');
+            header('Content-Description: File Transfer');
+            header('Content-Type: '.$mimeType);
+            header(
             'Content-Disposition: inline; filename='.basename('maarch').'.'
             .$ext.';'
-        );
-        header('Content-Transfer-Encoding: binary');
-        $loc = $_SESSION['config']['tmppath'].'tmp_file_'
-             .$_SESSION['upfile']['md5'].'.'.$ext;
-        readfile($loc);
-    } else {
-        echo '<br/>PROBLEM DURING FILE SEND';
+            );
+            header('Content-Transfer-Encoding: binary');
+            $ext = strtolower($_SESSION['upfile'][$num]['format']);
+            if (file_exists($_SESSION['upfile'][$num]['local_path'])) {
+                $loc = $_SESSION['upfile'][$num]['local_path'];
+                readfile($loc);
+            }
+            exit();
+        } else {
+            $core->load_html();
+            $core->load_header();
+            //time = $core->get_session_time_expire();?>
+            <body style="background: url(static.php?filename=logo_maarch_only.svg) center center no-repeat;background-size: 90%;">
+            <?php
+            $ext = strtolower($_SESSION['upfile'][$num]['format']);
+            if (file_exists($_SESSION['upfile'][$num]['local_path'])) {
+                echo '<br/><br/><div class="error">'
+                ._FILE_LOADED_BUT_NOT_VISIBLE._ONLY_FILETYPES_AUTHORISED
+                .' <br/><ul>';
+                for ($i = 0; $i < count($extList); ++$i) {
+                    echo '<li>'.$extList[$i].'</li>';
+                }
+                echo '</ul></div>';
+            } else {
+                echo '<br/><br/><div class="error">'
+                ._PROBLEM_LOADING_FILE_TMP_DIR.'.</div>';
+            } ?>
+            &nbsp;
+            </body>
+            </html>
+            <?php
+        }
     }
-    exit();
-} elseif (!empty($_SESSION['upfile']['fileNamePdfOnTmp'])) {
-    $mimeType = $is->get_mime_type('pdf');
-    header('Pragma: public');
-    header('Expires: 0');
-    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
-    header('Cache-Control: public');
-    header('Content-Description: File Transfer');
-    header('Content-Type: '.$mimeType);
-    header('Content-Disposition: inline; filename='.basename('maarch').'.pdf');
-    header('Content-Transfer-Encoding: binary');
-    if (file_exists($_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'])) {
-        $loc = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
-        readfile($loc);
+} else {
+    $extension = explode('.', $_SESSION['upfile']['name']);
+    $count_level = count($extension) - 1;
+    $the_ext = $extension[$count_level];
+    $_SESSION['upfile']['format'] = $the_ext;
+
+    $extList = $is->filetypes_showed_indexation();
+
+    if (isset($_SESSION['upfile']['format'])) {
+        $showFile = $is->show_index_frame($_SESSION['upfile']['format']);
+        $ext = strtolower($_SESSION['upfile']['format']);
+    } else {
+        $showFile = false;
+        $ext = '';
     }
-    exit();
-} elseif (isset($_SESSION['upfile']['mime'])
-    && !empty($_SESSION['upfile']['mime'])
-    && isset($_SESSION['upfile']['format'])
-    && !empty($_SESSION['upfile']['format'])
-    && $_SESSION['upfile']['error'] != 1
-) {
-    if ($showFile) {
-        $mimeType = $is->get_mime_type($_SESSION['upfile']['format']);
-        //print_r($_SESSION['upfile']);exit;
+
+    if ($_SESSION['origin'] == 'scan') {
+        if (file_exists(
+            $_SESSION['config']['tmppath'].'tmp_file_'
+            .$_SESSION['upfile']['md5'].'.'.$ext
+        )
+        ) {
+            header('Pragma: public');
+            header('Expires: 0');
+            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+            header('Cache-Control: public');
+            header('Content-Description: File Transfer');
+            header('Content-Type: '.$_SESSION['upfile']['mime']);
+            header(
+                'Content-Disposition: inline; filename='.basename('maarch').'.'
+                .$ext.';'
+            );
+            header('Content-Transfer-Encoding: binary');
+            $loc = $_SESSION['config']['tmppath'].'tmp_file_'
+                 .$_SESSION['upfile']['md5'].'.'.$ext;
+            readfile($loc);
+        } else {
+            echo '<br/>PROBLEM DURING FILE SEND';
+        }
+        exit();
+    } elseif (!empty($_SESSION['upfile']['fileNamePdfOnTmp'])) {
+        $mimeType = $is->get_mime_type('pdf');
         header('Pragma: public');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Cache-Control: public');
         header('Content-Description: File Transfer');
         header('Content-Type: '.$mimeType);
-        header(
-            'Content-Disposition: inline; filename='.basename('maarch').'.'
-            .$ext.';'
-        );
+        header('Content-Disposition: inline; filename='.basename('maarch').'.pdf');
         header('Content-Transfer-Encoding: binary');
-        $ext = strtolower($_SESSION['upfile']['format']);
-        if (file_exists($_SESSION['upfile']['local_path'])) {
-            $loc = $_SESSION['upfile']['local_path'];
+        if (file_exists($_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'])) {
+            $loc = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
             readfile($loc);
         }
         exit();
+    } elseif (isset($_SESSION['upfile']['mime'])
+        && !empty($_SESSION['upfile']['mime'])
+        && isset($_SESSION['upfile']['format'])
+        && !empty($_SESSION['upfile']['format'])
+        && $_SESSION['upfile']['error'] != 1
+    ) {
+        if ($showFile) {
+            $mimeType = $is->get_mime_type($_SESSION['upfile']['format']);
+            //print_r($_SESSION['upfile']);exit;
+            header('Pragma: public');
+            header('Expires: 0');
+            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+            header('Cache-Control: public');
+            header('Content-Description: File Transfer');
+            header('Content-Type: '.$mimeType);
+            header(
+                'Content-Disposition: inline; filename='.basename('maarch').'.'
+                .$ext.';'
+            );
+            header('Content-Transfer-Encoding: binary');
+            $ext = strtolower($_SESSION['upfile']['format']);
+            if (file_exists($_SESSION['upfile']['local_path'])) {
+                $loc = $_SESSION['upfile']['local_path'];
+                readfile($loc);
+            }
+            exit();
+        } else {
+            $core->load_html();
+            $core->load_header();
+            //time = $core->get_session_time_expire();?>
+            <body style="background: url(static.php?filename=logo_maarch_only.svg) center center no-repeat;background-size: 90%;">
+            <?php
+                $ext = strtolower($_SESSION['upfile']['format']);
+            if (file_exists($_SESSION['upfile']['local_path'])) {
+                echo '<br/><br/><div class="error">'
+                    ._FILE_LOADED_BUT_NOT_VISIBLE._ONLY_FILETYPES_AUTHORISED
+                    .' <br/><ul>';
+                for ($i = 0; $i < count($extList); ++$i) {
+                    echo '<li>'.$extList[$i].'</li>';
+                }
+                echo '</ul></div>';
+            } else {
+                echo '<br/><br/><div class="error">'
+                    ._PROBLEM_LOADING_FILE_TMP_DIR.'.</div>';
+            } ?>
+            &nbsp;
+            </body>
+            </html>
+            <?php
+        }
     } else {
         $core->load_html();
-        $core->load_header();
-        //time = $core->get_session_time_expire();?>
-		<body style="background: url(static.php?filename=logo_maarch_only.svg) center center no-repeat;background-size: 90%;">
-		<?php
-        $ext = strtolower($_SESSION['upfile']['format']);
-        if (file_exists($_SESSION['upfile']['local_path'])) {
-            echo '<br/><br/><div class="error">'
-                ._FILE_LOADED_BUT_NOT_VISIBLE._ONLY_FILETYPES_AUTHORISED
-                .' <br/><ul>';
+        $core->load_header(); ?>
+        <body style="background: url(static.php?filename=logo_maarch_only.svg) center center no-repeat;background-size: 90%;">
+        <?php
+        if (isset($_SESSION['upfile']['error'])
+            && $_SESSION['upfile']['error'] == 1
+        ) {
+            $filesize = $func->return_bytes(ini_get('upload_max_filesize'));
+            echo '<br/><br/><div class="error">'._MAX_SIZE_UPLOAD_REACHED
+                .' ('.round($filesize / 1024, 2).'Ko Max)</div>';
+        } else {
+            echo '<br/><br/><div class="advertissement">'.$_SESSION['error']
+                .' '._ONLY_FILETYPES_AUTHORISED.' :<br/><ul>';
+            $displayedExtList = '';
+            $extension_array = array();
             for ($i = 0; $i < count($extList); ++$i) {
-                echo '<li>'.$extList[$i].'</li>';
+                if (!array_search($extList[$i], $extension_array)) {
+                    $extension_array[] = $extList[$i];
+                    $displayedExtList .= $extList[$i].', ';
+                }
             }
+
+            echo '<li>'.substr($displayedExtList, 0, -2).'</li>';
             echo '</ul></div>';
-        } else {
-            echo '<br/><br/><div class="error">'
-                ._PROBLEM_LOADING_FILE_TMP_DIR.'.</div>';
-        } ?>
+        }
+        $_SESSION['error'] = ''; ?>
         &nbsp;
         </body>
         </html>
         <?php
     }
-} else {
-    $core->load_html();
-    $core->load_header(); ?>
-    <body style="background: url(static.php?filename=logo_maarch_only.svg) center center no-repeat;background-size: 90%;">
-	<?php
-    if (isset($_SESSION['upfile']['error'])
-        && $_SESSION['upfile']['error'] == 1
-    ) {
-        $filesize = $func->return_bytes(ini_get('upload_max_filesize'));
-        echo '<br/><br/><div class="error">'._MAX_SIZE_UPLOAD_REACHED
-            .' ('.round($filesize / 1024, 2).'Ko Max)</div>';
-    } else {
-        echo '<br/><br/><div class="advertissement">'.$_SESSION['error']
-            .' '._ONLY_FILETYPES_AUTHORISED.' :<br/><ul>';
-        $displayedExtList = '';
-        $extension_array = array();
-        for ($i = 0; $i < count($extList); ++$i) {
-            if (!array_search($extList[$i], $extension_array)) {
-                $extension_array[] = $extList[$i];
-                $displayedExtList .= $extList[$i].', ';
-            }
-        }
-
-        echo '<li>'.substr($displayedExtList, 0, -2).'</li>';
-        echo '</ul></div>';
-    }
-    $_SESSION['error'] = ''; ?>
-    &nbsp;
-    </body>
-    </html>
-    <?php
 }
diff --git a/modules/attachments/ajaxDelAttachment.php b/modules/attachments/ajaxDelAttachment.php
new file mode 100644
index 00000000000..c56c37ff80c
--- /dev/null
+++ b/modules/attachments/ajaxDelAttachment.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   ajaxDelAttachment
+* @author  dev <dev@maarch.org>
+* @ingroup attachments
+*/
+if (isset($_POST['index'])) {
+    if (!empty($_SESSION['upfile'][$_POST['index']])) {
+        //RESET UPFILE SESSION
+        $tmpUpfile = $_SESSION['upfile'];
+        unset($_SESSION['upfile']);
+
+        $_SESSION['upfile']['error'] = 0;
+        $j = 0;
+        for ($i = 0; $i < count($tmpUpfile); ++$i) {
+            if ($i != $_POST['index'] && !empty($tmpUpfile[$i])) {
+                $_SESSION['upfile'][$j] = $tmpUpfile[$i];
+                ++$j;
+            }
+        }
+    }
+    //RESET CHRONO SESSION
+    $tmpSaveChonoNumber = $_SESSION['save_chrono_number'];
+    unset($_SESSION['save_chrono_number']);
+    $j = 0;
+    for ($i = 0; $i < count($tmpSaveChonoNumber); ++$i) {
+        if ($i != $_POST['index']) {
+            $_SESSION['save_chrono_number'][$j] = $tmpSaveChonoNumber[$i];
+            ++$j;
+        }
+    }
+
+    $status = 0;
+    $error = '';
+} else {
+    $status = 0;
+    $error = 'no index';
+}
+echo '{"status" : "'.$status.'", "content" : "", "error" : "'.addslashes($error).'", "exec_js" : ""}';
+exit();
diff --git a/modules/attachments/attachments_content.php b/modules/attachments/attachments_content.php
index d5ac173732c..5fb2854900f 100755
--- a/modules/attachments/attachments_content.php
+++ b/modules/attachments/attachments_content.php
@@ -1,2105 +1,1542 @@
 <?php
-
-/*
-*   Copyright 2008-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/>.
-*/
-
 /**
-* File : attachments_content.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.
+
 *
-* Add an answer in the process
+* @brief   attachments_content
 *
-* @package Maarch 1.5
-* @license GPL
-* @author <dev@maarch.org>
+* @author  dev <dev@maarch.org>
+* @ingroup attachments
 */
-
-require_once "core/class/class_security.php";
-require_once "core/class/class_request.php";
-require_once "core/class/class_resource.php";
-require_once "apps" . DIRECTORY_SEPARATOR . $_SESSION['config']['app_id']
-    . DIRECTORY_SEPARATOR . "class" . DIRECTORY_SEPARATOR
-    . "class_indexing_searching_app.php";
-require_once "core/class/docservers_controler.php";
+require_once 'core/class/class_security.php';
+require_once 'core/class/class_request.php';
+require_once 'core/class/class_resource.php';
+require_once 'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id']
+    .DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR
+    .'class_indexing_searching_app.php';
+require_once 'core/class/docservers_controler.php';
 require_once 'modules/attachments/attachments_tables.php';
-require_once "core/class/class_history.php";
+require_once 'core/class/class_history.php';
 require_once 'modules/attachments/class/attachments_controler.php';
 
-
-$core               = new core_tools();
+$core = new core_tools();
 $core->load_lang();
-$sec                = new security();
-$func               = new functions();
-$db                 = new Database();
-$req                = new request();
+$sec = new security();
+$func = new functions();
+$db = new Database();
+$req = new request();
 $docserverControler = new docservers_controler();
-$ac                 = new attachments_controler();
+$ac = new attachments_controler();
 
-$_SESSION['error'] = "";
+$_SESSION['error'] = '';
 
 $status = 0;
-$error  = $content = $js = $parameters = '';
+$error = $content = $js = $parameters = '';
 $_SESSION['cm_applet'][$_SESSION['user']['UserId']] = '';
 
-function _parse($text) {
+function _parse($text)
+{
     $text = str_replace("\r\n", "\n", $text);
     $text = str_replace("\r", "\n", $text);
-    $text = str_replace("\n", "\\n ", $text);
-    return $text;
-}
-
-function checkTransmissionError($nb) {
-    if (empty($_REQUEST["transmissionType{$nb}"]) && empty($_REQUEST["transmissionChrono{$nb}"]) && empty($_REQUEST["transmissionTitle{$nb}"]))
-        return false;
-    if (empty($_REQUEST["transmissionType{$nb}"]) || empty($_REQUEST["transmissionChrono{$nb}"])) {
-        $_SESSION['error'] .= "Transmission {$nb} : " . _ATTACHMENT_TYPES . ' ' . _MANDATORY . ". ";
-        return false;
-    }
-    if (empty($_REQUEST["transmissionTitle{$nb}"])) {
-        $_SESSION['error'] .= "Transmission {$nb} : " . _OBJECT . ' ' . _MANDATORY . ". ";
-        return false;
-    }
-    return true;
-}
-
-function setTransmissionData($nb, $storeResult) {
-    $func = new functions();
-    $transmissionData = [];
-
-    $transmissionData[] = [
-        'column' => 'typist',
-        'value' => $_SESSION['user']['UserId'],
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'format',
-        'value' => $_SESSION['upfileTransmission'][$nb]['format'],
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'docserver_id',
-        'value' => $storeResult['docserver_id'],
-        'type' => 'string'
-    ];
-    if (!empty($_REQUEST["transmissionExpectedDate{$nb}"])) {
-        $rturn = $_REQUEST["transmissionExpectedDate{$nb}"];
-    } else {
-        $rturn = 'NO_RTURN';
-    }
-    $transmissionData[] = [
-        'column' => 'status',
-        'value' => $func->protect_string_db($rturn),
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'offset_doc',
-        'value' => ' ',
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'logical_adr',
-        'value' => ' ',
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'title',
-        'value' => str_replace("&#039;", "'", $_REQUEST["transmissionTitle{$nb}"]),
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'attachment_type',
-        'value' => $func->protect_string_db($_REQUEST["transmissionType{$nb}"]),
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'coll_id',
-        'value' => $_SESSION['collection_id_choice'],
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'res_id_master',
-        'value' => $_SESSION['doc_id'],
-        'type' => 'integer'
-    ];
-    $transmissionData[] = [
-        'column' => 'identifier',
-        'value' => $_REQUEST["transmissionChrono{$nb}"],
-        'type' => 'string'
-    ];
-    $transmissionData[] = [
-        'column' => 'type_id',
-        'value' => 0,
-        'type' => 'int'
-    ];
-    $transmissionData[] = [
-        'column' => 'relation',
-        'value' => 1,
-        'type' => 'int'
-    ];
-
-    if (!empty($_REQUEST["transmissionBackDate{$nb}"])) {
-        $transmissionData[] = [
-            'column' => 'validation_date',
-            'value' => $func->format_date_db($_REQUEST["transmissionBackDate{$nb}"]),
-            'type' => 'date'
-        ];
-    }
+    $text = str_replace("\n", '\\n ', $text);
 
-    if (!empty($_REQUEST["transmissionContactidAttach{$nb}"]) && is_numeric($_REQUEST["transmissionContactidAttach{$nb}"])) {
-        $transmissionData[] = [
-            'column' => 'dest_contact_id',
-            'value' => $_REQUEST["transmissionContactidAttach{$nb}"],
-            'type' => 'integer'
-        ];
-    } else if (!empty($_REQUEST["transmissionContactidAttach{$nb}"]) && !is_numeric($_REQUEST["transmissionContactidAttach{$nb}"])) {
-        $transmissionData[] = [
-            'column' => 'dest_user',
-            'value' => $_REQUEST["transmissionContactidAttach{$nb}"],
-            'type' => 'string'
-        ];
-    }
-
-    if (!empty($_REQUEST["transmissionAddressidAttach{$nb}"]) && is_numeric($_REQUEST["transmissionAddressidAttach{$nb}"])) {
-        $transmissionData[] = [
-            'column' => 'dest_address_id',
-            'value' => $_REQUEST["transmissionAddressidAttach{$nb}"],
-            'type' => 'integer'
-        ];
-    }
-
-    return $transmissionData;
-}
-
-function setTransmissionDataPdf($nb, $storeResult) {
-    $transmissionDataPdf = [];
-
-//    $_SESSION['new_id'] = $id;
-    $file    = $_SESSION['config']['tmppath'] . $_SESSION['upfileTransmission'][$nb]['fileNamePdfOnTmp'];
-    $newfile = $storeResult['path_template'] . str_replace('#',"/",$storeResult['destination_dir']) . substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )) . '.pdf';
-
-    copy($file, $newfile);
-
-    $transmissionDataPdf[] = [
-        'column' => 'typist',
-        'value' => $_SESSION['user']['UserId'],
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'format',
-        'value' => 'pdf',
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'docserver_id',
-        'value' => $storeResult['docserver_id'],
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'status',
-        'value' => 'TRA',
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'offset_doc',
-        'value' => ' ',
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'logical_adr',
-        'value' => ' ',
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'title',
-        'value' => str_replace("&#039;", "'", $_REQUEST["transmissionTitle{$nb}"]),
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'attachment_type',
-        'value' => 'converted_pdf',
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'coll_id',
-        'value' => $_SESSION['collection_id_choice'],
-        'type' => 'string'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'res_id_master',
-        'value' => $_SESSION['doc_id'],
-        'type' => 'integer'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'type_id',
-        'value' => 0,
-        'type' => 'int'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'relation',
-        'value' => 1,
-        'type' => 'int'
-    ];
-    $transmissionDataPdf[] = [
-        'column' => 'in_signature_book',
-        'value' => 1,
-        'type' => 'bool'
-    ];
-
-    return $transmissionDataPdf;
+    return $text;
 }
 
 if (!empty($_REQUEST['docId'])) {
     $_SESSION['doc_id'] = $_REQUEST['docId'];
 }
 
+//BEGIN SAVE ATTACHMENT VALIDATE BUTTTON
 if (isset($_POST['add']) && $_POST['add']) {
-    if (empty($_SESSION['upfile']['tmp_name'])) {
-        $_SESSION['error'] .= _FILE_MISSING . ". ";
-    } elseif ($_SESSION['upfile']['size'] == 0) {
-        $_SESSION['error'] .= _FILE_EMPTY . ". ";
-    }
-
-    if ($_SESSION['upfile']['error'] == 1) {
-        $filesize = $func->return_bytes(ini_get("upload_max_filesize"));
-        $_SESSION['error'] = _ERROR_FILE_UPLOAD_MAX . "(" . round(
-            $filesize / 1024, 2
-        ) . "Ko Max).<br />";
-    }
-
-    for ($nb = 1; checkTransmissionError($nb); $nb++) {
-        if (empty($_SESSION['upfileTransmission'][$nb]['tmp_name'])) {
-            $_SESSION['error'] .= "Transmission {$nb} : " . _FILE_MISSING . '. ';
-        } elseif ($_SESSION['upfileTransmission'][$nb]['size'] == 0) {
-            $_SESSION['error'] .= "Transmission {$nb} : " . _FILE_EMPTY . '. ';
-        }
-    }
-
-    $attachment_types = '';
-    if (! isset($_REQUEST['attachment_types']) || empty($_REQUEST['attachment_types'])) {
-        $_SESSION['error'] .= _ATTACHMENT_TYPES . ' ' . _MANDATORY . ". ";
+    //CHECK FORM ERRORS
+    if ((count($_SESSION['upfile']) - 1) != count($_REQUEST['attachNum'])) {
+        $error = _MODEL_NOT_EDITED;
+        $status = 1;
     } else {
-        $attachment_types = $func->protect_string_db($_REQUEST['attachment_types']);
-    }
+        for ($numAttach = 0; $numAttach < count($_SESSION['upfile']) - 1; ++$numAttach) {
+            //EMPTY ATTACHMENTS FILE ?
+            if (empty($_SESSION['upfile'][$numAttach]['tmp_name'])) {
+                $error = _FILE_MISSING;
+            } elseif ($_SESSION['upfile'][$numAttach]['size'] == 0) {
+                $error = _FILE_EMPTY;
+            }
+            //MAX SIZE FILE ?
+            if ($_SESSION['upfile'][$numAttach]['error'] == 1) {
+                $filesize = $func->return_bytes(ini_get('upload_max_filesize'));
+                $error = _ERROR_FILE_UPLOAD_MAX.'('.round($filesize / 1024, 2).'Ko Max)';
+            }
 
-    $title = '';
-    if (! isset($_REQUEST['title']) || empty($_REQUEST['title'])) {
-        $_SESSION['error'] .= _OBJECT . ' ' . _MANDATORY . ". ";
-    } else {
-        $title = $_REQUEST['title'];
-        $title = str_replace("&#039;", "'", $title);
-    }
-    
-    if (empty($_SESSION['error'])) {
-        require_once 'core/docservers_tools.php';
-        $arrayIsAllowed = array();
-        $arrayIsAllowed = Ds_isFileTypeAllowed(
-            $_SESSION['config']['tmppath'] . $_SESSION['upfile']['fileNameOnTmp']
-        );
-        if ($arrayIsAllowed['status'] == false) {
-            $_SESSION['error'] = _WRONG_FILE_TYPE
-                . ' ' . $arrayIsAllowed['mime_type'];
-            $_SESSION['upfile'] = array();
-        } else {
-            if (! isset($_SESSION['collection_id_choice'])
-                || empty($_SESSION['collection_id_choice'])
-            ) {
-                $_SESSION['collection_id_choice'] = $_SESSION['user']['collections'][0];
+            //EMPTY ATTACHMENT TYPE ?
+            $attachment_types = '';
+            if (!isset($_REQUEST['attachment_types'][$numAttach]) || empty($_REQUEST['attachment_types'][$numAttach])) {
+                $error = _ATTACHMENT_TYPES.' '._MANDATORY;
+            } else {
+                $attachment_types = $func->protect_string_db($_REQUEST['attachment_types'][$numAttach]);
             }
 
-            $docserver = $docserverControler->getDocserverToInsert(
-                $_SESSION['collection_id_choice']
-            );
-            if (empty($docserver)) {
-                $_SESSION['error'] = _DOCSERVER_ERROR . ' : '
-                    . _NO_AVAILABLE_DOCSERVER . ". " . _MORE_INFOS . ".";
-                $location = "";
+            //EMPTY TITLE ?
+            $title = '';
+            if (!isset($_REQUEST['title'][$numAttach]) || empty($_REQUEST['title'][$numAttach])) {
+                $error = _OBJECT.' '._MANDATORY;
             } else {
-                // some checking on docserver size limit
-                $newSize = $docserverControler->checkSize(
-                    $docserver, $_SESSION['upfile']['size']
-                );
-                if ($newSize == 0) {
-                    $_SESSION['error'] = _DOCSERVER_ERROR . ' : '
-                        . _NOT_ENOUGH_DISK_SPACE . ". " . _MORE_INFOS . ".";
-                    ?>
-                    <script type="text/javascript">
-                        var eleframe1 =  window.parent.top.document.getElementById('list_attach');
-                        eleframe1.location.href = '<?php
-                    echo $_SESSION['config']['businessappurl'];
-                    ?>index.php?display=true&module=attachments&page=frame_list_attachments&attach_type_exclude=converted_pdf,print_folder&mode=normal&load';
-                    </script>
-                    <?php
-                    exit();
-                } else {
-                    $path_parts = pathinfo($_SESSION['upfile']['fileNameOnTmp']);
-                    $fileInfos = array(
-                        "tmpDir"      => $_SESSION['config']['tmppath'],
-                        "size"        => $_SESSION['upfile']['size'],
-                        "format"      => $path_parts['extension'],
-                        "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
-                    );
+                $title = $_REQUEST['title'][$numAttach];
+                $title = str_replace('&#039;', "'", $title);
+            }
 
-                    $storeResult = array();
-                    $storeResult = $docserverControler->storeResourceOnDocserver(
-                        $_SESSION['collection_id_choice'], $fileInfos
-                    );
+            //PROCESS ATTACHMENT
+            if (empty($error)) {
+                $back_date = $_REQUEST['back_date'][$numAttach];
+                $contactidAttach = $_REQUEST['contactidAttach'][$numAttach];
+                $addressidAttach = $_REQUEST['addressidAttach'][$numAttach];
+                $chrono = $_REQUEST['chrono'][$numAttach];
+                $attachStatus = $_REQUEST['effectiveDateStatus'][$numAttach];
 
-                    if($attachment_types == 'outgoing_mail' && strpos($fileInfos['format'], 'xl') === false && strpos($fileInfos['format'], 'ppt') === false){
-                        $_SESSION['upfile']['outgoingMail'] = true;
+                require_once 'core/docservers_tools.php';
+                $arrayIsAllowed = array();
+                $arrayIsAllowed = Ds_isFileTypeAllowed(
+                    $_SESSION['config']['tmppath'].$_SESSION['upfile'][$numAttach]['fileNameOnTmp']
+                );
+                if ($arrayIsAllowed['status'] == false) {
+                    $error = _WRONG_FILE_TYPE.' '.$arrayIsAllowed['mime_type'];
+                    $_SESSION['upfile'] = array();
+                } else {
+                    if (!isset($_SESSION['collection_id_choice'])
+                        || empty($_SESSION['collection_id_choice'])
+                    ) {
+                        $_SESSION['collection_id_choice'] = $_SESSION['user']['collections'][0];
                     }
 
-                    if (isset($storeResult['error']) && $storeResult['error'] <> '') {
-                        $_SESSION['error'] = $storeResult['error'];
+                    //CHECK DOCSERVER FOR ATTACHMENT
+                    $docserver = $docserverControler->getDocserverToInsert(
+                        $_SESSION['collection_id_choice']
+                    );
+                    if (empty($docserver)) {
+                        $error = _DOCSERVER_ERROR.' : '._NO_AVAILABLE_DOCSERVER.'. '._MORE_INFOS;
+                        $location = '';
                     } else {
-                        $resAttach = new resource();
-                        $_SESSION['data'] = array();
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "typist",
-                                'value' => $_SESSION['user']['UserId'],
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "format",
-                                'value' => $fileInfos['format'],
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "docserver_id",
-                                'value' => $storeResult['docserver_id'],
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "status",
-                                'value' => 'A_TRA',
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "offset_doc",
-                                'value' => ' ',
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "logical_adr",
-                                'value' => ' ',
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "title",
-                                'value' => $title,
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "attachment_type",
-                                'value' => $attachment_types,
-                                'type' => "string",
-                            )
+                        //CHECK DOCSERVER SPACE
+                        $newSize = $docserverControler->checkSize(
+                            $docserver, $_SESSION['upfile'][$numAttach]['size']
                         );
+                        if ($newSize == 0) {
+                            $error = _DOCSERVER_ERROR.' : '._NOT_ENOUGH_DISK_SPACE.'. '._MORE_INFOS; ?>
+                            <script type="text/javascript">
+                                var eleframe1 =  window.parent.top.document.getElementById('list_attach');
+                                eleframe1.location.href = '<?php
+                            echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=attachments&page=frame_list_attachments&attach_type_exclude=converted_pdf,print_folder&mode=normal&load';
+                            </script>
+                            <?php
+                            exit();
+                        } else {
+                            //GET FILE INFOS
+                            $path_parts = pathinfo($_SESSION['upfile'][$numAttach]['fileNameOnTmp']);
+                            $fileInfos = array(
+                                'tmpDir' => $_SESSION['config']['tmppath'],
+                                'size' => $_SESSION['upfile'][$numAttach]['size'],
+                                'format' => $path_parts['extension'],
+                                'tmpFileName' => $_SESSION['upfile'][$numAttach]['fileNameOnTmp'],
+                            );
+
+                            //SAVE FILE ON DOCSERVER
+                            $storeResult = array();
+                            $storeResult = $docserverControler->storeResourceOnDocserver(
+                                $_SESSION['collection_id_choice'], $fileInfos
+                            );
+
+                            if ($attachment_types == 'outgoing_mail' && strpos($fileInfos['format'], 'xl') === false && strpos($fileInfos['format'], 'ppt') === false) {
+                                $_SESSION['upfile'][$numAttach]['outgoingMail'] = true;
+                            }
 
-                        $attachmentTypesList = \Attachment\models\AttachmentModel::getAttachmentsTypesByXML();
-                        foreach ($attachmentTypesList as $keyAttachment => $valueAttachment) {
-                            if ($keyAttachment == $attachment_types && $valueAttachment['sign']) {
+                            if (isset($storeResult['error']) && $storeResult['error'] != '') {
+                                $error = $storeResult['error'];
+                            } else {
+                                $resAttach = new resource();
+                                $_SESSION['data'] = array();
                                 array_push(
                                     $_SESSION['data'],
                                     array(
-                                        'column' => "in_signature_book",
-                                        'value' => 1,
-                                        'type' => "bool",
+                                        'column' => 'typist',
+                                        'value' => $_SESSION['user']['UserId'],
+                                        'type' => 'string',
                                     )
                                 );
-                            }
-                        }
-
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "coll_id",
-                                'value' => $_SESSION['collection_id_choice'],
-                                'type' => "string",
-                            )
-                        );
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "res_id_master",
-                                'value' => $_SESSION['doc_id'],
-                                'type' => "integer",
-                            )
-                        );
-                        if ($_SESSION['origin'] == "scan") {
-                            array_push(
-                                $_SESSION['data'],
-                                array(
-                                    'column' => "scan_user",
-                                    'value' => $_SESSION['user']['UserId'],
-                                    'type' => "string",
-                                )
-                            );
-                            array_push(
-                                $_SESSION['data'],
-                                array(
-                                    'column' => "scan_date",
-                                    'value' => $req->current_datetime(),
-                                    'type' => "function",
-                                )
-                            );
-                        }
-                        if (isset($_REQUEST['back_date']) && $_REQUEST['back_date'] <> '') {
-                            array_push(
-                                $_SESSION['data'],
-                                array(
-                                    'column' => "validation_date",
-                                    'value' => $func->format_date_db($_REQUEST['back_date']),
-                                    'type' => "date",
-                                )
-                            );
-                        }
-
-                        if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] <> '' && is_numeric($_REQUEST['contactidAttach'])) {
-                            array_push(
-                                $_SESSION['data'],
-                                array(
-                                    'column' => "dest_contact_id",
-                                    'value' => $_REQUEST['contactidAttach'],
-                                    'type' => "integer",
-                                )
-                            );
-                        } else if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] != '' && !is_numeric($_REQUEST['contactidAttach'])) {
-                            $_SESSION['data'][] = [
-                                'column' => 'dest_user',
-                                'value' => $_REQUEST['contactidAttach'],
-                                'type' => 'string',
-                            ];
-                        }
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'format',
+                                        'value' => $fileInfos['format'],
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'docserver_id',
+                                        'value' => $storeResult['docserver_id'],
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'status',
+                                        'value' => $attachStatus,
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'offset_doc',
+                                        'value' => ' ',
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'logical_adr',
+                                        'value' => ' ',
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'title',
+                                        'value' => $title,
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'attachment_type',
+                                        'value' => $attachment_types,
+                                        'type' => 'string',
+                                    )
+                                );
+                                //GET SIGN PROPERTY FOR CURRENT ATTACHMENT TYPE
+                                $attachmentTypesList = \Attachment\models\AttachmentModel::getAttachmentsTypesByXML();
+                                foreach ($attachmentTypesList as $keyAttachment => $valueAttachment) {
+                                    if ($keyAttachment == $attachment_types && $valueAttachment['sign']) {
+                                        array_push(
+                                            $_SESSION['data'],
+                                            array(
+                                                'column' => 'in_signature_book',
+                                                'value' => 1,
+                                                'type' => 'bool',
+                                            )
+                                        );
+                                    }
+                                }
 
-                        if (isset($_REQUEST['addressidAttach']) && $_REQUEST['addressidAttach'] <> '' && is_numeric($_REQUEST['addressidAttach'])) {
-                            array_push(
-                                $_SESSION['data'],
-                                array(
-                                    'column' => "dest_address_id",
-                                    'value' => $_REQUEST['addressidAttach'],
-                                    'type' => "integer",
-                                )
-                            );
-                        }
-                        if(!empty($_REQUEST['chrono'])){
-                            array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "identifier",
-                                'value' => $_REQUEST['chrono'],
-                                'type' => "string",
-                            )
-                            );
-                        }
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "type_id",
-                                'value' => 0,
-                                'type' => "int",
-                            )
-                        );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'coll_id',
+                                        'value' => $_SESSION['collection_id_choice'],
+                                        'type' => 'string',
+                                    )
+                                );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'res_id_master',
+                                        'value' => $_SESSION['doc_id'],
+                                        'type' => 'integer',
+                                    )
+                                );
+                                if ($_SESSION['origin'] == 'scan') {
+                                    array_push(
+                                        $_SESSION['data'],
+                                        array(
+                                            'column' => 'scan_user',
+                                            'value' => $_SESSION['user']['UserId'],
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data'],
+                                        array(
+                                            'column' => 'scan_date',
+                                            'value' => $req->current_datetime(),
+                                            'type' => 'function',
+                                        )
+                                    );
+                                }
+                                if (isset($back_date) && $back_date != '') {
+                                    array_push(
+                                        $_SESSION['data'],
+                                        array(
+                                            'column' => 'validation_date',
+                                            'value' => $func->format_date_db($back_date),
+                                            'type' => 'date',
+                                        )
+                                    );
+                                }
+
+                                if (isset($contactidAttach) && $contactidAttach != '' && is_numeric($contactidAttach)) {
+                                    array_push(
+                                        $_SESSION['data'],
+                                        array(
+                                            'column' => 'dest_contact_id',
+                                            'value' => $contactidAttach,
+                                            'type' => 'integer',
+                                        )
+                                    );
+                                } elseif (isset($contactidAttach) && $contactidAttach != '' && !is_numeric($contactidAttach)) {
+                                    $_SESSION['data'][] = [
+                                        'column' => 'dest_user',
+                                        'value' => $contactidAttach,
+                                        'type' => 'string',
+                                    ];
+                                }
+
+                                if (isset($addressidAttach) && $addressidAttach != '' && is_numeric($addressidAttach)) {
+                                    array_push(
+                                        $_SESSION['data'],
+                                        array(
+                                            'column' => 'dest_address_id',
+                                            'value' => $addressidAttach,
+                                            'type' => 'integer',
+                                        )
+                                    );
+                                }
+                                if (!empty($chrono)) {
+                                    array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'identifier',
+                                        'value' => $chrono,
+                                        'type' => 'string',
+                                    )
+                                    );
+                                }
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'type_id',
+                                        'value' => 0,
+                                        'type' => 'int',
+                                    )
+                                );
 
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "relation",
-                                'value' => 1,
-                                'type' => "int",
-                            )
-                        );
-						
-						$id = $resAttach->load_into_db(
-							RES_ATTACHMENTS_TABLE,
-							$storeResult['destination_dir'],
-							$storeResult['file_destination_name'] ,
-							$storeResult['path_template'],
-							$storeResult['docserver_id'],
-                            $_SESSION['data'],
-							$_SESSION['config']['databasetype']
-						);
-
-                        for ($nb = 1; checkTransmissionError($nb); $nb++) {
-                            $fileInfosTr = [
-                                'tmpDir'      => $_SESSION['config']['tmppath'],
-                                'size'        => $_SESSION['upfileTransmission'][$nb]['size'],
-                                'format'      => $_SESSION['upfileTransmission'][$nb]['format'],
-                                'tmpFileName' => $_SESSION['upfileTransmission'][$nb]['fileNameOnTmp'],
-                            ];
-
-                            $storeResultTr = $docserverControler->storeResourceOnDocserver($_SESSION['collection_id_choice'], $fileInfosTr);
-
-                            $resAttach->load_into_db(
-                                RES_ATTACHMENTS_TABLE,
-                                $storeResultTr['destination_dir'],
-                                $storeResultTr['file_destination_name'] ,
-                                $storeResultTr['path_template'],
-                                $storeResultTr['docserver_id'],
-                                setTransmissionData($nb, $storeResultTr),
-                                $_SESSION['config']['databasetype']
-                            );
+                                array_push(
+                                    $_SESSION['data'],
+                                    array(
+                                        'column' => 'relation',
+                                        'value' => 1,
+                                        'type' => 'int',
+                                    )
+                                );
 
-                            if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfileTransmission'][$nb]['fileNamePdfOnTmp'] != '') {
-                                $resAttach->load_into_db(
+                                //SAVE META DATAS IN DB
+                                $id = $resAttach->load_into_db(
                                     RES_ATTACHMENTS_TABLE,
-                                    $storeResultTr['destination_dir'],
-                                    substr($storeResultTr['file_destination_name'], 0, strrpos($storeResultTr['file_destination_name'], "." )) . '.pdf' ,
-                                    $storeResultTr['path_template'],
-                                    $storeResultTr['docserver_id'],
-                                    setTransmissionDataPdf($nb, $storeResultTr),
+                                    $storeResult['destination_dir'],
+                                    $storeResult['file_destination_name'],
+                                    $storeResult['path_template'],
+                                    $storeResult['docserver_id'],
+                                    $_SESSION['data'],
                                     $_SESSION['config']['databasetype']
                                 );
+                                //copie de la version PDF de la pièce si mode de conversion sur le client
+                                if ($_SESSION['upfile'][$numAttach]['fileNamePdfOnTmp'] != '' && empty($templateOffice)) {
+                                    //case onlyConvert
+                                    $query = "select template_id from templates where template_type = 'OFFICE' and template_target = 'attachments'";
+                                    $stmt = $db->query($query);
+                                    $templateOffice = $stmt->fetchObject()->template_id;
+                                }
+                                if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfile'][$numAttach]['fileNamePdfOnTmp'] != '' && isset($templateOffice)) {
+                                    $_SESSION['new_id'] = $id;
+                                    $file = $_SESSION['config']['tmppath'].$_SESSION['upfile'][$numAttach]['fileNamePdfOnTmp'];
+                                    $newfile = $storeResult['path_template'].str_replace('#', '/', $storeResult['destination_dir']).substr($storeResult['file_destination_name'], 0, strrpos($storeResult['file_destination_name'], '.')).'.pdf';
+
+                                    copy($file, $newfile);
+
+                                    //CREATE METAS DATA FOR CONVERTED PDF
+                                    $_SESSION['data_pdf'] = array();
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'typist',
+                                            'value' => $_SESSION['user']['UserId'],
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'format',
+                                            'value' => 'pdf',
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'docserver_id',
+                                            'value' => $storeResult['docserver_id'],
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'status',
+                                            'value' => 'TRA',
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'offset_doc',
+                                            'value' => ' ',
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'logical_adr',
+                                            'value' => ' ',
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'title',
+                                            'value' => $title,
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'attachment_type',
+                                            'value' => 'converted_pdf',
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'coll_id',
+                                            'value' => $_SESSION['collection_id_choice'],
+                                            'type' => 'string',
+                                        )
+                                    );
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'res_id_master',
+                                            'value' => $_SESSION['doc_id'],
+                                            'type' => 'integer',
+                                        )
+                                    );
+
+                                    if (isset($_SESSION['upfile'][$numAttach]['outgoingMail']) && $_SESSION['upfile'][$numAttach]['outgoingMail']) {
+                                        array_push(
+                                            $_SESSION['data_pdf'],
+                                            array(
+                                                'column' => 'type_id',
+                                                'value' => 1,
+                                                'type' => 'int',
+                                            )
+                                        );
+                                    } else {
+                                        array_push(
+                                            $_SESSION['data_pdf'],
+                                            array(
+                                                'column' => 'type_id',
+                                                'value' => 0,
+                                                'type' => 'int',
+                                            )
+                                        );
+                                    }
+
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'relation',
+                                            'value' => 1,
+                                            'type' => 'int',
+                                        )
+                                    );
+
+                                    array_push(
+                                        $_SESSION['data_pdf'],
+                                        array(
+                                            'column' => 'in_signature_book',
+                                            'value' => 1,
+                                            'type' => 'bool',
+                                        )
+                                    );
+
+                                    $id_up = $resAttach->load_into_db(
+                                        RES_ATTACHMENTS_TABLE,
+                                        $storeResult['destination_dir'],
+                                        substr($storeResult['file_destination_name'], 0, strrpos($storeResult['file_destination_name'], '.')).'.pdf',
+                                        $storeResult['path_template'],
+                                        $storeResult['docserver_id'], $_SESSION['data_pdf'],
+                                        $_SESSION['config']['databasetype']
+                                    );
+
+                                    unset($_SESSION['upfile'][$attachNum]['fileNamePdfOnTmp']);
+                                }
+
+                                if ($id == false) {
+                                    $error = $resAttach->get_error();
+                                } else {
+                                    // Delete temporary backup
+                                    $db->query("DELETE FROM res_attachments WHERE res_id = ? and status = 'TMP' and typist = ?",
+                                                    array($_SESSION['attachmentInfo'][$attachNum]['inProgressResId'], $_SESSION['user']['UserId']));
+
+                                    if ($_SESSION['history']['attachadd'] == 'true') {
+                                        $hist = new history();
+                                        $view = $sec->retrieve_view_from_coll_id(
+                                            $_SESSION['collection_id_choice']
+                                        );
+                                        $hist->add(
+                                            $view, $_SESSION['doc_id'], 'ADD', 'attachadd',
+                                            ucfirst(_DOC_NUM).$id.' '
+                                            ._NEW_ATTACH_ADDED.' '._TO_MASTER_DOCUMENT
+                                            .$_SESSION['doc_id'],
+                                            $_SESSION['config']['databasetype'],
+                                            'apps'
+                                        );
+                                        $content = _NEW_ATTACH_ADDED;
+                                        $hist->add(
+                                            RES_ATTACHMENTS_TABLE, $id, 'ADD', 'attachadd',
+                                            $content.' ('.$title
+                                            .') ',
+                                            $_SESSION['config']['databasetype'],
+                                            'attachments'
+                                        );
+                                    }
+                                }
                             }
                         }
-                        unset($_SESSION['transmissionContacts']);
-                        
-                        //copie de la version PDF de la pièce si mode de conversion sur le client
-                        if (
-                            $_SESSION['upfile']['fileNamePdfOnTmp'] != '' &&
-                            empty($_REQUEST['templateOffice'])
-                        ) {
-                            //case onlyConvert
-                            $query = "select template_id from templates where template_type = 'OFFICE' and template_target = 'attachments'";
-                            $stmt = $db->query($query);
-                            $_REQUEST['templateOffice'] = $stmt->fetchObject()->template_id;
-                        }
-                        if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfile']['fileNamePdfOnTmp'] != '' && isset($_REQUEST['templateOffice'])){
-							$_SESSION['new_id'] = $id;
-                            $file    = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
-                            $newfile = $storeResult['path_template'].str_replace('#',"/",$storeResult['destination_dir']).substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf";
-                            
-                            copy($file, $newfile);
-							
-							$_SESSION['data_pdf'] = array();
-							
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "typist",
-									'value' => $_SESSION['user']['UserId'],
-									'type' => "string",
-								)
-							);
-							
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "format",
-									'value' => 'pdf',
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "docserver_id",
-									'value' => $storeResult['docserver_id'],
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "status",
-									'value' => 'TRA',
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "offset_doc",
-									'value' => ' ',
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "logical_adr",
-									'value' => ' ',
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "title",
-									'value' => $title,
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "attachment_type",
-									'value' => 'converted_pdf',
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "coll_id",
-									'value' => $_SESSION['collection_id_choice'],
-									'type' => "string",
-								)
-							);
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "res_id_master",
-									'value' => $_SESSION['doc_id'],
-									'type' => "integer",
-								)
-							);
-						
-							if (isset($_SESSION['upfile']['outgoingMail']) && $_SESSION['upfile']['outgoingMail']){
-								array_push(
-									$_SESSION['data_pdf'],
-									array(
-										'column' => "type_id",
-										'value' => 1,
-										'type' => "int",
-									)
-								);
-							}
-							else {
-								array_push(
-									$_SESSION['data_pdf'],
-									array(
-										'column' => "type_id",
-										'value' => 0,
-										'type' => "int",
-									)
-								);
-
-							}
-
-							array_push(
-								$_SESSION['data_pdf'],
-								array(
-									'column' => "relation",
-									'value' => 1,
-									'type' => "int",
-								)
-							);
-
-                            array_push(
-                                $_SESSION['data_pdf'],
-                                array(
-                                    'column' => "in_signature_book",
-                                    'value' => 1,
-                                    'type' => "bool",
-                                )
-                            );
-
-							$id_up = $resAttach->load_into_db(
-								RES_ATTACHMENTS_TABLE,
-								$storeResult['destination_dir'],
-								substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf" ,
-								$storeResult['path_template'],
-								$storeResult['docserver_id'], $_SESSION['data_pdf'],
-								$_SESSION['config']['databasetype']
-							);
-							
-                            unset($_SESSION['upfile']['fileNamePdfOnTmp']);
+                    }
+                    //IF SUCCESS EXTRA JS FOR UPDATE TABS
+                    if (empty($error) || $content == _NEW_ATTACH_ADDED) {
+                        $new_nb_attach = 0;
+                        $stmt = $db->query('select res_id from '
+                            .$_SESSION['tablename']['attach_res_attachments']
+                            ." where status <> 'DEL' and attachment_type <> 'converted_pdf' and attachment_type <> 'print_folder' and res_id_master = ?", array($_SESSION['doc_id']));
+                        if ($stmt->rowCount() > 0) {
+                            $new_nb_attach = $stmt->rowCount();
                         }
-                        
-                        if ($id == false) {
-                            $_SESSION['error'] = $resAttach->get_error();
-                        } else {
-                            // Delete temporary backup
-                            $db->query("DELETE FROM res_attachments WHERE res_id = ? and status = 'TMP' and typist = ?", 
-                                            array($_SESSION['attachmentInfo']['inProgressResId'], $_SESSION['user']['UserId']));
-                            unset($_SESSION['attachmentInfo']);
-                            unset($_SESSION['resIdVersionAttachment']);
-                            unset($_SESSION['targetAttachment']);
-
-                            if ($_SESSION['history']['attachadd'] == "true") {
-                                $hist = new history();
-                                $view = $sec->retrieve_view_from_coll_id(
-                                    $_SESSION['collection_id_choice']
-                                );
-                                $hist->add(
-                                    $view, $_SESSION['doc_id'], "ADD", 'attachadd',
-                                    ucfirst(_DOC_NUM) . $id . ' '
-                                    . _NEW_ATTACH_ADDED . ' ' . _TO_MASTER_DOCUMENT
-                                    . $_SESSION['doc_id'],
-                                    $_SESSION['config']['databasetype'],
-                                    'apps'
-                                );
-                                $_SESSION['info'] = _NEW_ATTACH_ADDED;
-                                $hist->add(
-                                    RES_ATTACHMENTS_TABLE, $id, "ADD",'attachadd',
-                                    $_SESSION['info'] . " (" . $title
-                                    . ") ",
-                                    $_SESSION['config']['databasetype'],
-                                    'attachments'
-                                );
+                        if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'create') {
+                            //Redirection vers bannette MyBasket s'il s'agit d'un courrier spontané et que l'utilisateur connecté est le destinataire du courrier
+                            if (isset($_SESSION['upfile'][$attachNum]['outgoingMail']) && $_SESSION['upfile'][$attachNum]['outgoingMail'] && $_SESSION['user']['UserId'] == $_SESSION['details']['diff_list']['dest']['users'][0]['user_id']) {
+                                $js .= "window.parent.top.location.href = 'index.php?page=view_baskets&module=basket&baskets=MyBasket&resid=".$_SESSION['doc_id']."&directLinkToAction';";
+                            } else {
+                                if ($attachment_types == 'response_project' || $attachment_types == 'outgoing_mail' || $attachment_types == 'signed_response' || $attachment_types == 'aihp') {
+                                    $js .= 'loadSpecificTab(\'uniqueDetailsIframe\',\''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&view_only=true&load&fromDetail=response&attach_type=response_project,outgoing_mail_signed,signed_response,outgoing_mail,aihp\');';
+                                } else {
+                                    $js .= 'loadSpecificTab(\'uniqueDetailsIframe\',\''.$_SESSION['config']['businessappurl'].'index.php?display=true&page=show_attachments_details_tab&module=attachments&resId='.$_SESSION['doc_id'].'&collId=letterbox_coll&fromDetail=attachments&attach_type_exclude=response_project,signed_response,outgoing_mail_signed,converted_pdf,outgoing_mail,print_folder,aihp\');';
+                                }
                             }
+                        } else {
+                            $js .= 'var eleframe1 =  window.parent.top.document.getElementById(\'list_attach\');';
+                            $js .= 'eleframe1.src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&attach_type_exclude=converted_pdf,print_folder&load\';';
                         }
+                    } else {
+                        $status = 1;
                     }
                 }
-            }
-            
-            if ( empty($_SESSION['error']) || $_SESSION['error'] == _NEW_ATTACH_ADDED ) {
-                $new_nb_attach = 0;
-                $stmt = $db->query("select res_id from "
-                    . $_SESSION['tablename']['attach_res_attachments']
-                    . " where status <> 'DEL' and attachment_type <> 'converted_pdf' and attachment_type <> 'print_folder' and res_id_master = ?", array($_SESSION['doc_id']));
-                if ($stmt->rowCount() > 0) {
-                    $new_nb_attach = $stmt->rowCount();
-                }
-                if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'create') {
-                    //Redirection vers bannette MyBasket s'il s'agit d'un courrier spontané et que l'utilisateur connecté est le destinataire du courrier
-                    if (isset($_SESSION['upfile']['outgoingMail']) && $_SESSION['upfile']['outgoingMail'] && $_SESSION['user']['UserId'] == $_SESSION['details']['diff_list']['dest']['users'][0]['user_id']){
-                            $js .= "window.parent.top.location.href = 'index.php?page=view_baskets&module=basket&baskets=MyBasket&resid=".$_SESSION['doc_id']."&directLinkToAction';";
-                    }
-                    else {
-                        if($attachment_types == 'response_project' || $attachment_types == 'outgoing_mail' || $attachment_types == 'signed_response' || $attachment_types == 'aihp'){
-                            $js .= 'loadSpecificTab(\'uniqueDetailsIframe\',\''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&view_only=true&load&fromDetail=response&attach_type=response_project,outgoing_mail_signed,signed_response,outgoing_mail,aihp\');';
-                        }else{
-                            $js .= 'loadSpecificTab(\'uniqueDetailsIframe\',\''.$_SESSION['config']['businessappurl'].'index.php?display=true&page=show_attachments_details_tab&module=attachments&resId='.$_SESSION['doc_id'].'&collId=letterbox_coll&fromDetail=attachments&attach_type_exclude=response_project,signed_response,outgoing_mail_signed,converted_pdf,outgoing_mail,print_folder,aihp\');';
-
-                        }
-                        
-                    }
-                } else {
-                    $js .= 'var eleframe1 =  window.parent.top.document.getElementById(\'list_attach\');';
-                    $js .= 'eleframe1.src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&attach_type_exclude=converted_pdf,print_folder&load\';';
-                }
             } else {
-                $error = $_SESSION['error'];
                 $status = 1;
             }
         }
-    } else {
-        $error = $_SESSION['error'];
-        $status = 1;
     }
-    if (!isset($_SESSION['new_id'])) $_SESSION['new_id'] = 0;
 
-    echo "{status : " . $status . ", content : '" . addslashes(_parse($content)) . "', error : '" . addslashes($error) . "', majFrameId : ".functions::xssafe($_SESSION['new_id']).", exec_js : '".addslashes($js)."', \"type\" : \"".$attachment_types."\"}";
-    unset($_SESSION['new_id']);
+    if (!isset($_SESSION['new_id'])) {
+        $_SESSION['new_id'] = 0;
+    }
+
+    echo '{"status" : "'.$status.'", "content" : "'.addslashes(_parse($content)).'", "error" : "'.addslashes($error).'", "majFrameId" : "'.functions::xssafe($_SESSION['new_id']).'", "exec_js" : "'.addslashes($js).'", "type" : "'.$attachment_types.'"}';
+    //RAZ SESSIONS FILE
+    if (empty($error)) {
+        unset($_SESSION['new_id']);
+        unset($_SESSION['attachmentInfo']);
+        unset($_SESSION['transmissionContacts']);
+        unset($_SESSION['resIdVersionAttachment']);
+        unset($_SESSION['targetAttachment']);
+    }
     exit();
-} else if (isset($_POST['edit']) && $_POST['edit']) {
+
+    //BEGIN EDIT ATTACHMENT VALIDATE BUTTTON
+} elseif (isset($_POST['edit']) && $_POST['edit']) {
+    $resAttach = new resource();
+    $status = 0;
+    $error = '';
+
+    //EMPTY TITLE ?
     $title = '';
+    if (!isset($_REQUEST['title'][0]) || empty($_REQUEST['title'][0])) {
+        $error .= _OBJECT.' '._MANDATORY.'. ';
+    } else {
+        $title = $_REQUEST['title'][0];
+        $title = str_replace('&#039;', "'", $title);
+    }
 
-    if (!isset($_REQUEST['title']) || empty($_REQUEST['title'])) {
-        $_SESSION['error'] .= _OBJECT . ' ' . _MANDATORY . ". ";
-        $status = 1;
+    //CURRENT ATTACHMENT IS A VERSION OF OLD ATTACHMENT ?
+    if ((int) $_REQUEST['relation'] > 1) {
+        $column_res = 'res_id_version';
     } else {
-        $title = $_REQUEST['title'];
-        $title = str_replace("&#039;", "'", $title);
+        $column_res = 'res_id';
     }
 
-    if ($status <> 1) {
-        if ($_REQUEST['new_version'] == "yes") {
-            $isVersion = 1;
-            if ((int)$_REQUEST['relation'] > 1) {
-                $column_res = 'res_id_version';
-            } else {
-                $column_res = 'res_id';
-            }
-            $stmt = $db->query("SELECT attachment_type, identifier, relation, attachment_id_master 
-                                FROM res_view_attachments
-                                WHERE ".$column_res." = ? and res_id_master = ?
-                                ORDER BY relation desc", array($_REQUEST['res_id'],$_SESSION['doc_id']));
-            $previous_attachment = $stmt->fetchObject();
-
-            $path_parts = pathinfo($_SESSION['upfile']['fileNameOnTmp']);
-            $fileInfos = array(
-                "tmpDir"      => $_SESSION['config']['tmppath'],
-                "size"        => $_SESSION['upfile']['size'],
-                "format"      => $path_parts['extension'],
-                "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
-            );
+    //IS NEW VERSION ?
+    if ($_REQUEST['new_version'] == 'yes') {
+        $is_new_version = true;
 
-            $storeResult = array();
-            
-            $storeResult = $docserverControler->storeResourceOnDocserver(
-                $_SESSION['collection_id_choice'], $fileInfos
-            );
+        //RETRIEVE PREVIOUS ATTACHMENT
+        $stmt = $db->query('SELECT res_id, res_id_version, attachment_type, identifier, relation, attachment_id_master 
+                            FROM res_view_attachments
+                            WHERE '.$column_res.' = ? and res_id_master = ?
+                            ORDER BY relation desc', array($_REQUEST['res_id'], $_SESSION['doc_id']));
+        $previous_attachment = $stmt->fetchObject();
 
-            if (isset($storeResult['error']) && $storeResult['error'] <> '') {
-                $_SESSION['error'] = $storeResult['error'];
+        $path_parts = pathinfo($_SESSION['upfile'][0]['fileNameOnTmp']);
+        $fileInfos = array(
+            'tmpDir' => $_SESSION['config']['tmppath'],
+            'size' => $_SESSION['upfile'][0]['size'],
+            'format' => $path_parts['extension'],
+            'tmpFileName' => $_SESSION['upfile'][0]['fileNameOnTmp'],
+        );
+        $storeResult = array();
+
+        $storeResult = $docserverControler->storeResourceOnDocserver(
+            $_SESSION['collection_id_choice'], $fileInfos
+        );
+
+        if (isset($storeResult['error']) && $storeResult['error'] != '') {
+            $error = $storeResult['error'];
+        }
+        //SET META DATAS OF NEW ATTACHMENT
+        if (empty($error)) {
+            $_SESSION['data'] = array();
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'typist',
+                    'value' => $_SESSION['user']['UserId'],
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'format',
+                    'value' => $fileInfos['format'],
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'docserver_id',
+                    'value' => $storeResult['docserver_id'],
+                    'type' => 'string',
+                )
+            );
+            if (!empty($_REQUEST['effectiveDateStatus'][0])) {
+                $_SESSION['data'][] = [
+                    'column' => 'status',
+                    'value' => $_REQUEST['effectiveDateStatus'][0],
+                    'type' => 'string',
+                ];
             } else {
-                $resAttach = new resource();
-                $_SESSION['data'] = array();
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "typist",
-                        'value' => $_SESSION['user']['UserId'],
-                        'type' => "string",
-                    )
-                );
-                array_push(
-                    $_SESSION['data'],
-                    array(
-                        'column' => "format",
-                        'value' => $fileInfos['format'],
-                        'type' => "string",
-                    )
-                );
-                array_push(
-                    $_SESSION['data'],
-                    array(
-                        'column' => "docserver_id",
-                        'value' => $storeResult['docserver_id'],
-                        'type' => "string",
+                        'column' => 'status',
+                        'value' => 'A_TRA',
+                        'type' => 'string',
                     )
                 );
-                if (!empty($_REQUEST['effectiveDateStatus'])) {
-                    $_SESSION['data'][] = [
-                        'column' => 'status',
-                        'value'  => $_REQUEST['effectiveDateStatus'],
-                        'type'   => 'string'
-                    ];
-                } else {
+            }
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'offset_doc',
+                    'value' => ' ',
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'logical_adr',
+                    'value' => ' ',
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'title',
+                    'value' => $title,
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'attachment_type',
+                    'value' => $previous_attachment->attachment_type,
+                    'type' => 'string',
+                )
+            );
+            $attachmentTypesList = \Attachment\models\AttachmentModel::getAttachmentsTypesByXML();
+            foreach ($attachmentTypesList as $keyAttachment => $valueAttachment) {
+                if ($keyAttachment == $previous_attachment->attachment_type && $valueAttachment['sign']) {
                     array_push(
                         $_SESSION['data'],
                         array(
-                            'column' => "status",
-                            'value' => 'A_TRA',
-                            'type' => "string",
+                            'column' => 'in_signature_book',
+                            'value' => 1,
+                            'type' => 'bool',
                         )
                     );
                 }
+            }
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'coll_id',
+                    'value' => $_SESSION['collection_id_choice'],
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'res_id_master',
+                    'value' => $_SESSION['doc_id'],
+                    'type' => 'integer',
+                )
+            );
+            if ((int) $previous_attachment->attachment_id_master == 0) {
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "offset_doc",
-                        'value' => ' ',
-                        'type' => "string",
-                    )
-                );
-                array_push(
-                    $_SESSION['data'],
-                    array(
-                        'column' => "logical_adr",
-                        'value' => ' ',
-                        'type' => "string",
+                        'column' => 'attachment_id_master',
+                        'value' => $_REQUEST['res_id'],
+                        'type' => 'integer',
                     )
                 );
+            } else {
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "title",
-                        'value' => $title,
-                        'type' => "string",
+                        'column' => 'attachment_id_master',
+                        'value' => (int) $previous_attachment->attachment_id_master,
+                        'type' => 'integer',
                     )
                 );
+            }
+
+            if ($_SESSION['origin'] == 'scan') {
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "attachment_type",
-                        'value' => $previous_attachment->attachment_type,
-                        'type' => "string",
+                        'column' => 'scan_user',
+                        'value' => $_SESSION['user']['UserId'],
+                        'type' => 'string',
                     )
                 );
-                $attachmentTypesList = \Attachment\models\AttachmentModel::getAttachmentsTypesByXML();
-                foreach ($attachmentTypesList as $keyAttachment => $valueAttachment) {
-                    if ($keyAttachment == $previous_attachment->attachment_type && $valueAttachment['sign']) {
-                        array_push(
-                            $_SESSION['data'],
-                            array(
-                                'column' => "in_signature_book",
-                                'value' => 1,
-                                'type' => "bool",
-                            )
-                        );
-                    }
-                }
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "coll_id",
-                        'value' => $_SESSION['collection_id_choice'],
-                        'type' => "string",
+                        'column' => 'scan_date',
+                        'value' => $req->current_datetime(),
+                        'type' => 'function',
                     )
                 );
+            }
+            if (isset($_REQUEST['back_date'][0]) && $_REQUEST['back_date'][0] != '') {
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "res_id_master",
-                        'value' => $_SESSION['doc_id'],
-                        'type' => "integer",
+                        'column' => 'validation_date',
+                        'value' => $func->format_date_db($_REQUEST['back_date'][0]),
+                        'type' => 'date',
                     )
                 );
-                if ((int)$previous_attachment->attachment_id_master == 0) {
-                    array_push(
-                        $_SESSION['data'],
-                        array(
-                            'column' => "attachment_id_master",
-                            'value' => $_REQUEST['res_id'],
-                            'type' => "integer",
-                        )
-                    );
-                } else {
-                    array_push(
-                        $_SESSION['data'],
-                        array(
-                            'column' => "attachment_id_master",
-                            'value' => (int)$previous_attachment->attachment_id_master,
-                            'type' => "integer",
-                        )
-                    );                    
-                }
+            }
 
-                if ($_SESSION['origin'] == "scan") {
-                    array_push(
-                        $_SESSION['data'],
-                        array(
-                            'column' => "scan_user",
-                            'value' => $_SESSION['user']['UserId'],
-                            'type' => "string",
-                        )
-                    );
-                    array_push(
-                        $_SESSION['data'],
-                        array(
-                            'column' => "scan_date",
-                            'value' => $req->current_datetime(),
-                            'type' => "function",
-                        )
-                    );
-                }
-                if (isset($_REQUEST['back_date']) && $_REQUEST['back_date'] <> '') {
-                    array_push(
-                        $_SESSION['data'],
-                        array(
-                            'column' => "validation_date",
-                            'value' => $func->format_date_db($_REQUEST['back_date']),
-                            'type' => "date",
-                        )
-                    );
-                }
+            if (!empty($_REQUEST['effectiveDate'][0])) {
+                $_SESSION['data'][] = [
+                    'column' => 'effective_date',
+                    'value' => $func->format_date_db($_REQUEST['effectiveDate'][0]),
+                    'type' => 'date',
+                ];
+            }
 
-                if (!empty($_REQUEST['effectiveDate'])) {
-                    $_SESSION['data'][] = [
-                        'column' => 'effective_date',
-                        'value'  => $func->format_date_db($_REQUEST['effectiveDate']),
-                        'type'   => 'date'
+            if (isset($_REQUEST['contactidAttach'][0]) && $_REQUEST['contactidAttach'][0] != '' && is_numeric($_REQUEST['contactidAttach'][0])) {
+                $_SESSION['data'][] = [
+                        'column' => 'dest_contact_id',
+                        'value' => $_REQUEST['contactidAttach'][0],
+                        'type' => 'integer',
                     ];
-                }
-
-                if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] != '' && is_numeric($_REQUEST['contactidAttach'])) {
-                        $_SESSION['data'][] = [
-                            'column' => 'dest_contact_id',
-                            'value' => $_REQUEST['contactidAttach'],
-                            'type' => 'integer'
-                        ];
-                } else if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] != '' && !is_numeric($_REQUEST['contactidAttach'])) {
-                        $_SESSION['data'][] = [
-                            'column' => 'dest_user',
-                            'value' => $_REQUEST['contactidAttach'],
-                            'type' => 'string'
-                        ];
-                }
-
-                if (isset($_REQUEST['addressidAttach']) && $_REQUEST['addressidAttach'] <> '') {
-                    array_push(
-                        $_SESSION['data'],
-                        array(
-                            'column' => "dest_address_id",
-                            'value' => $_REQUEST['addressidAttach'],
-                            'type' => "integer",
-                        )
-                    );
-                }
-                array_push(
-                    $_SESSION['data'],
-                    array(
-                        'column' => "identifier",
-                        'value' => $previous_attachment->identifier,
-                        'type' => "string",
-                    )
-                );
-                array_push(
-                    $_SESSION['data'],
-                    array(
-                        'column' => "type_id",
-                        'value' => 0,
-                        'type' => "int",
-                    )
-                );
-
-                $relation = (int)$previous_attachment->relation;
-                $relation++;
+            } elseif (isset($_REQUEST['contactidAttach'][0]) && $_REQUEST['contactidAttach'][0] != '' && !is_numeric($_REQUEST['contactidAttach'][0])) {
+                $_SESSION['data'][] = [
+                        'column' => 'dest_user',
+                        'value' => $_REQUEST['contactidAttach'][0],
+                        'type' => 'string',
+                    ];
+            }
 
+            if (isset($_REQUEST['addressidAttach'][0]) && $_REQUEST['addressidAttach'][0] != '') {
                 array_push(
                     $_SESSION['data'],
                     array(
-                        'column' => "relation",
-                        'value' => $relation,
-                        'type' => "int",
+                        'column' => 'dest_address_id',
+                        'value' => $_REQUEST['addressidAttach'][0],
+                        'type' => 'integer',
                     )
                 );
-
-                $id = $resAttach->load_into_db(
-                    'res_version_attachments',
-                    $storeResult['destination_dir'],
-                    $storeResult['file_destination_name'] ,
-                    $storeResult['path_template'],
-                    $storeResult['docserver_id'], $_SESSION['data'],
-                    $_SESSION['config']['databasetype']
-                );
-                
-                //copie de la version PDF de la pièce si mode de conversion sur le client
-                if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfile']['fileNamePdfOnTmp'] != ''){
-					$_SESSION['new_id'] = $id;
-                    $file = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
-                    $newfile = $storeResult['path_template'].str_replace('#',"/",$storeResult['destination_dir']).substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf";
-                    
-                    copy($file, $newfile);
-                    $_SESSION['data_pdf'] = array();
-							
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "typist",
-							'value' => $_SESSION['user']['UserId'],
-							'type' => "string",
-						)
-					);
-					
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "format",
-							'value' => 'pdf',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "docserver_id",
-							'value' => $storeResult['docserver_id'],
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "status",
-							'value' => 'TRA',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "offset_doc",
-							'value' => ' ',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "logical_adr",
-							'value' => ' ',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "title",
-							'value' => $title,
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "attachment_type",
-							'value' => 'converted_pdf',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "coll_id",
-							'value' => $_SESSION['collection_id_choice'],
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "res_id_master",
-							'value' => $_SESSION['doc_id'],
-							'type' => "integer",
-						)
-					);
-					$old_pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
-					if (isset($old_pdf_id) && $old_pdf_id != 0) $infos_old_pdf = $ac->getAttachmentInfos($old_pdf_id);
-					if ((isset($_SESSION['upfile']['outgoingMail']) && $_SESSION['upfile']['outgoingMail']) || ($infos_old_pdf['type_id']==1)){
-						array_push(
-							$_SESSION['data_pdf'],
-							array(
-								'column' => "type_id",
-								'value' => 1,
-								'type' => "int",
-							)
-						);
-					}
-					else {
-						array_push(
-							$_SESSION['data_pdf'],
-							array(
-								'column' => "type_id",
-								'value' => 0,
-								'type' => "int",
-							)
-						);
-
-					}
-
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "relation",
-							'value' => 1,
-							'type' => "int",
-						)
-					);
-
-                    array_push(
-                        $_SESSION['data_pdf'],
-                        array(
-                            'column' => "in_signature_book",
-                            'value' => 1,
-                            'type' => "bool",
-                        )
-                    );
-
-					$id_up = $resAttach->load_into_db(
-						RES_ATTACHMENTS_TABLE,
-						$storeResult['destination_dir'],
-						substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf" ,
-						$storeResult['path_template'],
-						$storeResult['docserver_id'], $_SESSION['data_pdf'],
-						$_SESSION['config']['databasetype']
-					);
-                    unset($_SESSION['upfile']['fileNamePdfOnTmp']);
-                }
-                
-                if ($previous_attachment->relation == 1) {
-					$pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
-					if (isset($pdf_id) && $pdf_id != 0) $stmt = $db->query("UPDATE res_attachments SET status = 'OBS' WHERE res_id = ?", array($pdf_id) );
-                    $stmt = $db->query("UPDATE res_attachments SET status = 'OBS' WHERE res_id = ?",array($_REQUEST['res_id']));
-                } else {
-					$pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
-					if (isset($pdf_id) && $pdf_id != 0) $stmt = $db->query("UPDATE res_attachments SET status = 'OBS' WHERE res_id = ?", array($pdf_id) );
-                    $stmt = $db->query("UPDATE res_version_attachments SET status = 'OBS' WHERE res_id = ?",array($_REQUEST['res_id']));
-                }
-
             }
-        } else {
-            //UPDATE VERSION
-            $isVersion = 0;
-            $set_update = "";
-            $arrayPDO = array();
-
-            $set_update = " title = :title";
-            $arrayPDO = array_merge($arrayPDO, array(":title" => $title));
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'identifier',
+                    'value' => $previous_attachment->identifier,
+                    'type' => 'string',
+                )
+            );
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'type_id',
+                    'value' => 0,
+                    'type' => 'int',
+                )
+            );
 
-            if (isset($_REQUEST['back_date']) && $_REQUEST['back_date'] <> "") {
-                $set_update .= ", validation_date = '".$req->format_date_db($_REQUEST['back_date'])."'";
-            } else {
-                $set_update .= ", validation_date = null";
-            }
+            $relation = (int) $previous_attachment->relation;
+            ++$relation;
 
-            if (!empty($_REQUEST['effectiveDate'])) {
-                $set_update .= ", effective_date = '".$req->format_date_db($_REQUEST['effectiveDate'])."'";
-            }
+            array_push(
+                $_SESSION['data'],
+                array(
+                    'column' => 'relation',
+                    'value' => $relation,
+                    'type' => 'int',
+                )
+            );
 
-            if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] != '' && is_numeric($_REQUEST['contactidAttach'])) {
-                $set_update .= ", dest_user = null, dest_contact_id = ".$_REQUEST['contactidAttach'].", dest_address_id = ".$_REQUEST['addressidAttach'];
-            } else if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] != '' && !is_numeric($_REQUEST['contactidAttach'])) {
-                $set_update .= ", dest_user = '".$_REQUEST['contactidAttach']."', dest_contact_id = null, dest_address_id = null";
-            } else {
-                $set_update .= ", dest_user = null, dest_contact_id = null, dest_address_id = null";
-            }
+            //SAVE META DATAS IN DB
+            $id = $resAttach->load_into_db(
+                'res_version_attachments',
+                $storeResult['destination_dir'],
+                $storeResult['file_destination_name'],
+                $storeResult['path_template'],
+                $storeResult['docserver_id'], $_SESSION['data'],
+                $_SESSION['config']['databasetype']
+            );
 
-            if ((int)$_REQUEST['relation'] > 1) {
-                $column_res = 'res_id_version';
+            //DEPRECATED OLD ATTACHMENT FILE
+            if ((int) $_REQUEST['relation'] == 1) {
+                $stmt = $db->query("UPDATE res_attachments SET status = 'OBS' WHERE res_id = ?", array($previous_attachment->res_id));
             } else {
-                $column_res = 'res_id';
+                $stmt = $db->query("UPDATE res_version_attachments SET status = 'OBS' WHERE res_id = ?", array($previous_attachment->res_id_version));
             }
+        }
+    } else {
+        $is_new_version = false;
+        $set_update = '';
+        $arrayPDO = array();
+
+        //CREATE SQL UPDATE
+        $set_update = ' title = :title';
+        $arrayPDO = array_merge($arrayPDO, array(':title' => $title));
+        if (isset($_REQUEST['back_date'][0]) && $_REQUEST['back_date'][0] != '') {
+            $set_update .= ", validation_date = '".$req->format_date_db($_REQUEST['back_date'][0])."'";
+        } else {
+            $set_update .= ', validation_date = null';
+        }
+        if (!empty($_REQUEST['effectiveDate'][0])) {
+            $set_update .= ", effective_date = '".$req->format_date_db($_REQUEST['effectiveDate'][0])."'";
+        }
+        if (isset($_REQUEST['contactidAttach'][0]) && $_REQUEST['contactidAttach'][0] != '' && is_numeric($_REQUEST['contactidAttach'][0])) {
+            $set_update .= ', dest_user = null, dest_contact_id = '.$_REQUEST['contactidAttach'][0].', dest_address_id = '.$_REQUEST['addressidAttach'][0];
+        } elseif (isset($_REQUEST['contactidAttach'][0]) && $_REQUEST['contactidAttach'][0] != '' && !is_numeric($_REQUEST['contactidAttach'][0])) {
+            $set_update .= ", dest_user = '".$_REQUEST['contactidAttach'][0]."', dest_contact_id = null, dest_address_id = null";
+        } else {
+            $set_update .= ', dest_user = null, dest_contact_id = null, dest_address_id = null';
+        }
+        if ((int) $_REQUEST['relation'] > 1) {
+            $column_res = 'res_id_version';
+        } else {
+            $column_res = 'res_id';
+        }
 
-            $stmt = $db->query("SELECT fingerprint FROM res_view_attachments WHERE ".$column_res." = ? and res_id_master = ? and status <> 'OBS'"
-                                , array($_REQUEST['res_id'], $_SESSION['doc_id']));
-            $res = $stmt->fetchObject();
-
+        //IF FILE IS EDITED
+        if ($_SESSION['upfile'][0]['upAttachment'] != false) {
+            //RETRIEVE CURRENT ATTACHMENT FILE
             require_once 'core/class/docserver_types_controler.php';
             require_once 'core/docservers_tools.php';
             $docserverTypeControler = new docserver_types_controler();
             $docserverInfo = $docserverControler->getDocserverToInsert($collId);
             $docserver = $docserverControler->get($docserverInfo->docserver_id);
             $docserverTypeObject = $docserverTypeControler->get($docserver->docserver_type_id);
-            $NewHash = Ds_doFingerprint($_SESSION['upfile']['tmp_name'], $docserverTypeObject->fingerprint_mode);
+
+            //HASH OLD AND NEW ATTACHMENT FILE
+            $stmt = $db->query('SELECT fingerprint FROM res_view_attachments WHERE '.$column_res." = ? and res_id_master = ? and status <> 'OBS'", array($_REQUEST['res_id'], $_SESSION['doc_id']));
+            $res = $stmt->fetchObject();
+            $NewHash = Ds_doFingerprint($_SESSION['upfile'][0]['tmp_name'], $docserverTypeObject->fingerprint_mode);
             $OriginalHash = $res->fingerprint;
 
-            if ($_SESSION['upfile']['upAttachment'] && $OriginalHash <> $NewHash) {
-                $_SESSION['upfile']['upAttachment'] = false;
-                $path_parts = pathinfo($_SESSION['upfile']['fileNameOnTmp']);
+            //SAVE NEW ATTACHMENT FILE (IF <> HASH)
+            if ($OriginalHash != $NewHash) {
+                //$_SESSION['upfile'][0]['upAttachment'] = false;
+                $path_parts = pathinfo($_SESSION['upfile'][0]['fileNameOnTmp']);
                 $fileInfos = array(
-                    "tmpDir"      => $_SESSION['config']['tmppath'],
-                    "size"        => $_SESSION['upfile']['size'],
-                    "format"      => $path_parts['extension'],
-                    "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
+                    'tmpDir' => $_SESSION['config']['tmppath'],
+                    'size' => $_SESSION['upfile'][0]['size'],
+                    'format' => $path_parts['extension'],
+                    'tmpFileName' => $_SESSION['upfile'][0]['fileNameOnTmp'],
                 );
-
                 $storeResult = array();
                 $storeResult = $docserverControler->storeResourceOnDocserver(
                     $_SESSION['collection_id_choice'], $fileInfos
                 );
-
-                $filetmp = $storeResult['path_template'];
-                $tmp = $storeResult['destination_dir'];
-                $tmp = str_replace('#',DIRECTORY_SEPARATOR,$tmp);
-                $filetmp .= $tmp;
-                $filetmp .= $storeResult['file_destination_name'];
-                require_once 'core/class/docserver_types_controler.php';
-                require_once 'core/docservers_tools.php';
-                $docserverTypeControler = new docserver_types_controler();
-                $docserver = $docserverControler->get($storeResult['docserver_id']);
-                $docserverTypeObject = $docserverTypeControler->get($docserver->docserver_type_id);
-                $fingerprint = Ds_doFingerprint($filetmp, $docserverTypeObject->fingerprint_mode);
-                $filesize = filesize($filetmp);
-                $set_update .= ", fingerprint = :fingerprint";
-                $set_update .= ", filesize = :filesize";
-                $set_update .= ", path = :path";
-                $set_update .= ", filename = :filename";
-                $set_update .= ", docserver_id = :docserver_id";
-                $arrayPDO = array_merge($arrayPDO, 
-                        array(  ":fingerprint" => $fingerprint, 
-                                ":filesize" => $filesize, 
-                                ":path" => $storeResult['destination_dir'],
-                                ":filename" => $storeResult['file_destination_name'],
-                                ":docserver_id" => $storeResult['docserver_id'])
+                if (isset($storeResult['error']) && $storeResult['error'] != '') {
+                    $error = $storeResult['error'];
+                } else {
+                    $filetmp = $storeResult['path_template'];
+                    $tmp = $storeResult['destination_dir'];
+                    $tmp = str_replace('#', DIRECTORY_SEPARATOR, $tmp);
+                    $filetmp .= $tmp;
+                    $filetmp .= $storeResult['file_destination_name'];
+                    $docserverTypeControler = new docserver_types_controler();
+                    $docserver = $docserverControler->get($storeResult['docserver_id']);
+                    $docserverTypeObject = $docserverTypeControler->get($docserver->docserver_type_id);
+                    $fingerprint = Ds_doFingerprint($filetmp, $docserverTypeObject->fingerprint_mode);
+                    $filesize = filesize($filetmp);
+
+                    //CREATE SQL UPDATE (FOR METAS DATA FILE)
+                    $set_update .= ', fingerprint = :fingerprint';
+                    $set_update .= ', filesize = :filesize';
+                    $set_update .= ', path = :path';
+                    $set_update .= ', filename = :filename';
+                    $set_update .= ', docserver_id = :docserver_id';
+                    $arrayPDO = array_merge($arrayPDO,
+                        array(':fingerprint' => $fingerprint,
+                                ':filesize' => $filesize,
+                                ':path' => $storeResult['destination_dir'],
+                                ':filename' => $storeResult['file_destination_name'],
+                                ':docserver_id' => $storeResult['docserver_id'], )
                         );
-                // $set_update .= ", docserver_id = ".$storeResult['docserver_id'];
-                
-                //copie de la version PDF de la pièce si mode de conversion sur le client
-                if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfile']['fileNamePdfOnTmp'] != ''){
-					 $_SESSION['new_id'] = $id;
-                    $file = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
-                    $newfile = $storeResult['path_template'].str_replace('#',"/",$storeResult['destination_dir']).substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf";
-                    
-                    copy($file, $newfile);
-                   
-					$_SESSION['data_pdf'] = array();
-							
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "typist",
-							'value' => $_SESSION['user']['UserId'],
-							'type' => "string",
-						)
-					);
-					
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "format",
-							'value' => 'pdf',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "docserver_id",
-							'value' => $storeResult['docserver_id'],
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "status",
-							'value' => 'TRA',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "offset_doc",
-							'value' => ' ',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "logical_adr",
-							'value' => ' ',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "title",
-							'value' => $title,
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "attachment_type",
-							'value' => 'converted_pdf',
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "coll_id",
-							'value' => $_SESSION['collection_id_choice'],
-							'type' => "string",
-						)
-					);
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "res_id_master",
-							'value' => $_SESSION['doc_id'],
-							'type' => "integer",
-						)
-					);
-					
-					$old_pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
-					if (isset($old_pdf_id) && $old_pdf_id != 0) $infos_old_pdf = $ac->getAttachmentInfos($old_pdf_id);
-					if ((isset($_SESSION['upfile']['outgoingMail']) && $_SESSION['upfile']['outgoingMail']) || ($infos_old_pdf['type_id']==1)){
-						array_push(
-							$_SESSION['data_pdf'],
-							array(
-								'column' => "type_id",
-								'value' => 1,
-								'type' => "int",
-							)
-						);
-					}
-					else {
-						array_push(
-							$_SESSION['data_pdf'],
-							array(
-								'column' => "type_id",
-								'value' => 0,
-								'type' => "int",
-							)
-						);
-
-					}
-
-					array_push(
-						$_SESSION['data_pdf'],
-						array(
-							'column' => "relation",
-							'value' => 1,
-							'type' => "int",
-						)
-					);
-
-                    array_push(
-                        $_SESSION['data_pdf'],
-                        array(
-                            'column' => "in_signature_book",
-                            'value' => 1,
-                            'type' => "bool",
-                        )
-                    );
-
-					$resAttach = new resource();
-					$id_up = $resAttach->load_into_db(
-						RES_ATTACHMENTS_TABLE,
-						$storeResult['destination_dir'],
-						substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf" ,
-						$storeResult['path_template'],
-						$storeResult['docserver_id'], $_SESSION['data_pdf'],
-						$_SESSION['config']['databasetype']
-					);
                 }
             }
+        }
 
-            $set_update .= ", doc_date = ".$req->current_datetime().", updated_by = :updated_by";
-            if (!empty($_REQUEST['effectiveDateStatus'])) {
-                $set_update .= ", status = :effectiveStatus";
-                $arrayPDO = array_merge($arrayPDO, array(":effectiveStatus" => $_REQUEST['effectiveDateStatus']));
-            } else {
-                $set_update .= ", status = 'A_TRA'";
-            }
-            $arrayPDO = array_merge($arrayPDO, array(":updated_by" => $_SESSION['user']['UserId']));
+        $set_update .= ', doc_date = '.$req->current_datetime().', updated_by = :updated_by';
+        $arrayPDO = array_merge($arrayPDO, array(':updated_by' => $_SESSION['user']['UserId']));
+        if (!empty($_REQUEST['effectiveDateStatus'])) {
+            $set_update .= ', status = :effectiveStatus';
+            $arrayPDO = array_merge($arrayPDO, array(':effectiveStatus' => $_REQUEST['effectiveDateStatus'][0]));
+        } else {
+            $set_update .= ", status = 'A_TRA'";
+        }
+        $arrayPDO = array_merge($arrayPDO, array(':res_id' => $_REQUEST['res_id']));
 
-            if (isset($storeResult['error']) && $storeResult['error'] <> '') {
-                $_SESSION['error'] = $storeResult['error'];
-            } else {
-                $arrayPDO = array_merge($arrayPDO, array(":res_id" => $_REQUEST['res_id']));
-                if ((int)$_REQUEST['relation'] == 1) {
-					$pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
-					if (isset($pdf_id) && $pdf_id != 0 && (!empty($_SESSION['upfile']['fileNamePdfOnTmp']))){
-                        $stmt = $db->query("UPDATE res_attachments SET status = 'DEL' WHERE res_id = ?", array($pdf_id) );
-                    }
-                    $stmt = $db->query("UPDATE res_attachments SET " . $set_update . " WHERE res_id = :res_id", $arrayPDO);
-                } else {
-					$pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
-					if (isset($pdf_id) && $pdf_id != 0 && (!empty($_SESSION['upfile']['fileNamePdfOnTmp']))){
-                        $stmt = $db->query("UPDATE res_attachments SET status = 'OBS' WHERE res_id = ?", array($pdf_id) );
-                    }
-                    $stmt = $db->query("UPDATE res_version_attachments SET " . $set_update . " WHERE res_id = :res_id", $arrayPDO);
-                }
+        //UPDATE QUERY
+        if ((int) $_REQUEST['relation'] == 1) {
+            $stmt = $db->query('UPDATE res_attachments SET '.$set_update.' WHERE res_id = :res_id', $arrayPDO);
+        } else {
+            $stmt = $db->query('UPDATE res_version_attachments SET '.$set_update.' WHERE res_id = :res_id', $arrayPDO);
+        }
+    }
+    //copie de la version PDF de la pièce si mode de conversion sur le client
+    if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfile'][0]['fileNamePdfOnTmp'] != '' && empty($error) && $_SESSION['upfile'][0]['upAttachment'] != false) {
+        $_SESSION['new_id'] = $id;
+        $file = $_SESSION['config']['tmppath'].$_SESSION['upfile'][0]['fileNamePdfOnTmp'];
+        $newfile = $storeResult['path_template'].str_replace('#', '/', $storeResult['destination_dir']).substr($storeResult['file_destination_name'], 0, strrpos($storeResult['file_destination_name'], '.')).'.pdf';
+
+        copy($file, $newfile);
+
+        //SET META DATAS OF CONVERTED PDF
+        $_SESSION['data_pdf'] = array();
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'typist',
+                'value' => $_SESSION['user']['UserId'],
+                'type' => 'string',
+            )
+        );
+
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'format',
+                'value' => 'pdf',
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'docserver_id',
+                'value' => $storeResult['docserver_id'],
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'status',
+                'value' => 'TRA',
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'offset_doc',
+                'value' => ' ',
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'logical_adr',
+                'value' => ' ',
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'title',
+                'value' => $title,
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'attachment_type',
+                'value' => 'converted_pdf',
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'coll_id',
+                'value' => $_SESSION['collection_id_choice'],
+                'type' => 'string',
+            )
+        );
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'res_id_master',
+                'value' => $_SESSION['doc_id'],
+                'type' => 'integer',
+            )
+        );
+
+        //RETRIEVE OLD CONVERTED PDF
+        $old_pdf_id = $ac->getCorrespondingPdf($_REQUEST['res_id']);
+        if (isset($old_pdf_id) && $old_pdf_id != 0) {
+            $infos_old_pdf = $ac->getAttachmentInfos($old_pdf_id);
+        }
+
+        //DEPRECATED OLD CONVERTED PDF
+        if ((int) $_REQUEST['relation'] == 1) {
+            if (isset($old_pdf_id) && $old_pdf_id != 0 && (!empty($_SESSION['upfile'][0]['fileNamePdfOnTmp']))) {
+                $stmt = $db->query("UPDATE res_attachments SET status = 'DEL' WHERE res_id = ?", array($old_pdf_id));
+            }
+        } else {
+            if (isset($pdf_id) && $pdf_id != 0 && (!empty($_SESSION['upfile'][0]['fileNamePdfOnTmp']))) {
+                $stmt = $db->query("UPDATE res_attachments SET status = 'OBS' WHERE res_id = ?", array($old_pdf_id));
             }
-            unset($_SESSION['upfile']['fileNamePdfOnTmp']);
         }
 
-        // Delete temporary backup
+        if ((isset($_SESSION['upfile'][0]['outgoingMail']) && $_SESSION['upfile'][0]['outgoingMail']) || ($infos_old_pdf['type_id'] == 1)) {
+            $type_id = 1;
+        } else {
+            $type_id = 0;
+        }
+
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'type_id',
+                'value' => $type_id,
+                'type' => 'int',
+            )
+        );
+
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'relation',
+                'value' => 1,
+                'type' => 'int',
+            )
+        );
+
+        array_push(
+            $_SESSION['data_pdf'],
+            array(
+                'column' => 'in_signature_book',
+                'value' => 1,
+                'type' => 'bool',
+            )
+        );
+
+        //SAVE META DATAS IN DB
+        $id_up = $resAttach->load_into_db(
+            RES_ATTACHMENTS_TABLE,
+            $storeResult['destination_dir'],
+            substr($storeResult['file_destination_name'], 0, strrpos($storeResult['file_destination_name'], '.')).'.pdf',
+            $storeResult['path_template'],
+            $storeResult['docserver_id'], $_SESSION['data_pdf'],
+            $_SESSION['config']['databasetype']
+        );
+    }
+
+    if (empty($error)) {
+        //DELETE TEMPORARY BACKUP
         $stmt = $db->query("SELECT attachment_id_master 
                             FROM res_version_attachments
-                            WHERE res_id = ? and status = 'TMP' and res_id_master = ?" 
-                            , array($_SESSION['attachmentInfo']['inProgressResId'], $_SESSION['doc_id']));
+                            WHERE res_id = ? and status = 'TMP' and res_id_master = ?", array($_SESSION['attachmentInfo']['inProgressResId'], $_SESSION['doc_id']));
         $previous_attachment = $stmt->fetchObject();
 
         $db->query("DELETE FROM res_version_attachments WHERE attachment_id_master = ? and status = 'TMP'", array($previous_attachment->attachment_id_master));
-        unset($_SESSION['attachmentInfo']);
-        unset($_SESSION['resIdVersionAttachment']);
-        unset($_SESSION['targetAttachment']);
 
-        // Add in history
-        if ($_SESSION['history']['attachup'] == "true") {
+        //ADD ACTION IN HISTORY
+        if ($_SESSION['history']['attachup'] == 'true') {
             $hist = new history();
             $view = $sec->retrieve_view_from_coll_id(
                 $_SESSION['collection_id_choice']
             );
             $hist->add(
-                $view, $_SESSION['doc_id'], "UP", 'attachup',
-                ucfirst(_DOC_NUM) . $id . ' '
-                . _ATTACH_UPDATED,
+                $view, $_SESSION['doc_id'], 'UP', 'attachup',
+                ucfirst(_DOC_NUM).$id.' '
+                ._ATTACH_UPDATED,
                 $_SESSION['config']['databasetype'],
                 'apps'
             );
-            $_SESSION['info'] = _ATTACH_UPDATED;
+            $content = _ATTACH_UPDATED;
             $hist->add(
-                RES_ATTACHMENTS_TABLE, $id, "UP",'attachup',
-                $_SESSION['info'] . " (" . $title
-                . ") ",
+                RES_ATTACHMENTS_TABLE, $id, 'UP', 'attachup',
+                $_SESSION['info'].' ('.$title
+                .') ',
                 $_SESSION['config']['databasetype'],
                 'attachments'
             );
         }
 
-        if (empty($_SESSION['error'])) {
-            if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
-                $js .= 'eleframe1 =  parent.document.getElementsByName(\'attachments_iframe\');';
-                $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=show_attachments_details_tab&load';
-                $js .= '&attach_type_exclude=response_project,signed_response,outgoing_mail_signed,converted_pdf,outgoing_mail,print_folder,aihp&fromDetail=attachments&collId=letterbox_coll&resId='.$_SESSION['doc_id'];
-            } else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response'){
-                $js .= 'eleframe1 =  parent.document.getElementsByName(\'responses_iframe\');';
-                $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=show_attachments_details_tab&load';
-                $js .= '&attach_type=response_project,outgoing_mail_signed,signed_response,outgoing_mail,aihp&fromDetail=response&collId=letterbox_coll&resId='.$_SESSION['doc_id'];
-            } else {
-                $js .= 'var eleframe1 =  parent.document.getElementsByName(\'list_attach\');';
-                $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&attach_type_exclude=converted_pdf,print_folder&load';
-            }
-            $js .='\';';
+        //EXTRAS JS FOR TABS
+        if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
+            $js .= 'eleframe1 =  parent.document.getElementsByName(\'attachments_iframe\');';
+            $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=show_attachments_details_tab&load';
+            $js .= '&attach_type_exclude=response_project,signed_response,outgoing_mail_signed,converted_pdf,outgoing_mail,print_folder,aihp&fromDetail=attachments&collId=letterbox_coll&resId='.$_SESSION['doc_id'];
+        } elseif (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response') {
+            $js .= 'eleframe1 =  parent.document.getElementsByName(\'responses_iframe\');';
+            $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=show_attachments_details_tab&load';
+            $js .= '&attach_type=response_project,outgoing_mail_signed,signed_response,outgoing_mail,aihp&fromDetail=response&collId=letterbox_coll&resId='.$_SESSION['doc_id'];
         } else {
-            $error = $_SESSION['error'];
-            $status = 1;
+            $js .= 'var eleframe1 =  parent.document.getElementsByName(\'list_attach\');';
+            $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&attach_type_exclude=converted_pdf,print_folder&load';
         }
+        $js .= '\';';
 
-    } else {
-        $error = $_SESSION['error'];
-        $status = 1;
+        //RAZ SESSIONS
+        if (!isset($_SESSION['new_id'])) {
+            $_SESSION['new_id'] = 0;
+        }
+        unset($_SESSION['upfile'][0]['fileNamePdfOnTmp']);
+        unset($_SESSION['new_id']);
+        unset($_SESSION['attachmentInfo']);
+        unset($_SESSION['resIdVersionAttachment']);
+        unset($_SESSION['targetAttachment']);
     }
 
-    if (!isset($_SESSION['new_id'])) $_SESSION['new_id'] = 0;
-    echo "{status : " . $status . ", content : '" . addslashes(_parse($content)) . "', title : '" . addslashes($title) . "', isVersion : " . $isVersion . ", error : '" . addslashes($error) . "', majFrameId : ".$_SESSION['new_id'].", exec_js : '".addslashes($js)."', cur_id : ".$_REQUEST['res_id']."}";
-    unset($_SESSION['new_id']);
+    echo '{"status" : "'.$status.'", "content" : "'.addslashes(_parse($content)).'", "title" : "'.addslashes($title).'", "isVersion" : "'.$isVersion.'", "error" : "'.addslashes($error).'", "majFrameId" : "'.$_SESSION['new_id'].'", "exec_js" : "'.addslashes($js).'", "cur_id" : "'.$_REQUEST['res_id'].'"}';
+
     exit();
 }
 
+//INITIALIZE EDIT MODE
 if (isset($_REQUEST['id'])) {
-
+    $mode = 'edit';
+    $title = _MODIFY_ANSWER;
     $_SESSION['targetAttachment'] = 'edit';
+    $resId = $_REQUEST['id'];
+    unset($_SESSION['upfile']);
 
-    if ((int)$_REQUEST['relation'] > 1) {
-        $column_res = 'res_id_version';
-    } else {
-        $column_res = 'res_id';
-    }
-    
-    $stmt = $db->query("SELECT validation_date, effective_date, attachment_type, title, dest_user, dest_contact_id, dest_address_id, dest_address_id as address_id, relation, format, identifier, status
-                        FROM res_view_attachments 
-                        WHERE ".$column_res." = ? and res_id_master = ?
-                        ORDER BY relation desc", array($_REQUEST['id'], $_SESSION['doc_id']));
-    $data_attachment = $stmt->fetchObject();
-    $attachmentFormat = $data_attachment->format;
-    $statusEditAttachment = $data_attachment->status;
-    //var_dump($data_attachment);
-    if ($data_attachment->relation == 1) {
-        $res_table = 'res_attachments';
-    } else {
-        $res_table = 'res_version_attachments';  
-    }
-
-    $viewResourceArr = $docserverControler->viewResource(
-        $_REQUEST['id'], 
-        $res_table, 
-        'adr_x', 
-        false
-    );
+    //GET DATAS attachment
+    $infoAttach = (object) $ac->getAttachmentInfos($resId);
+    if (!file_exists($infoAttach->pathfile)) {
+        $status = 1;
+        $error = _FILE_NOT_EXISTS_ON_THE_SERVER;
 
-    $_SESSION['upfile']['size']          = filesize($viewResourceArr['file_path']);
-    $_SESSION['upfile']['format']        = $viewResourceArr['ext'];
-    $fileNameOnTmp                       = str_replace($viewResourceArr['tmp_path'].DIRECTORY_SEPARATOR, '', $viewResourceArr['file_path']);
-    $_SESSION['upfile']['fileNameOnTmp'] = $fileNameOnTmp;
-    $_SESSION['upfile']['fileNamePdfOnTmp'] = $viewResourceArr['filenamePdf'];
+        echo '{"status" : "'.$status.'", "content" : "'.addslashes(_parse($content)).'", "title" : "'.addslashes($title).'", "isVersion" : "'.$isVersion.'", "error" : "'.addslashes($error).'", "majFrameId" : "'.$_SESSION['new_id'].'", "exec_js" : "'.addslashes($js).'", "cur_id" : "'.$_REQUEST['res_id'].'"}';
+        exit;
+    } else {
+        //RETRIEVE ATTACHMENT FILE
+        $_SESSION['upfile'][0]['upAttachment'] = false;
+        $_SESSION['upfile'][0]['size'] = filesize($infoAttach->pathfile);
+        $_SESSION['upfile'][0]['format'] = $infoAttach->format;
+        $_SESSION['upfile'][0]['fileNamePdfOnTmp'] = $infoAttach->pathfile_pdf;
+
+        $viewResourceArr = $docserverControler->viewResource(
+            $resId,
+            $infoAttach->target_table_origin,
+            'adr_x',
+            false
+        );
 
+        $_SESSION['upfile'][0]['fileNameOnTmp'] = str_replace($viewResourceArr->tmp_path.DIRECTORY_SEPARATOR, '', $viewResourceArr->file_path);
+    }
 } else {
-    $_SESSION['targetAttachment'] = 'add';
-
-    $stmt = $db->query("SELECT subject, exp_contact_id, dest_contact_id, exp_user_id, address_id, dest_user_id, alt_identifier FROM res_view_letterbox WHERE res_id = ?",array($_SESSION['doc_id']));
-    $data_attachment = $stmt->fetchObject();
+    //INITIALIZE ADD MODE
+    $mode = 'add';
+    $title = _ATTACH_ANSWER;
 
+    $_SESSION['targetAttachment'] = 'add';
     unset($_SESSION['upfile']);
-    unset($_SESSION['upfileTransmission']);
-
-}
+    unset($_SESSION['transmissionContacts']);
 
-$stmt = $db->query('SELECT creation_date FROM res_letterbox WHERE res_id = ?', [$_SESSION['doc_id']]);
-$dataForDate = $stmt->fetchObject();
-
-if ($data_attachment->dest_contact_id <> "") {
-    $stmt = $db->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
-                        FROM view_contacts 
-                        WHERE contact_id = ? and ca_id = ?', array($data_attachment->dest_contact_id,$data_attachment->address_id));
-} else if ($data_attachment->exp_contact_id <> "") {
-    $stmt = $db->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
-                        FROM view_contacts 
-                        WHERE contact_id = ? and ca_id = ?', array($data_attachment->exp_contact_id,$data_attachment->address_id));       
-} else if ($data_attachment->dest_user != '') {
-    $stmt = $db->query('SELECT lastname, firstname FROM users WHERE user_id = ?', [$data_attachment->dest_user]);
-} else if ($data_attachment->exp_user_id != '') {
-    $stmt = $db->query('SELECT lastname, firstname FROM users WHERE user_id = ?', [$data_attachment->exp_user_id]);
-} else if ($data_attachment->dest_user_id != '') {
-    $stmt = $db->query('SELECT lastname, firstname FROM users WHERE user_id = ?', [$data_attachment->dest_user_id]);
-}
+    //GET DATAS attachment
+    $infoAttach = (object) $ac->initAttachmentInfos($_SESSION['doc_id']);
 
-if ($data_attachment->exp_contact_id <> '' || $data_attachment->dest_contact_id <> '') {
-    $res = $stmt->fetchObject();
-    if ($res->is_corporate_person == 'Y') {
-        $data_contact = $res->society;
-        if (!empty ($res->society_short)) {
-            $data_contact .= ' ('.$res->society_short.')';
-        }
-        if (!empty($res->lastname) || !empty($res->firstname)) {
-            $data_contact .= ' - ' . $res->lastname . ' ' . $res->firstname;
-        }
-        $data_contact .= ', ';
-    } else {
-        $data_contact .= $res->contact_lastname . ' ' . $res->contact_firstname;
-        if (!empty ($res->society)) {
-            $data_contact .= ' (' .$res->society . ')';
+    //On recherche le type de document attaché à ce courrier
+    $stmt = $db->query('SELECT type_id, creation_date FROM res_letterbox WHERE res_id = ?', array($_SESSION['doc_id']));
+    $type_id = $stmt->fetchObject();
+    $type_id = $type_id->type_id;
+    $dataForDate = $type_id->creation_date;
+    //On recherche le sve_type
+    $stmt = $db->query('SELECT * FROM mlb_doctype_ext WHERE type_id = ?', array($type_id));
+    $sve = $stmt->fetchObject();
+    $sve_type = $sve->process_mode;
+    //On met tous les attachments ayant le type_sve attaché au courrier dans un tableau
+    $attachments_types_for_process = array();
+    foreach ($_SESSION['attachment_types_with_process'] as $key => $value) {
+        if ($sve_type == $value or $value == '') {
+            $attachments_types_for_process[$key] = $_SESSION['attachment_types'][$key];
         }
-        $data_contact .= ', ';
-    }
-    if ($res->is_private == 'Y') {
-        $data_contact .= '(' . _CONFIDENTIAL_ADDRESS . ')';
-    } else {
-        $data_contact .= $res->address_num . ' ' . $res->address_street . ' ' . strtoupper($res->address_town);
-    }
-} else if ($data_attachment->exp_user_id != '' || $data_attachment->dest_user != '' || $data_attachment->dest_user_id != '') {
-    $res = $stmt->fetchObject();
-    if (!empty($res->lastname) || !empty($res->firstname)) {
-        $data_contact .= $res->lastname . ' ' . $res->firstname;
-    }
-//si multicontact
-} else {
-    $stmt = $db->query("SELECT cr.address_id, c.contact_id, c.is_corporate_person, c.society, c.society_short, c.firstname, c.lastname,ca.is_private,ca.address_street, ca.address_num, ca.address_town 
-                        FROM contacts_res cr, contacts_v2 c, contact_addresses ca 
-                        WHERE cr.res_id = ? and cast(c.contact_id as char) = cast(cr.contact_id as char) and ca.contact_id=c.contact_id and ca.id=cr.address_id",array($_SESSION['doc_id']));
-    $i=0;
-    while($multi_contacts_attachment = $stmt->fetchObject()){
-        if(is_integer($multi_contacts_attachment->contact_id)){
-            $format_contact='';
-            $stmt2 = $db->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
-                            FROM view_contacts 
-                            WHERE contact_id = ? and ca_id = ?',array($multi_contacts_attachment->contact_id,$multi_contacts_attachment->address_id));
-
-            $res = $stmt2->fetchObject();
-            if ($res->is_corporate_person == 'Y') {
-                $format_contact = $res->society;
-                if (!empty ($res->society_short)) {
-                    $format_contact .= ' ('.$res->society_short.')';
-                }
-                if (!empty($res->lastname) || !empty($res->firstname)) {
-                    $format_contact .= ' - ' . $res->lastname . ' ' . $res->firstname;
-                }
-                $format_contact .= ', ';
-            } else {
-                $format_contact .= $res->contact_lastname . ' ' . $res->contact_firstname;
-                if (!empty ($res->society)) {
-                    $format_contact .= ' (' .$res->society . ')';
-                }
-                $format_contact .= ', ';
-            }
-            if ($res->is_private == 'Y') {
-                $format_contact .= '('._CONFIDENTIAL_ADDRESS.')';
-            } else {
-                $format_contact .= $res->address_num .' ' . $res->address_street .' ' . strtoupper($res->address_town);                         
-            }
-            $contacts[] = array(
-                'contact_id'     => $multi_contacts_attachment->contact_id,
-                'firstname'      => $multi_contacts_attachment->firstname,
-                'lastname'       => $multi_contacts_attachment->lastname,
-                'society'        => $multi_contacts_attachment->society,
-                'address_id'     => $multi_contacts_attachment->address_id,
-                'format_contact' => $format_contact
-            );
-
-            if($i==0){
-                $data_contact                    = $format_contact; 
-                $data_attachment->exp_contact_id = $multi_contacts_attachment->contact_id;
-            }
-            $i++;
-        } 
     }
 }
 
-unset($_SESSION['transmissionContacts']);
-$content .= '<div class="error" style="left:10px;" id="divErrorAttachment" onClick="this.style.display=\'none\'">' . $_SESSION['error'];
-
-$_SESSION['error'] = "";
-
+//BEGIN FORM ATTACHMENT
+//INITIALIZE
+unset($_SESSION['adresses']);
+unset($_SESSION['cm_applet'][$_SESSION['user']['UserId']]);
 $objectTable = $sec->retrieve_table_from_coll($_SESSION['collection_id_choice']);
-$content .= '</div>';
-$content .= '<div class="info" style="left:10px;" id="divInfoAttachment" onClick="this.style.display=\'none\'">' . $_SESSION['info'].'</div>';
-if (isset($_REQUEST['id'])) {
-    $title = _MODIFY_ANSWER;
-} else {
-    $title = _ATTACH_ANSWER;
-}
 
-$content .= '<h2>&nbsp;' . $title;
+//BEDING HEADER
+$content .= '<h2>&nbsp;'.$title;
 
 //multicontact
-if (!empty($contacts)) {
+if (!empty($infoAttach->multi_contact)) {
     $content .= ' pour le contact : <select style="background-color: #FFF;border: 1px solid #999;color: #666;text-align: left;" id="selectContactIdRes" onchange="loadSelectedContact()">';
 
-    foreach ($contacts as $key => $value) {
+    foreach ($infoAttach->multi_contact as $key => $value) {
         $content .= '<option value="'.$value['contact_id'].'#'.$value['address_id'].'#'.$value['format_contact'].'">'.$value['format_contact'].'</option>';
-        //$content .= '<input type="hidden" id="format_list_contact_'.$value['contact_id'].'_res" value="'.$value['format_contact'].'"/>';
     }
     $content .= '</select>';
-    $content .= '<script>parent.$("contactidAttach").value='.$contacts[0]['contact_id'].';parent.$("addressidAttach").value='.$contacts[0]['address_id'].';launch_autocompleter2_contacts_v2("'. $_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "contact_attach", "show_contacts_attach", "", "contactidAttach", "addressidAttach")</script>';
+    $content .= '<script>$j("#selectContactIdRes", window.top.document).change();</script>';
 }
-
 $content .= '</h2>';
-
-$content .= '<form enctype="multipart/form-data" method="post" name="formAttachment" id="formAttachment" action="#" class="forms" style="width:500px;float:left;margin-left:-5px;background-color:#deedf3">';
-$content .= '<div class="transmissionDiv">';
-$content .= '<hr style="width:85%;margin-left:0px">';
-$content .= '<input type="hidden" id="category_id" value="outgoing"/>';
-if (isset($_REQUEST['id'])) {
-    $content .= '<input type="hidden" name="res_id" id="res_id" value="'.$_REQUEST['id'].'"/>';
-    $content .= '<input type="hidden" name="relation" id="relation" value="'.$_REQUEST['relation'].'"/>';
-    $_SESSION['relationAttachment'] = $_REQUEST['relation'];
-    $_SESSION['resIdVersionAttachment'] = $_REQUEST['id'];
-}
-$content .= '<input type="hidden" name="fromDetail" id="fromDetail" value="'.$_REQUEST['fromDetail'].'"/>';
-
-if (!isset($_REQUEST['id'])) {
-    if(isset($_SESSION['attachment_types']['transmission'])){
-        $function_transmssion = 'disableTransmissionButton(this.options[this.selectedIndex].value);';
-        $function_transmssion2 = 'showOrButtonForAttachment();';
-    }else{
-        $function_transmssion = '';
-        $function_transmssion2 = '';
-    }
-    //On recherche le type de document attaché à ce courrier
-    //var_dump($_SESSION['doc_id']);
-    $stmt = $db->query("SELECT type_id FROM res_letterbox WHERE res_id = ?",array($_SESSION['doc_id']));
-    $type_id = $stmt->fetchObject();
-    //var_dump ($type_id->type_id);
-    $type_id = $type_id->type_id;
-    //On recherche le sve_type
-    $stmt = $db->query("SELECT * FROM mlb_doctype_ext WHERE type_id = ?",array($type_id));
-    $sve = $stmt->fetchObject();
-    $sve_type = $sve->process_mode;
-    //On met tous les attachments ayant le type_sve attaché au courrier dans un tableau
-    $attachments_types_for_process = array();
-    foreach($_SESSION['attachment_types_with_process'] as $key => $value){
-        // var_dump($key);
-        // var_dump($value);
-        if($sve_type == $value or $value == ''){
-            //var_dump($_SESSION['attachment_types'][$key]);
-            //$attachments_types_for_process[] = $key;
-            //$attachments_types_for_process = array($key => $attachments_types_for_process);
-            $attachments_types_for_process[$key] = $_SESSION['attachment_types'][$key];
-
-        }
-
+//END HEADER
+
+//BEGIN FORM
+$content .= '<form enctype="multipart/form-data" method="post" name="formAttachment" id="formAttachment" action="#" class="forms" style="width:35%;float:left;margin-left:-5px;background-color:#deedf3">';
+$content .= '<div class="transmissionDiv" id="addAttach1">';
+    $content .= '<hr style="width:85%;margin-left:0px">';
+    $content .= '<input type="hidden" id="category_id" value="outgoing"/>';
+
+    if ($mode == 'edit') {
+        $content .= '<input type="hidden" name="res_id" id="res_id" value="'.$_REQUEST['id'].'"/>';
+        $content .= '<input type="hidden" name="relation" id="relation" value="'.$_REQUEST['relation'].'"/>';
+        $_SESSION['relationAttachment'] = $_REQUEST['relation'];
+        $_SESSION['resIdVersionAttachment'] = $_REQUEST['id'];
     }
-    //var_dump($attachments_types_for_process);
-    //var_dump($_SESSION['attachment_types']);
+    $content .= '<input type="hidden" name="fromDetail" id="fromDetail" value="'.$_REQUEST['fromDetail'].'"/>';
 
+    //ATTACHMENT TYPE
     $content .= '<p>';
-    $content .= '<label>' . _ATTACHMENT_TYPES . '</label>';
-    $content .= '<select name="attachment_types" id="attachment_types" onchange="affiche_chrono();'.$function_transmssion.'select_template(\'' . $_SESSION['config']['businessappurl']
-        . 'index.php?display=true&module=templates&page='
-        . 'select_templates\', this.options[this.selectedIndex].value);"/>';
-    $content .= '<option value="">' . _CHOOSE_ATTACHMENT_TYPE . '</option>';
-    
-
-    foreach(array_keys($attachments_types_for_process) as $attachmentType) {
-        if(empty($_SESSION['attachment_types_get_chrono'][$attachmentType][0])){
-            $_SESSION['attachment_types_get_chrono'][$attachmentType] = '';
-        }
-        if(empty($_SESSION['attachment_types_with_delay'][$attachmentType][0])){
-            $_SESSION['attachment_types_with_delay'][$attachmentType] = '';
-        }
-        if($_SESSION['attachment_types_show'][$attachmentType] == "true"){
-            $content .= '<option value="' . $attachmentType . '" with_chrono = "'. $_SESSION['attachment_types_with_chrono'][$attachmentType].'" get_chrono = "'. $_SESSION['attachment_types_get_chrono'][$attachmentType].'"';
+    $content .= '<label>'._ATTACHMENT_TYPES.'</label>';
+    if ($mode == 'add') {
+        $content .= '<select name="attachment_types[]" id="attachment_types" onchange="affiche_chrono(this);select_template(\''.$_SESSION['config']['businessappurl']
+        .'index.php?display=true&module=templates&page='
+        .'select_templates\', this);"/>';
+        $content .= '<option value="">'._CHOOSE_ATTACHMENT_TYPE.'</option>';
+        foreach (array_keys($attachments_types_for_process) as $attachmentType) {
+            if (empty($_SESSION['attachment_types_get_chrono'][$attachmentType][0])) {
+                $_SESSION['attachment_types_get_chrono'][$attachmentType] = '';
+            }
+            if (empty($_SESSION['attachment_types_with_delay'][$attachmentType][0])) {
+                $_SESSION['attachment_types_with_delay'][$attachmentType] = '';
+            }
+            if ($_SESSION['attachment_types_show'][$attachmentType] == 'true') {
+                $content .= '<option value="'.$attachmentType.'" width_delay="'.$_SESSION['attachment_types_with_delay'][$attachmentType].'" with_chrono = "'.$_SESSION['attachment_types_with_chrono'][$attachmentType].'" get_chrono = "'.$_SESSION['attachment_types_get_chrono'][$attachmentType].'"';
 
-            if(isset($_GET['cat']) && $_GET['cat'] == 'outgoing' && $attachmentType == 'outgoing_mail'){
-                $content .= ' selected = "selected"';
-                $content .= '<script>$("attachment_types").onchange();</script>';
+                if (isset($_GET['cat']) && $_GET['cat'] == 'outgoing' && $attachmentType == 'outgoing_mail') {
+                    $content .= ' selected = "selected"';
+                    $content .= '<script>$("attachment_types").onchange();</script>';
+                }
+                $content .= '>';
+                $content .= $_SESSION['attachment_types'][$attachmentType];
+                $content .= '</option>';
             }
-            $content .= '>';
-            $content .= $_SESSION['attachment_types'][$attachmentType];
-            $content .= '</option>';
         }
+        $content .= '</select>&nbsp;<span class="red_asterisk" id="attachment_types_mandatory"><i class="fa fa-star"></i></span>';
+    } else {
+        $content .= '<input type="text" name="attachment_types_show[]" id="attachment_types_show" value="'.$_SESSION['attachment_types'][$infoAttach->attachment_type].'" disabled class="readonly"/>';
+        $content .= '<input type="hidden" name="attachment_types[]" id="attachment_types" value="'.$infoAttach->attachment_type.'" readonly class="readonly"/>';
     }
-
-    $content .= '</select>&nbsp;<span class="red_asterisk" id="attachment_types_mandatory"><i class="fa fa-star"></i></span>';
     $content .= '</p>';
+
+    //PJ CHRONO
     $content .= '<p>';
-    $content .= '<label id="chrono_label" style="display:none">'. _CHRONO_NUMBER.'</label>';
-    $content .= '<input type="text" name="chrono_display" id="chrono_display" style="display:none" disabled class="readonly"/>';
-    $content .= '<select name="get_chrono_display" id="get_chrono_display" style="display:none" onchange="$(\'chrono\').value=this.options[this.selectedIndex].value"/>';
-    $content .= '<input type="hidden" name="chrono" id="chrono" value="' . $data_attachment->alt_identifier . '"/>';
+    $content .= '<label id="chrono_label" name="chrono_label[]" style="display:none">'._CHRONO_NUMBER.'</label>';
+    $content .= '<input type="text" name="chrono_display[]" id="chrono_display" value="'.$infoAttach->identifier.'"  style="display:none" disabled class="readonly"/>';
+    if ($mode == 'add') {
+        $content .= '<select name="get_chrono_display[]" id="get_chrono_display" style="display:none" onchange="$(\'chrono\').value=this.options[this.selectedIndex].value"/>';
+    } else {
+        $js .= '$j("#chrono_label,#chrono_display", window.top.document).show();';
+    }
+    $content .= '<input type="hidden" name="chrono[]" id="chrono" value="'.$infoAttach->identifier.'"/>';
     $content .= '</p>';
+
     $content .= '<p style="text-align:left;margin-left:74.5%;"></p>';
-    $content .= '<p>';
-    $content .= '<label>'. _FILE.' <span><i class="fa fa-paperclip fa-lg" title="'._LOADED_FILE.'" style="cursor:pointer;" id="attachment_type_icon" onclick="$(\'attachment_type_icon\').setStyle({color: \'#009DC5\'});$(\'attachment_type_icon2\').setStyle({color: \'#666\'});$(\'templateOffice\').setStyle({display: \'none\'});$(\'templateOffice\').disabled=true;$(\'edit\').setStyle({display: \'none\'});$(\'choose_file\').setStyle({display: \'inline-block\'});document.getElementById(\'choose_file\').contentDocument.getElementById(\'file\').click();"></i> <i class="fa fa-file-text-o fa-lg" title="'._GENERATED_FILE.'" style="cursor:pointer;color:#009DC5;" id="attachment_type_icon2" onclick="$(\'attachment_type_icon2\').setStyle({color: \'#009DC5\'});$(\'attachment_type_icon\').setStyle({color: \'#666\'});$(\'templateOffice\').setStyle({display: \'inline-block\'});$(\'templateOffice\').disabled=false;$(\'choose_file\').setStyle({display: \'none\'});"></i></span></label>';
-    $content .= '<select name="templateOffice" id="templateOffice" style="display:inline-block;" onchange="showEditButton();'.$function_transmssion2.'">';
-    $content .= '<option value="">'. _CHOOSE_MODEL.'</option>';
+    //FILE
+    if ($mode == 'add') {
+        $content .= '<p>';
+        $content .= '<label id="file_label">'._FILE.' <span id="templateOfficeTool"><i class="fa fa-paperclip fa-lg" title="'._LOADED_FILE.'" style="cursor:pointer;" id="attachment_type_icon" onclick="$(\'attachment_type_icon\').setStyle({color: \'#009DC5\'});$(\'attachment_type_icon2\').setStyle({color: \'#666\'});$(\'templateOffice\').setStyle({display: \'none\'});$(\'templateOffice\').disabled=true;$(\'templateOffice_edit\').setStyle({display: \'none\'});$(\'choose_file\').setStyle({display: \'inline-block\'});document.getElementById(\'choose_file\').contentDocument.getElementById(\'file\').click();"></i> <i class="fa fa-file-text-o fa-lg" title="'._GENERATED_FILE.'" style="cursor:pointer;color:#009DC5;" id="attachment_type_icon2" onclick="$(\'attachment_type_icon2\').setStyle({color: \'#009DC5\'});$(\'attachment_type_icon\').setStyle({color: \'#666\'});$(\'templateOffice\').setStyle({display: \'inline-block\'});$(\'templateOffice\').disabled=false;$(\'choose_file\').setStyle({display: \'none\'});"></i></span></label>';
+        $content .= '<select name="templateOffice[]" id="templateOffice" style="display:inline-block;" onchange="showEditButton(this);">';
+        $content .= '<option value="">'._CHOOSE_MODEL.'</option>';
 
-    $content .= '</select>';
-    $content .= '<iframe style="display:none; width:210px" name="choose_file" id="choose_file" frameborder="0" scrolling="no" height="25" src="' . $_SESSION['config']['businessappurl']
-        . 'index.php?display=true&module=attachments&page=choose_attachment"></iframe>';
+        $content .= '</select>';
+        if ($mode == 'add') {
+            $content .= ' <input type="button" value="';
+            $content .= _EDIT_MODEL;
+            $content .= '" name="templateOffice_edit[]" id="templateOffice_edit" style="display:none;margin-top: 0" class="button" '
+                .'onclick="showAppletLauncher(this, \''.$_SESSION['doc_id'].'\',\''.$objectTable.'\',\'attachmentVersion\',\'attachment\');$(\'add\').value=\'Edition en cours ...\';editingDoc(this,\''.$_SESSION['user']['UserId'].'\');$(\'add\').disabled=\'disabled\';$(\'add\').style.opacity=\'0.5\';this.hide();$j(\'#\'+this.id).parent().find(\'[name=templateOffice\\\\[\\\\]]\').css(\'width\',\'206px\');"/>';
+        }
+        $content .= '<iframe style="display:none; width:210px" name="choose_file" id="choose_file" frameborder="0" scrolling="no" height="25" src="'.$_SESSION['config']['businessappurl']
+            .'index.php?display=true&module=attachments&page=choose_attachment"></iframe>';
 
-    $content .='&nbsp;<span class="red_asterisk" id="templateOffice_mandatory"><i class="fa fa-star"></i></span>';
-    
-    $content .= '</p>';
-}
+        $content .= '&nbsp;<span class="red_asterisk" id="templateOffice_mandatory"><i class="fa fa-star"></i></span>';
+        $content .= '</p>';
+    }
 
-if (isset($statusEditAttachment) && $statusEditAttachment == 'TMP') {
-    $content .= '<p align="middle"><span style="color:green">'._RETRIEVE_BACK_UP.'</span></p>';
-}
-if (isset($_REQUEST['id'])) {
-    $content .= '<p>';
-    $content .= '<label id="chrono_label" >'. _ATTACHMENT_TYPES.'</label>';
-    $content .= '<input type="text" name="attachment_type" id="attachment_type" value="' . $_SESSION['attachment_types'][$data_attachment->attachment_type] . '" disabled class="readonly"/>';
-    $content .= '</p>';
+    if (isset($statusEditAttachment) && $statusEditAttachment == 'TMP') {
+        $content .= '<p align="middle"><span style="color:green">'._RETRIEVE_BACK_UP.'</span></p>';
+    }
+
+    //PJ SUBJECT
     $content .= '<p>';
-    $content .= '<label id="chrono_label" >'. _CHRONO_NUMBER.'</label>';
-    $content .= '<input type="text" name="chrono_display" id="chrono_display" value="' . $data_attachment->identifier . '" disabled class="readonly"/>';
-    $content .= '</p>';
-}
-$content .= '<p>';
-$content .= '<label>'. _OBJECT .'</label>';
-$content .= '<input type="text" name="title" id="title" maxlength="250" value="';
-if (isset($_REQUEST['id'])) {
-    $content .= str_replace('"', '&quot;', $data_attachment->title);
-} else {
-    $content .= $req->show_string(substr($data_attachment->subject, 0, 250));
-}
-$content .= '"/>&nbsp;<span class="red_asterisk" id="templateOffice_mandatory"><i class="fa fa-star"></i></span>';
-$content .= '</p>';
-$content .= '<p>';
-$content .= '<label>'. _BACK_DATE.'</label>';
-if (isset($_REQUEST['id'])) {
-    $content .= '<input type="text" name="back_date" id="back_date" onClick="showCalender(this);" onfocus="checkBackDate(this);" onchange="checkBackDate(this);" value="';
-    $content .= $req->format_date_db($data_attachment->validation_date);
-    $content .= '"/>';
+    $content .= '<label>'._OBJECT.'</label>';
+    $content .= "<input type='text' name='title[]' id='title' maxlength='250' value='{$infoAttach->title}'/> ";
+    $content .= '&nbsp;<span class="red_asterisk" id="templateOffice_mandatory"><i class="fa fa-star"></i></span>';
     $content .= '</p>';
-    if ($data_attachment->attachment_type == 'transmission' && ($data_attachment->status == "RTURN" || $data_attachment->status == "EXP_RTURN")) {
+
+    //BACK DATE
+    if ($mode == 'add' || ($mode == 'edit' && (($infoAttach->attachment_type == 'transmission' && $infoAttach->status != 'NO_RTURN') || $infoAttach->attachment_type != 'transmission'))) {
         $content .= '<p>';
-        $content .= '<label>'. "Date de retour effective".'</label>';
-        $content .= '<input type="text" name="effectiveDate" id="effectiveDate" onblur="setRturnForEffectiveDate();" onClick="showCalender(this);" onfocus="checkBackDate(this);" onchange="checkBackDate(this);" style="width: 75px" value="';
-        $content .= $req->format_date_db($data_attachment->effective_date);
-        $content .= '" />';
-        $content .= '<select name="effectiveDateStatus" id="effectiveDateStatus" style="margin-left: 20px;width: 105px" />';
-        $content .= '<option value="EXP_RTURN">Attente retour</option>';
-        if ($data_attachment->status == "RTURN")
-            $content .= '<option selected="selected" value="RTURN">Retourné</option>';
-        else
-            $content .= '<option value="RTURN">Retourné</option>';
-        $content .= '</select>';
+        $content .= '<label>'._BACK_DATE.'</label>';
+        $content .= "<input type='text' name='back_date[]' id='back_date' onClick='showCalender(this);' onfocus='checkBackDate(this);' onchange='checkBackDate(this);' value='{$req->format_date_db($infoAttach->validation_date)}'/>";
+        if ($mode == 'add') {
+            $content .= '<select name="effectiveDateStatus[]" id="effectiveDateStatus" style="display:none;margin-left: 20px;width: 105px" onchange="checkEffectiveDateStatus(this);"/>';
+            $content .= '<option value="A_TRA">A traiter</option>';
+            $content .= '</select>';
+        }
+        $content .= '</p>';
     }
-} else {
-    $content .= '<input type="text" name="back_date" id="back_date" onClick="showCalender(this);" onfocus="checkBackDate(this);" onchange="checkBackDate(this);" value="" />';
-}
-$content .= "<input type='hidden' name='withDelay' id='withDelay' value='".$_SESSION['attachment_types_with_delay']['transmission']."' />";
-$content .= "<input type='hidden' name='dataCreationDate' id='dataCreationDate' value='{$dataForDate->creation_date}' />";
-$content .= '</p>';
-$content .= '<div>';
-$content .= '<label>'. _DEST_USER_PJ;
-if ($core->test_admin('my_contacts', 'apps', false)) {
-    $content .= ' <a href="#" id="create_multi_contact" title="' . _CREATE_CONTACT
-            . '" onclick="new Effect.toggle(\'create_contact_div_attach\', '
-            . '\'blind\', {delay:0.2});return false;" '
-            . 'style="display:inline;" ><i class="fa fa-pencil fa-lg" title="' . _CREATE_CONTACT . '"></i></a>';
-}
-$content .= '</label>';
-$content .= '<span style="position:relative;"><input type="text" name="contact_attach" onblur="display_contact_card(\'visible\', \'contact_card_attach\');" onkeyup="erase_contact_external_id(\'contact_attach\', \'contactidAttach\');erase_contact_external_id(\'contact_attach\', \'addressidAttach\');" id="contact_attach" value="';
-$content .= $data_contact;
-$content .= '"/><div id="show_contacts_attach" class="autocomplete autocompleteIndex" style="width: 100%;left: 0px;"></div><div class="autocomplete autocompleteIndex" id="searching_autocomplete" style="display: none;text-align:left;padding:5px;width: 100%;left: 0px;"><i class="fa fa-spinner fa-spin" aria-hidden="true"></i> chargement ...</div></span>';
-$content .='<a href="#" id="contact_card_attach" title="'._CONTACT_CARD.'" onclick="document.getElementById(\'info_contact_iframe_attach\').src=\'' . $_SESSION['config']['businessappurl']
-    . 'index.php?display=false&dir=my_contacts&page=info_contact_iframe&fromAttachmentContact=Y&seeAllAddresses&contactid=\'+document.getElementById(\'contactidAttach\').value+\'&addressid=\'+document.getElementById(\'addressidAttach\').value+\'\';new Effect.toggle(\'info_contact_div_attach\', '
-    . '\'blind\', {delay:0.2});return false;"'
-    . ' style=""> <i class="fa fa-book fa-lg"></i></a>';
-$content .= '</div>';
-$content .= '<input type="hidden" id="contactidAttach" name="contactidAttach" value="';
-if (isset($_REQUEST['id']) && !empty($data_attachment->dest_contact_id)) {
-    $content .= $data_attachment->dest_contact_id;
-} else if (isset($_REQUEST['id']) && !empty($data_attachment->dest_user)){
-    $content .= $data_attachment->dest_user;
-} else if ($data_attachment->exp_contact_id){
-    $content .= $data_attachment->exp_contact_id;
-} else if ($data_attachment->dest_contact_id) {
-    $content .= $data_attachment->dest_contact_id;
-} else if ($data_attachment->exp_user_id) {
-    $content .= $data_attachment->exp_user_id;
-} else if ($data_attachment->dest_user_id) {
-    $content .= $data_attachment->dest_user_id;
-}
 
-$content .= '"/>';
-$content .= '<input type="hidden" id="addressidAttach" name="addressidAttach" value="';
+    //EFFECTIVE BACK DATE (for transmission)
+    if ($mode == 'edit' && $infoAttach->attachment_type == 'transmission') {
+        $content .= '<p>';
+        $content .= '<label>'._EFFECTIVE_DATE.'</label>';
+        $content .= "<input type='text' name='effectiveDate[]' id='effectiveDate' onblur='setRturnForEffectiveDate();' onClick='showCalender(this);' onfocus='checkBackDate(this);' onchange='checkBackDate(this);' style='width: 75px' value='{$req->format_date_db($infoAttach->effective_date)}'";
+        if ($infoAttach->status == 'NO_RTURN') {
+            $content .= ' disabled="disabled" class="readonly"';
+        }
+        $content .= '/>';
+        $content .= '<select name="effectiveDateStatus[]" id="effectiveDateStatus" style="margin-left: 20px;width: 105px" />';
 
-if (isset($_REQUEST['id'])) {
-    $content .= $data_attachment->dest_address_id;
-} else if ($data_attachment->address_id <> ''){
-    $content .= $data_attachment->address_id;
-}
+        if ($infoAttach->status == 'EXP_RTURN' || $infoAttach->status == 'RTURN') {
+            $content .= '<option value="EXP_RTURN">Attente retour</option>';
+            if ($infoAttach->status == 'RTURN') {
+                $content .= '<option selected="selected" value="RTURN">Retourné</option>';
+            } else {
+                $content .= '<option value="RTURN">Retourné</option>';
+            }
+        } else {
+            $content .= '<option selected="selected" value="NO_RTURN">Pas de retour</option>';
+        }
+
+        $content .= '</select>';
+        $content .= '</p>';
+    }
+    $content .= "<input type='hidden' name='dataCreationDate' id='dataCreationDate' value='{$dataForDate}' />";
 
-$content .= '"/>';
-
-$langArrayForTransmission = [
-    _ATTACHMENT_TYPES,
-    _CHRONO_NUMBER,
-    _FILE,
-    _OBJECT,
-    _BACK_DATE,
-    _DEST_USER_PJ,
-    _EDIT_MODEL,
-    _CREATE_CONTACT
-];
-$canCreateContact = $core->test_admin('my_contacts', 'apps', false);
-if (!$canCreateContact)
-    $canCreateContact = 0;
-
-if(!isset($_REQUEST['id'])) {
-    $content .= '<p><div style="float: left;margin-bottom: 5px">';
-    $content .= '<input type="button" value="';
-    $content .= _EDIT_MODEL;
-    /*$content .= '" name="edit" id="edit" style="display:none;margin-top: 0" class="button" '
-        . 'onclick="window.open(\'' . $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_popup_launcher&objectType=attachmentVersion&objectId=\'+$(\'templateOffice\').value+\'&attachType=\'+$(\'attachment_types\').value+\'&objectTable=' . $objectTable . '&contactId=\'+$(\'contactidAttach\').value+\'&addressId=\'+$(\'addressidAttach\').value+\'&chronoAttachment=\'+$(\'chrono\').value+\'&titleAttachment=\'+cleanTitle($(\'title\').value)+\'&back_date=\'+$(\'back_date\').value+\'&resMaster=' . $_SESSION['doc_id']
-        . '\', \'\', \'height=200, width=250,scrollbars=no,resizable=no,directories=no,toolbar=no\');$(\'add\').value=\'Edition en cours ...\';setInterval(function() {checkEditingDoc(\''.$_SESSION['user']['UserId'].'\')}, 500);$(\'add\').disabled=\'disabled\';$(\'add\').style.opacity=\'0.5\';this.hide();"/>';*/
-    $content .= '" name="edit" id="edit" style="display:none;margin-top: 0" class="button" '
-        . 'onclick="showAppletLauncher(\'' . $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_modal_launcher&objectType=attachmentVersion&objectId=\'+$(\'templateOffice\').value+\'&attachType=\'+$(\'attachment_types\').value+\'&objectTable=' . $objectTable . '&contactId=\'+$(\'contactidAttach\').value+\'&addressId=\'+$(\'addressidAttach\').value+\'&chronoAttachment=\'+$(\'chrono\').value+\'&titleAttachment=\'+cleanTitle($(\'title\').value)+\'&back_date=\'+$(\'back_date\').value+\'&resMaster=' . $_SESSION['doc_id']
-        . '\', \'100px\', \'500px\');$(\'add\').value=\'Edition en cours ...\';editingDoc(\''.$_SESSION['user']['UserId'].'\');$(\'add\').disabled=\'disabled\';$(\'add\').style.opacity=\'0.5\';this.hide();"/>';
-    $content .= '<span style="display: none" id="divOr0">&nbsp;ou&nbsp;</span>';
+    //CONTACT
+    $content .= '<div style="margin-bottom:10px;">';
+    $content .= '<label>'._DEST_USER_PJ;
+    if ($core->test_admin('my_contacts', 'apps', false)) {
+        $content .= ' <a href="#" id="create_multi_contact" title="'._CREATE_CONTACT
+                .'" onclick="new Effect.toggle(\'create_contact_div_attach\', '
+                .'\'blind\', {delay:0.2});return false;" '
+                .'style="display:inline;" ><i class="fa fa-pencil fa-lg" title="'._CREATE_CONTACT.'"></i></a>';
+    }
+    $content .= '</label>';
+    $content .= '<span style="position:relative;"><input type="text" name="contact_attach[]" onblur="display_contact_card(\'visible\', \'contact_card_attach\');" onkeyup="erase_contact_external_id(\'contact_attach\', \'contactidAttach\');erase_contact_external_id(\'contact_attach\', \'addressidAttach\');" id="contact_attach" onchange="saveContactToSession(this);" value="';
+    $content .= $infoAttach->contact_show;
+    $content .= '"/><div id="show_contacts_attach" class="autocomplete autocompleteIndex" style="width: 100%;left: 0px;"></div><div class="autocomplete autocompleteIndex" id="searching_autocomplete" style="display: none;text-align:left;padding:5px;width: 100%;left: 0px;"><i class="fa fa-spinner fa-spin" aria-hidden="true"></i> chargement ...</div></span>';
+    $content .= '<a href="#" id="contact_card_attach" name="contact_card_attach" title="'._CONTACT_CARD.'" onclick="showContactInfo(this,document.getElementById(\'contactidAttach\'),document.getElementById(\'addressidAttach\'));" style=""> <i class="fa fa-book fa-lg"></i></a>';
     $content .= '</div>';
+    $content .= "<input type='hidden' id='contactidAttach' name='contactidAttach[]' value='{$infoAttach->contact_id}' />";
+    $content .= "<input type='hidden' id='addressidAttach' name='addressidAttach[]' value='{$infoAttach->address_id}' />";
 
-    $content .= '<div style="float: left">';
-    if(isset($_SESSION['attachment_types']['transmission'])){
-        $content .= '<i id="newTransmissionButton0" title="Nouvelle transmission" style="opacity: 0.5;cursor: pointer" class="fa fa-plus-circle fa-2x"
-                         onclick="addNewTransmission(\'' . $_SESSION['config']['businessappurl'] . '\', \'' . $_SESSION['doc_id'] . '\', ' . $canCreateContact . ', \'' . addslashes(implode('#', $langArrayForTransmission)) . '\', \'' . $_SESSION['user']['UserId'] . '\')"></i>';
+    $canCreateContact = $core->test_admin('my_contacts', 'apps', false);
+    if (!$canCreateContact) {
+        $canCreateContact = 0;
     }
-    $content .= '</div></p>';
-}
 
-if (isset($_REQUEST['id']) && ($data_attachment->status <> 'TMP' || ($data_attachment->status == 'TMP' && $data_attachment->relation > 1))) {
-    $content .= '<p>';
-    $content .= '<label>'. _CREATE_NEW_ATTACHMENT_VERSION.'</label>';
-    $content .= '<input type="radio" name="new_version" id="new_version_yes" value="yes" onclick="setButtonStyle(\'yes\', \''.$attachmentFormat.'\', $(\'hiddenValidateStatus\').value)"/>'._YES;
-    $content .= '&nbsp;&nbsp;';
-    $content .= '<input type="radio" name="new_version" id="new_version_no" checked value="no" onclick="setButtonStyle(\'no\', \''.$attachmentFormat.'\', $(\'hiddenValidateStatus\').value)"/>'._NO;
-    $content .= '</p>';
-}
+    if ($mode == 'add' && $_GET['cat'] != 'outgoing') {
+        $content .= '<p>';
+
+        $content .= '<div style="float: left">';
+
+        //ADD ATTACH OTHER ATTACHEMENT
+        $content .= '<input type="button" class="button readonly" id="newAttachButton" value="'._NEW_ATTACH_ADDED.'" title="'._NEW_ATTACH_ADDED.'" onclick="addNewAttach();" disabled="disabled"></input>';
+        $content .= '&nbsp;';
+        //DEL ATTACH (HIDDEN DEFAULT)
+        $content .= '<input type="button" class="button readonly" style="background:#d14836;color:white;display:none;" name="delAttachButton[]" id="delAttachButton" value="'._DELETE.'" title="'._DELETE.'" disabled="disabled"></input>';
+
+        $content .= '</div>';
+
+        $content .= '</p>';
+    }
 
+    $content .= "<input type='hidden' id='attachNum' name='attachNum[]' value='0' />";
+
+    //NEW VERSION IN EDIT MODE
+    if ($mode == 'edit' && ($infoAttach->status != 'TMP' || ($infoAttach->status == 'TMP' && $infoAttach->relation > 1))) {
+        $content .= '<p>';
+        $content .= '<label>'._CREATE_NEW_ATTACHMENT_VERSION.'</label>';
+        $content .= '<input type="radio" name="new_version" id="new_version_yes" value="yes" onclick="$j(\'#edit\').css(\'visibility\',\'hidden\');$j(\'#editModel\').css(\'display\',\'inline-block\');"/>'._YES;
+        $content .= '&nbsp;&nbsp;';
+        $content .= '<input type="radio" name="new_version" id="new_version_no" checked value="no" onclick="$j(\'#edit\').css(\'visibility\',\'visible\');"/>'._NO;
+        $content .= '</p>';
+    }
 $content .= '</div>';
 
-    $content .= '<div id="transmission"></div>';
-    $content .= '<input type="hidden" id="hiddenValidateStatus" value="1"/>';
-        $content .= '<p class="buttons">';
-            if (isset($_REQUEST['id']) && !in_array($attachmentFormat, ["pdf", "jpg", "jpeg", "png"])) {
-                $content .= '<input type="button" value="';
-                $content .= _EDIT_MODEL;
-                /*$content .= '" name="editModel" id="editModel" class="button" onclick="$(\'hiddenValidateStatus\').value=\'2\';$(\'edit\').style.visibility=\'visible\';window.open(\''
-                    . $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_popup_launcher&objectType=attachmentUpVersion&objectId='.$_REQUEST['id'].'&contactId=\'+$(\'contactidAttach\').value+\'&addressId=\'+$(\'addressidAttach\').value+\'&titleAttachment=\'+cleanTitle($(\'title\').value)+\'&back_date=\'+$(\'back_date\').value+\'&objectTable=res_view_attachments&resMaster='.$_SESSION['doc_id']
-                    .'\', \'\', \'height=200, width=250,scrollbars=no,resizable=no,directories=no,toolbar=no\');$(\'edit\').value=\'Edition en cours ...\';setInterval(function() {checkEditingDoc(\''.$_SESSION['user']['UserId'].'\')}, 500);$(\'edit\').disabled=\'disabled\';$(\'edit\').style.opacity=\'0.5\';this.hide();"/>';*/
-                $content .= '" name="editModel" id="editModel" class="button" onclick="$(\'hiddenValidateStatus\').value=\'2\';$(\'edit\').style.visibility=\'visible\';showAppletLauncher(\''
-                    . $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_modal_launcher&objectType=attachmentUpVersion&objectId='.$_REQUEST['id'].'&contactId=\'+$(\'contactidAttach\').value+\'&addressId=\'+$(\'addressidAttach\').value+\'&titleAttachment=\'+cleanTitle($(\'title\').value)+\'&back_date=\'+$(\'back_date\').value+\'&objectTable=res_view_attachments&resMaster='.$_SESSION['doc_id']
-                    .'\', \'\', \'height=200, width=250,scrollbars=no,resizable=no,directories=no,toolbar=no\');$(\'edit\').value=\'Edition en cours ...\';editingDoc(\''.$_SESSION['user']['UserId'].'\');$(\'edit\').disabled=\'disabled\';$(\'edit\').style.opacity=\'0.5\';this.hide();"/>';
-            } /*else {
-                                    $content .= '" name="edit" id="edit" style="display:none" class="button" '
-                                                .'onclick="window.open(\''. $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_popup_launcher&objectType=attachmentVersion&objectId=\'+$(\'templateOffice\').value+\'&objectTable='. $objectTable .'&contactId=\'+$(\'contactidAttach\').value+\'&chronoAttachment=\'+$(\'chrono\').value+\'&resMaster='.$_SESSION['doc_id']
-                                                .'\', \'\', \'height=200, width=250,scrollbars=no,resizable=no,directories=no,toolbar=no\');"/>';
-                                }*/
-
-            $content .= '&nbsp;';
-            $content .= '&nbsp;';
+$content .= '<div id="transmission"></div>';
+    $content .= '<p class="buttons">';
+        //EDIT MODEL BUTTON
+        if ($mode == 'edit' && !in_array($infoAttach->format, ['pdf', 'jpg', 'jpeg', 'png'])) {
             $content .= '<input type="button" value="';
-            $content .=  _VALIDATE;
-            if (isset($_REQUEST['id'])) {
-                $content .= '" name="edit" id="edit" class="button" onclick="ValidAttachmentsForm(\'' . $_SESSION['config']['businessappurl'] ;
-            } else {
-                $content .= '" name="add" id="add" class="button" onclick="simpleAjax(\'' . $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetReservedChronoNumber\');ValidAttachmentsForm(\'' . $_SESSION['config']['businessappurl'] ;
-            }
-            $content .= 'index.php?display=true&module=attachments&page=attachments_content\', \'formAttachment\'';
-            if (!empty($_REQUEST['docId'])) {
-                if (isset($_REQUEST['id'])) {
-                    $content .= ', \'edit\'';
-                } else {
-                    $content .= ', \'add\'';
-                }
-            }
-            if (isset($_REQUEST['id'])) {
-                $content .= ');simpleAjax(\'' . $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetTemporarySaved&mode=edit\')"/>';
-            } else {
-                $content .= ');simpleAjax(\'' . $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetTemporarySaved&mode=add\')"/>';
-            }
+            $content .= _EDIT_MODEL;
+            $content .= '" name="editModel" id="editModel" class="button" onclick="$(\'edit\').style.visibility=\'visible\';showAppletLauncher(this, \''.$_SESSION['doc_id'].'\',\''.$objectTable.'\',\'attachmentUpVersion\',\'attachment\');$(\'edit\').value=\'Edition en cours ...\';editingDoc(this,\''.$_SESSION['user']['UserId'].'\');$(\'edit\').disabled=\'disabled\';$(\'edit\').style.opacity=\'0.5\';this.hide();"/>';
+        }
 
-            $content .= '&nbsp;';
-            $content .= '&nbsp;';
-            $content .= '<label>&nbsp;</label>';
+        $content .= '&nbsp;';
+        $content .= '&nbsp;';
 
-            $content .= '<input id="cancelpj" type="button" value="';
-            $content .=  _CANCEL;
-            $content .= '" name="cancel" class="button"  onclick="simpleAjax(\'' . $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetReservedChronoNumber\');';
-            if (isset($_REQUEST['id'])) {
-                $content .= 'simpleAjax(\'' . $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetTemporarySaved&mode=edit\');destroyModal(\'form_attachments\');"/>';
-            } else {
-                $content .= 'simpleAjax(\'' . $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetTemporarySaved&mode=add\');destroyModal(\'form_attachments\');"/>';
-            }
+        //VALIDATE BUTTON
+        $content .= '<input type="button" value="';
+        $content .= _VALIDATE;
+        if (isset($_REQUEST['id'])) {
+            $content .= '" name="edit" id="edit" class="button" onclick="ValidAttachmentsForm(\''.$_SESSION['config']['businessappurl'];
+        } else {
+            $content .= '" name="add" id="add" class="button" onclick="simpleAjax(\''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetReservedChronoNumber\');ValidAttachmentsForm(\''.$_SESSION['config']['businessappurl'];
+        }
+        $content .= 'index.php?display=true&module=attachments&page=attachments_content\', \'formAttachment\'';
+
+        //SIGNATURE BOOK
+        if (!empty($_REQUEST['docId'])) {
+            $content .= ", '{$mode}'";
+        }
+
+        $content .= ');simpleAjax(\''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetTemporarySaved&mode='.$mode.'\')"/>';
 
-        $content .= '</p>';
         $content .= '&nbsp;';
         $content .= '&nbsp;';
-        $content .= '</p>';
-    $content .= '</form>';
+        $content .= '<label>&nbsp;</label>';
 
-    if (!isset($_REQUEST['id'])) {
-        $content .= '<script>launch_autocompleter2_contacts_v2("'. $_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "contact_attach", "show_contacts_attach", "", "contactidAttach", "addressidAttach")</script>';
-    } else {
-        $content .= '<script>launch_autocompleter2_contacts_v2("'. $_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "contact_attach", "show_contacts_attach", "", "contactidAttach", "addressidAttach")</script>';
-    }
+        //CANCEL BUTTON
+        $content .= '<input id="cancelpj" type="button" value="';
+        $content .= _CANCEL;
+        $content .= '" name="cancel" class="button"  onclick="simpleAjax(\''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetReservedChronoNumber\');';
+        $content .= 'simpleAjax(\''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=unsetTemporarySaved&mode='.$mode.'\');destroyModal(\'form_attachments\');"/>';
+
+    $content .= '</p>';
+$content .= '</form>';
 
-    $content .= '<script>display_contact_card(\'visible\', \'contact_card_attach\');</script>';
+//EXTRA JS
+$content .= '<script>launch_autocompleter2_contacts_v2("'.$_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "contact_attach", "show_contacts_attach", "", "contactidAttach", "addressidAttach")</script>';
+$content .= '<script>display_contact_card(\'visible\', \'contact_card_attach\');</script>';
 
-    if ($core->test_admin('my_contacts', 'apps', false)) {
-        $content .= '<div id="create_contact_div_attach" style="display:none;float:right;width:65%;background-color:#deedf3">';
-            $content .= '<iframe width="100%" height="550" src="' . $_SESSION['config']['businessappurl']
-                    . 'index.php?display=false&dir=my_contacts&page=create_contact_iframe&fromAttachmentContact=Y&transmissionInput=0" name="contact_iframe_attach" id="contact_iframe_attach"'
-                    . ' scrolling="auto" frameborder="0" style="display:block;">'
-                    . '</iframe>';
-        $content .= '</div>';
-    }
-    $content .= '<div id="info_contact_div_attach" style="display:none;float:right;width:65%;background-color:#deedf3">';
-        $content .= '<iframe width="100%" height="800" name="info_contact_iframe_attach" id="info_contact_iframe_attach"'
-                . ' scrolling="auto" frameborder="0" style="display:block;">'
-                . '</iframe>';
+//IFRAME CREATE CONTACT
+if ($core->test_admin('my_contacts', 'apps', false)) {
+    $content .= '<div id="create_contact_div_attach" style="display:none;float:right;width:65%;background-color:#deedf3">';
+    $content .= '<iframe width="100%" height="550" src="'.$_SESSION['config']['businessappurl']
+                .'index.php?display=false&dir=my_contacts&page=create_contact_iframe&fromAttachmentContact=Y&transmissionInput=0" name="contact_iframe_attach" id="contact_iframe_attach"'
+                .' scrolling="auto" frameborder="0" style="display:block;">'
+                .'</iframe>';
     $content .= '</div>';
-$content .= '<div style="float: right; width: 65%">';
-
-$content .= '<div id="menuOnglet">
-                <ul id="ongletAttachement" style="cursor:pointer">
-                    <li id="liAttachement" ';
+}
+//IFRAME INFO CONTACT
+$content .= '<div id="info_contact_div_attach" style="display:none;float:right;width:65%;background-color:#deedf3">';
+    $content .= '<iframe width="100%" height="800" name="contact_card_attach_iframe" id="contact_card_attach_iframe"'
+            .' scrolling="auto" frameborder="0" style="display:block;">'
+            .'</iframe>';
+$content .= '</div>';
 
-                if(empty($_REQUEST['id'])){
-                    $content .= ' style="display:none" ';
-                }
+$content .= '<div style="float: right; width: 65%">';
 
-                    $content .= 'onclick="activeOngletAttachement()"><span> Pièce jointe </span></li>';
-                    if($_GET['cat'] != 'outgoing' && $data_attachment->attachment_type != 'outgoing_mail'){
-                        $content .='<li id="liMainDocument" onclick="activeOngletMainDocument()"><span> Document principal </span></li>';
-                    }
-                $content .='</ul>
-            </div>';
+//TABS
+$content .= '<div id="menuOnglet">';
+    $content .= '<ul id="ongletAttachement" style="cursor:pointer;width:auto;">';
+        $content .= '<li id="MainDocument" onclick="activePjTab(this)"><span> Document principal </span></li>';
+        if ($mode == 'edit') {
+            $content .= '<li id="PjDocument_0" onclick="activePjTab(this)"><span> PJ n°1 </span></li>';
+        }
+    $content .= '</ul>';
+$content .= '</div>';
 
-// ATTACHEMENT //
-if(empty($_REQUEST['id'])){
-    $srcAttachment = '';
-} else {
+// ATTACHMENT IFRAME
+if ($mode == 'edit') {
     $srcAttachment = 'index.php?display=true&module=attachments&page=view_attachment&editingMode=true&res_id_master='.functions::xssafe($_SESSION['doc_id']).'&id='.functions::xssafe($_REQUEST['id']);
+    $content .= '<iframe src="'.$srcAttachment.'" name="iframePjDocument_0" id="iframePjDocument_0" scrolling="auto" frameborder="0" style="width:100% !important;height:85vh;display:none" onmouseover="this.focus()"></iframe>';
 }
 
-$content .= '<iframe src="'.$srcAttachment.'" name="viewframevalid_attachment" id="viewframevalid_attachment" scrolling="auto" frameborder="0" style="width:100% !important;height:90vh;display:none" onmouseover="this.focus()"></iframe>';
+// MAIN DOCUMENT IFRAME
+$content .= '<iframe src="index.php?display=true&editingMode=true&dir=indexing_searching&page=view_resource_controler&id='.functions::xssafe($_SESSION['doc_id']).'#view=FitH" name="iframeMainDocument" id="iframeMainDocument" scrolling="auto" frameborder="0" style="width:100% !important;height:85vh;display:none" onmouseover="this.focus()"></iframe>';
 
-// DOCUMENT PRINCIPAL //
-$content .= '<iframe src="index.php?display=true&editingMode=true&dir=indexing_searching&page=view_resource_controler&id='. functions::xssafe($_SESSION['doc_id']).'" name="viewframevalid_main" id="viewframevalid_main" scrolling="auto" frameborder="0" style="width:100% !important;height:90vh;display:none" onmouseover="this.focus()"></iframe>';
-    
 $content .= '</div>';
 
-if(empty($_REQUEST['id'])){
-    $js = 'setTimeout(function(){window.parent.document.getElementById(\'liMainDocument\').click()}, 1000);';
+if ($mode == 'add') {
+    $js .= 'setTimeout(function(){window.parent.document.getElementById(\'MainDocument\').click()}, 1000);';
 } else {
-    $js = 'setTimeout(function(){window.top.document.getElementById(\'liAttachement\').click()}, 1000);';
+    $js .= 'setTimeout(function(){window.top.document.getElementById(\'PjDocument_0\').click()}, 1000);';
 }
 
-$js .= "setInterval(function(){window.top.clearTimeout(window.top.chronoExpiration);window.top.chronoExpiration=window.top.setTimeout('redirect_to_url(\'index.php?display=true&page=logout&logout=true\')', ".$_SESSION['config']['cookietime']."*60*1000); }, 60000);";
-echo "{status : " . $status . ", content : '" . addslashes(_parse($content)) . "', error : '" . addslashes($error) . "', exec_js : '".addslashes($js)."'}";
-exit ();
+$js .= "setInterval(function(){window.top.clearTimeout(window.top.chronoExpiration);window.top.chronoExpiration=window.top.setTimeout('redirect_to_url(\'index.php?display=true&page=logout&logout=true\')', ".$_SESSION['config']['cookietime'].'*60*1000); }, 60000);';
+
+echo '{status : '.$status.", content : '".addslashes(_parse($content))."', error : '".addslashes($error)."', exec_js : '".addslashes($js)."'}";
+exit();
diff --git a/modules/attachments/choose_attachment.php b/modules/attachments/choose_attachment.php
index 05fdfc9a26b..9064832bcbe 100755
--- a/modules/attachments/choose_attachment.php
+++ b/modules/attachments/choose_attachment.php
@@ -13,150 +13,156 @@ $core_tools = new core_tools();
 $core_tools->load_lang();
 $func = new functions();
 $core_tools->load_html();
-$core_tools->load_header('', true, false);
+$core_tools->load_header('', true, true);
 $upFileOK = false;
-?>
-    
-    <?php
-    $_SESSION['upfile']['error'] = 0;
-    if (isset($_FILES['file']['error']) && $_FILES['file']['error'] == 1) {
-        $_SESSION['upfile']['error'] = $_FILES['file']['error'];
-        if ($_SESSION['upfile']['error'] == 1) {
-            $_SESSION['error'] = 'La taille du fichier telecharge excede la valeur de upload_max_filesize';
-        }
-    } elseif (!empty($_FILES['file']['tmp_name']) && $_FILES['file']['error'] <> 1) {
-        $_SESSION['error'] = '';
-        $_SESSION['upfile']['tmp_name'] = $_FILES['file']['tmp_name'];
-        $extension = explode(".", $_FILES['file']['name']);
-        $name_without_ext = substr($_FILES['file']['name'], 0, strrpos($_FILES['file']['name'], "."));
-        echo '<script>window.parent.document.getElementById(\'title\').value=\''.$name_without_ext.'\';</script>';
-        $count_level = count($extension)-1;
-        $the_ext = $extension[$count_level];
-        $fileNameOnTmp = 'tmp_file_' . $_SESSION['user']['UserId']
-            . '_' . rand() . '.' . strtolower($the_ext);
-            $_SESSION['upfile']['fileNameOnTmp'] = $fileNameOnTmp;
-        $filePathOnTmp = $_SESSION['config']['tmppath'] . $fileNameOnTmp;
 
-        if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
-                $_SESSION['error'] = _FILE_NOT_SEND . ". " . _TRY_AGAIN
-                    . ". " . _MORE_INFOS . " (<a href=\"mailto:"
-                    . $_SESSION['config']['adminmail'] . "\">"
-                    . $_SESSION['config']['adminname'] . "</a>)";
+
+$_SESSION['upfile']['error'] = 0;
+$_SESSION['error'] = '';
+
+if (isset($_FILES) && $_FILES['file']['error'] == 1) {
+
+    $_SESSION['upfile'][0]['error'] = $value;
+    $error = 'La taille excede la valeur de upload_max_filesize';
+    echo '<script>$j("#main_error",window.parent.document).html(\''.$error.'\').show().delay(5000).fadeOut();</script>';   
+        
+} elseif (!empty($_FILES['file']['tmp_name']) && $_FILES['file']['error'] <> 1) {
+    $_SESSION['upfile'][0]['tmp_name'] = $_FILES['file']['tmp_name'];
+    $extension = explode(".", $_FILES['file']['name']);
+    $name_without_ext = substr($_FILES['file']['name'], 0, strrpos($_FILES['file']['name'], "."));
+    echo '<script>window.parent.document.getElementById(\'title\').value=\''.$name_without_ext.'\';</script>';
+    $count_level = count($extension)-1;
+    $the_ext = $extension[$count_level];
+    $fileNameOnTmp = 'tmp_file_' . $_SESSION['user']['UserId']
+        . '_' . rand() . '.' . strtolower($the_ext);
+    $_SESSION['upfile'][0]['fileNameOnTmp'] = $fileNameOnTmp;
+    $filePathOnTmp = $_SESSION['config']['tmppath'] . $fileNameOnTmp;
+
+    if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
+            $_SESSION['error'] = _FILE_NOT_SEND . ". " . _TRY_AGAIN
+                . ". " . _MORE_INFOS . " (<a href=\"mailto:"
+                . $_SESSION['config']['adminmail'] . "\">"
+                . $_SESSION['config']['adminname'] . "</a>)";
+    } else {
+        include_once 'core/docservers_tools.php';
+        $arrayIsAllowed = array();
+        $arrayIsAllowed = Ds_isFileTypeAllowed($_FILES['file']['tmp_name'], strtolower($the_ext));
+        if ($arrayIsAllowed['status'] == false) {
+            $_SESSION['error'] = _WRONG_FILE_TYPE . ' ' . $arrayIsAllowed['mime_type'];
+            $_SESSION['upfile'] = array();
+        } elseif (!@move_uploaded_file($_FILES['file']['tmp_name'], $filePathOnTmp)) {
+            $_SESSION['error'] = _FILE_NOT_SEND . ". " . _TRY_AGAIN . ". "
+                . _MORE_INFOS . " (<a href=\"mailto:"
+                . $_SESSION['config']['adminmail'] . "\">"
+                . $_SESSION['config']['adminname'] . "</a>)";
         } else {
-            include_once 'core/docservers_tools.php';
-            $arrayIsAllowed = array();
-            $arrayIsAllowed = Ds_isFileTypeAllowed($_FILES['file']['tmp_name'], strtolower($the_ext));
-            if ($arrayIsAllowed['status'] == false) {
-                $_SESSION['error'] = _WRONG_FILE_TYPE . ' ' . $arrayIsAllowed['mime_type'];
-                $_SESSION['upfile'] = array();
-            } elseif (!@move_uploaded_file($_FILES['file']['tmp_name'], $filePathOnTmp)) {
-                $_SESSION['error'] = _FILE_NOT_SEND . ". " . _TRY_AGAIN . ". "
-                    . _MORE_INFOS . " (<a href=\"mailto:"
-                    . $_SESSION['config']['adminmail'] . "\">"
-                    . $_SESSION['config']['adminname'] . "</a>)";
-            } else {
-                $_SESSION['upfile']['size'] = $_FILES['file']['size'];
-                $_SESSION['upfile']['mime'] = $_FILES['file']['type'];
-                $_SESSION['upfile']['local_path'] = $filePathOnTmp;
-                //$_SESSION['upfile']['name'] = $_FILES['file']['name'];
-                $_SESSION['upfile']['name'] = $fileNameOnTmp;
-                $_SESSION['upfile']['format'] = $the_ext;
-                $upFileOK = true;
+            $_SESSION['upfile'][0]['size'] = $_FILES['file']['size'];
+            $_SESSION['upfile'][0]['mime'] = $_FILES['file']['type'];
+            $_SESSION['upfile'][0]['local_path'] = $filePathOnTmp;
+            //$_SESSION['upfile']['name'] = $_FILES['file']['name'];
+            $_SESSION['upfile'][0]['name'] = $fileNameOnTmp;
+            $_SESSION['upfile'][0]['format'] = $the_ext;
+            $upFileOK = true;
 
-                if (in_array(strtolower($_SESSION['upfile']['format']), ['pdf', 'jpg', 'jpeg', 'png'])) {
-                    echo '<script>window.parent.document.getElementById(\'viewframevalid_attachment\').src=\''.$_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=file_iframe&#navpanes=0'.$_SESSION['upfile']['local_path'].'\';window.parent.document.getElementById(\'liAttachement\').click()</script>';
-                }
+            //CONSTRUCT TAB (IF PDF)
+            if (in_array(strtolower($_SESSION['upfile'][0]['format']), ['pdf', 'jpg', 'jpeg', 'png'])) {
+                echo '<script>if($j("#ongletAttachement #PjDocument_0",window.parent.document).length) {$j("#ongletAttachement #PjDocument_0",window.parent.document).remove();$j("div #iframePjDocument_0",window.parent.document).remove();}</script>';
+                echo '<script>$j("#MainDocument",window.parent.document).after($j("#MainDocument",window.parent.document).clone());</script>';
+                echo '<script>$j("#iframeMainDocument",window.parent.document).after($j("#iframeMainDocument",window.parent.document).clone());</script>';
+                echo '<script>$j("div #iframeMainDocument",window.parent.document).eq(1).attr("id","iframePjDocument_0");</script>';
+                echo '<script>$j("div #iframePjDocument_0",window.parent.document).attr("src","index.php?display=true&dir=indexing_searching&page=file_iframe&num=0&#navpanes=0'.$_SESSION['upfile'][0]['local_path'].'");</script>';
+                echo '<script>$j("#ongletAttachement #MainDocument",window.parent.document).eq(1).attr("id","PjDocument_0");</script>';
+                echo '<script>$j("#ongletAttachement #PjDocument_0",window.parent.document).html("<span>PJ n°1</span>");</script>';
+                echo '<script>$j("#ongletAttachement #PjDocument_0",window.parent.document).click();</script>';
             }
         }
     }
-    ?>
-    <body>
-    <form name="select_file_form" id="select_file_form" method="get" enctype="multipart/form-data" action="<?php
-        echo $_SESSION['config']['businessappurl'];
-        ?>index.php?display=true&module=attachments&page=choose_attachment" class="forms">
-        <input type="hidden" name="display" value="true" />
-        <input type="hidden" name="dir" value="indexing_searching" />
-        <input type="hidden" name="page" value="choose_attachment" />
-        <?php
-        if (!empty($_SESSION['upfile']['local_path']) && empty($_SESSION['error'])) { 
-
-                ?>
-                <i class="fa fa-check-square fa-2x" title="<?php echo _DOWNLOADED_FILE; ?>"></i>
-                <input type="button" id="fileButton" onclick="$j('#file').click();" class="button"
-                       value="<?php if($_REQUEST['with_file'] == 'true'){ echo _WITHOUT_FILE; } else {echo $_FILES['file']['name']; }?>"
-                       title="<?php if($_REQUEST['with_file'] == 'true'){ echo _WITHOUT_FILE; } else {echo $_FILES['file']['name']; }?>"
-                       style="width: 85%;margin: 0px;margin-top: -10px;font-size: 12px;text-align: center;text-overflow: ellipsis;overflow: hidden;">
-            <?php } elseif (!empty($_SESSION['error'])) { ?>
-                <i class="fa fa-remove fa-2x" title="<?php echo $_SESSION['error']; ?>"></i>
-                <input type="button" id="fileButton" onclick="$j('#file').click();" class="button" value="<?php echo $_SESSION['error']; ?>" style="width: 85%;margin: 0px;margin-top: -10px;font-size: 12px;text-align: center;text-overflow: ellipsis;overflow: hidden;">
-            <?php } else { ?>
-                <i class="fa fa-remove fa-2x" title="<?php echo _NO_FILE_SELECTED; ?>"></i>
-                <input type="button" id="fileButton" onclick="$j('#file').click();" class="button" value="<?php echo _CHOOSE_FILE; ?>" style="width: 85%;margin: 0px;margin-top: -10px;font-size: 12px;text-align: center;text-overflow: ellipsis;overflow: hidden;">
-            <?php } ?>
-        <p style="display:none">
-        <!-- window.parent.$('title').value = this.value.substring(0,this.value.indexOf('.')); -->
-            <input type="file" name="file" id="file" onchange="$('with_file').value='false';this.form.method = 'post';this.form.submit();" value="<?php
-                if (isset($_SESSION['file_path'])) {
-                    echo $_SESSION['file_path'];
-                } ?>" style="width:200px" />
-        </p>
-        <p style="display:none">
-            <div align="center">
-                <input type="radio" name="with_file" id="with_file" value="false" onclick="this.form.method = 'post';this.form.submit();" />
-            </div>
-        </p>
-    </form>
-    <?php 
-    if (!empty($_SESSION['upfile']['local_path']) && empty($_SESSION['error'])) { 
-        //launch auto convert in PDF
-        if (in_array(strtolower($_SESSION['upfile']['format']), array('odt','docx','doc','docm'))) {
-        //if (strtolower($_SESSION['upfile']['format']) == 'odt' || strtolower($_SESSION['upfile']['format']) == 'docx') {
-            echo "<script>window.parent.$('add').value='Edition en cours ...';window.parent.editingDoc('superadmin');window.parent.$('add').disabled='disabled';window.parent.$('add').style.opacity='0.5';</script>";
-            include_once 'modules/content_management/class/class_content_manager_tools.php';
+}
+?>
+<body>
+<form name="select_file_form" id="select_file_form" method="get" enctype="multipart/form-data" action="<?php
+    echo $_SESSION['config']['businessappurl'];
+    ?>index.php?display=true&module=attachments&page=choose_attachment" class="forms">
+    <input type="hidden" name="display" value="true" />
+    <input type="hidden" name="dir" value="indexing_searching" />
+    <input type="hidden" name="page" value="choose_attachment" />
+    <?php
+    if (!empty($_SESSION['upfile'][0]['local_path']) && empty($_SESSION['error'])) { 
 
-            $cM = new content_management_tools();
-            if (
-                file_exists('custom'.DIRECTORY_SEPARATOR. $_SESSION['custom_override_id']
-                            . DIRECTORY_SEPARATOR . 'modules'. DIRECTORY_SEPARATOR . 'content_management'
-                            . DIRECTORY_SEPARATOR . 'applet_controller.php'
-                )
-            ) {
-                $path = 'custom/'. $_SESSION['custom_override_id'] .'/modules/content_management/applet_controller.php';
-            } else {
-                $path = 'modules/content_management/applet_controller.php';
-            }
-            $path_appli = explode('/', $_SESSION['config']['coreurl']);
-            if (count($path_appli) <> 5) {
-                $path_appli = array_slice($path_appli, 0, 4);
-                $path_appli = implode('/', $path_appli);
-            } else {
-                $path_appli = implode('/', $path_appli);
-            }
-            // require_once 'core/class/class_db_pdo.php';
-            // $database = new Database();
-            // $query = "select template_id from templates where template_type = 'OFFICE' and template_target = 'attachments'";
-            // $stmt = $database->query($query);
-            // $aTemplateId = $stmt->fetchObject()->template_id;
-            $cookieKey = $_SESSION['sessionName'] . '=' . $_COOKIE[$_SESSION['sessionName']];
+            ?>
+            <i class="fa fa-check-square fa-2x" title="<?php echo _DOWNLOADED_FILE; ?>"></i>
+            <input type="button" id="fileButton" onclick="$j('#file').click();" class="button"
+                    value="<?php if($_REQUEST['with_file'] == 'true'){ echo _WITHOUT_FILE; } else {echo $_FILES['file']['name']; }?>"
+                    title="<?php if($_REQUEST['with_file'] == 'true'){ echo _WITHOUT_FILE; } else {echo $_FILES['file']['name']; }?>"
+                    style="width: 85%;margin: 0px;margin-top: -10px;font-size: 12px;text-align: center;text-overflow: ellipsis;overflow: hidden;">
+        <?php } elseif (!empty($_SESSION['error'])) { ?>
+            <i class="fa fa-remove fa-2x" title="<?php echo $_SESSION['error']; ?>"></i>
+            <input type="button" id="fileButton" onclick="$j('#file').click();" class="button" value="<?php echo $_SESSION['error']; ?>" style="width: 85%;margin: 0px;margin-top: -10px;font-size: 12px;text-align: center;text-overflow: ellipsis;overflow: hidden;">
+        <?php } else { ?>
+            <i class="fa fa-remove fa-2x" title="<?php echo _NO_FILE_SELECTED; ?>"></i>
+            <input type="button" id="fileButton" onclick="$j('#file').click();" class="button" value="<?php echo _CHOOSE_FILE; ?>" style="width: 85%;margin: 0px;margin-top: -10px;font-size: 12px;text-align: center;text-overflow: ellipsis;overflow: hidden;">
+        <?php } ?>
+    <p style="display:none">
+        <input type="file" name="file" id="file" onchange="$('with_file').value='false';this.form.method = 'post';this.form.submit();" value="<?php
+            if (isset($_SESSION['file_path'])) {
+                echo $_SESSION['file_path'];
+            } ?>" style="width:200px" />
+    </p>
+    <p style="display:none">
+        <div align="center">
+            <input type="radio" name="with_file" id="with_file" value="false" onclick="this.form.method = 'post';this.form.submit();" />
+        </div>
+    </p>
+</form>
+<?php 
+if (!empty($_SESSION['upfile'][0]['local_path']) && empty($_SESSION['error'])) { 
+    //launch auto convert in PDF
+    if (in_array(strtolower($_SESSION['upfile'][0]['format']), array('odt','docx','doc','docm'))) {
+        echo "<script>window.parent.$('add').value='Edition en cours ...';window.parent.editingDoc(this,'superadmin');window.parent.$('add').disabled='disabled';window.parent.$('add').style.opacity='0.5';</script>";
+        include_once 'modules/content_management/class/class_content_manager_tools.php';
 
-            $onlyConvert = "true";
-            $cM->generateJNLP(
-                $path_appli,
-                $path_appli . '/' . $path,
-                'newAttachment',
-                'res_letterbox',
-                //$aTemplateId,
-                $_SESSION['doc_id'],
-                '',
-                $cookieKey,
-                $_SESSION['user']['UserId'],
-                $_SESSION['clientSideCookies'], 
-                $_SESSION['modules_loaded']['attachments']['convertPdf'],
-                $onlyConvert
-            );
+        $cM = new content_management_tools();
+        if (
+            file_exists('custom'.DIRECTORY_SEPARATOR. $_SESSION['custom_override_id']
+                        . DIRECTORY_SEPARATOR . 'modules'. DIRECTORY_SEPARATOR . 'content_management'
+                        . DIRECTORY_SEPARATOR . 'applet_controller.php'
+            )
+        ) {
+            $path = 'custom/'. $_SESSION['custom_override_id'] .'/modules/content_management/applet_controller.php';
+        } else {
+            $path = 'modules/content_management/applet_controller.php';
         }
+        $path_appli = explode('/', $_SESSION['config']['coreurl']);
+        if (count($path_appli) <> 5) {
+            $path_appli = array_slice($path_appli, 0, 4);
+            $path_appli = implode('/', $path_appli);
+        } else {
+            $path_appli = implode('/', $path_appli);
+        }
+        // require_once 'core/class/class_db_pdo.php';
+        // $database = new Database();
+        // $query = "select template_id from templates where template_type = 'OFFICE' and template_target = 'attachments'";
+        // $stmt = $database->query($query);
+        // $aTemplateId = $stmt->fetchObject()->template_id;
+        $cookieKey = $_SESSION['sessionName'] . '=' . $_COOKIE[$_SESSION['sessionName']];
+
+        $onlyConvert = "true";
+        $cM->generateJNLP(
+            $path_appli,
+            $path_appli . '/' . $path,
+            'newAttachment',
+            'res_letterbox',
+            $_SESSION['doc_id'],
+            '0',
+            $cookieKey,
+            $_SESSION['user']['UserId'],
+            $_SESSION['clientSideCookies'], 
+            $_SESSION['modules_loaded']['attachments']['convertPdf'],
+            $onlyConvert
+        );
     }
-    $core_tools->load_js();?>
-    </body>
+}
+?>
+</body>
 </html>
 
diff --git a/modules/attachments/class/attachments_controler_Abstract.php b/modules/attachments/class/attachments_controler_Abstract.php
index 5ea79e49704..0002b4d76bd 100755
--- a/modules/attachments/class/attachments_controler_Abstract.php
+++ b/modules/attachments/class/attachments_controler_Abstract.php
@@ -238,7 +238,130 @@ abstract class attachments_controler_Abstract
         );
         return $returnArray;
     }
-	
+    
+    public function initAttachmentInfos($resId){
+		$db = new Database();
+		
+		$stmt = $db->query("SELECT subject, exp_contact_id, dest_contact_id, exp_user_id, address_id, dest_user_id, alt_identifier FROM res_view_letterbox WHERE res_id = ?",array($resId));
+        $data_attachment = $stmt->fetchObject();
+
+        $infos['title'] = $data_attachment->subject;
+
+        if ($data_attachment->dest_contact_id <> "") {
+
+            $infos['contact_id'] = $data_attachment->dest_contact_id;
+            $infos['address_id'] = $data_attachment->address_id;
+
+            $stmt = $db->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
+                                FROM view_contacts 
+                                WHERE contact_id = ? and ca_id = ?', array($data_attachment->dest_contact_id,$data_attachment->address_id));
+        } else if ($data_attachment->exp_contact_id <> "") {
+            $infos['contact_id'] = $data_attachment->exp_contact_id;
+            $infos['address_id'] = $data_attachment->address_id;
+            $stmt = $db->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
+                                FROM view_contacts 
+                                WHERE contact_id = ? and ca_id = ?', array($data_attachment->exp_contact_id,$data_attachment->address_id));       
+        } else if ($data_attachment->dest_user != '') {
+            $infos['contact_id'] = $data_attachment->dest_user;
+            $infos['address_id'] = $data_attachment->address_id;
+            $stmt = $db->query('SELECT lastname, firstname FROM users WHERE user_id = ?', [$data_attachment->dest_user]);
+        } else if ($data_attachment->exp_user_id != '') {
+            $infos['contact_id'] = $data_attachment->exp_user_id;
+            $infos['address_id'] = $data_attachment->address_id;
+            $stmt = $db->query('SELECT lastname, firstname FROM users WHERE user_id = ?', [$data_attachment->exp_user_id]);
+        } else if ($data_attachment->dest_user_id != '') {
+            $infos['contact_id'] = $data_attachment->dest_user_id;
+            $infos['address_id'] = $data_attachment->address_id;
+            $stmt = $db->query('SELECT lastname, firstname FROM users WHERE user_id = ?', [$data_attachment->dest_user_id]);
+        }
+    
+        if ($data_attachment->exp_contact_id <> '' || $data_attachment->dest_contact_id <> '') {
+            $res = $stmt->fetchObject();
+            if ($res->is_corporate_person == 'Y') {
+                $data_contact = $res->society;
+                if (!empty ($res->society_short)) {
+                    $data_contact .= ' ('.$res->society_short.')';
+                }
+                if (!empty($res->lastname) || !empty($res->firstname)) {
+                    $data_contact .= ' - ' . $res->lastname . ' ' . $res->firstname;
+                }
+                $data_contact .= ', ';
+            } else {
+                $data_contact .= $res->contact_lastname . ' ' . $res->contact_firstname;
+                if (!empty ($res->society)) {
+                    $data_contact .= ' (' .$res->society . ')';
+                }
+                $data_contact .= ', ';
+            }
+            if ($res->is_private == 'Y') {
+                $data_contact .= '(' . _CONFIDENTIAL_ADDRESS . ')';
+            } else {
+                $data_contact .= $res->address_num . ' ' . $res->address_street . ' ' . strtoupper($res->address_town);
+            }
+            $infos['contact_show'] = $data_contact;
+        } else if ($data_attachment->exp_user_id != '' || $data_attachment->dest_user != '' || $data_attachment->dest_user_id != '') {
+            $res = $stmt->fetchObject();
+            if (!empty($res->lastname) || !empty($res->firstname)) {
+                $data_contact .= $res->lastname . ' ' . $res->firstname;
+            }
+            $infos['contact_show'] = $data_contact;
+        //si multicontact
+        } else {
+            $stmt = $db->query("SELECT cr.address_id, c.contact_id, c.is_corporate_person, c.society, c.society_short, c.firstname, c.lastname,ca.is_private,ca.address_street, ca.address_num, ca.address_town 
+                                FROM contacts_res cr, contacts_v2 c, contact_addresses ca 
+                                WHERE cr.res_id = ? and cast(c.contact_id as char) = cast(cr.contact_id as char) and ca.contact_id=c.contact_id and ca.id=cr.address_id",array($_SESSION['doc_id']));
+            $i=0;
+            while($multi_contacts_attachment = $stmt->fetchObject()){
+                if(is_integer($multi_contacts_attachment->contact_id)){
+                    $format_contact='';
+                    $stmt2 = $db->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
+                                    FROM view_contacts 
+                                    WHERE contact_id = ? and ca_id = ?',array($multi_contacts_attachment->contact_id,$multi_contacts_attachment->address_id));
+        
+                    $res = $stmt2->fetchObject();
+                    if ($res->is_corporate_person == 'Y') {
+                        $format_contact = $res->society;
+                        if (!empty ($res->society_short)) {
+                            $format_contact .= ' ('.$res->society_short.')';
+                        }
+                        if (!empty($res->lastname) || !empty($res->firstname)) {
+                            $format_contact .= ' - ' . $res->lastname . ' ' . $res->firstname;
+                        }
+                        $format_contact .= ', ';
+                    } else {
+                        $format_contact .= $res->contact_lastname . ' ' . $res->contact_firstname;
+                        if (!empty ($res->society)) {
+                            $format_contact .= ' (' .$res->society . ')';
+                        }
+                        $format_contact .= ', ';
+                    }
+                    if ($res->is_private == 'Y') {
+                        $format_contact .= '('._CONFIDENTIAL_ADDRESS.')';
+                    } else {
+                        $format_contact .= $res->address_num .' ' . $res->address_street .' ' . strtoupper($res->address_town);                         
+                    }
+                    $contacts[] = array(
+                        'contact_id'     => $multi_contacts_attachment->contact_id,
+                        'firstname'      => $multi_contacts_attachment->firstname,
+                        'lastname'       => $multi_contacts_attachment->lastname,
+                        'society'        => $multi_contacts_attachment->society,
+                        'address_id'     => $multi_contacts_attachment->address_id,
+                        'format_contact' => $format_contact
+                    );
+        
+                    if($i==0){
+                        $data_contact                    = $format_contact; 
+                        $data_attachment->exp_contact_id = $multi_contacts_attachment->contact_id;
+                    }
+                    $i++;
+                } 
+            }
+            $infos['multi_contact'] = $contacts;
+        }
+		
+		return $infos;
+    }
+    
 	public function getAttachmentInfos($resId){
 		$db = new Database();
 		
@@ -287,8 +410,66 @@ abstract class attachments_controler_Abstract
 			$infos['type_id'] = $line->type_id;
 			$infos['title'] = $line->title;
             $infos['typist'] = $line->typist;
+            $infos['validation_date'] = $line->validation_date;
+            $infos['effective_date'] = $line->effective_date;
             $infos['res_id_master'] = $line->res_id_master;
-			$infos['identifier'] = $line->identifier;
+            $infos['identifier'] = $line->identifier;
+            if (!empty($line->res_id_version)) {
+                $infos['is_version'] =  true;
+                if (empty($infos['target_table_origin'])) {
+                    $infos['target_table_origin'] = 'res_version_attachments';
+                }
+            }else{
+                $infos['is_version'] =  false;
+                if (empty($infos['target_table_origin'])) {
+                    $infos['target_table_origin'] = 'res_attachments';
+                }
+            }
+            
+            //contact
+            if (!empty($line->dest_user)) {
+                $stmt = $db->query(
+                    "SELECT user_id,lastname,firstname 
+                        FROM users 
+                        WHERE user_id = ?", array($line->dest_user)
+                );
+                $res = $stmt->fetchObject();
+                $data_contact = $res->lastname . ' ' . $res->firstname;
+                $infos['contact_id'] = $res->user_id;
+                $infos['contact_show'] = $data_contact;
+            } else {
+                $stmt = $db->query(
+                    "SELECT * 
+                        FROM view_contacts 
+                        WHERE contact_id = ? and ca_id = ?", array($line->dest_contact_id,$line->dest_address_id)
+                );
+                $res = $stmt->fetchObject();
+                if ($res->is_corporate_person == 'Y') {
+                    $data_contact = $res->society;
+                    if (!empty ($res->society_short)) {
+                        $data_contact .= ' ('.$res->society_short.')';
+                    }
+                    if (!empty($res->lastname) || !empty($res->firstname)) {
+                        $data_contact .= ' - ' . $res->lastname . ' ' . $res->firstname;
+                    }
+                    $data_contact .= ', ';
+                } else {
+                    $data_contact .= $res->contact_lastname . ' ' . $res->contact_firstname;
+                    if (!empty ($res->society)) {
+                        $data_contact .= ' (' .$res->society . ')';
+                    }
+                    $data_contact .= ', ';
+                }
+                if ($res->is_private == 'Y') {
+                    $data_contact .= '(' . _CONFIDENTIAL_ADDRESS . ')';
+                } else {
+                    $data_contact .= $res->address_num . ' ' . $res->address_street . ' ' . strtoupper($res->address_town);
+                }
+                $infos['contact_id'] = $line->dest_contact_id;
+                $infos['address_id'] = $line->dest_address_id;
+                $infos['contact_show'] = $data_contact;
+            }
+
 		}
 		return $infos;
 	}
diff --git a/modules/attachments/css/module.css b/modules/attachments/css/module.css
index 593c6efb6c8..5712e659c17 100755
--- a/modules/attachments/css/module.css
+++ b/modules/attachments/css/module.css
@@ -14,7 +14,7 @@
     margin : 2px 2px 0 2px !important;  /* Pour les navigateurs autre que IE */
     margin : 1px 2px 0 2px;  /* Pour IE  */
     border : 1px solid #9EA0A1;
-    min-width  : 30%;
+    /*min-width  : 30%;*/
     text-align: center;
     font-family: Verdana,Geneva,Arial,Helvetica,sans-serif;
 }
diff --git a/modules/attachments/del_attachment.php b/modules/attachments/del_attachment.php
index 7846e87b0b9..4ff17ee98e4 100755
--- a/modules/attachments/del_attachment.php
+++ b/modules/attachments/del_attachment.php
@@ -4,144 +4,97 @@
 * See LICENCE.txt file at the root folder for more details.
 * This file is part of Maarch software.
 
+*
 * @brief   del_attachment
+*
 * @author  dev <dev@maarch.org>
 * @ingroup attachments
 */
-
-require_once "core/class/class_security.php";
-require_once "core/class/class_request.php";
-require_once "core/class/class_resource.php";
-require_once "core/class/class_history.php";
+require_once 'core/class/class_security.php';
+require_once 'core/class/class_request.php';
+require_once 'core/class/class_resource.php';
+require_once 'core/class/class_history.php';
 require_once 'modules/attachments/attachments_tables.php';
 require_once 'modules/attachments/class/attachments_controler.php';
 $core = new core_tools();
 $core->load_lang();
+$core->load_js();
 
 $func = new functions();
 $ac = new attachments_controler();
-
 $db = new Database();
 
+//RETRIEVE INFO CURRENT ATTACHMENT
 $info_doc = $ac->getAttachmentInfos($_REQUEST['id']);
+$pdf_id = $ac->getCorrespondingPdf($_REQUEST['id']);
 
-if ($_REQUEST['relation'] == 1) {
-    $stmt = $db->query("UPDATE " . RES_ATTACHMENTS_TABLE . " SET status = 'DEL' WHERE res_id = ?", array($_REQUEST['id']));
-    $pdf_id = $ac->getCorrespondingPdf($_REQUEST['id']);
-    if (isset($pdf_id) && $pdf_id != 0) $stmt = $db->query("UPDATE " . RES_ATTACHMENTS_TABLE . " SET status = 'DEL' WHERE res_id = ?", array($pdf_id));
-    $document = $ac->getCorrespondingDocument($_REQUEST['id']);
-    $document_relation = $document->relation;
-    $attach_type = $_SESSION['attachment_types'][$document->attachment_type];
-    if ($document_relation == 1) {
-        $target_table = "res_attachments";
-        $document_id = $document->res_id;
-        $is_version = 0;
+//DEL CURRENT ATTACHMENT
+$stmt = $db->query("UPDATE {$info_doc['target_table_origin']}  SET status = 'DEL' WHERE res_id = ?", array($_REQUEST['id']));
 
-    } else {
-        $target_table = "res_version_attachments";
-        $document_id = $document->res_id_version;
-        $is_version = 1;
-    }
+//DEL CONVERTED PDF
+if ($pdf_id != 0) {
+    $stmt = $db->query('UPDATE '.RES_ATTACHMENTS_TABLE." SET status = 'DEL' WHERE res_id = ?", array($pdf_id));
+}
 
-    if (isset($document_id) && $document_id != 0) $stmt = $db->query("UPDATE " . $target_table . " SET status = 'A_TRA' WHERE res_id = ?", array($document_id));
-    
-} else {
-    $stmt = $db->query("SELECT attachment_id_master FROM res_version_attachments WHERE res_id = ?", array($_REQUEST['id']));
-    $res=$stmt->fetchObject();
+// IS VERSION ATTACHMENT ?
+if ($info_doc['is_version'] == true && $info_doc['status'] != 'TMP') {
+    //DEL PREVIOUS ATTACHMENT VERSION
+    $stmt = $db->query('SELECT attachment_id_master FROM res_version_attachments WHERE res_id = ?', array($_REQUEST['id']));
+    $res = $stmt->fetchObject();
     $stmt = $db->query("UPDATE res_version_attachments SET status = 'DEL' WHERE attachment_id_master = ?", array($res->attachment_id_master));
     $stmt = $db->query("UPDATE res_attachments SET status = 'DEL' WHERE res_id = ?", array($res->attachment_id_master));
-    
-    $pdf_id = $ac->getCorrespondingPdf($_REQUEST['id']);
-    if (isset($pdf_id) && $pdf_id != 0) $stmt = $db->query("UPDATE " . RES_ATTACHMENTS_TABLE . " SET status = 'DEL' WHERE res_id = ?", array($pdf_id));
-    $document = $ac->getCorrespondingDocument($_REQUEST['id']);
-    $document_id = $document->res_id;
-    $document_relation = $document->relation;
-    $attach_type = $_SESSION['attachment_types'][$document->attachment_type];
-    
-    if ($document_relation == 1) {
-        $target_table = "res_attachments";
-        $document_id = $document->res_id;
-
-    } else {
-        $target_table = "res_version_attachments";
-        $document_id = $document->res_id_version;
-    }
-
-    if (isset($document_id) && $document_id != 0) {
-        $stmt = $db->query("UPDATE " . $target_table . " SET status = 'A_TRA' WHERE res_id = ?", array($document_id));
-    } 
 }
 
-if ($_SESSION['history']['attachdel'] == "true") {
+//LOG DELETE ACTION IN HISTORY
+if ($_SESSION['history']['attachdel'] == 'true') {
     $hist = new history();
-    if (! isset($_SESSION['collection_id_choice'])
-        || empty($_SESSION['collection_id_choice'])
-    ) {
-        $_SESSION['collection_id_choice'] = $_SESSION['user']['collections'][0];
-    }
-    $sec = new security();
-    $view = $sec->retrieve_view_from_coll_id($_SESSION['collection_id_choice']);
-    if ($_REQUEST['relation'] == 1) {
-        $stmt = $db->query("SELECT res_id_master FROM " . RES_ATTACHMENTS_TABLE . " WHERE res_id = ?", array($_REQUEST['id']));
-    } else {
-        $stmt = $db->query("SELECT res_id_master FROM res_version_attachments WHERE res_id = ?", array($_REQUEST['id']));
-    }
-
-    $res = $stmt->fetchObject();
-    $resIdMaster = $res->res_id_master;
     $hist->add(
-        $view, $resIdMaster, "DEL", 'attachdel', _ATTACH_DELETED . ' ' . _ON_DOC_NUM
-        . $resIdMaster . "  (" . $_REQUEST['id'] . ')',
-        $_SESSION['config']['databasetype'], "attachments"
+        $view, $resIdMaster, 'DEL', 'attachdel', _ATTACH_DELETED.' '._ON_DOC_NUM
+        .$info_doc['res_id_master'].'  ('.$_REQUEST['id'].')',
+        $_SESSION['config']['databasetype'], 'attachments'
     );
     $hist->add(
-        RES_ATTACHMENTS_TABLE, $_REQUEST['id'], "DEL", 'attachdel', _ATTACH_DELETED . " : "
-        . $_REQUEST['id'], $_SESSION['config']['databasetype'], "attachments"
+        RES_ATTACHMENTS_TABLE, $_REQUEST['id'], 'DEL', 'attachdel', _ATTACH_DELETED.' : '
+        .$_REQUEST['id'], $_SESSION['config']['databasetype'], 'attachments'
     );
+    echo '<script>$j("#main_error",window.parent.document).html(\''._ATTACH_DELETED.' : '.$_REQUEST['id'].'\').show().delay(5000).fadeOut();</script>';
 }
 
+//SIGNATURE BOOK
 if (!empty($_REQUEST['rest'])) {
     echo '{"status" : "ok"}';
     exit;
 }
 
-if ($_REQUEST['relation'] == 1) {
-    $stmt = $db->query("SELECT res_id_master FROM " . RES_ATTACHMENTS_TABLE . " WHERE res_id = ?", array($_REQUEST['id']));
-} else {
-    $stmt = $db->query("SELECT res_id_master FROM res_version_attachments WHERE res_id = ?", array($_REQUEST['id']));
-}
-
-$res = $stmt->fetchObject();
-$resIdMaster = $res->res_id_master;
-$query = "SELECT title FROM res_view_attachments WHERE status NOT IN ('DEL','OBS','TMP') and res_id_master = ?";
+//REFRESH TABS
+$query = "SELECT count(1) as total FROM res_view_attachments WHERE status NOT IN ('DEL','OBS','TMP') and res_id_master = ?";
 if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
     $query .= " and (attachment_type <> 'response_project' and attachment_type <> 'outgoing_mail_signed' and attachment_type <> 'signed_response' and attachment_type <> 'converted_pdf' and attachment_type <> 'outgoing_mail' and attachment_type <> 'print_folder' and attachment_type <> 'aihp')";
-} else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response') {
+} elseif (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response') {
     $query .= " and (attachment_type = 'response_project' or attachment_type = 'outgoing_mail_signed' or attachment_type = 'outgoing_mail' or attachment_type = 'signed_response' or attachment_type = 'aihp')";
-
 } else {
     $query .= " and attachment_type NOT IN ('converted_pdf','print_folder')";
 }
-$stmt = $db->query($query, array($resIdMaster));
-if ($stmt->rowCount() > 0) {
-    $new_nb_attach = $stmt->rowCount();
-} else {
-    $new_nb_attach = 0;
-}
+$stmt = $db->query($query, array($info_doc['res_id_master']));
+$new_nb_attach = $stmt->total;
 ?>
 <script type="text/javascript">
-
     var eleframe1 =  parent.document.getElementsByName('list_attach');
     if(eleframe1[0] === undefined){
-        eleframe1 =  parent.document.getElementsByName('responses_iframe');
+        eleframe1 =  parent.document.getElementsByName('uniqueDetailsIframe');
     }
-    var nb_attach = '<?php functions::xecho($new_nb_attach);?>';
-    <?php if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') { ?>
-        eleframe1[0].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load&attach_type_exclude=response_project,signed_response,outgoing_mail_signed,converted_pdf,outgoing_mail,print_folder,aihp&fromDetail=attachments';?>";
-    <?php } else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response') { ?>
-        eleframe1[0].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load&attach_type=response_project,outgoing_mail_signed,signed_response,outgoing_mail,aihp&fromDetail=response';?>";
-    <?php } else { ?>
-        parent.document.getElementById('list_attach').src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&template_selected=documents_list_attachments_simple&page=frame_list_attachments&load&attach_type_exclude=converted_pdf,print_folder';?>";
-    <?php } ?>
-
+    var nb_attach = '<?php functions::xecho($new_nb_attach); ?>';
+    <?php if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
+    ?>
+        eleframe1[0].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load&attach_type_exclude=response_project,signed_response,outgoing_mail_signed,converted_pdf,outgoing_mail,print_folder,aihp&fromDetail=attachments'; ?>";
+    <?php
+} elseif (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response') {
+        ?>
+        eleframe1[0].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load&attach_type=response_project,outgoing_mail_signed,signed_response,outgoing_mail,aihp&fromDetail=response'; ?>";
+    <?php
+    } else {
+        ?>
+        parent.document.getElementById('list_attach').src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&template_selected=documents_list_attachments_simple&page=frame_list_attachments&load&attach_type_exclude=converted_pdf,print_folder'; ?>";
+    <?php
+    } ?>
 </script>
diff --git a/modules/attachments/get_chrono_attachment.php b/modules/attachments/get_chrono_attachment.php
index 712a24c44e6..3516df8e00e 100755
--- a/modules/attachments/get_chrono_attachment.php
+++ b/modules/attachments/get_chrono_attachment.php
@@ -1,84 +1,63 @@
 <?php
-
-/*
-*   Copyright 2015 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   Chrono for attachments
-*
-* Open a modal box to displays the indexing form, make the form checks and loads
-* the result in database. Used by the core (manage_action.php page).
-*
-* @file
-* @author <dev@maarch.org>
-* @date $date$
-* @version $Revision$
-* @ingroup apps
-*/
-
-    require_once 'core' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_request.php';
-    require_once 'apps' . DIRECTORY_SEPARATOR . $_SESSION['config']['app_id']
-        . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_chrono.php';
-    require_once("core".DIRECTORY_SEPARATOR."class".DIRECTORY_SEPARATOR."class_security.php");
-
-    $core = new core_tools();
-    $core->test_user();
-    $db = new Database();
-    $sec = new security();
+* 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.
 
-        $view = $sec->retrieve_view_from_coll_id($_SESSION['collection_id_choice']);
-        if(empty($view))
-        {
-            $view = $sec->retrieve_table_from_coll($_SESSION['collection_id_choice']);
-        }
-
-        $stmt = $db->query("SELECT category_id FROM ".$view." WHERE res_id = ? ", array($_SESSION['doc_id']));
-        $resMaster = $stmt->fetchObject();
-
-        $category_id = $resMaster->category_id;
-
-        $nb_attachment = 0;
-
-        // Check if reponse project was already attached to this outgoing document.
-        if ($category_id == "outgoing") {
-                $stmt = $db->query("SELECT res_id FROM res_view_attachments WHERE res_id_master = ? and (attachment_type = 'response_project' or attachment_type = 'outgoing_mail') and status <> 'DEL' and status <> 'OBS'"
-                                    ,array($_SESSION['doc_id']));
-                $nb_attachment = $stmt->rowCount();
-        }
-
-        if ($category_id == "attachment" || $category_id == "incoming" || $category_id == "internal" || ($category_id == "outgoing" && $nb_attachment > 0)){
-            if (isset($_SESSION['save_chrono_number']) && $_SESSION['save_chrono_number'] <> "") {
-                echo "{status: 1, chronoNB: '".$_SESSION['save_chrono_number']."'}";
-            } else {
-                $chronoX = new chrono();
-                $myVars = array(
-                    'category_id' => 'outgoing',
-                    'entity_id' => $_SESSION['user']['primaryentity']['id']
-                );
+* @brief   get_chrono_attachment
+* @author  dev <dev@maarch.org>
+* @ingroup attachments
+*/
 
-                $myChrono = $chronoX->generate_chrono('outgoing', $myVars);
-                $_SESSION['save_chrono_number'] = $myChrono;
-                echo "{status: 1, chronoNB: '".functions::xssafe($myChrono)."'}";
-            }
-        } else if ($category_id == "outgoing" && $nb_attachment == 0) {
-            $stmt = $db->query("SELECT alt_identifier FROM ".$view." WHERE res_id = ?", array($_SESSION['doc_id']));
-            $chronoMaster = $stmt->fetchObject();
-            echo "{status: 1, chronoNB: '".functions::xssafe($chronoMaster->alt_identifier)."'}";
-        }
+require_once 'core' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_request.php';
+require_once 'apps' . DIRECTORY_SEPARATOR . $_SESSION['config']['app_id']
+    . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_chrono.php';
+require_once("core".DIRECTORY_SEPARATOR."class".DIRECTORY_SEPARATOR."class_security.php");
+
+$core = new core_tools();
+$core->test_user();
+$db = new Database();
+$sec = new security();
+
+$view = $sec->retrieve_view_from_coll_id($_SESSION['collection_id_choice']);
+if(empty($view))
+{
+    $view = $sec->retrieve_table_from_coll($_SESSION['collection_id_choice']);
+}
+$index = $_REQUEST['index'];
+
+//RETRIEVE CATEGORY OF DOCUMENT
+$stmt = $db->query("SELECT category_id FROM ".$view." WHERE res_id = ? ", array($_SESSION['doc_id']));
+$resMaster = $stmt->fetchObject();
+$category_id = $resMaster->category_id;
+
+$nb_attachment = 0;
+
+// Check if reponse project was already attached to this outgoing document.
+if ($category_id == "outgoing") {
+    $stmt = $db->query("SELECT res_id FROM res_view_attachments WHERE res_id_master = ? and (attachment_type = 'response_project' or attachment_type = 'outgoing_mail') and status <> 'DEL' and status <> 'OBS'"
+                        ,array($_SESSION['doc_id']));
+    $nb_attachment = $stmt->rowCount();
+}
+if ($category_id == "attachment" || $category_id == "incoming" || $category_id == "internal" || ($category_id == "outgoing" && $nb_attachment > 0)){
+
+    if (isset($_SESSION['save_chrono_number']) && $_SESSION['save_chrono_number'][$index] <> "") {
+        echo "{status: 1, chronoNB: '".$_SESSION['save_chrono_number'][$index]."'}";
+    } else {
+        //GENERATE NEW CHRONO
+        $chronoX = new chrono();
+        $myVars = array(
+            'category_id' => 'outgoing',
+            'entity_id' => $_SESSION['user']['primaryentity']['id']
+        );
+
+        $myChrono = $chronoX->generate_chrono('outgoing', $myVars);
+        $_SESSION['save_chrono_number'][$index] = $myChrono;
+        echo "{status: 1, chronoNB: '".functions::xssafe($myChrono)."'}";
+    }
+} else if ($category_id == "outgoing" && $nb_attachment == 0) {
+    $stmt = $db->query("SELECT alt_identifier FROM ".$view." WHERE res_id = ?", array($_SESSION['doc_id']));
+    $chronoMaster = $stmt->fetchObject();
+    echo "{status: 1, chronoNB: '".functions::xssafe($chronoMaster->alt_identifier)."'}";
+}
 
diff --git a/modules/attachments/js/functions.js b/modules/attachments/js/functions.js
index 069e830ed5e..d1ae0e98caf 100755
--- a/modules/attachments/js/functions.js
+++ b/modules/attachments/js/functions.js
@@ -1,7 +1,6 @@
 // Date + 60 jours, utile pour les transmissions
-function defineBackDate() {
+function defineBackDate(delay) {
 	var date1 = new Date();
-	var delay = $j('#withDelay')[0].value;
 	date1.setDate(date1.getDate() + Number(delay));
 	var str_date = date1.toLocaleDateString();
     var t = str_date.split('/');
@@ -59,211 +58,58 @@ function setRturnForEffectiveDate() {
   $('effectiveDateStatus').selectedIndex = 1;
 }
 
-function saveContactToSession(size, prePath) {
+function saveContactToSession(target) {
 
   setTimeout(function() {
-    var contactId = $("transmissionContactidAttach" + size).value;
-    var addressId = $("transmissionAddressidAttach" + size).value;
-    console.log(contactId);
-    console.log(addressId);
+    var transmissionContactidAttach = [];
+    var transmissionAddressidAttach = [];
+    
+    $j('#formAttachment #addAttach1').each(function (index) {
+        if ($j('#formAttachment #addAttach1').find('[name=attachment_types\\[\\]]').eq(index).val() == 'transmission') {
+            var item1 = {
+                "index": index,
+                "val": $j('#formAttachment #addAttach1').find('[name=contactidAttach\\[\\]]').eq(index).val(),
+            };
+            transmissionContactidAttach.push(item1);
+            var item2 = {
+                "index": index,
+                "val": $j('#formAttachment #addAttach1').find('[name=addressidAttach\\[\\]]').eq(index).val(),
+            };
+            transmissionAddressidAttach.push(item2);
+        }        
+    });
 
-    if (contactId) {
-      new Ajax.Request(prePath + "index.php?display=true&module=attachments&page=saveTransmissionContact",
-        {
-          method:'post',
-          parameters: {
-            size      : size,
-            contactId : contactId,
-            addressId : addressId
-          }
-        });
-    }
+    $j.ajax({
+        type: "POST",
+        data: {
+            transmissionContactidAttach : transmissionContactidAttach,
+            transmissionAddressidAttach : transmissionAddressidAttach
+        },
+        url: "index.php?display=true&module=attachments&page=saveTransmissionContact",
+        success: function(msg){
+            
+        }
+    });
 
   }, 500);
 }
 
-function displayTransmissionContactCard(mode, id, size)
-{
-  var contactCard = $(id);
-
-  var contactId = $("transmissionContact_attach" + size).value;
-
-  if(contactCard && (mode == 'hidden' || mode == 'visible') && contactId != '') {
-    contactCard.style.visibility = mode;
-  } else if (contactId == '') {
-    contactCard.style.visibility = "hidden";
-  }
-}
-
-function disableTransmissionButton(currentValue) {
-  var size = $('transmission').childElementCount;
-
-  for (var i = 1; i <= size; i++) {
-    $('transmission').lastElementChild.remove();
-  }
-
-  var addButton = $('newTransmissionButton0');
-
-  addButton.style.display = "";
-  if (currentValue == "" || $("chrono_display").style.display == "none") {
-    addButton.style.opacity = 0.5;
-  } else {
-    addButton.style.opacity = 1;
-  }
-}
-
-function showOrButtonForAttachment() {
-  if ($("edit").style.display != "none" && $("newTransmissionButton0").style.display != "none") {
-    $("divOr0").style.display = "";
-  } else {
-    $("divOr0").style.display = "none";
-  }
-}
-
-function showTransmissionEditButton(currentValue, editParagraph, size) {
-  if (currentValue == "") {
-    $(editParagraph).style.display = "none";
-    $("divOr" + size).style.display = "none";
-  } else {
-    $(editParagraph).style.display = "";
-    if ($("newTransmissionButton" + size).style.display != "none")
-      $("divOr" + size).style.display = "";
-  }
-}
 
 function hideEditAndAddButton(editParagraph) {
   $(editParagraph).style.display = "none";
 }
 
-function delLastTransmission() {
-
-  var size = $('transmission').childElementCount;
-
-  if ($('delTransmissionButton' + size).style.opacity == 1) {
-    if (size >= 1) {
-      $('transmission').lastElementChild.remove();
-
-      $('newTransmissionButton' + (size - 1)).style.display = "";
-      if (size > 1) {
-        $('delTransmissionButton' + (size - 1)).style.display = "";
-        if ($("paraEdit" + (size - 1)).style.display != "none")
-          $("divOr" + (size - 1)).style.display = "";
-      } else if (size == 1) {
-        if ($("edit").style.display != "none")
-          $("divOr0").style.display = "";
-      }
-    }
-  }
-}
 
-function hideInput(currentValue, editDate) {
-	if (currentValue == "NO_RTURN") {
-		editDate.value = null
+function hideInput(target) {
+	if ($j('#'+target.id).val() == "NO_RTURN") {
+        $j('#'+target.id).parent().parent().find('[name=back_date\\[\\]]').val("");
 	} else {
-		editDate.value = defineBackDate();
+        var delay = $j('#'+target.id).parent().parent().find('[name=attachment_types\\[\\]] option:selected').attr("width_delay");
+        var delay_date = defineBackDate(delay);
+        $j('#'+target.id).parent().parent().find('[name=back_date\\[\\]]').val(delay_date);
 	}
 }
 
-function addNewTransmission(prePath, docId, canCreateContact, langString, user) {
-  var size = $j('#transmission')[0].childElementCount;
-  
-  var extra_js = '$("add").value="Edition en cours ...";editingDoc("'+user+'");$("add").disabled="disabled";$("add").style.opacity="0.5";';
-
-  if ($('newTransmissionButton' + size).style.opacity == 1) {
-
-    var div = document.createElement('div');
-    $('transmission').appendChild(div);
-    size = $('transmission').childElementCount;
-
-    $('newTransmissionButton' + (size - 1)).style.display = "none";
-    $("divOr" + (size - 1)).style.display = "none";
-    if (size > 1) {
-      $('delTransmissionButton' + (size - 1)).style.display = "none";
-    }
-
-    div.className = "transmissionDiv";
-    var content   = "<hr style='width:85%; height: 4px; margin-left:0px; margin-bottom:10px; margin-top: 10px'>" +
-                    "<p>" +
-                      "<label>" + "Type d'attachement" + "</label>" +
-                      "<select name='transmissionType" + size + "' id='transmissionType" + size + "' />" +
-                        "<option value='transmission'>Transmission</option>" +
-                      "</select>" +
-                      "&nbsp;<span class='red_asterisk'><i class='fa fa-star'></i></span>" +
-                    "</p>" +
-                    "<p>" +
-                      "<label>" + "Numéro chrono" + "</label>" +
-                      "<input type='text' name='DisTransmissionChrono" + size + "' id='DisTransmissionChrono" + size + "' disabled class='readonly' />" +
-                      "<input type='hidden' name='transmissionChrono" + size + "' id='transmissionChrono" + size + "' />" +
-                    "</p>" +
-                    "<p>" +
-                      "<label>" + "Fichier" + "</label>" +
-                      "<select name='transmissionTemplate" + size + "' id='transmissionTemplate" + size + "' style='display:inline-block;' onchange='showTransmissionEditButton(this.options[this.selectedIndex].value, paraEdit" + size + ", " + size + ")'>" +
-                      "</select>" +
-                      "&nbsp;<span class='red_asterisk'><i class='fa fa-star'></i></span>" +
-                    "</p>" +
-                    "<p>" +
-                      "<label>" + "Objet" + "</label>" +
-                      "<input type='text' name='transmissionTitle" + size + "' id='transmissionTitle" + size + "' maxlength='250' value='' />" +
-                      "&nbsp;<span class='red_asterisk'><i class='fa fa-star'></i></span>" +
-                    "</p>" +
-                    "<p>" +
-                      "<label>" + "Date de retour attendue" + "</label>" +
-                      "<input type='hidden' name='withDelay" + size + "' id='withDelay" + size + "' value='' style='width: 75px' />" +
-                      "<input type='text' name='transmissionBackDate" + size + "' id='transmissionBackDate" + size + "' onClick='showCalender(this);' onchange='checkBackDate(this)' onfocus='checkBackDate(this)' value='' style='width: 75px' />" +
-                      "<select name='transmissionExpectedDate" + size + "' id='transmissionExpectedDate" + size + "' style='margin-left: 20px;width: 105px' onchange = 'hideInput(this.options[this.selectedIndex].value,transmissionBackDate" + size +")'/>" +
-                        "<option value='EXP_RTURN'>Attente retour</option>" +
-                        "<option value='NO_RTURN'>Pas de retour</option>" +
-                      "</select>" +
-                    "</p>";
-
-                    if (canCreateContact) {
-    content +=        "<label>" + "Destinataire" +
-                        " <a href='#' title='" + "Ajouter un contact ou une adresse" + "' " +
-                          "onclick='document.getElementById(\"contact_iframe_attach\").src=\"index.php?display=false&dir=my_contacts&page=create_contact_iframe&fromAttachmentContact=Y&transmissionInput="+size+"\";new Effect.toggle(\"create_contact_div_attach\", \"blind\", {delay:0.2});return false;' style='display:inline;' >" +
-                          "<i class='fa fa-pencil fa-lg' title='" + "Ajouter un contact ou une adresse" + "'>" +
-                          "</i>" +
-                        "</a>" +
-                      "</label>";
-                    } else {
-    content +=        "<label>Destinataire</label>";
-                    }
-
-    content +=        "<span style='position:relative'><input type='text' name='transmissionContact_attach" + size + "' id='transmissionContact_attach" + size + "' value='' " +
-                        "onblur='displayTransmissionContactCard(\"visible\", \"transmissionContactCard" + size + "\", " + size + ");' " +
-                        "onkeyup='erase_contact_external_id(\"transmissionContact_attach" + size + "\", \"transmissionContactidAttach" + size + "\");erase_contact_external_id(\"transmissionContact_attach" + size + "\", \"transmissionAddressidAttach" + size + "\");' />" +
-                      "<a href='#' id='transmissionContactCard" + size + "' title='Fiche contact' onclick='document.getElementById(\"info_contact_iframe_attach\").src=\"" + prePath + "index.php?display=false&dir=my_contacts&page=info_contact_iframe&seeAllAddresses&contactid=\"+document.getElementById(\"transmissionContactidAttach"+size+"\").value+\"&addressid=\"+document.getElementById(\"transmissionAddressidAttach"+size+"\").value+\"\";new Effect.toggle(\"info_contact_div_attach\", \"blind\", {delay:0.2});return false;' style='visibility:hidden;'> " +
-                        "<i class='fa fa-book fa-lg'></i>" +
-                      "</a>" +
-                    "<div id='transmission_show_contacts_attach" + size + "' class='autocomplete autocompleteIndex' style='display: none;width:100%;left:0px;'></div></span>" +
-
-                    "<input type='hidden' id='transmissionContactidAttach" + size + "' name='transmissionContactidAttach" + size + "' value='' onchange='saveContactToSession(\"" + size + "\", \"" + prePath + "\")' />" +
-                    "<input type='hidden' id='transmissionAddressidAttach" + size + "' name='transmissionAddressidAttach" + size + "' value='' />" +
-                    "<p><div style='float: left;display: none;margin-bottom: 5px' id='paraEdit" + size + "'>" +
-                      "<input type='button' style='margin-top: 0' value='" + "Editer" + "' name='transmissionEdit" + size + "' id='transmissionEdit" + size + "' class='button transmissionEdit' " +
-                        "onclick='showAppletLauncher(\"" + prePath + "index.php?display=true&module=content_management&page=applet_modal_launcher&transmissionNumber=" + size + "&objectType=transmission&objectId=\"+$(\"transmissionTemplate" + size + "\").value+\"&attachType=transmission&objectTable=res_letterbox&contactId=\"+$(\"contactidAttach\").value+\"&addressId=\"+$(\"addressidAttach\").value+\"&chronoAttachment=\"+$(\"transmissionChrono" + size + "\").value+\"&titleAttachment=\"+$(\"transmissionTitle" + size + "\").value+\"&back_date=\"+$(\"transmissionBackDate" + size + "\").value+\"&resMaster=" + docId + "\", \"100px\", \"500px\");" +
-                        "hideEditAndAddButton(paraEdit" + size + ");"+ extra_js +"' />" +
-                      "<span style='display: none' id='divOr" + size + "'>" +
-                        "&nbsp;ou&nbsp;" +
-                      "</span>" +
-                    "</div>" +
-                    "<div style='float: left'>" +
-                      "<i id='newTransmissionButton" + size + "' title='Nouvelle transmission' style='opacity: 1;cursor: pointer;' class='fa fa-plus-circle fa-2x' " +
-                        "onclick='addNewTransmission(\"" + prePath + "\", " + docId + ", " + canCreateContact + ")'></i>" +
-                      "&nbsp;" +
-                      "<i id='delTransmissionButton" + size + "' title='Supprimer la dernière transmission' style='opacity: 1;cursor: pointer;' class='fa fa-minus-circle fa-2x' " +
-                        "onclick='delLastTransmission()'></i>" +
-                    "</div></p>";
-
-    div.innerHTML = content;
-    $('transmissionChrono' + size).value = $('chrono').value + "." + String.fromCharCode(64 + size);
-    $('DisTransmissionChrono' + size).value = $('chrono').value + "." + String.fromCharCode(64 + size);
-    $('transmissionTitle' + size).value = $('title').value;
-    $('transmissionBackDate' + size).value = defineBackDate();
-    getTemplatesForSelect((prePath + "index.php?display=true&module=templates&page=select_templates"), "transmission", "transmissionTemplate" + size);
-    launch_autocompleter_contacts_v2(prePath + "index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "transmissionContact_attach" + size, "transmission_show_contacts_attach" + size, "", "transmissionContactidAttach" + size, "transmissionAddressidAttach" + size)
-  }
-}
-
 function getTemplatesForSelect(path_to_script, attachment_type, selectToChange)
 {
   new Ajax.Request(path_to_script,
@@ -304,15 +150,6 @@ function showAttachmentsForm(path, width, height) {
     });
 }
 
-function get_num_rep(res_id){
-	var trig_elements = document.getElementsByClassName('trig');
-	for (i=0; i<trig_elements.length; i++){
-		var id = trig_elements[i].id;
-		var splitted_id = id.split("_");
-		if (splitted_id.length == 3 && splitted_id[0] == 'ans' && splitted_id[2] == res_id) return splitted_id[1];
-	}
-	return 0;
-}
 function ValidAttachmentsForm(path, form_id, fromAngular) {
 
     new Ajax.Request(path,
@@ -323,7 +160,9 @@ function ValidAttachmentsForm(path, form_id, fromAngular) {
         encoding: 'UTF-8',
         onSuccess: function (answer) {
             eval("response = " + answer.responseText);
+
             if (response.status == 0) {
+
                 destroyModal('form_attachments');
 
                 if (typeof fromAngular != "undefined") {
@@ -350,30 +189,13 @@ function ValidAttachmentsForm(path, form_id, fromAngular) {
                         }
                     }
 
-                    if ($('cur_idAffich'))
-                        var num_rep = $('cur_idAffich').value;
-                    if ($('cur_resId'))
-                        var res_id_master = $('cur_resId').value;
-                    if (response.cur_id)
-                        var rep_id = response.cur_id;
-                    if (num_rep == 0)
-                        num_rep = get_num_rep(rep_id);
-
-                    if ($('viewframevalidRep' + num_rep + '_' + rep_id)) {
-                        if (response.majFrameId > 0) {
-                            $('viewframevalidRep' + num_rep + '_' + rep_id).src = "index.php?display=true&module=visa&page=view_pdf_attachement&res_id_master=" + res_id_master + "&id=" + response.majFrameId;
-                            if ($('cur_rep'))
-                                $('cur_rep').value = response.majFrameId;
-                            $('viewframevalidRep' + num_rep + '_' + rep_id).id = 'viewframevalidRep' + num_rep + '_' + response.majFrameId;
-                        }
-                        else
-                            $('viewframevalidRep' + num_rep + '_' + rep_id).src = $('viewframevalidRep' + num_rep + '_' + rep_id).src;
-                    }
+                    $j("#main_info").html(response.content).show().delay(5000).fadeOut();
 
                     eval(response.exec_js);
                 }
             } else {
-                alert(response.error);
+                $j("#main_error").css("opacity","1");
+                $j("#main_error").html(response.error).show().delay(5000).fadeOut();
             }
         }
     });
@@ -395,13 +217,12 @@ function modifyAttachmentsForm(path, width, height) {
                     },  
         onSuccess: function(answer) {
             eval("response = "+answer.responseText);
-           
             if(response.status == 0){
                 var modal_content = convertToTextVisibleNewLine(response.content);
                 createModalinAttachmentList(modal_content, 'form_attachments', height, width, 'fullscreen'); 
                 eval(response.exec_js);
             } else {
-                window.top.$('main_error').innerHTML = response.error;
+                alert(response.error);
             }
         }
     });
@@ -442,7 +263,6 @@ function createModalinAttachmentList(txt, id_mod, height, width, mode_frm){
     if($j('#rightPanelShowDocumentIframe')){
        $j('#rightPanelShowDocumentIframe').hide(); 
     }
-
     if(height == undefined || height=='') {
         height = '100px';
     }
@@ -466,8 +286,9 @@ function createModalinAttachmentList(txt, id_mod, height, width, mode_frm){
     var tmp_height = height;
     
     var layer_height = document.body.clientHeight;
-    
     var layer_width = window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 5;
+
+    
     var layer = new Element('div', {'id':id_layer, 'class' : 'lb1-layer', 'style' : "display:block;filter:alpha(opacity=70);opacity:.70;z-index:"+get_z_indexes()['layer']+';width :'+ (layer_width)+"px;height:"+layer_height+'px;'});
 
     if( mode_frm == 'fullscreen') {
@@ -486,25 +307,26 @@ function createModalinAttachmentList(txt, id_mod, height, width, mode_frm){
                 fenetre.style.width = (window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 55)+"px";
             }
         } else {
-            fenetre.style.width = (window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 30)+"px";
+            //fenetre.style.width = (window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 30)+"px";
+            fenetre.style.width = "98%";
         }
-        fenetre.style.height = (window.top.window.document.getElementsByTagName('body')[0].offsetHeight - 20)+"px";
+        //fenetre.style.height = (window.top.window.document.getElementsByTagName('body')[0].offsetHeight - 20)+"px";
+        fenetre.style.height = "95%";
     }
 
     Element.update(fenetre,txt);
+    
+    
     Event.observe(layer, 'mousewheel', function(event){Event.stop(event);}.bindAsEventListener(), true);
     Event.observe(layer, 'DOMMouseScroll', function(event){Event.stop(event);}.bindAsEventListener(), false);
+    
+    $j('html',window.top.window.document).scrollTop(0);
+    $j('body',window.top.window.document).scrollTop(0);
+    
+    $j('body',window.top.window.document).css("overflow","hidden");
     window.top.window.$(id_mod).focus();
 }
 
-function setButtonStyle(radioButton, fileFormat, statusValidateButton) {
-    if (radioButton == "yes" && fileFormat != "pdf" && statusValidateButton == "1") {
-        $('edit').style.visibility="hidden";
-    } else if (radioButton == "no" && fileFormat != "pdf") {
-        $('edit').style.visibility="visible";
-    }
-}
-
 function cleanTitle(str) {
     //permet de supprimer les # dans le titre qui bloque l'ouverture de l'applet java
     var res = str.replace(/#/g, " ");
@@ -648,3 +470,352 @@ function activeOngletMainDocument() {
     $j('#liMainDocument').css('height', '23px');
   }
 }
+
+function activePjTab(target) {
+
+    $j('[id^=PjDocument_],#MainDocument').css('background-color', 'rgb(197, 197, 197)');
+    $j('[id^=PjDocument_],#MainDocument').css('height', '21px');
+    $j('[id^=iframePjDocument_],#iframeMainDocument').hide();
+
+    $j('#'+target.id).css('background-color', 'white');
+    $j('#'+target.id).css('height', '23px');
+    $j('#iframe'+target.id).show();
+}
+
+function addNewAttach() {
+
+    //STEP 1 : add content
+    $j("#formAttachment #addAttach1").last().after($j("#formAttachment #addAttach1").first().clone().find("#choose_file").remove().end().clone());
+    
+    //STEP 2 : remove templateOfficeTool
+    $j("#formAttachment .transmissionDiv #templateOfficeTool").hide();
+
+    //STEP 3 : change ids
+    $j("[name=attachment_types\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+    });
+    $j("[name=chrono_display\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+    });
+    $j("[name=chrono\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+    });
+    $j("[name=attachNum\\[\\]]").each(function( index ) {
+        this.value = index;
+        this.id = this.id.replace(/\d+/,'')+index;    
+    });
+    $j("[name=back_date\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+    });
+    $j("[name=effectiveDateStatus\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+        $j("#"+this.id).attr("onchange","checkEffectiveDateStatus(this);");
+    });
+    $j("[name=contact_card_attach]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+        $j('#'+this.id).attr("onclick","showContactInfo(this,$j('[name=contactidAttach\\\\[\\\\]]')["+index+"],$j('[name=addressidAttach\\\\[\\\\]]')["+index+"]);");
+    });
+    $j("[name=contactidAttach\\[\\]]").each(function( index ) {
+        if ($j("#selectContactIdRes option:eq("+index+")").length) {
+            var contact = $j("#selectContactIdRes option:eq("+index+")").val();
+            contactId = contact.split('#');
+            this.value = contactId[0];
+        }
+        this.id = this.id.replace(/\d+/,'')+index;
+    });
+    $j("[name=addressidAttach\\[\\]]").each(function( index ) {
+        if($j("#selectContactIdRes option:eq("+index+")").length) {
+            var contact = $j("#selectContactIdRes option:eq("+index+")").val();
+            contactId = contact.split('#');
+            this.value = contactId[1];
+        }
+        this.id = this.id.replace(/\d+/,'')+index;
+    });
+    $j("[name=contact_attach\\[\\]]").each(function( index ) {
+        if ($j("#selectContactIdRes option:eq("+index+")").length) {
+            $j("#"+this.id).val($j("#selectContactIdRes option:eq("+index+")").html());
+        }
+        $j("#"+this.id).attr("onchange","saveContactToSession(this);");
+        $j("#"+this.id).change();
+        this.id = this.id+index;
+        
+    });
+    $j("[name=templateOffice\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+        $j("#"+this.id).attr("onchange","showEditButton(this);");
+    });
+
+    $j("[name=templateOffice_edit\\[\\]]").each(function( index ) {
+        var id_split = this.id.replace(/\d+/,'').split('_');
+        this.id = id_split[0]+index+'_'+id_split[1];
+    });
+
+    $j("[name=delAttachButton\\[\\]]").each(function( index ) {
+        this.id = this.id.replace(/\d+/,'')+index;
+        $j("#"+this.id).attr("onclick","delAttach("+index+");");
+
+        if ($j("[name=delAttachButton\\[\\]]").length == 1 || index == 0) {
+            $j("#"+this.id).css("display","none");
+            $j("#"+this.id).prop("disabled",true);
+        } else {
+            $j("#"+this.id).css("display","inline-block");
+            $j("#"+this.id).prop("disabled",false);
+        }
+    });
+
+    //STEP 4 : reset new element
+    $j("#formAttachment .transmissionDiv [name=attachment_types\\[\\]]").last().val('');
+    $j("#formAttachment .transmissionDiv [name=attachment_types\\[\\]]").last().change();
+    $j("#formAttachment .transmissionDiv [name=templateOffice\\[\\]]").last().val('');
+    $j("#formAttachment .transmissionDiv [name=templateOffice\\[\\]]").last().css('display','inline-block');
+    $j("#formAttachment .transmissionDiv [name=templateOffice\\[\\]]").last().prop('disabled',false);
+    $j("#formAttachment .transmissionDiv [name=templateOffice\\[\\]]").last().change();
+    $j("#formAttachment .transmissionDiv [name=chrono_display\\[\\]]").last().val('');
+    $j("#formAttachment .transmissionDiv [name=chrono\\[\\]]").last().val('');
+    $j("#formAttachment .transmissionDiv [name=back_date\\[\\]]").last().val('');
+    $j("#formAttachment .transmissionDiv #newAttachButton").css("visibility","hidden");
+    $j("#formAttachment .transmissionDiv #newAttachButton").prop("disabled",true);
+    $j("#formAttachment .transmissionDiv #newAttachButton").last().css("visibility","visible");
+    $j("#formAttachment .transmissionDiv #newAttachButton").last().addClass("readonly");
+
+    $j("#formAttachment .transmissionDiv #templateOfficeTool #attachment_type_icon").first().attr("onclick","$j('#'+this.id).css('color','#009DC5');$j('#'+this.id).parent().parent().parent().parent().find('#attachment_type_icon2').first().css('color','#666');$j('#'+this.id).parent().parent().parent().parent().find('#templateOffice0').css('display','none');$j('#'+this.id).parent().parent().parent().parent().find('#templateOffice0').prop('disabled',true);$j('#'+this.id).parent().parent().parent().parent().find('#templateOffice0').css('display','none');$j('#'+this.id).parent().parent().parent().parent().find('#choose_file').css('display','inline-block');$j('#'+this.id).parent().parent().parent().parent().find('#choose_file').contents().find('#file').click()");
+    $j("#formAttachment .transmissionDiv #templateOfficeTool #attachment_type_icon2").first().attr("onclick","$j('#'+this.id).css('color','#009DC5');$j('#'+this.id).parent().parent().parent().parent().find('#attachment_type_icon').first().css('color','#666');$j('#'+this.id).parent().parent().parent().parent().find('#templateOffice0').css('display','inline-block');$j('#'+this.id).parent().parent().parent().parent().find('#templateOffice0').prop('disabled',false);$j('#'+this.id).parent().parent().parent().parent().find('#choose_file').css('display','none');");
+
+
+    $j("#formAttachment .transmissionDiv #templateOfficeTool").first().show();
+
+    launch_autocompleter2_contacts_v2("index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", $j("#formAttachment .transmissionDiv [name=contact_attach\\[\\]]").last().attr("id"), "show_contacts_attach", "", $j("#formAttachment .transmissionDiv [name=contactidAttach\\[\\]]").last().attr("id"), $j("#formAttachment .transmissionDiv [name=addressidAttach\\[\\]]").last().attr("id"));
+    launch_autocompleter2_contacts_v2("index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", $j("#formAttachment .transmissionDiv [name=contact_attach\\[\\]]").first().attr("id"), "show_contacts_attach", "", $j("#formAttachment .transmissionDiv [name=contactidAttach\\[\\]]").first().attr("id"), $j("#formAttachment .transmissionDiv [name=addressidAttach\\[\\]]").first().attr("id"));
+}
+
+function delAttach(index) {
+
+    //DELETE DATA IN SESSION
+    $j.ajax({
+        url: 'index.php?display=true&module=attachments&page=ajaxDelAttachment',
+        type: 'POST',
+        dataType: 'JSON',
+        data: {
+            index: index,
+        },
+        success: function (response) {
+            if (response.status == 0) {
+                //alert('ok');
+                $j("#MainDocument").click();
+                $j("#delAttachButton"+index).parent().parent().remove();
+                $j("#PjDocument_"+index).remove();
+                $j("#iframePjDocument_"+index).remove();
+
+                //reset ids
+                $j("[id^=PjDocument_]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                    $j("#"+this.id).html("<span>PJ n°"+(parseInt(index)+1)+"</span>");
+                });
+                $j("[id^=iframePjDocument_]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=attachment_types\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=chrono_display\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=chrono\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=attachNum\\[\\]]").each(function( index ) {
+                    this.value = index;
+                    this.id = this.id.replace(/\d+/,'')+index;    
+                });
+                $j("[name=back_date\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=backDateStatus\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=contact_card_attach]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                    $j('#'+this.id).attr("onclick","showContactInfo(this,$j('[name=contactidAttach\\\\[\\\\]]')["+index+"],$j('[name=addressidAttach\\\\[\\\\]]')["+index+"]);");
+                });
+                $j("[name=contactidAttach\\[\\]]").each(function( index ) {
+                    if ($j("#selectContactIdRes option:eq("+index+")").length) {
+                        var contact = $j("#selectContactIdRes option:eq("+index+")").val();
+                        contactId = contact.split('#');
+                        this.value = contactId[0];
+                    }
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=addressidAttach\\[\\]]").each(function( index ) {
+                    if($j("#selectContactIdRes option:eq("+index+")").length) {
+                        var contact = $j("#selectContactIdRes option:eq("+index+")").val();
+                        contactId = contact.split('#');
+                        this.value = contactId[1];
+                    }
+                    this.id = this.id.replace(/\d+/,'')+index;
+                });
+                $j("[name=contact_attach\\[\\]]").each(function( index ) {
+                    if ($j("#selectContactIdRes option:eq("+index+")").length) {
+                        $j("#"+this.id).val($j("#selectContactIdRes option:eq("+index+")").html());
+                    }
+                    $j("#"+this.id).attr("onchange","saveContactToSession(this);");
+                    $j("#"+this.id).change();
+                    this.id = this.id+index;
+                    
+                });
+                $j("[name=templateOffice\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                    $j("#"+this.id).attr("onchange","showEditButton(this);");
+                });
+
+                $j("[name=templateOffice_edit\\[\\]]").each(function( index ) {
+                    var id_split = this.id.replace(/\d+/,'').split('_');
+                    this.id = id_split[0]+index+'_'+id_split[1];
+                });
+
+                $j("[name=delAttachButton\\[\\]]").each(function( index ) {
+                    this.id = this.id.replace(/\d+/,'')+index;
+                    $j("#"+this.id).attr("onclick","delAttach("+index+");");
+
+                    if ($j("[name=delAttachButton\\[\\]]").length == 1 || index == 0) {
+                        $j("#"+this.id).css("display","none");
+                        $j("#"+this.id).prop("disabled",true);
+                    } else {
+                        $j("#"+this.id).css("display","inline-block");
+                        $j("#"+this.id).prop("disabled",false);
+                    }
+                });
+
+                $j("#formAttachment .transmissionDiv #templateOfficeTool").first().show();
+                $j("#formAttachment .transmissionDiv #newAttachButton").last().prop("disabled",false);
+                $j("#formAttachment .transmissionDiv #newAttachButton").last().css("visibility","visible");
+                $j("#formAttachment .transmissionDiv #newAttachButton").last().removeClass("readonly");
+                
+            }
+        },
+        error: function (error) {
+            alert(error);
+        }
+
+    });
+
+    
+}
+
+function showEditButton(target) {
+
+    var modele_id = $j('#'+target.id).val();
+
+    if (modele_id != '') {
+
+        $j('#'+target.id+'_edit').css("display","inline");
+        $j('#'+target.id).css("width","166px");
+        
+        if ($('not_enabled')) {
+            $('not_enabled').setStyle({display: 'inline'});
+        }
+
+        $j('#'+target.id).parent().parent().find('#choose_file').css("display","none");
+
+        if ($('file_loaded')) {
+            $('file_loaded').setStyle({display: 'none'});
+        }
+    } else {
+        $j('#'+target.id+'_edit').css("display","none");
+        $j('#'+target.id).css("width","206px");
+
+        if ($('not_enabled')) {
+            $('not_enabled').setStyle({display: 'none'});
+        }
+        if ($('file_loaded')) {
+            $('file_loaded').setStyle({display: 'none'});
+        }
+    }
+}
+
+function affiche_chrono(target){
+    var type_id = document.getElementById(target.id).options[document.getElementById(target.id).selectedIndex];
+    var chrono_display = $j(target).parent().parent().find("[name=chrono_display\\[\\]]");
+    var chrono_label = $j(target).parent().parent().find("[name=chrono_label\\[\\]]");
+    var get_chrono_display = $j(target).parent().parent().find("[name=get_chrono_display\\[\\]]");
+    var chrono = $j(target).parent().parent().find("[name=chrono\\[\\]]");
+
+    //FOR MULTI ATTACHMENT
+    var index = '0';
+    var regexIndex = chrono.attr("id").match(/\d+/);
+    if (regexIndex != null) {
+        index = regexIndex[0];
+    }
+
+    //GENERATE CHRONO
+    if (type_id.value == 'transmission' && index != '0') {
+        get_chrono_display.css("display","none"); 
+        chrono_label.css("display","inline"); 
+        chrono_display.css("display","inline"); 
+        var num = $j('[value=transmission]:selected').length;
+        var chr = String.fromCharCode(64 + num);
+        chrono_display.val($j("#chrono0").val()+'.'+chr);
+        chrono.val($j("#chrono0").val()+'.'+chr);
+
+    } else if (type_id.getAttribute('with_chrono') == 'true') {
+        get_chrono_display.css("display","none"); 
+        chrono_label.css("display","inline"); 
+        chrono_display.css("display","inline"); 
+        
+        new Ajax.Request('index.php?display=true&module=attachments&page=get_chrono_attachment',
+        {
+            method:'post',
+            parameters:
+            {
+                index : index,
+                type_id : type_id
+            },
+                onSuccess: function(answer){
+                eval("response = "+answer.responseText);
+                chrono_display.val(response.chronoNB);
+                chrono.val(response.chronoNB);
+            }
+        });
+    } else if (type_id.getAttribute('get_chrono') != '' && type_id.getAttribute('get_chrono') != null) {
+        chrono_display.css("display","none");
+        chrono_display.val('');
+        chrono_label.css("display","inline");
+        get_chrono_display.css("display","inline");
+        chrono.val('');
+        new Ajax.Request('index.php?display=true&module=attachments&page=get_other_chrono_attachment',
+        {
+            method:'post',
+            parameters:
+            {
+                type_id : type_id.value
+            },
+                onSuccess: function(answer){
+                eval("response = "+answer.responseText);
+                get_chrono_display.html(response.chronoList);
+            }
+        });
+    } else {
+        chrono_label.css("display","none");
+        get_chrono_display.css("display","none");
+        chrono_display.css("display","none");
+        chrono_display.val('');
+        chrono.val('');
+    }
+}
+
+function showContactInfo(target,contactTarget,addressTarget) {
+    $j('#info_contact_div_attach').slideToggle("slow",function(){
+        $j('#'+target.name+'_iframe').attr('src','index.php?display=false&dir=my_contacts&page=info_contact_iframe&fromAttachmentContact=Y&seeAllAddresses&contactid='+contactTarget.value+'&addressid='+addressTarget.value);
+    });
+}
+
+function checkEffectiveDateStatus(effectiveDateStatus) {
+    console.log($j('#'+effectiveDateStatus.id).val());
+    if ($j('#'+effectiveDateStatus.id).val() == 'NO_RTURN') {
+        $j('#'+effectiveDateStatus.id).parent().find('[name=back_date\\[\\]]').val('');
+        $j('#'+effectiveDateStatus.id).parent().find('[name=back_date\\[\\]]').prop('disabled',true);
+        $j('#'+effectiveDateStatus.id).parent().find('[name=back_date\\[\\]]').addClass('readonly');
+    } else {
+        $j('#'+effectiveDateStatus.id).parent().find('[name=back_date\\[\\]]').prop('disabled',false);
+        $j('#'+effectiveDateStatus.id).parent().find('[name=back_date\\[\\]]').removeClass('readonly');
+    }    
+}
\ No newline at end of file
diff --git a/modules/attachments/lang/en.php b/modules/attachments/lang/en.php
index 6531e01147e..754b7cff789 100755
--- a/modules/attachments/lang/en.php
+++ b/modules/attachments/lang/en.php
@@ -79,6 +79,8 @@ if (!defined("_CHOOSE_MODEL"))
     define( "_CHOOSE_MODEL", "Select the model");
 if (!defined("_BACK_DATE"))
     define( "_BACK_DATE", "Return date");
+if (!defined("_EFFECTIVE_DATE"))
+    define( "_EFFECTIVE_DATE", "Effective date");
 if (!defined("_ATTACHMENT_TYPES"))
     define( "_ATTACHMENT_TYPES", "Attachment type");
 if (!defined("_RESPONSE_PROJECT"))
@@ -150,6 +152,9 @@ if (!defined("_NO_PREVIEW_AVAILABLE"))
 if (!defined("_FILE_HAS_NO_PDF"))
     define( "_FILE_HAS_NO_PDF", "PDF version does not exist for this file.");
 
+if (!defined("_MODEL_NOT_EDITED"))
+    define( "_MODEL_NOT_EDITED", "Model not edited");
+
 // Reconciliation
 
 if(!defined('_RECONCILIATION'))
diff --git a/modules/attachments/lang/fr.php b/modules/attachments/lang/fr.php
index e22144582f9..d5d1e219020 100755
--- a/modules/attachments/lang/fr.php
+++ b/modules/attachments/lang/fr.php
@@ -79,6 +79,8 @@ if (!defined("_CHOOSE_MODEL"))
     define( "_CHOOSE_MODEL", "Sélectionnez le modèle");
 if (!defined("_BACK_DATE"))
     define( "_BACK_DATE", "Date de retour");
+if (!defined("_EFFECTIVE_DATE"))
+    define( "_EFFECTIVE_DATE", "Date de retour effective");
 if (!defined("_ATTACHMENT_TYPES"))
     define( "_ATTACHMENT_TYPES", "Type d'attachement");
 if (!defined("_RESPONSE_PROJECT"))
@@ -150,6 +152,9 @@ if (!defined("_NO_PREVIEW_AVAILABLE"))
 if (!defined("_FILE_HAS_NO_PDF"))
     define( "_FILE_HAS_NO_PDF", "La version PDF du fichier n'existe pas.");
 
+if (!defined("_MODEL_NOT_EDITED"))
+    define( "_MODEL_NOT_EDITED", "Modèle non édité");
+
 // RECONCILIATION
 
 if(!defined('_RECONCILIATION'))
diff --git a/modules/attachments/saveTransmissionContact.php b/modules/attachments/saveTransmissionContact.php
index 193e3bfdfac..a23574bbd65 100755
--- a/modules/attachments/saveTransmissionContact.php
+++ b/modules/attachments/saveTransmissionContact.php
@@ -1,53 +1,38 @@
 <?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.
 
-/*
-*   Copyright 2008-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   saveTransmissionContact
+* @author  dev <dev@maarch.org>
+* @ingroup attachment
 */
+unset($_SESSION['transmissionContacts']);
 
-if (!empty($_POST['size']) && isset($_POST['contactId'])) {
-    $nb = $_POST['size'];
+if (isset($_POST['transmissionContactidAttach']) && !empty($_POST['transmissionContactidAttach'])) {
+ 
+    $db = new Database();
 
-    if (empty($_POST['contactId'])) {
-        unset($_SESSION['transmissionContacts'][$nb]);
-    } else {
-        $db = new Database();
-
-        if (is_numeric($_POST['contactId'])) {
-            if (isset($_POST['addressId'])) {
-                $stmt = $db->query('SELECT * FROM view_contacts WHERE contact_id = ? AND ca_id = ?', [$_POST['contactId'], $_POST['addressId']]);
+    foreach ($_POST['transmissionContactidAttach'] as $key => $contactId) {
+        if (is_numeric($_POST['transmissionContactidAttach'][$key]['val'])) {
+            if (isset($_POST['transmissionAddressidAttach'][$key]['val'])) {
+                $stmt = $db->query('SELECT * FROM view_contacts WHERE contact_id = ? AND ca_id = ?', [$_POST['transmissionContactidAttach'][$key]['val'], $_POST['transmissionAddressidAttach'][$key]['val']]);
             } else {
-                $stmt = $db->query('SELECT * FROM view_contacts WHERE contact_id = ?', [$_POST['contactId']]);
+                $stmt = $db->query('SELECT * FROM view_contacts WHERE contact_id = ?', [$_POST['transmissionContactidAttach'][$key]['val']]);
             }
         } else {
-            $stmt = $db->query('SELECT firstname, lastname, user_id, mail, phone, initials FROM users WHERE user_id = ?', [$_POST['contactId']]);
+            $stmt = $db->query('SELECT firstname, lastname, user_id, mail, phone, initials FROM users WHERE user_id = ?', [$_POST['transmissionContactidAttach'][$key]['val']]);
         }
 
         $contact = $stmt->fetchObject();
-        if (!isset($_SESSION['transmissionContacts']))
-            $_SESSION['transmissionContacts'] = [];
-
-        foreach($contact as $key => $value) {
-            $_SESSION['transmissionContacts'][$nb][$key] = $value;
+        foreach ($contact as $column => $value) {
+            $_SESSION['transmissionContacts'][$_POST['transmissionAddressidAttach'][$key]['index']][$column] = $value;
         }
-        if (is_numeric($_POST['contactId'])) {
-            $_SESSION['transmissionContacts'][$nb]['firstname'] = $contact->contact_firstname == '' ? $contact->firstname : $contact->contact_firstname;
-            $_SESSION['transmissionContacts'][$nb]['lastname']  = $contact->contact_lastname == '' ? $contact->lastname : $contact->contact_lastname;
-            $_SESSION['transmissionContacts'][$nb]['title']     = $contact->contact_title == '' ? $contact->title : $contact->contact_title;
+        if (is_numeric($_POST['transmissionContactidAttach'][$key])) {
+            $_SESSION['transmissionContacts'][$_POST['transmissionAddressidAttach'][$key]['index']]['firstname'] = $contact->contact_firstname == '' ? $contact->firstname : $contact->contact_firstname;
+            $_SESSION['transmissionContacts'][$_POST['transmissionAddressidAttach'][$key]['index']]['lastname']  = $contact->contact_lastname == '' ? $contact->lastname : $contact->contact_lastname;
+            $_SESSION['transmissionContacts'][$_POST['transmissionAddressidAttach'][$key]['index']]['title']     = $contact->contact_title == '' ? $contact->title : $contact->contact_title;
         }
     }
 }
\ No newline at end of file
diff --git a/modules/attachments/xml/IVS/validation_rules.xml b/modules/attachments/xml/IVS/validation_rules.xml
index 2394fd843c1..13306b29b72 100755
--- a/modules/attachments/xml/IVS/validation_rules.xml
+++ b/modules/attachments/xml/IVS/validation_rules.xml
@@ -10,7 +10,7 @@
 		<parameter name="relation" type="identifier" />
 		<parameter name="add" type="string" />
 		<parameter name="attachment_types" type="identifier" />
-		<parameter name="back_date" type="datefr" />
+		<parameter name="back_date" type="arrayOfStrings" />
 		<parameter name="cancel" type="string" />
 		<parameter name="chrono" type="string" />
 		<parameter name="contact_attach" type="string" />
@@ -28,7 +28,7 @@
 
 	<validationRule name="get_chrono_attachment" extends="standardForm" mode="error">
 		<parameter name="module" type="identifier" />
-		<parameter name="type_id" type="identifier" />
+		<parameter name="index" type="integer" />
 	</validationRule>
 
 	<validationRule name="frame_list_attachments" extends="standardForm" mode="error">
diff --git a/modules/content_management/applet_controller.php b/modules/content_management/applet_controller.php
index 70e58355976..210c274a426 100755
--- a/modules/content_management/applet_controller.php
+++ b/modules/content_management/applet_controller.php
@@ -156,7 +156,7 @@ if (!empty($_REQUEST['action'])
             && $objectType <> 'newAttachment'
             && $objectType != 'transmission'
         ) {
-            //case of res -> master or version
+            //case of res -> master or version (DEPRECATED DO NOT USE!)
             include 'modules/content_management/retrieve_res_from_cm.php';
         } elseif ($objectType == 'attachment' || $objectType == 'attachmentUpVersion') {
             //case of res -> update attachment
@@ -316,24 +316,25 @@ if (!empty($_REQUEST['action'])
                 );
                 createXML('ERROR', $result);
             } else {
-                //depending on the type of object, the action is not the same
+                //depending on the type of object, the action is not the same (???)
                 if ($objectType == 'resource') {
                     include 'modules/content_management/save_new_version_from_cm.php';
                 }
+                //EDIT ATTACHMENT (???)
                 if ($objectType == 'resourceEdit') {
                     include 'modules/content_management/save_editRes_from_cm.php';
-                } elseif ($objectType == 'attachmentFromTemplate' || $objectType == 'newAttachment') {
+                //ADD NEW ATTACHMENT (???)  
+                } elseif ($objectType == 'attachmentFromTemplate') {
                     include 'modules/content_management/save_attach_res_from_cm.php';
+                //(???)
                 } elseif ($objectType == 'attachment') {
                     include 'modules/content_management/save_attach_from_cm.php';
+                //ADD - EDIT NEW TEMPLATE
                 } elseif ($objectType == 'templateStyle' || $objectType == 'template') {
                     include 'modules/content_management/save_template_from_cm.php';
-                } elseif ($objectType == 'attachmentVersion' || $objectType == 'attachmentUpVersion') {
+                //ADD - EDIT NEW ATTACHMENT (FOR TEMPORARY SAVE)
+                } elseif ($objectType == 'attachmentVersion' || $objectType == 'attachmentUpVersion' || $objectType == 'outgoingMail' || $objectType == 'newAttachment') {
                     include 'modules/content_management/save_attachment_from_cm.php';
-                } elseif ($objectType == 'outgoingMail') {
-                    include 'modules/content_management/save_outmail_from_cm.php';
-                } elseif ($objectType == 'transmission') {
-                    include 'modules/content_management/save_transmission_from_cm.php';
                 }
 
                 if ($_REQUEST['step']== 'end') {
diff --git a/modules/content_management/applet_modal_launcher.php b/modules/content_management/applet_modal_launcher.php
index f21ef86ee31..1cad30e86c0 100755
--- a/modules/content_management/applet_modal_launcher.php
+++ b/modules/content_management/applet_modal_launcher.php
@@ -1,43 +1,31 @@
 <?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.
 
-/*
-*
-*    Copyright 2008,2015 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/>.
-*
-*   @author <dev@maarch.org>
+* @brief   applet_modal_launcher
+* @author  dev <dev@maarch.org>
+* @ingroup content_management
 */
 
 require_once 'core/class/class_core_tools.php';
 $core_tools = new core_tools();
-//$core_tools->load_html();
-//$core_tools->load_header();
-//$core_tools->load_js();
 
 // sessions use for temporary backup
-if (!isset($_REQUEST['transmissionNumber'])) {
+/*if (!isset($_SESSION['attachmentInfo'])) {
     $_SESSION['attachmentInfo'] = array();
-    $_SESSION['attachmentInfo']['title'] = $_REQUEST['titleAttachment'];
-    $_SESSION['attachmentInfo']['chrono'] = $_REQUEST['chronoAttachment'];
-    $_SESSION['attachmentInfo']['type'] = $_REQUEST['attachType'];
-    $_SESSION['attachmentInfo']['contactId'] = $_REQUEST['contactId'];
-    $_SESSION['attachmentInfo']['addressId'] = $_REQUEST['addressId'];
-    $_SESSION['attachmentInfo']['back_date'] = $_REQUEST['back_date'];
-}
+}*/
+$attachNum = $_REQUEST['uniqueId'];
+$_SESSION['attachmentInfo']['attachNum'] = $attachNum;
+$_SESSION['attachmentInfo'][$attachNum]['title'] = $_REQUEST['titleAttachment'];
+$_SESSION['attachmentInfo'][$attachNum]['chrono'] = $_REQUEST['chronoAttachment'];
+$_SESSION['attachmentInfo'][$attachNum]['type'] = $_REQUEST['attachType'];
+$_SESSION['attachmentInfo'][$attachNum]['contactId'] = $_REQUEST['contactId'];
+$_SESSION['attachmentInfo'][$attachNum]['addressId'] = $_REQUEST['addressId'];
+$_SESSION['attachmentInfo'][$attachNum]['back_date'] = $_REQUEST['back_date'];
+$_SESSION['attachmentInfo'][$attachNum]['backDateStatus'] = $_REQUEST['backDateStatus'];
+
 
 if (isset($_REQUEST['attachType']) && $_REQUEST['attachType'] == 'outgoing_mail'){
 	$objType = 'outgoingMail';
@@ -57,8 +45,7 @@ if (
 } else {
     $path = 'modules/content_management/applet_launcher.php';
 }
-$_SESSION['upfileTransmissionNumber'] = (isset($_REQUEST['transmissionNumber']) ? $_REQUEST['transmissionNumber'] : null);
-$uniqueId = (isset($_REQUEST['transmissionNumber']) ? $_REQUEST['transmissionNumber'] : null);
+
 
 $content = '<style type="text/css">html{overflow:hidden}</style>'
     . '<body>'
@@ -75,7 +62,7 @@ $content = '<style type="text/css">html{overflow:hidden}</style>'
                         . '&objectTable='
                         . $_REQUEST['objectTable']
                         . '&uniqueId='
-                        . $uniqueId
+                        . $_REQUEST['uniqueId']
                         . '&resMaster='
                         . $_REQUEST['resMaster']
                         . '&contactId='
diff --git a/modules/content_management/checkEditingDoc.php b/modules/content_management/checkEditingDoc.php
index 5f504dcbfbc..480523994a4 100755
--- a/modules/content_management/checkEditingDoc.php
+++ b/modules/content_management/checkEditingDoc.php
@@ -8,11 +8,10 @@
 * @author  dev <dev@maarch.org>
 * @ingroup content_management
 */
-
 if (!empty($_SESSION['cm_applet'][$_SESSION['user']['UserId']])) {
     echo "{\"status\" : 1, \"status_txt\" : \"LCK FOUND !\"}";
-} else if (strpos($_SESSION['upfile']['format'], 'xl') !== false || strpos($_SESSION['upfile']['format'], 'ppt') !== false) {
+} else if (strpos($_SESSION['upfile'][$_POST['attachNum']]['format'], 'xl') !== false || strpos($_SESSION['upfile'][$_POST['attachNum']]['format'], 'ppt') !== false) {
     echo "{\"status\" : 0, \"status_txt\" : \"LCK NOT FOUND !\", \"pdf_version\" : \"\"}";
 } else {
-    echo "{\"status\" : 0, \"status_txt\" : \"LCK NOT FOUND !\", \"pdf_version\" : \"".$_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp']."\"}";
+    echo "{\"status\" : 0, \"status_txt\" : \"LCK NOT FOUND !\", \"pdf_version\" : \"".$_SESSION['config']['tmppath'].$_SESSION['upfile'][$_POST['attachNum']]['fileNamePdfOnTmp']."\"}";
 }
diff --git a/modules/content_management/class/class_content_manager_tools_Abstract.php b/modules/content_management/class/class_content_manager_tools_Abstract.php
index 56ce01dc761..6b9a56b0008 100755
--- a/modules/content_management/class/class_content_manager_tools_Abstract.php
+++ b/modules/content_management/class/class_content_manager_tools_Abstract.php
@@ -355,6 +355,7 @@ abstract class content_management_tools_Abstract
         $convertPdf = "false",
         $onlyConvert = "false"
     ) {
+        
         $docXML = new DomDocument('1.0', "UTF-8");
 
         //create unique id for APPLET
@@ -509,7 +510,7 @@ abstract class content_management_tools_Abstract
         }
         $param4_balise=$docXML->createElement("argument", htmlentities($objectId));
 
-        if (empty($uniqueId)) {
+        if ($uniqueId < 0) {
             $uniqueId = 'empty';
         }
         $param5_balise=$docXML->createElement("argument", htmlentities($uniqueId));
diff --git a/modules/content_management/js/functions.js b/modules/content_management/js/functions.js
index 5dfea7c8515..7d266e22f9d 100755
--- a/modules/content_management/js/functions.js
+++ b/modules/content_management/js/functions.js
@@ -1,7 +1,7 @@
 var editing;
-function editingDoc(user){
+function editingDoc(elem,user){
 
-    editing = setInterval(function() {checkEditingDoc('user')}, 500);
+    editing = setInterval(function() {checkEditingDoc(elem,'user')}, 500);
 
 }
 //load applet in a modal
@@ -192,10 +192,17 @@ function showDiv(divName, spanNb, divCreate, path_manage_script)
     });
 }
 
-function checkEditingDoc(userId) {
-    if($j('#add').length){
+function checkEditingDoc(elem, userId) {
+
+    if ($j('#'+elem.id).parent().parent().find('[name=attachNum\\[\\]]').length) {
+        var attachNum = $j('#'+elem.id).parent().parent().find('[name=attachNum\\[\\]]').val();
+    } else {
+        var attachNum = '0';
+    }
+    
+    if ($j('#add').length) {
         var target = $j('#add');
-    }else{
+    } else {
         var target = $j('#edit');
     }
     //LOCK VALIDATE BUTTON
@@ -203,14 +210,15 @@ function checkEditingDoc(userId) {
     target.css({"opacity":"0.5"});
     target.val('Edition en cours ...');
 
-    //LOCK EDIT BUTTON TRANSMISSION
-    $j(".transmissionEdit").css({"opacity":"0.5"});
-    $j(".transmissionEdit").prop('disabled', true);
+    //LOCK EDIT BUTTON (IF MULTI ATTACHMENT)
+    $j("[name=templateOffice_edit\\[\\]]").css({"opacity":"0.5"});
+    $j("[name=templateOffice_edit\\[\\]]").prop('disabled', true);
 
     $j.ajax({
        url : 'index.php?display=true&page=checkEditingDoc&module=content_management',
        type : 'POST',
        dataType : 'JSON',
+       data: {attachNum : attachNum},
        success : function(response){
             if (response.status == 0) {
                 console.log('no lck found!');
@@ -220,27 +228,42 @@ function checkEditingDoc(userId) {
                 target.css({"opacity":"1"});
                 target.val('Valider');
 
+                //UNLOCK EDIT BUTTON (IF MULTI ATTACHMENT)
+                $j("[name=templateOffice_edit\\[\\]], #edit").css({"opacity":"1"});
+                $j("[name=templateOffice_edit\\[\\]], #edit").prop('disabled', false);
+
                 if($j('#cancelpj').length){
                     $j('#cancelpj').prop('disabled', false);
                     $j('#cancelpj').css({'opacity':'1'});
                 }
 
-                //UNLOCK EDIT BUTTON TRANSMISSION
-                $j(".transmissionEdit, #edit").css({"opacity":"1"});
-                $j(".transmissionEdit, #edit").prop('disabled', false);
-
                 //END OF CHECKING APPLET
                 console.log('clearInterval');
+                clearInterval(editing);
 
-                if($j('#liAttachement', window.top.document).length && response.pdf_version != '') {
-                	window.top.document.getElementById('liAttachement').click();
+                //CONSTRUCT TAB (IF PDF)
+                if ($j("#ongletAttachement li",window.parent.document).eq(attachNum).length) {
+                    $j("#ongletAttachement li",window.parent.document).eq(attachNum).after($j("#MainDocument",window.parent.document).clone())
+                } else {
+                    $j("#MainDocument",window.parent.document).after($j("#MainDocument",window.parent.document).clone());
                 }
                 
-                if($j('#viewframevalid_attachment').length && response.pdf_version != '') {
-                    document.getElementById('viewframevalid_attachment').src='index.php?display=true&dir=indexing_searching&page=file_iframe&#navpanes=0'+response.pdf_version;                    
+                //$j("#MainDocument",window.parent.document).after($j("#MainDocument",window.parent.document).clone());
+                $j("#iframeMainDocument",window.parent.document).after($j("#iframeMainDocument",window.parent.document).clone());
+                if ($j("#ongletAttachement #PjDocument_"+attachNum,window.parent.document).length) {
+                    $j("#ongletAttachement #PjDocument_"+attachNum,window.parent.document).remove();
+                    $j("div #iframePjDocument_"+attachNum,window.parent.document).remove();
                 }
-                //console.log(response.pdf_version);
-                clearInterval(editing);
+                $j("div #iframeMainDocument",window.parent.document).eq(1).attr("id","iframePjDocument_"+attachNum);
+                $j("div #iframePjDocument_"+attachNum,window.parent.document).attr("src","index.php?display=true&dir=indexing_searching&page=file_iframe&num="+attachNum+"&#navpanes=0"+response.pdf_version);              
+
+                $j("#ongletAttachement #MainDocument",window.parent.document).eq(1).attr("id","PjDocument_"+attachNum);
+                $j("#ongletAttachement #PjDocument_"+attachNum,window.parent.document).html("<span>PJ n°"+(parseInt(attachNum)+1)+"</span>");
+                $j("#ongletAttachement #PjDocument_"+attachNum,window.parent.document).click();
+                $j("#ongletAttachement [id^=PjDocument_]",window.parent.document).each(function( index ) {
+                    $j("#"+this.id,window.parent.document).attr("onclick","activePjTab(this);");
+                });
+                
             } else {
                 console.log('lck found! Editing in progress !');
 
@@ -249,15 +272,15 @@ function checkEditingDoc(userId) {
                 target.css({"opacity":"0.5"});
                 target.val('Edition en cours ...');
 
+                //LOCK EDIT BUTTON (IF MULTI ATTACHMENT)
+                $j("[name=templateOffice_edit\\[\\]]").css({"opacity":"0.5"});
+                $j("[name=templateOffice_edit\\[\\]]").prop('disabled', true);
+
                 if($j('#cancelpj').length){
                     $j('#cancelpj').prop('disabled', true);
                     $j('#cancelpj').css({'opacity':'0.5'});
                 }
 
-                //LOCK EDIT BUTTON TRANSMISSION
-                $j(".transmissionEdit, #edit").css({"opacity":"0.5"});
-                $j(".transmissionEdit, #edit").prop('disabled', true);
-
             }
        },
        error : function(error){
@@ -269,8 +292,48 @@ function checkEditingDoc(userId) {
 
 }
 
-function showAppletLauncher(path, width, height) {
+function showAppletLauncher(target, resId, objectTable, objectType, mode) {
+
+    if (mode == 'template') {
+        var path = 'index.php?display=true&module=content_management&page=applet_modal_launcher&uniqueId=0&objectType=' + objectType + '&objectId=' + resId + '&objectTable=' + objectTable;
+    
+    } else {
+        //Num of Attachment
+        var attachNum = $j('#'+target.id).parent().parent().find('[name=attachNum\\[\\]]').val();
+        //Only add mode
+        if (objectType == 'attachmentVersion') {
+            var templateOffice = $j('#'+target.id).parent().parent().find('[name=templateOffice\\[\\]]').val();
+        } else {
+            var templateOffice = $j('#'+target.id).parent().parent().find('#res_id').val();
+        }
+        var attachment_types = $j('#'+target.id).parent().parent().find('[name=attachment_types\\[\\]]').val();
+
+        if (attachment_types == 'transmission') {
+            var contactidAttach = $j('#formAttachment [name=contactidAttach\\[\\]]').first().val();
+            var addressidAttach = $j('#formAttachment [name=addressidAttach\\[\\]]').first().val();
+        } else {
+            var contactidAttach = $j('#'+target.id).parent().parent().find('[name=contactidAttach\\[\\]]').val();
+            var addressidAttach = $j('#'+target.id).parent().parent().find('[name=addressidAttach\\[\\]]').val();
+        }
+        
+        var chrono = $j('#'+target.id).parent().parent().find('[name=chrono\\[\\]]').val();
+        var title = cleanTitle($j('#'+target.id).parent().parent().find('[name=title\\[\\]]').val());
+        var back_date = $j('#'+target.id).parent().parent().find('[name=back_date\\[\\]]').val();
+        var backDateStatus = $j('#'+target.id).parent().parent().find('[name=backDateStatus\\[\\]]').val();
+        var path = 'index.php?display=true&module=content_management&page=applet_modal_launcher&uniqueId='+attachNum+'&objectType='+objectType+'&objectId='+templateOffice+'&attachType='+attachment_types+'&objectTable=' + objectTable + '&contactId='+contactidAttach+'&addressId='+addressidAttach+'&chronoAttachment='+chrono+'&titleAttachment='+title+'&backDateStatus='+backDateStatus+'&back_date='+back_date+'&resMaster=' + resId
+    }
+    
 
+    /*console.log('attach number : '+attachNum);
+    console.log('template_id : '+templateOffice);
+    console.log('attachment type : '+attachment_types);
+    console.log('contact_id : '+contactidAttach);
+    console.log('address_id : '+addressidAttach);
+    console.log('chrono : '+chrono);
+    console.log('title : '+title);
+    console.log('back date : '+back_date);
+    console.log('path : '+path);*/
+    
     new Ajax.Request(path,
     {
         method:'post',
diff --git a/modules/content_management/retrieve_new_attachment_from_cm.php b/modules/content_management/retrieve_new_attachment_from_cm.php
index 2aec72af083..13e6cfc1d4a 100755
--- a/modules/content_management/retrieve_new_attachment_from_cm.php
+++ b/modules/content_management/retrieve_new_attachment_from_cm.php
@@ -1,14 +1,14 @@
 <?php
-//case of res -> new attachment
+//case of res -> new attachment with only conversion
 
 
-if (!file_exists($_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'])) {
-    $result = array('ERROR' => _THE_DOC . ' ' . $_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'] . ' ' . _EXISTS_OR_RIGHT);
+if (!file_exists($_SESSION['config']['tmppath'] . $_SESSION['upfile'][0]['name'])) {
+    $result = array('ERROR' => _THE_DOC . ' ' . $_SESSION['config']['tmppath'] . $_SESSION['upfile'][0]['name'] . ' ' . _EXISTS_OR_RIGHT);
     createXML('ERROR', $result);
 } else {
     $func = new functions();
-    $fileExtension = $func->extractFileExt($_SESSION['config']['tmppath'] . $_SESSION['upfile']['name']);
-    $filePathOnTmp = $_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'];
+    $fileExtension = $func->extractFileExt($_SESSION['config']['tmppath'] . $_SESSION['upfile'][0]['name']);
+    $filePathOnTmp = $_SESSION['config']['tmppath'] . $_SESSION['upfile'][0]['name'];
     // $file = fopen('file.log', a);
     // fwrite($file, '[' . date('Y-m-d H:i:s') . '] ------BEGIN------- ' . PHP_EOL);
     // fwrite($file, '[' . date('Y-m-d H:i:s') . '] EXT ' . $fileExtension . PHP_EOL);
diff --git a/modules/content_management/save_attachment_from_cm.php b/modules/content_management/save_attachment_from_cm.php
index 3637af17b4c..6c7c81b78eb 100755
--- a/modules/content_management/save_attachment_from_cm.php
+++ b/modules/content_management/save_attachment_from_cm.php
@@ -1,42 +1,36 @@
 <?php
-
-/*
-*
-*    Copyright 2008,2015 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/>.
-*
-*   @author <dev@maarch.org>
+/**
+* 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   save_attachment_from_cm
+* @author  dev <dev@maarch.org>
+* @ingroup content_management
 */
 
 // FOR ADD, UP TEMPLATES and temporary backup
+if (empty($_REQUEST['uniqueId']) || $_REQUEST['uniqueId'] == null) {
+    $i = 0;
+} else {
+    $i = $_REQUEST['uniqueId'];
+}
 
-/*$_SESSION['m_admin']['templates']['current_style'] 
-        = $_SESSION['config']['tmppath'] . $tmpFileName; */
+if (!isset($_SESSION['upfile'])) {
+    $_SESSION['upfile'] = [];
+}
+
+$_SESSION['upfile'][$i]['tmp_name']             = $_SESSION['config']['tmppath'] . $tmpFileName;
+$_SESSION['upfile'][$i]['size']                 = filesize($_SESSION['config']['tmppath'] . $tmpFileName);
+$_SESSION['upfile'][$i]['error']                = "";
+$_SESSION['upfile'][$i]['fileNameOnTmp']        = $tmpFileName;
+$_SESSION['upfile'][$i]['format']               = $fileExtension;
+$_SESSION['upfile'][$i]['upAttachment']         = true;
 
-$_SESSION['upfile']['tmp_name']             = $_SESSION['config']['tmppath'] . $tmpFileName;
-$_SESSION['upfile']['size']                 = filesize($_SESSION['config']['tmppath'] . $tmpFileName);
-$_SESSION['upfile']['error']                = "";
-$_SESSION['upfile']['fileNameOnTmp']        = $tmpFileName;
-$_SESSION['upfile']['format']               = $fileExtension;
-$_SESSION['upfile']['upAttachment']         = true;
-$_SESSION['m_admin']['templates']['applet'] = true;
+$_SESSION['m_admin']['templates']['applet']     = true;
 
-if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true){
-	$_SESSION['upfile']['fileNamePdfOnTmp'] = $tmpFilePdfName;
+if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true) {
+	$_SESSION['upfile'][$i]['fileNamePdfOnTmp'] = $tmpFilePdfName;
 }
 
 // Temporary backup
@@ -56,18 +50,17 @@ $ac 				= new attachments_controler();
 
 require_once 'core/docservers_tools.php';
 
+//CHECK AUTHORIZED EXTENSION
 $arrayIsAllowed = array();
 $arrayIsAllowed = Ds_isFileTypeAllowed(
-    $_SESSION['config']['tmppath'] . $_SESSION['upfile']['fileNameOnTmp']
+    $_SESSION['config']['tmppath'] . $_SESSION['upfile'][$i]['fileNameOnTmp']
 );
 
 if ($arrayIsAllowed['status'] == false) {
 	$_SESSION['error']  = _WRONG_FILE_TYPE . ' ' . $arrayIsAllowed['mime_type'];
 	$_SESSION['upfile'] = array();
 } else {
-    if (! isset($_SESSION['collection_id_choice'])
-        || empty($_SESSION['collection_id_choice'])
-    ) {
+    if (! isset($_SESSION['collection_id_choice']) || empty($_SESSION['collection_id_choice'])) {
         $_SESSION['collection_id_choice'] = $_SESSION['user']['collections'][0];
     }
 
@@ -80,7 +73,7 @@ if ($arrayIsAllowed['status'] == false) {
 
         // some checking on docserver size limit
         $newSize = $docserverControler->checkSize(
-            $docserver, $_SESSION['upfile']['size']
+            $docserver, $_SESSION['upfile'][$i]['size']
         );
         if ($newSize == 0) {
             $_SESSION['error'] = _DOCSERVER_ERROR . ' : ' . _NOT_ENOUGH_DISK_SPACE . ". " . _MORE_INFOS . ".";
@@ -96,11 +89,12 @@ if ($arrayIsAllowed['status'] == false) {
         } else {
             $fileInfos = array(
                 "tmpDir"      => $_SESSION['config']['tmppath'],
-                "size"        => $_SESSION['upfile']['size'],
-                "format"      => $_SESSION['upfile']['format'],
-                "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
+                "size"        => $_SESSION['upfile'][$i]['size'],
+                "format"      => $_SESSION['upfile'][$i]['format'],
+                "tmpFileName" => $_SESSION['upfile'][$i]['fileNameOnTmp'],
             );
 
+            //SAVE FILE ON DOCSERVER ATTACHMENT
             $storeResult = array();
             $storeResult = $docserverControler->storeResourceOnDocserver(
                 $_SESSION['collection_id_choice'], $fileInfos
@@ -110,11 +104,16 @@ if ($arrayIsAllowed['status'] == false) {
                 $_SESSION['error'] = $storeResult['error'];
             } else if(isset($_SESSION['attachmentInfo']['inProgressResId'])){
 
-				$ac->removeTemporaryAttachmentOnDocserver($_SESSION['attachmentInfo']['inProgressResId'], $_SESSION['doc_id'], $_SESSION['user']['UserId']);
+            //MODE SECOND BACKUP AND MORE
+            } else if(isset($_SESSION['attachmentInfo'][$i]['inProgressResId'])){
+
+                //DELETE OLD BACKUP
+				$ac->removeTemporaryAttachmentOnDocserver($_SESSION['attachmentInfo'][$i]['inProgressResId'], $_SESSION['doc_id'], $_SESSION['user']['UserId']);
 
 		        require_once 'core/class/docserver_types_controler.php';
 				$docserverTypeControler = new docserver_types_controler();
 
+                //RETRIEVE FILE PATH
 				$filetmp = $storeResult['path_template'];
 				$filetmp .= str_replace('#',DIRECTORY_SEPARATOR, $storeResult['destination_dir']);
 				$filetmp .= $storeResult['file_destination_name'];
@@ -127,10 +126,14 @@ if ($arrayIsAllowed['status'] == false) {
 		        	$tableName = 'res_attachments';
 	        	} else if ($_SESSION['targetAttachment'] == 'edit') {
 		        	$tableName = 'res_version_attachments';
-	        	}
+                }
+                
+                //UPDATE NEW FILE PATH
 	        	$db->query('UPDATE '.$tableName.' SET fingerprint = ?, filesize = ?, path = ?, filename = ? WHERE res_id = ?', 
-	        		array($fingerprint, filesize($filetmp), $storeResult['destination_dir'], $storeResult['file_destination_name'], $_SESSION['attachmentInfo']['inProgressResId']));
-	        } else {
+	        		array($fingerprint, filesize($filetmp), $storeResult['destination_dir'], $storeResult['file_destination_name'], $_SESSION['attachmentInfo'][$i]['inProgressResId']));
+            
+            //MODE FIRST BACKUP
+            } else {
                 $_SESSION['data'] = array();
 
                 array_push($_SESSION['data'], array( 'column' => "typist", 			'value' => $_SESSION['user']['UserId'], 			'type' => "string" ) );
@@ -139,42 +142,49 @@ if ($arrayIsAllowed['status'] == false) {
                 array_push($_SESSION['data'], array( 'column' => "status", 			'value' => 'TMP', 									'type' => "string" ) );
                 array_push($_SESSION['data'], array( 'column' => "offset_doc", 		'value' => ' ', 									'type' => "string" ) );
                 array_push($_SESSION['data'], array( 'column' => "logical_adr", 	'value' => ' ', 									'type' => "string" ) );
-                array_push($_SESSION['data'], array( 'column' => "title", 			'value' => $_SESSION['attachmentInfo']['title'], 	'type' => "string" ) );
+                array_push($_SESSION['data'], array( 'column' => "title", 			'value' => $_SESSION['attachmentInfo'][$i]['title'], 	'type' => "string" ) );
                 array_push($_SESSION['data'], array( 'column' => "coll_id", 		'value' => $_SESSION['collection_id_choice'], 		'type' => "string" ) );
                 array_push($_SESSION['data'], array( 'column' => "res_id_master", 	'value' => $_SESSION['doc_id'], 					'type' => "integer") );
-                array_push($_SESSION['data'], array( 'column' => "type_id", 		'value' => 0, 										'type' => "integer" ) );
+                
+                if ($objectType == 'outgoingMail') {
+                    $_SESSION['upfile'][$i]['outgoingMail'] = true;
+                    array_push($_SESSION['data'], array( 'column' => "type_id", 		'value' => 1, 										'type' => "integer" ) );
+                } else {
+                    array_push($_SESSION['data'], array( 'column' => "type_id", 		'value' => 0, 										'type' => "integer" ) );
+                }
+                
 
                 if ($_SESSION['origin'] == "scan") {
                     array_push($_SESSION['data'], array( 'column' => "scan_user", 	'value' => $_SESSION['user']['UserId'], 			'type' => "string" ) );
                     array_push($_SESSION['data'], array( 'column' => "scan_date", 	'value' => $req->current_datetime(), 				'type' => "function" ) );
                 }
-                if (isset($_SESSION['attachmentInfo']['back_date']) && $_SESSION['attachmentInfo']['back_date'] <> '') {
-                    array_push($_SESSION['data'], array( 'column' => "validation_date", 'value' => $func->format_date_db($_SESSION['attachmentInfo']['back_date']), 'type' => "date", ) );
+                if (isset($_SESSION['attachmentInfo'][$i]['back_date']) && $_SESSION['attachmentInfo'][$i]['back_date'] <> '') {
+                    array_push($_SESSION['data'], array( 'column' => "validation_date", 'value' => $func->format_date_db($_SESSION['attachmentInfo'][$i]['back_date']), 'type' => "date", ) );
                 }
 
-                if (isset($_SESSION['attachmentInfo']['contactId']) && $_SESSION['attachmentInfo']['contactId'] <> '' && is_numeric($_SESSION['attachmentInfo']['contactId'])) {
-                    array_push($_SESSION['data'], array( 'column' => 'dest_contact_id', 'value' => $_SESSION['attachmentInfo']['contactId'], 'type' => 'integer' ) );
-                } else if (isset($_SESSION['attachmentInfo']['contactId']) && $_SESSION['attachmentInfo']['contactId'] != '' && !is_numeric($_SESSION['attachmentInfo']['contactId'])) {
+                if (isset($_SESSION['attachmentInfo'][$i]['contactId']) && $_SESSION['attachmentInfo'][$i]['contactId'] <> '' && is_numeric($_SESSION['attachmentInfo'][$i]['contactId'])) {
+                    array_push($_SESSION['data'], array( 'column' => 'dest_contact_id', 'value' => $_SESSION['attachmentInfo'][$i]['contactId'], 'type' => 'integer' ) );
+                } else if (isset($_SESSION['attachmentInfo'][$i]['contactId']) && $_SESSION['attachmentInfo'][$i]['contactId'] != '' && !is_numeric($_SESSION['attachmentInfo'][$i]['contactId'])) {
                     $_SESSION['data'][] = [
                             'column' => 'dest_user',
-                            'value' => $_SESSION['attachmentInfo']['contactId'],
+                            'value' => $_SESSION['attachmentInfo'][$i]['contactId'],
                             'type' => 'string',
                         ];
                 }
 
-                if (isset($_SESSION['attachmentInfo']['addressId']) && $_SESSION['attachmentInfo']['addressId'] <> '' && is_numeric($_SESSION['attachmentInfo']['addressId'])) {
-                    array_push($_SESSION['data'], array( 'column' => "dest_address_id", 'value' => $_SESSION['attachmentInfo']['addressId'], 'type' => "integer" ) );
+                if (isset($_SESSION['attachmentInfo'][$i]['addressId']) && $_SESSION['attachmentInfo'][$i]['addressId'] <> '' && is_numeric($_SESSION['attachmentInfo']['addressId'])) {
+                    array_push($_SESSION['data'], array( 'column' => "dest_address_id", 'value' => $_SESSION['attachmentInfo'][$i]['addressId'], 'type' => "integer" ) );
                 }
 
                 if ($_SESSION['targetAttachment'] == 'add'){
 					$relation       = 1;
-                    if(!empty($_SESSION['attachmentInfo']['chrono'])){
-                        $identifier     = $_SESSION['attachmentInfo']['chrono'];
+                    if(!empty($_SESSION['attachmentInfo'][$i]['chrono'])){
+                        $identifier     = $_SESSION['attachmentInfo'][$i]['chrono'];
                     }else{
                         $identifier     = null;    
                     }
 					
-					$attachmentType = $_SESSION['attachmentInfo']['type'];
+					$attachmentType = $_SESSION['attachmentInfo'][$i]['type'];
 					$TableName      = RES_ATTACHMENTS_TABLE;
 
                 } else if ($_SESSION['targetAttachment'] == 'edit') {
@@ -224,7 +234,7 @@ if ($arrayIsAllowed['status'] == false) {
 					$_SESSION['config']['databasetype']
 				);
 
-				$_SESSION['attachmentInfo']['inProgressResId'] = $id;
+				$_SESSION['attachmentInfo'][$i]['inProgressResId'] = $id;
 	        }
         }
     }
diff --git a/modules/templates/js/functions.js b/modules/templates/js/functions.js
index 3b9b86870e5..ae99d402b17 100755
--- a/modules/templates/js/functions.js
+++ b/modules/templates/js/functions.js
@@ -26,7 +26,6 @@ function show_special_form(elem_to_view, elem_to_hide1)
 
 function show_special_form_3_elements(elem_to_view, elem_to_hide1, elem_to_hide2)
 {
-    console.log(elem_to_view);
     var elem_0 = window.document.getElementById(elem_to_view);
     var elem_1 = window.document.getElementById(elem_to_hide1);
     var elem_2 = window.document.getElementById(elem_to_hide2);
@@ -69,7 +68,6 @@ function setradiobutton(target)
     }else if(target=="sendmail") {
         $j("#office,#span_office").hide();
         $j("#html").click();
-        console.log("office caché !");
     } else if(target=="notifications") {
         $j("#txt,#span_txt,#office,#span_office").hide();
         $j("#html").click();
@@ -89,14 +87,45 @@ function setradiobutton(target)
 
 function select_template(path_to_script, attachment_type)
 {
+    
+    if ($j('#'+attachment_type.id).val() != '') {
+        $j('#formAttachment .transmissionDiv #newAttachButton').prop("disabled",false);
+        $j('#formAttachment .transmissionDiv #newAttachButton').removeClass("readonly");
+        
+    } else {
+        $j('#formAttachment .transmissionDiv #newAttachButton').prop("disabled",true);
+        $j('#formAttachment .transmissionDiv #newAttachButton').addClass("readonly");
+    }
+    if ($j('#'+attachment_type.id+' option:selected').attr("width_delay") != '' && $j('#'+attachment_type.id+' option:selected').attr("width_delay") != undefined) {
+        var delay = $j('#'+attachment_type.id+' option:selected').attr("width_delay");
+        var delay_date = defineBackDate(delay);
+        $j('#'+attachment_type.id).parent().parent().find('[name=back_date\\[\\]]').val(delay_date);
+
+    } else {
+        $j('#'+attachment_type.id).parent().parent().find('[name=back_date\\[\\]]').val("");
+    }
+
+    if ($j('#'+attachment_type.id+' option:selected').val() == "transmission") {
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]]').css('display','inline-block');
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]] option').remove();
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]]').append('<option value="EXP_RTURN">Attente retour</option>');
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]]').append('<option value="NO_RTURN">Pas de retour</option>');
+        $j('#'+attachment_type.id).parent().parent().find('[name=back_date\\[\\]]').css('width','75px');
+    } else {
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]]').css('display','none');
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]] option').remove();
+        $j('#'+attachment_type.id).parent().parent().find('[name=effectiveDateStatus\\[\\]]').append('<option value="A_TRA">A traiter</option>');
+        $j('#'+attachment_type.id).parent().parent().find('[name=back_date\\[\\]]').css('width','inherite');
+    }
+
     new Ajax.Request(path_to_script,
     {
         method:'post',
-        parameters: {attachment_type: attachment_type},
+        parameters: {attachment_type: $j('#'+attachment_type.id).val()},
         onSuccess: function(answer){
-            $('templateOffice').innerHTML = answer.responseText;
-            if (typeof ($('templateOffice').onchange) == 'function')
-                $('templateOffice').onchange();
+            $j('#'+attachment_type.id).parent().parent().find('[name=templateOffice\\[\\]]').html(answer.responseText);
+            $j('#'+attachment_type.id).parent().parent().find('[name=templateOffice\\[\\]]').change();    
+            $j('#'+attachment_type.id).parent().parent().find('[name=contact_attach\\[\\]]').change();
         }
     });
 }
diff --git a/modules/templates/templates_management.php b/modules/templates/templates_management.php
index 74ffbc569f3..f9995a60379 100755
--- a/modules/templates/templates_management.php
+++ b/modules/templates/templates_management.php
@@ -290,34 +290,24 @@ if ($mode == 'list') {
                     ?>
                     <p>
                         <span id="templateEditTr">
-                        <label><?php echo _EDIT_TEMPLATE;?> :</label>
+                            <label><?php echo _EDIT_TEMPLATE;?> :</label>
                   
                                 <?php
-                                $strAction .= 'showAppletLauncher(\''
-                                    . $_SESSION['config']['businessappurl'] . 'index.php?display=true'
-                                    . '&module=content_management&page=applet_modal_launcher&objectType='
-                                    . $objectType
-                                    . '&objectId='
-                                    . $objectId
-                                    . '&objectTable='
-                                    . $objectTable
-                                    . '\', \'100px\', \'500px\');$(\'add\').value=\'Edition en cours ...\';editingDoc(\''.$_SESSION['user']['UserId'].'\');$(\'add\').disabled=\'disabled\';$(\'add\').style.opacity=\'0.5\';';
+                                $strAction .= 'showAppletLauncher(this,\''.$objectId.'\',\''.$objectTable.'\',\''.$objectType.'\',\'template\', \'100px\', \'500px\');$(\'add\').value=\'Edition en cours ...\';editingDoc(\''.$_SESSION['user']['UserId'].'\');$(\'add\').disabled=\'disabled\';$(\'add\').style.opacity=\'0.5\';';
                                 ?>
                                 <a href="#" onClick="<?php functions::xecho($strAction);?>">
                                 
                                     <i class="fa fa-pencil fa-2x"></i>
                                 <?php echo _EDIT_TEMPLATE;?>
-                            </a>   
+                            </a>
                         </span>
                         <?php if ($mode == 'up') {?>
                         <a href="#" onclick="$j('#addTemplateFile').click();$('template_style_icon').setStyle({color: '#009DC5'})" style="margin-left:15px">
-
                             <i id="template_style_icon" class="fa fa-paperclip fa-2x"></i> Importer un fichier
                         </a>
                         <input class="button" name="addTemplate" id="addTemplate" onclick="$j('#addTemplateFile').click();" style="display:none;margin-left:15px" value="+" type="button"/>
                         <input id="addTemplateFile" type="file" onchange="addTemplateBase(this);" style="display:none;" accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml‌​.slideshow,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.presentation,application/vnd.oasis.opendocument.spreadsheet"/>
-                        <?php } ?>  
-
+                        <?php } ?>   
                     </p>
                 </div>
                 <div id="txt_div" name="txt_div">
-- 
GitLab